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#if defined(_MSC_VER)
584# pragma warning(disable : 4204)
585#endif
586
587#ifndef SQLITE_CIO_NO_TRANSLATE
588# if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
589#  ifndef SHELL_NO_SYSINC
590#   include <io.h>
591#   include <fcntl.h>
592#   undef WIN32_LEAN_AND_MEAN
593#   define WIN32_LEAN_AND_MEAN
594#   include <windows.h>
595#  endif
596#  define CIO_WIN_WC_XLATE 1 /* Use WCHAR Windows APIs for console I/O */
597# else
598#  ifndef SHELL_NO_SYSINC
599#   include <unistd.h>
600#  endif
601#  define CIO_WIN_WC_XLATE 0 /* Use plain C library stream I/O at console */
602# endif
603#else
604# define CIO_WIN_WC_XLATE 0 /* Not exposing translation routines at all */
605#endif
606
607#if CIO_WIN_WC_XLATE
608/* Character used to represent a known-incomplete UTF-8 char group (���) */
609static WCHAR cBadGroup = 0xfffd;
610#endif
611
612#if CIO_WIN_WC_XLATE
613static HANDLE handleOfFile(FILE *pf){
614  int fileDesc = _fileno(pf);
615  union { intptr_t osfh; HANDLE fh; } fid = {
616    (fileDesc>=0)? _get_osfhandle(fileDesc) : (intptr_t)INVALID_HANDLE_VALUE
617  };
618  return fid.fh;
619}
620#endif
621
622#ifndef SQLITE_CIO_NO_TRANSLATE
623typedef struct PerStreamTags {
624# if CIO_WIN_WC_XLATE
625  HANDLE hx;
626  DWORD consMode;
627  char acIncomplete[4];
628# else
629  short reachesConsole;
630# endif
631  FILE *pf;
632} PerStreamTags;
633
634/* Define NULL-like value for things which can validly be 0. */
635# define SHELL_INVALID_FILE_PTR ((FILE *)~0)
636# if CIO_WIN_WC_XLATE
637#  define SHELL_INVALID_CONS_MODE 0xFFFF0000
638# endif
639
640# if CIO_WIN_WC_XLATE
641#  define PST_INITIALIZER { INVALID_HANDLE_VALUE, SHELL_INVALID_CONS_MODE, \
642      {0,0,0,0}, SHELL_INVALID_FILE_PTR }
643# else
644#  define PST_INITIALIZER { 0, SHELL_INVALID_FILE_PTR }
645# endif
646
647/* Quickly say whether a known output is going to the console. */
648# if CIO_WIN_WC_XLATE
649static short pstReachesConsole(PerStreamTags *ppst){
650  return (ppst->hx != INVALID_HANDLE_VALUE);
651}
652# else
653#  define pstReachesConsole(ppst) 0
654# endif
655
656# if CIO_WIN_WC_XLATE
657static void restoreConsoleArb(PerStreamTags *ppst){
658  if( pstReachesConsole(ppst) ) SetConsoleMode(ppst->hx, ppst->consMode);
659}
660# else
661#  define restoreConsoleArb(ppst)
662# endif
663
664/* Say whether FILE* appears to be a console, collect associated info. */
665static short streamOfConsole(FILE *pf, /* out */ PerStreamTags *ppst){
666# if CIO_WIN_WC_XLATE
667  short rv = 0;
668  DWORD dwCM = SHELL_INVALID_CONS_MODE;
669  HANDLE fh = handleOfFile(pf);
670  ppst->pf = pf;
671  if( INVALID_HANDLE_VALUE != fh ){
672    rv = (GetFileType(fh) == FILE_TYPE_CHAR && GetConsoleMode(fh,&dwCM));
673  }
674  ppst->hx = (rv)? fh : INVALID_HANDLE_VALUE;
675  ppst->consMode = dwCM;
676  return rv;
677# else
678  ppst->pf = pf;
679  ppst->reachesConsole = ( (short)isatty(fileno(pf)) );
680  return ppst->reachesConsole;
681# endif
682}
683
684# ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
685#  define ENABLE_VIRTUAL_TERMINAL_PROCESSING  (0x4)
686# endif
687
688# if CIO_WIN_WC_XLATE
689/* Define console modes for use with the Windows Console API. */
690#  define SHELL_CONI_MODE \
691  (ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE | ENABLE_LINE_INPUT | 0x80 \
692  | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS | ENABLE_PROCESSED_INPUT)
693#  define SHELL_CONO_MODE (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT \
694  | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
695# endif
696
697typedef struct ConsoleInfo {
698  PerStreamTags pstSetup[3];
699  PerStreamTags pstDesignated[3];
700  StreamsAreConsole sacSetup;
701} ConsoleInfo;
702
703static short isValidStreamInfo(PerStreamTags *ppst){
704  return (ppst->pf != SHELL_INVALID_FILE_PTR);
705}
706
707static ConsoleInfo consoleInfo = {
708  { /* pstSetup */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
709  { /* pstDesignated[] */ PST_INITIALIZER, PST_INITIALIZER, PST_INITIALIZER },
710  SAC_NoConsole /* sacSetup */
711};
712
713SQLITE_INTERNAL_LINKAGE FILE* invalidFileStream = (FILE *)~0;
714
715# if CIO_WIN_WC_XLATE
716static void maybeSetupAsConsole(PerStreamTags *ppst, short odir){
717  if( pstReachesConsole(ppst) ){
718    DWORD cm = odir? SHELL_CONO_MODE : SHELL_CONI_MODE;
719    SetConsoleMode(ppst->hx, cm);
720  }
721}
722# else
723#  define maybeSetupAsConsole(ppst,odir)
724# endif
725
726SQLITE_INTERNAL_LINKAGE void consoleRenewSetup(void){
727# if CIO_WIN_WC_XLATE
728  int ix = 0;
729  while( ix < 6 ){
730    PerStreamTags *ppst = (ix<3)?
731      &consoleInfo.pstSetup[ix] : &consoleInfo.pstDesignated[ix-3];
732    maybeSetupAsConsole(ppst, (ix % 3)>0);
733    ++ix;
734  }
735# endif
736}
737
738SQLITE_INTERNAL_LINKAGE StreamsAreConsole
739consoleClassifySetup( FILE *pfIn, FILE *pfOut, FILE *pfErr ){
740  StreamsAreConsole rv = SAC_NoConsole;
741  FILE* apf[3] = { pfIn, pfOut, pfErr };
742  int ix;
743  for( ix = 2; ix >= 0; --ix ){
744    PerStreamTags *ppst = &consoleInfo.pstSetup[ix];
745    if( streamOfConsole(apf[ix], ppst) ){
746      rv |= (SAC_InConsole<<ix);
747    }
748    consoleInfo.pstDesignated[ix] = *ppst;
749    if( ix > 0 ) fflush(apf[ix]);
750  }
751  consoleInfo.sacSetup = rv;
752  consoleRenewSetup();
753  return rv;
754}
755
756SQLITE_INTERNAL_LINKAGE void SQLITE_CDECL consoleRestore( void ){
757# if CIO_WIN_WC_XLATE
758  static ConsoleInfo *pci = &consoleInfo;
759  if( pci->sacSetup ){
760    int ix;
761    for( ix=0; ix<3; ++ix ){
762      if( pci->sacSetup & (SAC_InConsole<<ix) ){
763        PerStreamTags *ppst = &pci->pstSetup[ix];
764        SetConsoleMode(ppst->hx, ppst->consMode);
765      }
766    }
767  }
768# endif
769}
770#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
771
772#ifdef SQLITE_CIO_INPUT_REDIR
773/* Say whether given FILE* is among those known, via either
774** consoleClassifySetup() or set{Output,Error}Stream, as
775** readable, and return an associated PerStreamTags pointer
776** if so. Otherwise, return 0.
777*/
778static PerStreamTags * isKnownReadable(FILE *pf){
779  static PerStreamTags *apst[] = {
780    &consoleInfo.pstDesignated[0], &consoleInfo.pstSetup[0], 0
781  };
782  int ix = 0;
783  do {
784    if( apst[ix]->pf == pf ) break;
785  } while( apst[++ix] != 0 );
786  return apst[ix];
787}
788#endif
789
790#ifndef SQLITE_CIO_NO_TRANSLATE
791/* Say whether given FILE* is among those known, via either
792** consoleClassifySetup() or set{Output,Error}Stream, as
793** writable, and return an associated PerStreamTags pointer
794** if so. Otherwise, return 0.
795*/
796static PerStreamTags * isKnownWritable(FILE *pf){
797  static PerStreamTags *apst[] = {
798    &consoleInfo.pstDesignated[1], &consoleInfo.pstDesignated[2],
799    &consoleInfo.pstSetup[1], &consoleInfo.pstSetup[2], 0
800  };
801  int ix = 0;
802  do {
803    if( apst[ix]->pf == pf ) break;
804  } while( apst[++ix] != 0 );
805  return apst[ix];
806}
807
808static FILE *designateEmitStream(FILE *pf, unsigned chix){
809  FILE *rv = consoleInfo.pstDesignated[chix].pf;
810  if( pf == invalidFileStream ) return rv;
811  else{
812    /* Setting a possibly new output stream. */
813    PerStreamTags *ppst = isKnownWritable(pf);
814    if( ppst != 0 ){
815      PerStreamTags pst = *ppst;
816      consoleInfo.pstDesignated[chix] = pst;
817    }else streamOfConsole(pf, &consoleInfo.pstDesignated[chix]);
818  }
819  return rv;
820}
821
822SQLITE_INTERNAL_LINKAGE FILE *setOutputStream(FILE *pf){
823  return designateEmitStream(pf, 1);
824}
825# ifdef CONSIO_SET_ERROR_STREAM
826SQLITE_INTERNAL_LINKAGE FILE *setErrorStream(FILE *pf){
827  return designateEmitStream(pf, 2);
828}
829# endif
830#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
831
832#ifndef SQLITE_CIO_NO_SETMODE
833# if CIO_WIN_WC_XLATE
834static void setModeFlushQ(FILE *pf, short bFlush, int mode){
835  if( bFlush ) fflush(pf);
836  _setmode(_fileno(pf), mode);
837}
838# else
839#  define setModeFlushQ(f, b, m) if(b) fflush(f)
840# endif
841
842SQLITE_INTERNAL_LINKAGE void setBinaryMode(FILE *pf, short bFlush){
843  setModeFlushQ(pf, bFlush, _O_BINARY);
844}
845SQLITE_INTERNAL_LINKAGE void setTextMode(FILE *pf, short bFlush){
846  setModeFlushQ(pf, bFlush, _O_TEXT);
847}
848# undef setModeFlushQ
849
850#else /* defined(SQLITE_CIO_NO_SETMODE) */
851# define setBinaryMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
852# define setTextMode(f, bFlush) do{ if((bFlush)) fflush(f); }while(0)
853#endif /* defined(SQLITE_CIO_NO_SETMODE) */
854
855#ifndef SQLITE_CIO_NO_TRANSLATE
856# if CIO_WIN_WC_XLATE
857/* Write buffer cBuf as output to stream known to reach console,
858** limited to ncTake char's. Return ncTake on success, else 0. */
859static int conZstrEmit(PerStreamTags *ppst, const char *z, int ncTake){
860  int rv = 0;
861  if( z!=NULL ){
862    int nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, 0,0);
863    if( nwc > 0 ){
864      WCHAR *zw = sqlite3_malloc64(nwc*sizeof(WCHAR));
865      if( zw!=NULL ){
866        nwc = MultiByteToWideChar(CP_UTF8,0, z,ncTake, zw,nwc);
867        if( nwc > 0 ){
868          /* Translation from UTF-8 to UTF-16, then WCHARs out. */
869          if( WriteConsoleW(ppst->hx, zw,nwc, 0, NULL) ){
870            rv = ncTake;
871          }
872        }
873        sqlite3_free(zw);
874      }
875    }
876  }
877  return rv;
878}
879
880/* For {f,o,e}PrintfUtf8() when stream is known to reach console. */
881static int conioVmPrintf(PerStreamTags *ppst, const char *zFormat, va_list ap){
882  char *z = sqlite3_vmprintf(zFormat, ap);
883  if( z ){
884    int rv = conZstrEmit(ppst, z, (int)strlen(z));
885    sqlite3_free(z);
886    return rv;
887  }else return 0;
888}
889# endif /* CIO_WIN_WC_XLATE */
890
891# ifdef CONSIO_GET_EMIT_STREAM
892static PerStreamTags * getDesignatedEmitStream(FILE *pf, unsigned chix,
893                                               PerStreamTags *ppst){
894  PerStreamTags *rv = isKnownWritable(pf);
895  short isValid = (rv!=0)? isValidStreamInfo(rv) : 0;
896  if( rv != 0 && isValid ) return rv;
897  streamOfConsole(pf, ppst);
898  return ppst;
899}
900# endif
901
902/* Get stream info, either for designated output or error stream when
903** chix equals 1 or 2, or for an arbitrary stream when chix == 0.
904** In either case, ppst references a caller-owned PerStreamTags
905** struct which may be filled in if none of the known writable
906** streams is being held by consoleInfo. The ppf parameter is a
907** byref output when chix!=0 and a byref input when chix==0.
908 */
909static PerStreamTags *
910getEmitStreamInfo(unsigned chix, PerStreamTags *ppst,
911                  /* in/out */ FILE **ppf){
912  PerStreamTags *ppstTry;
913  FILE *pfEmit;
914  if( chix > 0 ){
915    ppstTry = &consoleInfo.pstDesignated[chix];
916    if( !isValidStreamInfo(ppstTry) ){
917      ppstTry = &consoleInfo.pstSetup[chix];
918      pfEmit = ppst->pf;
919    }else pfEmit = ppstTry->pf;
920    if( !isValidStreamInfo(ppstTry) ){
921      pfEmit = (chix > 1)? stderr : stdout;
922      ppstTry = ppst;
923      streamOfConsole(pfEmit, ppstTry);
924    }
925    *ppf = pfEmit;
926  }else{
927    ppstTry = isKnownWritable(*ppf);
928    if( ppstTry != 0 ) return ppstTry;
929    streamOfConsole(*ppf, ppst);
930    return ppst;
931  }
932  return ppstTry;
933}
934
935SQLITE_INTERNAL_LINKAGE int oPrintfUtf8(const char *zFormat, ...){
936  va_list ap;
937  int rv;
938  FILE *pfOut;
939  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
940# if CIO_WIN_WC_XLATE
941  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
942# else
943  getEmitStreamInfo(1, &pst, &pfOut);
944# endif
945  assert(zFormat!=0);
946  va_start(ap, zFormat);
947# if CIO_WIN_WC_XLATE
948  if( pstReachesConsole(ppst) ){
949    rv = conioVmPrintf(ppst, zFormat, ap);
950  }else{
951# endif
952    rv = vfprintf(pfOut, zFormat, ap);
953# if CIO_WIN_WC_XLATE
954  }
955# endif
956  va_end(ap);
957  return rv;
958}
959
960SQLITE_INTERNAL_LINKAGE int ePrintfUtf8(const char *zFormat, ...){
961  va_list ap;
962  int rv;
963  FILE *pfErr;
964  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
965# if CIO_WIN_WC_XLATE
966  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
967# else
968  getEmitStreamInfo(2, &pst, &pfErr);
969# endif
970  assert(zFormat!=0);
971  va_start(ap, zFormat);
972# if CIO_WIN_WC_XLATE
973  if( pstReachesConsole(ppst) ){
974    rv = conioVmPrintf(ppst, zFormat, ap);
975  }else{
976# endif
977    rv = vfprintf(pfErr, zFormat, ap);
978# if CIO_WIN_WC_XLATE
979  }
980# endif
981  va_end(ap);
982  return rv;
983}
984
985SQLITE_INTERNAL_LINKAGE int fPrintfUtf8(FILE *pfO, const char *zFormat, ...){
986  va_list ap;
987  int rv;
988  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
989# if CIO_WIN_WC_XLATE
990  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
991# else
992  getEmitStreamInfo(0, &pst, &pfO);
993# endif
994  assert(zFormat!=0);
995  va_start(ap, zFormat);
996# if CIO_WIN_WC_XLATE
997  if( pstReachesConsole(ppst) ){
998    maybeSetupAsConsole(ppst, 1);
999    rv = conioVmPrintf(ppst, zFormat, ap);
1000    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1001  }else{
1002# endif
1003    rv = vfprintf(pfO, zFormat, ap);
1004# if CIO_WIN_WC_XLATE
1005  }
1006# endif
1007  va_end(ap);
1008  return rv;
1009}
1010
1011SQLITE_INTERNAL_LINKAGE int fPutsUtf8(const char *z, FILE *pfO){
1012  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1013# if CIO_WIN_WC_XLATE
1014  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1015# else
1016  getEmitStreamInfo(0, &pst, &pfO);
1017# endif
1018  assert(z!=0);
1019# if CIO_WIN_WC_XLATE
1020  if( pstReachesConsole(ppst) ){
1021    int rv;
1022    maybeSetupAsConsole(ppst, 1);
1023    rv = conZstrEmit(ppst, z, (int)strlen(z));
1024    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1025    return rv;
1026  }else {
1027# endif
1028    return (fputs(z, pfO)<0)? 0 : (int)strlen(z);
1029# if CIO_WIN_WC_XLATE
1030  }
1031# endif
1032}
1033
1034SQLITE_INTERNAL_LINKAGE int ePutsUtf8(const char *z){
1035  FILE *pfErr;
1036  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1037# if CIO_WIN_WC_XLATE
1038  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1039# else
1040  getEmitStreamInfo(2, &pst, &pfErr);
1041# endif
1042  assert(z!=0);
1043# if CIO_WIN_WC_XLATE
1044  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1045  else {
1046# endif
1047    return (fputs(z, pfErr)<0)? 0 : (int)strlen(z);
1048# if CIO_WIN_WC_XLATE
1049  }
1050# endif
1051}
1052
1053SQLITE_INTERNAL_LINKAGE int oPutsUtf8(const char *z){
1054  FILE *pfOut;
1055  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1056# if CIO_WIN_WC_XLATE
1057  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1058# else
1059  getEmitStreamInfo(1, &pst, &pfOut);
1060# endif
1061  assert(z!=0);
1062# if CIO_WIN_WC_XLATE
1063  if( pstReachesConsole(ppst) ) return conZstrEmit(ppst, z, (int)strlen(z));
1064  else {
1065# endif
1066    return (fputs(z, pfOut)<0)? 0 : (int)strlen(z);
1067# if CIO_WIN_WC_XLATE
1068  }
1069# endif
1070}
1071
1072#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1073
1074#if !(defined(SQLITE_CIO_NO_UTF8SCAN) && defined(SQLITE_CIO_NO_TRANSLATE))
1075/* Skip over as much z[] input char sequence as is valid UTF-8,
1076** limited per nAccept char's or whole characters and containing
1077** no char cn such that ((1<<cn) & ccm)!=0. On return, the
1078** sequence z:return (inclusive:exclusive) is validated UTF-8.
1079** Limit: nAccept>=0 => char count, nAccept<0 => character
1080 */
1081SQLITE_INTERNAL_LINKAGE const char*
1082zSkipValidUtf8(const char *z, int nAccept, long ccm){
1083  int ng = (nAccept<0)? -nAccept : 0;
1084  const char *pcLimit = (nAccept>=0)? z+nAccept : 0;
1085  assert(z!=0);
1086  while( (pcLimit)? (z<pcLimit) : (ng-- != 0) ){
1087    char c = *z;
1088    if( (c & 0x80) == 0 ){
1089      if( ccm != 0L && c < 0x20 && ((1L<<c) & ccm) != 0 ) return z;
1090      ++z; /* ASCII */
1091    }else if( (c & 0xC0) != 0xC0 ) return z; /* not a lead byte */
1092    else{
1093      const char *zt = z+1; /* Got lead byte, look at trail bytes.*/
1094      do{
1095        if( pcLimit && zt >= pcLimit ) return z;
1096        else{
1097          char ct = *zt++;
1098          if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){
1099            /* Trailing bytes are too few, too many, or invalid. */
1100            return z;
1101          }
1102        }
1103      } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */
1104      z = zt;
1105    }
1106  }
1107  return z;
1108}
1109#endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1110
1111#ifndef SQLITE_CIO_NO_TRANSLATE
1112# ifdef CONSIO_SPUTB
1113SQLITE_INTERNAL_LINKAGE int
1114fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1115  assert(pfO!=0);
1116#  if CIO_WIN_WC_XLATE
1117  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1118  PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1119  if( pstReachesConsole(ppst) ){
1120    int rv;
1121    maybeSetupAsConsole(ppst, 1);
1122    rv = conZstrEmit(ppst, cBuf, nAccept);
1123    if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1124    return rv;
1125  }else {
1126#  endif
1127    return (int)fwrite(cBuf, 1, nAccept, pfO);
1128#  if CIO_WIN_WC_XLATE
1129  }
1130#  endif
1131}
1132# endif
1133
1134SQLITE_INTERNAL_LINKAGE int
1135oPutbUtf8(const char *cBuf, int nAccept){
1136  FILE *pfOut;
1137  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1138# if CIO_WIN_WC_XLATE
1139  PerStreamTags *ppst = getEmitStreamInfo(1, &pst, &pfOut);
1140# else
1141  getEmitStreamInfo(1, &pst, &pfOut);
1142# endif
1143# if CIO_WIN_WC_XLATE
1144  if( pstReachesConsole(ppst) ){
1145    return conZstrEmit(ppst, cBuf, nAccept);
1146  }else {
1147# endif
1148    return (int)fwrite(cBuf, 1, nAccept, pfOut);
1149# if CIO_WIN_WC_XLATE
1150  }
1151# endif
1152}
1153
1154# ifdef CONSIO_EPUTB
1155SQLITE_INTERNAL_LINKAGE int
1156ePutbUtf8(const char *cBuf, int nAccept){
1157  FILE *pfErr;
1158  PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1159  PerStreamTags *ppst = getEmitStreamInfo(2, &pst, &pfErr);
1160#  if CIO_WIN_WC_XLATE
1161  if( pstReachesConsole(ppst) ){
1162    return conZstrEmit(ppst, cBuf, nAccept);
1163  }else {
1164#  endif
1165    return (int)fwrite(cBuf, 1, nAccept, pfErr);
1166#  if CIO_WIN_WC_XLATE
1167  }
1168#  endif
1169}
1170# endif /* defined(CONSIO_EPUTB) */
1171
1172SQLITE_INTERNAL_LINKAGE char* fGetsUtf8(char *cBuf, int ncMax, FILE *pfIn){
1173  if( pfIn==0 ) pfIn = stdin;
1174# if CIO_WIN_WC_XLATE
1175  if( pfIn == consoleInfo.pstSetup[0].pf
1176      && (consoleInfo.sacSetup & SAC_InConsole)!=0 ){
1177#  if CIO_WIN_WC_XLATE==1
1178#   define SHELL_GULP 150 /* Count of WCHARS to be gulped at a time */
1179    WCHAR wcBuf[SHELL_GULP+1];
1180    int lend = 0, noc = 0;
1181    if( ncMax > 0 ) cBuf[0] = 0;
1182    while( noc < ncMax-8-1 && !lend ){
1183      /* There is room for at least 2 more characters and a 0-terminator. */
1184      int na = (ncMax > SHELL_GULP*4+1 + noc)? SHELL_GULP : (ncMax-1 - noc)/4;
1185#   undef SHELL_GULP
1186      DWORD nbr = 0;
1187      BOOL bRC = ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf, na, &nbr, 0);
1188      if( bRC && nbr>0 && (wcBuf[nbr-1]&0xF800)==0xD800 ){
1189        /* Last WHAR read is first of a UTF-16 surrogate pair. Grab its mate. */
1190        DWORD nbrx;
1191        bRC &= ReadConsoleW(consoleInfo.pstSetup[0].hx, wcBuf+nbr, 1, &nbrx, 0);
1192        if( bRC ) nbr += nbrx;
1193      }
1194      if( !bRC || (noc==0 && nbr==0) ) return 0;
1195      if( nbr > 0 ){
1196        int nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,0,0,0,0);
1197        if( nmb != 0 && noc+nmb <= ncMax ){
1198          int iseg = noc;
1199          nmb = WideCharToMultiByte(CP_UTF8, 0, wcBuf,nbr,cBuf+noc,nmb,0,0);
1200          noc += nmb;
1201          /* Fixup line-ends as coded by Windows for CR (or "Enter".)
1202          ** This is done without regard for any setMode{Text,Binary}()
1203          ** call that might have been done on the interactive input.
1204          */
1205          if( noc > 0 ){
1206            if( cBuf[noc-1]=='\n' ){
1207              lend = 1;
1208              if( noc > 1 && cBuf[noc-2]=='\r' ) cBuf[--noc-1] = '\n';
1209            }
1210          }
1211          /* Check for ^Z (anywhere in line) too, to act as EOF. */
1212          while( iseg < noc ){
1213            if( cBuf[iseg]=='\x1a' ){
1214              noc = iseg; /* Chop ^Z and anything following. */
1215              lend = 1; /* Counts as end of line too. */
1216              break;
1217            }
1218            ++iseg;
1219          }
1220        }else break; /* Drop apparent garbage in. (Could assert.) */
1221      }else break;
1222    }
1223    /* If got nothing, (after ^Z chop), must be at end-of-file. */
1224    if( noc > 0 ){
1225      cBuf[noc] = 0;
1226      return cBuf;
1227    }else return 0;
1228#  endif
1229  }else{
1230# endif
1231    return fgets(cBuf, ncMax, pfIn);
1232# if CIO_WIN_WC_XLATE
1233  }
1234# endif
1235}
1236#endif /* !defined(SQLITE_CIO_NO_TRANSLATE) */
1237
1238#if defined(_MSC_VER)
1239# pragma warning(default : 4204)
1240#endif
1241
1242#undef SHELL_INVALID_FILE_PTR
1243
1244/************************* End ../ext/consio/console_io.c ********************/
1245
1246#ifndef SQLITE_SHELL_FIDDLE
1247
1248/* From here onward, fgets() is redirected to the console_io library. */
1249# define fgets(b,n,f) fGetsUtf8(b,n,f)
1250/*
1251 * Define macros for emitting output text in various ways:
1252 *  sputz(s, z)      => emit 0-terminated string z to given stream s
1253 *  sputf(s, f, ...) => emit varargs per format f to given stream s
1254 *  oputz(z)         => emit 0-terminated string z to default stream
1255 *  oputf(f, ...)    => emit varargs per format f to default stream
1256 *  eputz(z)         => emit 0-terminated string z to error stream
1257 *  eputf(f, ...)    => emit varargs per format f to error stream
1258 *  oputb(b, n)      => emit char buffer b[0..n-1] to default stream
1259 *
1260 * Note that the default stream is whatever has been last set via:
1261 *   setOutputStream(FILE *pf)
1262 * This is normally the stream that CLI normal output goes to.
1263 * For the stand-alone CLI, it is stdout with no .output redirect.
1264 *
1265 * The ?putz(z) forms are required for the Fiddle builds for string literal
1266 * output, in aid of enforcing format string to argument correspondence.
1267 */
1268# define sputz(s,z) fPutsUtf8(z,s)
1269# define sputf fPrintfUtf8
1270# define oputz(z) oPutsUtf8(z)
1271# define oputf oPrintfUtf8
1272# define eputz(z) ePutsUtf8(z)
1273# define eputf ePrintfUtf8
1274# define oputb(buf,na) oPutbUtf8(buf,na)
1275
1276#else
1277/* For Fiddle, all console handling and emit redirection is omitted. */
1278/* These next 3 macros are for emitting formatted output. When complaints
1279 * from the WASM build are issued for non-formatted output, (when a mere
1280 * string literal is to be emitted, the ?putz(z) forms should be used.
1281 * (This permits compile-time checking of format string / argument mismatch.)
1282 */
1283# define oputf(fmt, ...) printf(fmt,__VA_ARGS__)
1284# define eputf(fmt, ...) fprintf(stderr,fmt,__VA_ARGS__)
1285# define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1286/* These next 3 macros are for emitting simple string literals. */
1287# define oputz(z) fputs(z,stdout)
1288# define eputz(z) fputs(z,stderr)
1289# define sputz(fp,z) fputs(z,fp)
1290# define oputb(buf,na) fwrite(buf,1,na,stdout)
1291#endif
1292
1293/* True if the timer is enabled */
1294static int enableTimer = 0;
1295
1296/* A version of strcmp() that works with NULL values */
1297static int cli_strcmp(const char *a, const char *b){
1298  if( a==0 ) a = "";
1299  if( b==0 ) b = "";
1300  return strcmp(a,b);
1301}
1302static int cli_strncmp(const char *a, const char *b, size_t n){
1303  if( a==0 ) a = "";
1304  if( b==0 ) b = "";
1305  return strncmp(a,b,n);
1306}
1307
1308/* Return the current wall-clock time */
1309static sqlite3_int64 timeOfDay(void){
1310  static sqlite3_vfs *clockVfs = 0;
1311  sqlite3_int64 t;
1312  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
1313  if( clockVfs==0 ) return 0;  /* Never actually happens */
1314  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
1315    clockVfs->xCurrentTimeInt64(clockVfs, &t);
1316  }else{
1317    double r;
1318    clockVfs->xCurrentTime(clockVfs, &r);
1319    t = (sqlite3_int64)(r*86400000.0);
1320  }
1321  return t;
1322}
1323
1324#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
1325#include <sys/time.h>
1326#include <sys/resource.h>
1327
1328/* VxWorks does not support getrusage() as far as we can determine */
1329#if defined(_WRS_KERNEL) || defined(__RTP__)
1330struct rusage {
1331  struct timeval ru_utime; /* user CPU time used */
1332  struct timeval ru_stime; /* system CPU time used */
1333};
1334#define getrusage(A,B) memset(B,0,sizeof(*B))
1335#endif
1336
1337/* Saved resource information for the beginning of an operation */
1338static struct rusage sBegin;  /* CPU time at start */
1339static sqlite3_int64 iBegin;  /* Wall-clock time at start */
1340
1341/*
1342** Begin timing an operation
1343*/
1344static void beginTimer(void){
1345  if( enableTimer ){
1346    getrusage(RUSAGE_SELF, &sBegin);
1347    iBegin = timeOfDay();
1348  }
1349}
1350
1351/* Return the difference of two time_structs in seconds */
1352static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
1353  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
1354         (double)(pEnd->tv_sec - pStart->tv_sec);
1355}
1356
1357/*
1358** Print the timing results.
1359*/
1360static void endTimer(void){
1361  if( enableTimer ){
1362    sqlite3_int64 iEnd = timeOfDay();
1363    struct rusage sEnd;
1364    getrusage(RUSAGE_SELF, &sEnd);
1365    sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1366          (iEnd - iBegin)*0.001,
1367          timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1368          timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1369  }
1370}
1371
1372#define BEGIN_TIMER beginTimer()
1373#define END_TIMER endTimer()
1374#define HAS_TIMER 1
1375
1376#elif (defined(_WIN32) || defined(WIN32))
1377
1378/* Saved resource information for the beginning of an operation */
1379static HANDLE hProcess;
1380static FILETIME ftKernelBegin;
1381static FILETIME ftUserBegin;
1382static sqlite3_int64 ftWallBegin;
1383typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
1384                                    LPFILETIME, LPFILETIME);
1385static GETPROCTIMES getProcessTimesAddr = NULL;
1386
1387/*
1388** Check to see if we have timer support.  Return 1 if necessary
1389** support found (or found previously).
1390*/
1391static int hasTimer(void){
1392  if( getProcessTimesAddr ){
1393    return 1;
1394  } else {
1395#if !SQLITE_OS_WINRT
1396    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
1397    ** versions. See if the version we are running on has it, and if it
1398    ** does, save off a pointer to it and the current process handle.
1399    */
1400    hProcess = GetCurrentProcess();
1401    if( hProcess ){
1402      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
1403      if( NULL != hinstLib ){
1404        getProcessTimesAddr =
1405            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
1406        if( NULL != getProcessTimesAddr ){
1407          return 1;
1408        }
1409        FreeLibrary(hinstLib);
1410      }
1411    }
1412#endif
1413  }
1414  return 0;
1415}
1416
1417/*
1418** Begin timing an operation
1419*/
1420static void beginTimer(void){
1421  if( enableTimer && getProcessTimesAddr ){
1422    FILETIME ftCreation, ftExit;
1423    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
1424                        &ftKernelBegin,&ftUserBegin);
1425    ftWallBegin = timeOfDay();
1426  }
1427}
1428
1429/* Return the difference of two FILETIME structs in seconds */
1430static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
1431  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
1432  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
1433  return (double) ((i64End - i64Start) / 10000000.0);
1434}
1435
1436/*
1437** Print the timing results.
1438*/
1439static void endTimer(void){
1440  if( enableTimer && getProcessTimesAddr){
1441    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1442    sqlite3_int64 ftWallEnd = timeOfDay();
1443    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1444    sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1445          (ftWallEnd - ftWallBegin)*0.001,
1446          timeDiff(&ftUserBegin, &ftUserEnd),
1447          timeDiff(&ftKernelBegin, &ftKernelEnd));
1448  }
1449}
1450
1451#define BEGIN_TIMER beginTimer()
1452#define END_TIMER endTimer()
1453#define HAS_TIMER hasTimer()
1454
1455#else
1456#define BEGIN_TIMER
1457#define END_TIMER
1458#define HAS_TIMER 0
1459#endif
1460
1461/*
1462** Used to prevent warnings about unused parameters
1463*/
1464#define UNUSED_PARAMETER(x) (void)(x)
1465
1466/*
1467** Number of elements in an array
1468*/
1469#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
1470
1471/*
1472** If the following flag is set, then command execution stops
1473** at an error if we are not interactive.
1474*/
1475static int bail_on_error = 0;
1476
1477/*
1478** Treat stdin as an interactive input if the following variable
1479** is true.  Otherwise, assume stdin is connected to a file or pipe.
1480*/
1481static int stdin_is_interactive = 1;
1482
1483/*
1484** On Windows systems we need to know if standard output is a console
1485** in order to show that UTF-16 translation is done in the sign-on
1486** banner. The following variable is true if it is the console.
1487*/
1488static int stdout_is_console = 1;
1489
1490/*
1491** The following is the open SQLite database.  We make a pointer
1492** to this database a static variable so that it can be accessed
1493** by the SIGINT handler to interrupt database processing.
1494*/
1495static sqlite3 *globalDb = 0;
1496
1497/*
1498** True if an interrupt (Control-C) has been received.
1499*/
1500static volatile int seenInterrupt = 0;
1501
1502/*
1503** This is the name of our program. It is set in main(), used
1504** in a number of other places, mostly for error messages.
1505*/
1506static char *Argv0;
1507
1508/*
1509** Prompt strings. Initialized in main. Settable with
1510**   .prompt main continue
1511*/
1512#define PROMPT_LEN_MAX 20
1513/* First line prompt.   default: "sqlite> " */
1514static char mainPrompt[PROMPT_LEN_MAX];
1515/* Continuation prompt. default: "   ...> " */
1516static char continuePrompt[PROMPT_LEN_MAX];
1517
1518/* This is variant of the standard-library strncpy() routine with the
1519** one change that the destination string is always zero-terminated, even
1520** if there is no zero-terminator in the first n-1 characters of the source
1521** string.
1522*/
1523static char *shell_strncpy(char *dest, const char *src, size_t n){
1524  size_t i;
1525  for(i=0; i<n-1 && src[i]!=0; i++) dest[i] = src[i];
1526  dest[i] = 0;
1527  return dest;
1528}
1529
1530/*
1531** Optionally disable dynamic continuation prompt.
1532** Unless disabled, the continuation prompt shows open SQL lexemes if any,
1533** or open parentheses level if non-zero, or continuation prompt as set.
1534** This facility interacts with the scanner and process_input() where the
1535** below 5 macros are used.
1536*/
1537#ifdef SQLITE_OMIT_DYNAPROMPT
1538# define CONTINUATION_PROMPT continuePrompt
1539# define CONTINUE_PROMPT_RESET
1540# define CONTINUE_PROMPT_AWAITS(p,s)
1541# define CONTINUE_PROMPT_AWAITC(p,c)
1542# define CONTINUE_PAREN_INCR(p,n)
1543# define CONTINUE_PROMPT_PSTATE 0
1544typedef void *t_NoDynaPrompt;
1545# define SCAN_TRACKER_REFTYPE t_NoDynaPrompt
1546#else
1547# define CONTINUATION_PROMPT dynamicContinuePrompt()
1548# define CONTINUE_PROMPT_RESET \
1549  do {setLexemeOpen(&dynPrompt,0,0); trackParenLevel(&dynPrompt,0);} while(0)
1550# define CONTINUE_PROMPT_AWAITS(p,s) \
1551  if(p && stdin_is_interactive) setLexemeOpen(p, s, 0)
1552# define CONTINUE_PROMPT_AWAITC(p,c) \
1553  if(p && stdin_is_interactive) setLexemeOpen(p, 0, c)
1554# define CONTINUE_PAREN_INCR(p,n) \
1555  if(p && stdin_is_interactive) (trackParenLevel(p,n))
1556# define CONTINUE_PROMPT_PSTATE (&dynPrompt)
1557typedef struct DynaPrompt *t_DynaPromptRef;
1558# define SCAN_TRACKER_REFTYPE t_DynaPromptRef
1559
1560static struct DynaPrompt {
1561  char dynamicPrompt[PROMPT_LEN_MAX];
1562  char acAwait[2];
1563  int inParenLevel;
1564  char *zScannerAwaits;
1565} dynPrompt = { {0}, {0}, 0, 0 };
1566
1567/* Record parenthesis nesting level change, or force level to 0. */
1568static void trackParenLevel(struct DynaPrompt *p, int ni){
1569  p->inParenLevel += ni;
1570  if( ni==0 ) p->inParenLevel = 0;
1571  p->zScannerAwaits = 0;
1572}
1573
1574/* Record that a lexeme is opened, or closed with args==0. */
1575static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){
1576  if( s!=0 || c==0 ){
1577    p->zScannerAwaits = s;
1578    p->acAwait[0] = 0;
1579  }else{
1580    p->acAwait[0] = c;
1581    p->zScannerAwaits = p->acAwait;
1582  }
1583}
1584
1585/* Upon demand, derive the continuation prompt to display. */
1586static char *dynamicContinuePrompt(void){
1587  if( continuePrompt[0]==0
1588      || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){
1589    return continuePrompt;
1590  }else{
1591    if( dynPrompt.zScannerAwaits ){
1592      size_t ncp = strlen(continuePrompt);
1593      size_t ndp = strlen(dynPrompt.zScannerAwaits);
1594      if( ndp > ncp-3 ) return continuePrompt;
1595      strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits);
1596      while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' ';
1597      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1598              PROMPT_LEN_MAX-4);
1599    }else{
1600      if( dynPrompt.inParenLevel>9 ){
1601        shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4);
1602      }else if( dynPrompt.inParenLevel<0 ){
1603        shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4);
1604      }else{
1605        shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4);
1606        dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel);
1607      }
1608      shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3,
1609                    PROMPT_LEN_MAX-4);
1610    }
1611  }
1612  return dynPrompt.dynamicPrompt;
1613}
1614#endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */
1615
1616/* Indicate out-of-memory and exit. */
1617static void shell_out_of_memory(void){
1618  eputz("Error: out of memory\n");
1619  exit(1);
1620}
1621
1622/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
1623** out-of-memory error.
1624*/
1625static void shell_check_oom(const void *p){
1626  if( p==0 ) shell_out_of_memory();
1627}
1628
1629/*
1630** Write I/O traces to the following stream.
1631*/
1632#ifdef SQLITE_ENABLE_IOTRACE
1633static FILE *iotrace = 0;
1634#endif
1635
1636/*
1637** This routine works like printf in that its first argument is a
1638** format string and subsequent arguments are values to be substituted
1639** in place of % fields.  The result of formatting this string
1640** is written to iotrace.
1641*/
1642#ifdef SQLITE_ENABLE_IOTRACE
1643static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
1644  va_list ap;
1645  char *z;
1646  if( iotrace==0 ) return;
1647  va_start(ap, zFormat);
1648  z = sqlite3_vmprintf(zFormat, ap);
1649  va_end(ap);
1650  sputf(iotrace, "%s", z);
1651  sqlite3_free(z);
1652}
1653#endif
1654
1655/*
1656** Output string zUtf to Out stream as w characters.  If w is negative,
1657** then right-justify the text.  W is the width in UTF-8 characters, not
1658** in bytes.  This is different from the %*.*s specification in printf
1659** since with %*.*s the width is measured in bytes, not characters.
1660*/
1661static void utf8_width_print(int w, const char *zUtf){
1662  int i;
1663  int n;
1664  int aw = w<0 ? -w : w;
1665  if( zUtf==0 ) zUtf = "";
1666  for(i=n=0; zUtf[i]; i++){
1667    if( (zUtf[i]&0xc0)!=0x80 ){
1668      n++;
1669      if( n==aw ){
1670        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
1671        break;
1672      }
1673    }
1674  }
1675  if( n>=aw ){
1676    oputf("%.*s", i, zUtf);
1677  }else if( w<0 ){
1678    oputf("%*s%s", aw-n, "", zUtf);
1679  }else{
1680    oputf("%s%*s", zUtf, aw-n, "");
1681  }
1682}
1683
1684
1685/*
1686** Determines if a string is a number of not.
1687*/
1688static int isNumber(const char *z, int *realnum){
1689  if( *z=='-' || *z=='+' ) z++;
1690  if( !IsDigit(*z) ){
1691    return 0;
1692  }
1693  z++;
1694  if( realnum ) *realnum = 0;
1695  while( IsDigit(*z) ){ z++; }
1696  if( *z=='.' ){
1697    z++;
1698    if( !IsDigit(*z) ) return 0;
1699    while( IsDigit(*z) ){ z++; }
1700    if( realnum ) *realnum = 1;
1701  }
1702  if( *z=='e' || *z=='E' ){
1703    z++;
1704    if( *z=='+' || *z=='-' ) z++;
1705    if( !IsDigit(*z) ) return 0;
1706    while( IsDigit(*z) ){ z++; }
1707    if( realnum ) *realnum = 1;
1708  }
1709  return *z==0;
1710}
1711
1712/*
1713** Compute a string length that is limited to what can be stored in
1714** lower 30 bits of a 32-bit signed integer.
1715*/
1716static int strlen30(const char *z){
1717  const char *z2 = z;
1718  while( *z2 ){ z2++; }
1719  return 0x3fffffff & (int)(z2 - z);
1720}
1721
1722/*
1723** Return the length of a string in characters.  Multibyte UTF8 characters
1724** count as a single character.
1725*/
1726static int strlenChar(const char *z){
1727  int n = 0;
1728  while( *z ){
1729    if( (0xc0&*(z++))!=0x80 ) n++;
1730  }
1731  return n;
1732}
1733
1734/*
1735** Return open FILE * if zFile exists, can be opened for read
1736** and is an ordinary file or a character stream source.
1737** Otherwise return 0.
1738*/
1739static FILE * openChrSource(const char *zFile){
1740#if defined(_WIN32) || defined(WIN32)
1741  struct __stat64 x = {0};
1742# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1743  /* On Windows, open first, then check the stream nature. This order
1744  ** is necessary because _stat() and sibs, when checking a named pipe,
1745  ** effectively break the pipe as its supplier sees it. */
1746  FILE *rv = fopen(zFile, "rb");
1747  if( rv==0 ) return 0;
1748  if( _fstat64(_fileno(rv), &x) != 0
1749      || !STAT_CHR_SRC(x.st_mode)){
1750    fclose(rv);
1751    rv = 0;
1752  }
1753  return rv;
1754#else
1755  struct stat x = {0};
1756  int rc = stat(zFile, &x);
1757# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
1758  if( rc!=0 ) return 0;
1759  if( STAT_CHR_SRC(x.st_mode) ){
1760    return fopen(zFile, "rb");
1761  }else{
1762    return 0;
1763  }
1764#endif
1765#undef STAT_CHR_SRC
1766}
1767
1768/*
1769** This routine reads a line of text from FILE in, stores
1770** the text in memory obtained from malloc() and returns a pointer
1771** to the text.  NULL is returned at end of file, or if malloc()
1772** fails.
1773**
1774** If zLine is not NULL then it is a malloced buffer returned from
1775** a previous call to this routine that may be reused.
1776*/
1777static char *local_getline(char *zLine, FILE *in){
1778  int nLine = zLine==0 ? 0 : 100;
1779  int n = 0;
1780
1781  while( 1 ){
1782    if( n+100>nLine ){
1783      nLine = nLine*2 + 100;
1784      zLine = realloc(zLine, nLine);
1785      shell_check_oom(zLine);
1786    }
1787    if( fgets(&zLine[n], nLine - n, in)==0 ){
1788      if( n==0 ){
1789        free(zLine);
1790        return 0;
1791      }
1792      zLine[n] = 0;
1793      break;
1794    }
1795    while( zLine[n] ) n++;
1796    if( n>0 && zLine[n-1]=='\n' ){
1797      n--;
1798      if( n>0 && zLine[n-1]=='\r' ) n--;
1799      zLine[n] = 0;
1800      break;
1801    }
1802  }
1803  return zLine;
1804}
1805
1806/*
1807** Retrieve a single line of input text.
1808**
1809** If in==0 then read from standard input and prompt before each line.
1810** If isContinuation is true, then a continuation prompt is appropriate.
1811** If isContinuation is zero, then the main prompt should be used.
1812**
1813** If zPrior is not NULL then it is a buffer from a prior call to this
1814** routine that can be reused.
1815**
1816** The result is stored in space obtained from malloc() and must either
1817** be freed by the caller or else passed back into this routine via the
1818** zPrior argument for reuse.
1819*/
1820#ifndef SQLITE_SHELL_FIDDLE
1821static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
1822  char *zPrompt;
1823  char *zResult;
1824  if( in!=0 ){
1825    zResult = local_getline(zPrior, in);
1826  }else{
1827    zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt;
1828#if SHELL_USE_LOCAL_GETLINE
1829    sputz(stdout, zPrompt);
1830    fflush(stdout);
1831    do{
1832      zResult = local_getline(zPrior, stdin);
1833      zPrior = 0;
1834      /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1835      if( zResult==0 ) sqlite3_sleep(50);
1836    }while( zResult==0 && seenInterrupt>0 );
1837#else
1838    free(zPrior);
1839    zResult = shell_readline(zPrompt);
1840    while( zResult==0 ){
1841      /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
1842      sqlite3_sleep(50);
1843      if( seenInterrupt==0 ) break;
1844      zResult = shell_readline("");
1845    }
1846    if( zResult && *zResult ) shell_add_history(zResult);
1847#endif
1848  }
1849  return zResult;
1850}
1851#endif /* !SQLITE_SHELL_FIDDLE */
1852
1853/*
1854** Return the value of a hexadecimal digit.  Return -1 if the input
1855** is not a hex digit.
1856*/
1857static int hexDigitValue(char c){
1858  if( c>='0' && c<='9' ) return c - '0';
1859  if( c>='a' && c<='f' ) return c - 'a' + 10;
1860  if( c>='A' && c<='F' ) return c - 'A' + 10;
1861  return -1;
1862}
1863
1864/*
1865** Interpret zArg as an integer value, possibly with suffixes.
1866*/
1867static sqlite3_int64 integerValue(const char *zArg){
1868  sqlite3_int64 v = 0;
1869  static const struct { char *zSuffix; int iMult; } aMult[] = {
1870    { "KiB", 1024 },
1871    { "MiB", 1024*1024 },
1872    { "GiB", 1024*1024*1024 },
1873    { "KB",  1000 },
1874    { "MB",  1000000 },
1875    { "GB",  1000000000 },
1876    { "K",   1000 },
1877    { "M",   1000000 },
1878    { "G",   1000000000 },
1879  };
1880  int i;
1881  int isNeg = 0;
1882  if( zArg[0]=='-' ){
1883    isNeg = 1;
1884    zArg++;
1885  }else if( zArg[0]=='+' ){
1886    zArg++;
1887  }
1888  if( zArg[0]=='0' && zArg[1]=='x' ){
1889    int x;
1890    zArg += 2;
1891    while( (x = hexDigitValue(zArg[0]))>=0 ){
1892      v = (v<<4) + x;
1893      zArg++;
1894    }
1895  }else{
1896    while( IsDigit(zArg[0]) ){
1897      v = v*10 + zArg[0] - '0';
1898      zArg++;
1899    }
1900  }
1901  for(i=0; i<ArraySize(aMult); i++){
1902    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1903      v *= aMult[i].iMult;
1904      break;
1905    }
1906  }
1907  return isNeg? -v : v;
1908}
1909
1910/*
1911** A variable length string to which one can append text.
1912*/
1913typedef struct ShellText ShellText;
1914struct ShellText {
1915  char *z;
1916  int n;
1917  int nAlloc;
1918};
1919
1920/*
1921** Initialize and destroy a ShellText object
1922*/
1923static void initText(ShellText *p){
1924  memset(p, 0, sizeof(*p));
1925}
1926static void freeText(ShellText *p){
1927  free(p->z);
1928  initText(p);
1929}
1930
1931/* zIn is either a pointer to a NULL-terminated string in memory obtained
1932** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1933** added to zIn, and the result returned in memory obtained from malloc().
1934** zIn, if it was not NULL, is freed.
1935**
1936** If the third argument, quote, is not '\0', then it is used as a
1937** quote character for zAppend.
1938*/
1939static void appendText(ShellText *p, const char *zAppend, char quote){
1940  i64 len;
1941  i64 i;
1942  i64 nAppend = strlen30(zAppend);
1943
1944  len = nAppend+p->n+1;
1945  if( quote ){
1946    len += 2;
1947    for(i=0; i<nAppend; i++){
1948      if( zAppend[i]==quote ) len++;
1949    }
1950  }
1951
1952  if( p->z==0 || p->n+len>=p->nAlloc ){
1953    p->nAlloc = p->nAlloc*2 + len + 20;
1954    p->z = realloc(p->z, p->nAlloc);
1955    shell_check_oom(p->z);
1956  }
1957
1958  if( quote ){
1959    char *zCsr = p->z+p->n;
1960    *zCsr++ = quote;
1961    for(i=0; i<nAppend; i++){
1962      *zCsr++ = zAppend[i];
1963      if( zAppend[i]==quote ) *zCsr++ = quote;
1964    }
1965    *zCsr++ = quote;
1966    p->n = (int)(zCsr - p->z);
1967    *zCsr = '\0';
1968  }else{
1969    memcpy(p->z+p->n, zAppend, nAppend);
1970    p->n += nAppend;
1971    p->z[p->n] = '\0';
1972  }
1973}
1974
1975/*
1976** Attempt to determine if identifier zName needs to be quoted, either
1977** because it contains non-alphanumeric characters, or because it is an
1978** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
1979** that quoting is required.
1980**
1981** Return '"' if quoting is required.  Return 0 if no quoting is required.
1982*/
1983static char quoteChar(const char *zName){
1984  int i;
1985  if( zName==0 ) return '"';
1986  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
1987  for(i=0; zName[i]; i++){
1988    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
1989  }
1990  return sqlite3_keyword_check(zName, i) ? '"' : 0;
1991}
1992
1993/*
1994** Construct a fake object name and column list to describe the structure
1995** of the view, virtual table, or table valued function zSchema.zName.
1996*/
1997static char *shellFakeSchema(
1998  sqlite3 *db,            /* The database connection containing the vtab */
1999  const char *zSchema,    /* Schema of the database holding the vtab */
2000  const char *zName       /* The name of the virtual table */
2001){
2002  sqlite3_stmt *pStmt = 0;
2003  char *zSql;
2004  ShellText s;
2005  char cQuote;
2006  char *zDiv = "(";
2007  int nRow = 0;
2008
2009  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
2010                         zSchema ? zSchema : "main", zName);
2011  shell_check_oom(zSql);
2012  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
2013  sqlite3_free(zSql);
2014  initText(&s);
2015  if( zSchema ){
2016    cQuote = quoteChar(zSchema);
2017    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
2018    appendText(&s, zSchema, cQuote);
2019    appendText(&s, ".", 0);
2020  }
2021  cQuote = quoteChar(zName);
2022  appendText(&s, zName, cQuote);
2023  while( sqlite3_step(pStmt)==SQLITE_ROW ){
2024    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
2025    nRow++;
2026    appendText(&s, zDiv, 0);
2027    zDiv = ",";
2028    if( zCol==0 ) zCol = "";
2029    cQuote = quoteChar(zCol);
2030    appendText(&s, zCol, cQuote);
2031  }
2032  appendText(&s, ")", 0);
2033  sqlite3_finalize(pStmt);
2034  if( nRow==0 ){
2035    freeText(&s);
2036    s.z = 0;
2037  }
2038  return s.z;
2039}
2040
2041/*
2042** SQL function:  strtod(X)
2043**
2044** Use the C-library strtod() function to convert string X into a double.
2045** Used for comparing the accuracy of SQLite's internal text-to-float conversion
2046** routines against the C-library.
2047*/
2048static void shellStrtod(
2049  sqlite3_context *pCtx,
2050  int nVal,
2051  sqlite3_value **apVal
2052){
2053  char *z = (char*)sqlite3_value_text(apVal[0]);
2054  UNUSED_PARAMETER(nVal);
2055  if( z==0 ) return;
2056  sqlite3_result_double(pCtx, strtod(z,0));
2057}
2058
2059/*
2060** SQL function:  dtostr(X)
2061**
2062** Use the C-library printf() function to convert real value X into a string.
2063** Used for comparing the accuracy of SQLite's internal float-to-text conversion
2064** routines against the C-library.
2065*/
2066static void shellDtostr(
2067  sqlite3_context *pCtx,
2068  int nVal,
2069  sqlite3_value **apVal
2070){
2071  double r = sqlite3_value_double(apVal[0]);
2072  int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26;
2073  char z[400];
2074  if( n<1 ) n = 1;
2075  if( n>350 ) n = 350;
2076  sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r);
2077  sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
2078}
2079
2080
2081/*
2082** SQL function:  shell_module_schema(X)
2083**
2084** Return a fake schema for the table-valued function or eponymous virtual
2085** table X.
2086*/
2087static void shellModuleSchema(
2088  sqlite3_context *pCtx,
2089  int nVal,
2090  sqlite3_value **apVal
2091){
2092  const char *zName;
2093  char *zFake;
2094  UNUSED_PARAMETER(nVal);
2095  zName = (const char*)sqlite3_value_text(apVal[0]);
2096  zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
2097  if( zFake ){
2098    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
2099                        -1, sqlite3_free);
2100    free(zFake);
2101  }
2102}
2103
2104/*
2105** SQL function:  shell_add_schema(S,X)
2106**
2107** Add the schema name X to the CREATE statement in S and return the result.
2108** Examples:
2109**
2110**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
2111**
2112** Also works on
2113**
2114**    CREATE INDEX
2115**    CREATE UNIQUE INDEX
2116**    CREATE VIEW
2117**    CREATE TRIGGER
2118**    CREATE VIRTUAL TABLE
2119**
2120** This UDF is used by the .schema command to insert the schema name of
2121** attached databases into the middle of the sqlite_schema.sql field.
2122*/
2123static void shellAddSchemaName(
2124  sqlite3_context *pCtx,
2125  int nVal,
2126  sqlite3_value **apVal
2127){
2128  static const char *aPrefix[] = {
2129     "TABLE",
2130     "INDEX",
2131     "UNIQUE INDEX",
2132     "VIEW",
2133     "TRIGGER",
2134     "VIRTUAL TABLE"
2135  };
2136  int i = 0;
2137  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
2138  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
2139  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
2140  sqlite3 *db = sqlite3_context_db_handle(pCtx);
2141  UNUSED_PARAMETER(nVal);
2142  if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
2143    for(i=0; i<ArraySize(aPrefix); i++){
2144      int n = strlen30(aPrefix[i]);
2145      if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
2146        char *z = 0;
2147        char *zFake = 0;
2148        if( zSchema ){
2149          char cQuote = quoteChar(zSchema);
2150          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
2151            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
2152          }else{
2153            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
2154          }
2155        }
2156        if( zName
2157         && aPrefix[i][0]=='V'
2158         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
2159        ){
2160          if( z==0 ){
2161            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
2162          }else{
2163            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
2164          }
2165          free(zFake);
2166        }
2167        if( z ){
2168          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
2169          return;
2170        }
2171      }
2172    }
2173  }
2174  sqlite3_result_value(pCtx, apVal[0]);
2175}
2176
2177/*
2178** The source code for several run-time loadable extensions is inserted
2179** below by the ../tool/mkshellc.tcl script.  Before processing that included
2180** code, we need to override some macros to make the included program code
2181** work here in the middle of this regular program.
2182*/
2183#define SQLITE_EXTENSION_INIT1
2184#define SQLITE_EXTENSION_INIT2(X) (void)(X)
2185
2186#if defined(_WIN32) && defined(_MSC_VER)
2187/************************* Begin test_windirent.h ******************/
2188/*
2189** 2015 November 30
2190**
2191** The author disclaims copyright to this source code.  In place of
2192** a legal notice, here is a blessing:
2193**
2194**    May you do good and not evil.
2195**    May you find forgiveness for yourself and forgive others.
2196**    May you share freely, never taking more than you give.
2197**
2198*************************************************************************
2199** This file contains declarations for most of the opendir() family of
2200** POSIX functions on Win32 using the MSVCRT.
2201*/
2202
2203#if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
2204#define SQLITE_WINDIRENT_H
2205
2206/*
2207** We need several data types from the Windows SDK header.
2208*/
2209
2210#ifndef WIN32_LEAN_AND_MEAN
2211#define WIN32_LEAN_AND_MEAN
2212#endif
2213
2214#include "windows.h"
2215
2216/*
2217** We need several support functions from the SQLite core.
2218*/
2219
2220/* #include "sqlite3.h" */
2221
2222/*
2223** We need several things from the ANSI and MSVCRT headers.
2224*/
2225
2226#include <stdio.h>
2227#include <stdlib.h>
2228#include <errno.h>
2229#include <io.h>
2230#include <limits.h>
2231#include <sys/types.h>
2232#include <sys/stat.h>
2233
2234/*
2235** We may need several defines that should have been in "sys/stat.h".
2236*/
2237
2238#ifndef S_ISREG
2239#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
2240#endif
2241
2242#ifndef S_ISDIR
2243#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
2244#endif
2245
2246#ifndef S_ISLNK
2247#define S_ISLNK(mode) (0)
2248#endif
2249
2250/*
2251** We may need to provide the "mode_t" type.
2252*/
2253
2254#ifndef MODE_T_DEFINED
2255  #define MODE_T_DEFINED
2256  typedef unsigned short mode_t;
2257#endif
2258
2259/*
2260** We may need to provide the "ino_t" type.
2261*/
2262
2263#ifndef INO_T_DEFINED
2264  #define INO_T_DEFINED
2265  typedef unsigned short ino_t;
2266#endif
2267
2268/*
2269** We need to define "NAME_MAX" if it was not present in "limits.h".
2270*/
2271
2272#ifndef NAME_MAX
2273#  ifdef FILENAME_MAX
2274#    define NAME_MAX (FILENAME_MAX)
2275#  else
2276#    define NAME_MAX (260)
2277#  endif
2278#endif
2279
2280/*
2281** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
2282*/
2283
2284#ifndef NULL_INTPTR_T
2285#  define NULL_INTPTR_T ((intptr_t)(0))
2286#endif
2287
2288#ifndef BAD_INTPTR_T
2289#  define BAD_INTPTR_T ((intptr_t)(-1))
2290#endif
2291
2292/*
2293** We need to provide the necessary structures and related types.
2294*/
2295
2296#ifndef DIRENT_DEFINED
2297#define DIRENT_DEFINED
2298typedef struct DIRENT DIRENT;
2299typedef DIRENT *LPDIRENT;
2300struct DIRENT {
2301  ino_t d_ino;               /* Sequence number, do not use. */
2302  unsigned d_attributes;     /* Win32 file attributes. */
2303  char d_name[NAME_MAX + 1]; /* Name within the directory. */
2304};
2305#endif
2306
2307#ifndef DIR_DEFINED
2308#define DIR_DEFINED
2309typedef struct DIR DIR;
2310typedef DIR *LPDIR;
2311struct DIR {
2312  intptr_t d_handle; /* Value returned by "_findfirst". */
2313  DIRENT d_first;    /* DIRENT constructed based on "_findfirst". */
2314  DIRENT d_next;     /* DIRENT constructed based on "_findnext". */
2315};
2316#endif
2317
2318/*
2319** Provide a macro, for use by the implementation, to determine if a
2320** particular directory entry should be skipped over when searching for
2321** the next directory entry that should be returned by the readdir() or
2322** readdir_r() functions.
2323*/
2324
2325#ifndef is_filtered
2326#  define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
2327#endif
2328
2329/*
2330** Provide the function prototype for the POSIX compatible getenv()
2331** function.  This function is not thread-safe.
2332*/
2333
2334extern const char *windirent_getenv(const char *name);
2335
2336/*
2337** Finally, we can provide the function prototypes for the opendir(),
2338** readdir(), readdir_r(), and closedir() POSIX functions.
2339*/
2340
2341extern LPDIR opendir(const char *dirname);
2342extern LPDIRENT readdir(LPDIR dirp);
2343extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
2344extern INT closedir(LPDIR dirp);
2345
2346#endif /* defined(WIN32) && defined(_MSC_VER) */
2347
2348/************************* End test_windirent.h ********************/
2349/************************* Begin test_windirent.c ******************/
2350/*
2351** 2015 November 30
2352**
2353** The author disclaims copyright to this source code.  In place of
2354** a legal notice, here is a blessing:
2355**
2356**    May you do good and not evil.
2357**    May you find forgiveness for yourself and forgive others.
2358**    May you share freely, never taking more than you give.
2359**
2360*************************************************************************
2361** This file contains code to implement most of the opendir() family of
2362** POSIX functions on Win32 using the MSVCRT.
2363*/
2364
2365#if defined(_WIN32) && defined(_MSC_VER)
2366/* #include "test_windirent.h" */
2367
2368/*
2369** Implementation of the POSIX getenv() function using the Win32 API.
2370** This function is not thread-safe.
2371*/
2372const char *windirent_getenv(
2373  const char *name
2374){
2375  static char value[32768]; /* Maximum length, per MSDN */
2376  DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
2377  DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
2378
2379  memset(value, 0, sizeof(value));
2380  dwRet = GetEnvironmentVariableA(name, value, dwSize);
2381  if( dwRet==0 || dwRet>dwSize ){
2382    /*
2383    ** The function call to GetEnvironmentVariableA() failed -OR-
2384    ** the buffer is not large enough.  Either way, return NULL.
2385    */
2386    return 0;
2387  }else{
2388    /*
2389    ** The function call to GetEnvironmentVariableA() succeeded
2390    ** -AND- the buffer contains the entire value.
2391    */
2392    return value;
2393  }
2394}
2395
2396/*
2397** Implementation of the POSIX opendir() function using the MSVCRT.
2398*/
2399LPDIR opendir(
2400  const char *dirname
2401){
2402  struct _finddata_t data;
2403  LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
2404  SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
2405
2406  if( dirp==NULL ) return NULL;
2407  memset(dirp, 0, sizeof(DIR));
2408
2409  /* TODO: Remove this if Unix-style root paths are not used. */
2410  if( sqlite3_stricmp(dirname, "/")==0 ){
2411    dirname = windirent_getenv("SystemDrive");
2412  }
2413
2414  memset(&data, 0, sizeof(struct _finddata_t));
2415  _snprintf(data.name, namesize, "%s\\*", dirname);
2416  dirp->d_handle = _findfirst(data.name, &data);
2417
2418  if( dirp->d_handle==BAD_INTPTR_T ){
2419    closedir(dirp);
2420    return NULL;
2421  }
2422
2423  /* TODO: Remove this block to allow hidden and/or system files. */
2424  if( is_filtered(data) ){
2425next:
2426
2427    memset(&data, 0, sizeof(struct _finddata_t));
2428    if( _findnext(dirp->d_handle, &data)==-1 ){
2429      closedir(dirp);
2430      return NULL;
2431    }
2432
2433    /* TODO: Remove this block to allow hidden and/or system files. */
2434    if( is_filtered(data) ) goto next;
2435  }
2436
2437  dirp->d_first.d_attributes = data.attrib;
2438  strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
2439  dirp->d_first.d_name[NAME_MAX] = '\0';
2440
2441  return dirp;
2442}
2443
2444/*
2445** Implementation of the POSIX readdir() function using the MSVCRT.
2446*/
2447LPDIRENT readdir(
2448  LPDIR dirp
2449){
2450  struct _finddata_t data;
2451
2452  if( dirp==NULL ) return NULL;
2453
2454  if( dirp->d_first.d_ino==0 ){
2455    dirp->d_first.d_ino++;
2456    dirp->d_next.d_ino++;
2457
2458    return &dirp->d_first;
2459  }
2460
2461next:
2462
2463  memset(&data, 0, sizeof(struct _finddata_t));
2464  if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
2465
2466  /* TODO: Remove this block to allow hidden and/or system files. */
2467  if( is_filtered(data) ) goto next;
2468
2469  dirp->d_next.d_ino++;
2470  dirp->d_next.d_attributes = data.attrib;
2471  strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
2472  dirp->d_next.d_name[NAME_MAX] = '\0';
2473
2474  return &dirp->d_next;
2475}
2476
2477/*
2478** Implementation of the POSIX readdir_r() function using the MSVCRT.
2479*/
2480INT readdir_r(
2481  LPDIR dirp,
2482  LPDIRENT entry,
2483  LPDIRENT *result
2484){
2485  struct _finddata_t data;
2486
2487  if( dirp==NULL ) return EBADF;
2488
2489  if( dirp->d_first.d_ino==0 ){
2490    dirp->d_first.d_ino++;
2491    dirp->d_next.d_ino++;
2492
2493    entry->d_ino = dirp->d_first.d_ino;
2494    entry->d_attributes = dirp->d_first.d_attributes;
2495    strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
2496    entry->d_name[NAME_MAX] = '\0';
2497
2498    *result = entry;
2499    return 0;
2500  }
2501
2502next:
2503
2504  memset(&data, 0, sizeof(struct _finddata_t));
2505  if( _findnext(dirp->d_handle, &data)==-1 ){
2506    *result = NULL;
2507    return ENOENT;
2508  }
2509
2510  /* TODO: Remove this block to allow hidden and/or system files. */
2511  if( is_filtered(data) ) goto next;
2512
2513  entry->d_ino = (ino_t)-1; /* not available */
2514  entry->d_attributes = data.attrib;
2515  strncpy(entry->d_name, data.name, NAME_MAX);
2516  entry->d_name[NAME_MAX] = '\0';
2517
2518  *result = entry;
2519  return 0;
2520}
2521
2522/*
2523** Implementation of the POSIX closedir() function using the MSVCRT.
2524*/
2525INT closedir(
2526  LPDIR dirp
2527){
2528  INT result = 0;
2529
2530  if( dirp==NULL ) return EINVAL;
2531
2532  if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
2533    result = _findclose(dirp->d_handle);
2534  }
2535
2536  sqlite3_free(dirp);
2537  return result;
2538}
2539
2540#endif /* defined(WIN32) && defined(_MSC_VER) */
2541
2542/************************* End test_windirent.c ********************/
2543#define dirent DIRENT
2544#endif
2545/************************* Begin ../ext/misc/memtrace.c ******************/
2546/*
2547** 2019-01-21
2548**
2549** The author disclaims copyright to this source code.  In place of
2550** a legal notice, here is a blessing:
2551**
2552**    May you do good and not evil.
2553**    May you find forgiveness for yourself and forgive others.
2554**    May you share freely, never taking more than you give.
2555**
2556*************************************************************************
2557**
2558** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
2559** mechanism to add a tracing layer on top of SQLite.  If this extension
2560** is registered prior to sqlite3_initialize(), it will cause all memory
2561** allocation activities to be logged on standard output, or to some other
2562** FILE specified by the initializer.
2563**
2564** This file needs to be compiled into the application that uses it.
2565**
2566** This extension is used to implement the --memtrace option of the
2567** command-line shell.
2568*/
2569#include <assert.h>
2570#include <string.h>
2571#include <stdio.h>
2572
2573/* The original memory allocation routines */
2574static sqlite3_mem_methods memtraceBase;
2575static FILE *memtraceOut;
2576
2577/* Methods that trace memory allocations */
2578static void *memtraceMalloc(int n){
2579  if( memtraceOut ){
2580    fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n",
2581            memtraceBase.xRoundup(n));
2582  }
2583  return memtraceBase.xMalloc(n);
2584}
2585static void memtraceFree(void *p){
2586  if( p==0 ) return;
2587  if( memtraceOut ){
2588    fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
2589  }
2590  memtraceBase.xFree(p);
2591}
2592static void *memtraceRealloc(void *p, int n){
2593  if( p==0 ) return memtraceMalloc(n);
2594  if( n==0 ){
2595    memtraceFree(p);
2596    return 0;
2597  }
2598  if( memtraceOut ){
2599    fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
2600            memtraceBase.xSize(p), memtraceBase.xRoundup(n));
2601  }
2602  return memtraceBase.xRealloc(p, n);
2603}
2604static int memtraceSize(void *p){
2605  return memtraceBase.xSize(p);
2606}
2607static int memtraceRoundup(int n){
2608  return memtraceBase.xRoundup(n);
2609}
2610static int memtraceInit(void *p){
2611  return memtraceBase.xInit(p);
2612}
2613static void memtraceShutdown(void *p){
2614  memtraceBase.xShutdown(p);
2615}
2616
2617/* The substitute memory allocator */
2618static sqlite3_mem_methods ersaztMethods = {
2619  memtraceMalloc,
2620  memtraceFree,
2621  memtraceRealloc,
2622  memtraceSize,
2623  memtraceRoundup,
2624  memtraceInit,
2625  memtraceShutdown,
2626  0
2627};
2628
2629/* Begin tracing memory allocations to out. */
2630int sqlite3MemTraceActivate(FILE *out){
2631  int rc = SQLITE_OK;
2632  if( memtraceBase.xMalloc==0 ){
2633    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
2634    if( rc==SQLITE_OK ){
2635      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
2636    }
2637  }
2638  memtraceOut = out;
2639  return rc;
2640}
2641
2642/* Deactivate memory tracing */
2643int sqlite3MemTraceDeactivate(void){
2644  int rc = SQLITE_OK;
2645  if( memtraceBase.xMalloc!=0 ){
2646    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
2647    if( rc==SQLITE_OK ){
2648      memset(&memtraceBase, 0, sizeof(memtraceBase));
2649    }
2650  }
2651  memtraceOut = 0;
2652  return rc;
2653}
2654
2655/************************* End ../ext/misc/memtrace.c ********************/
2656/************************* Begin ../ext/misc/pcachetrace.c ******************/
2657/*
2658** 2023-06-21
2659**
2660** The author disclaims copyright to this source code.  In place of
2661** a legal notice, here is a blessing:
2662**
2663**    May you do good and not evil.
2664**    May you find forgiveness for yourself and forgive others.
2665**    May you share freely, never taking more than you give.
2666**
2667*************************************************************************
2668**
2669** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2
2670** mechanism to add a tracing layer on top of pluggable page cache of
2671** SQLite.  If this extension is registered prior to sqlite3_initialize(),
2672** it will cause all page cache activities to be logged on standard output,
2673** or to some other FILE specified by the initializer.
2674**
2675** This file needs to be compiled into the application that uses it.
2676**
2677** This extension is used to implement the --pcachetrace option of the
2678** command-line shell.
2679*/
2680#include <assert.h>
2681#include <string.h>
2682#include <stdio.h>
2683
2684/* The original page cache routines */
2685static sqlite3_pcache_methods2 pcacheBase;
2686static FILE *pcachetraceOut;
2687
2688/* Methods that trace pcache activity */
2689static int pcachetraceInit(void *pArg){
2690  int nRes;
2691  if( pcachetraceOut ){
2692    fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg);
2693  }
2694  nRes = pcacheBase.xInit(pArg);
2695  if( pcachetraceOut ){
2696    fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes);
2697  }
2698  return nRes;
2699}
2700static void pcachetraceShutdown(void *pArg){
2701  if( pcachetraceOut ){
2702    fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg);
2703  }
2704  pcacheBase.xShutdown(pArg);
2705}
2706static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){
2707  sqlite3_pcache *pRes;
2708  if( pcachetraceOut ){
2709    fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n",
2710            szPage, szExtra, bPurge);
2711  }
2712  pRes = pcacheBase.xCreate(szPage, szExtra, bPurge);
2713  if( pcachetraceOut ){
2714    fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n",
2715            szPage, szExtra, bPurge, pRes);
2716  }
2717  return pRes;
2718}
2719static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){
2720  if( pcachetraceOut ){
2721    fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize);
2722  }
2723  pcacheBase.xCachesize(p, nCachesize);
2724}
2725static int pcachetracePagecount(sqlite3_pcache *p){
2726  int nRes;
2727  if( pcachetraceOut ){
2728    fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p);
2729  }
2730  nRes = pcacheBase.xPagecount(p);
2731  if( pcachetraceOut ){
2732    fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes);
2733  }
2734  return nRes;
2735}
2736static sqlite3_pcache_page *pcachetraceFetch(
2737  sqlite3_pcache *p,
2738  unsigned key,
2739  int crFg
2740){
2741  sqlite3_pcache_page *pRes;
2742  if( pcachetraceOut ){
2743    fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg);
2744  }
2745  pRes = pcacheBase.xFetch(p, key, crFg);
2746  if( pcachetraceOut ){
2747    fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n",
2748            p, key, crFg, pRes);
2749  }
2750  return pRes;
2751}
2752static void pcachetraceUnpin(
2753  sqlite3_pcache *p,
2754  sqlite3_pcache_page *pPg,
2755  int bDiscard
2756){
2757  if( pcachetraceOut ){
2758    fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n",
2759            p, pPg, bDiscard);
2760  }
2761  pcacheBase.xUnpin(p, pPg, bDiscard);
2762}
2763static void pcachetraceRekey(
2764  sqlite3_pcache *p,
2765  sqlite3_pcache_page *pPg,
2766  unsigned oldKey,
2767  unsigned newKey
2768){
2769  if( pcachetraceOut ){
2770    fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n",
2771        p, pPg, oldKey, newKey);
2772  }
2773  pcacheBase.xRekey(p, pPg, oldKey, newKey);
2774}
2775static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){
2776  if( pcachetraceOut ){
2777    fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n);
2778  }
2779  pcacheBase.xTruncate(p, n);
2780}
2781static void pcachetraceDestroy(sqlite3_pcache *p){
2782  if( pcachetraceOut ){
2783    fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p);
2784  }
2785  pcacheBase.xDestroy(p);
2786}
2787static void pcachetraceShrink(sqlite3_pcache *p){
2788  if( pcachetraceOut ){
2789    fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p);
2790  }
2791  pcacheBase.xShrink(p);
2792}
2793
2794/* The substitute pcache methods */
2795static sqlite3_pcache_methods2 ersaztPcacheMethods = {
2796  0,
2797  0,
2798  pcachetraceInit,
2799  pcachetraceShutdown,
2800  pcachetraceCreate,
2801  pcachetraceCachesize,
2802  pcachetracePagecount,
2803  pcachetraceFetch,
2804  pcachetraceUnpin,
2805  pcachetraceRekey,
2806  pcachetraceTruncate,
2807  pcachetraceDestroy,
2808  pcachetraceShrink
2809};
2810
2811/* Begin tracing memory allocations to out. */
2812int sqlite3PcacheTraceActivate(FILE *out){
2813  int rc = SQLITE_OK;
2814  if( pcacheBase.xFetch==0 ){
2815    rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase);
2816    if( rc==SQLITE_OK ){
2817      rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods);
2818    }
2819  }
2820  pcachetraceOut = out;
2821  return rc;
2822}
2823
2824/* Deactivate memory tracing */
2825int sqlite3PcacheTraceDeactivate(void){
2826  int rc = SQLITE_OK;
2827  if( pcacheBase.xFetch!=0 ){
2828    rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase);
2829    if( rc==SQLITE_OK ){
2830      memset(&pcacheBase, 0, sizeof(pcacheBase));
2831    }
2832  }
2833  pcachetraceOut = 0;
2834  return rc;
2835}
2836
2837/************************* End ../ext/misc/pcachetrace.c ********************/
2838/************************* Begin ../ext/misc/shathree.c ******************/
2839/*
2840** 2017-03-08
2841**
2842** The author disclaims copyright to this source code.  In place of
2843** a legal notice, here is a blessing:
2844**
2845**    May you do good and not evil.
2846**    May you find forgiveness for yourself and forgive others.
2847**    May you share freely, never taking more than you give.
2848**
2849******************************************************************************
2850**
2851** This SQLite extension implements functions that compute SHA3 hashes
2852** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard.
2853** Two SQL functions are implemented:
2854**
2855**     sha3(X,SIZE)
2856**     sha3_query(Y,SIZE)
2857**
2858** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
2859** X is NULL.
2860**
2861** The sha3_query(Y) function evaluates all queries in the SQL statements of Y
2862** and returns a hash of their results.
2863**
2864** The SIZE argument is optional.  If omitted, the SHA3-256 hash algorithm
2865** is used.  If SIZE is included it must be one of the integers 224, 256,
2866** 384, or 512, to determine SHA3 hash variant that is computed.
2867*/
2868/* #include "sqlite3ext.h" */
2869SQLITE_EXTENSION_INIT1
2870#include <assert.h>
2871#include <string.h>
2872#include <stdarg.h>
2873
2874#ifndef SQLITE_AMALGAMATION
2875/* typedef sqlite3_uint64 u64; */
2876#endif /* SQLITE_AMALGAMATION */
2877
2878/******************************************************************************
2879** The Hash Engine
2880*/
2881/*
2882** Macros to determine whether the machine is big or little endian,
2883** and whether or not that determination is run-time or compile-time.
2884**
2885** For best performance, an attempt is made to guess at the byte-order
2886** using C-preprocessor macros.  If that is unsuccessful, or if
2887** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
2888** at run-time.
2889*/
2890#ifndef SHA3_BYTEORDER
2891# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
2892     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
2893     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
2894     defined(__arm__)
2895#   define SHA3_BYTEORDER    1234
2896# elif defined(sparc)    || defined(__ppc__)
2897#   define SHA3_BYTEORDER    4321
2898# else
2899#   define SHA3_BYTEORDER 0
2900# endif
2901#endif
2902
2903
2904/*
2905** State structure for a SHA3 hash in progress
2906*/
2907typedef struct SHA3Context SHA3Context;
2908struct SHA3Context {
2909  union {
2910    u64 s[25];                /* Keccak state. 5x5 lines of 64 bits each */
2911    unsigned char x[1600];    /* ... or 1600 bytes */
2912  } u;
2913  unsigned nRate;        /* Bytes of input accepted per Keccak iteration */
2914  unsigned nLoaded;      /* Input bytes loaded into u.x[] so far this cycle */
2915  unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
2916};
2917
2918/*
2919** A single step of the Keccak mixing function for a 1600-bit state
2920*/
2921static void KeccakF1600Step(SHA3Context *p){
2922  int i;
2923  u64 b0, b1, b2, b3, b4;
2924  u64 c0, c1, c2, c3, c4;
2925  u64 d0, d1, d2, d3, d4;
2926  static const u64 RC[] = {
2927    0x0000000000000001ULL,  0x0000000000008082ULL,
2928    0x800000000000808aULL,  0x8000000080008000ULL,
2929    0x000000000000808bULL,  0x0000000080000001ULL,
2930    0x8000000080008081ULL,  0x8000000000008009ULL,
2931    0x000000000000008aULL,  0x0000000000000088ULL,
2932    0x0000000080008009ULL,  0x000000008000000aULL,
2933    0x000000008000808bULL,  0x800000000000008bULL,
2934    0x8000000000008089ULL,  0x8000000000008003ULL,
2935    0x8000000000008002ULL,  0x8000000000000080ULL,
2936    0x000000000000800aULL,  0x800000008000000aULL,
2937    0x8000000080008081ULL,  0x8000000000008080ULL,
2938    0x0000000080000001ULL,  0x8000000080008008ULL
2939  };
2940# define a00 (p->u.s[0])
2941# define a01 (p->u.s[1])
2942# define a02 (p->u.s[2])
2943# define a03 (p->u.s[3])
2944# define a04 (p->u.s[4])
2945# define a10 (p->u.s[5])
2946# define a11 (p->u.s[6])
2947# define a12 (p->u.s[7])
2948# define a13 (p->u.s[8])
2949# define a14 (p->u.s[9])
2950# define a20 (p->u.s[10])
2951# define a21 (p->u.s[11])
2952# define a22 (p->u.s[12])
2953# define a23 (p->u.s[13])
2954# define a24 (p->u.s[14])
2955# define a30 (p->u.s[15])
2956# define a31 (p->u.s[16])
2957# define a32 (p->u.s[17])
2958# define a33 (p->u.s[18])
2959# define a34 (p->u.s[19])
2960# define a40 (p->u.s[20])
2961# define a41 (p->u.s[21])
2962# define a42 (p->u.s[22])
2963# define a43 (p->u.s[23])
2964# define a44 (p->u.s[24])
2965# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
2966
2967  for(i=0; i<24; i+=4){
2968    c0 = a00^a10^a20^a30^a40;
2969    c1 = a01^a11^a21^a31^a41;
2970    c2 = a02^a12^a22^a32^a42;
2971    c3 = a03^a13^a23^a33^a43;
2972    c4 = a04^a14^a24^a34^a44;
2973    d0 = c4^ROL64(c1, 1);
2974    d1 = c0^ROL64(c2, 1);
2975    d2 = c1^ROL64(c3, 1);
2976    d3 = c2^ROL64(c4, 1);
2977    d4 = c3^ROL64(c0, 1);
2978
2979    b0 = (a00^d0);
2980    b1 = ROL64((a11^d1), 44);
2981    b2 = ROL64((a22^d2), 43);
2982    b3 = ROL64((a33^d3), 21);
2983    b4 = ROL64((a44^d4), 14);
2984    a00 =   b0 ^((~b1)&  b2 );
2985    a00 ^= RC[i];
2986    a11 =   b1 ^((~b2)&  b3 );
2987    a22 =   b2 ^((~b3)&  b4 );
2988    a33 =   b3 ^((~b4)&  b0 );
2989    a44 =   b4 ^((~b0)&  b1 );
2990
2991    b2 = ROL64((a20^d0), 3);
2992    b3 = ROL64((a31^d1), 45);
2993    b4 = ROL64((a42^d2), 61);
2994    b0 = ROL64((a03^d3), 28);
2995    b1 = ROL64((a14^d4), 20);
2996    a20 =   b0 ^((~b1)&  b2 );
2997    a31 =   b1 ^((~b2)&  b3 );
2998    a42 =   b2 ^((~b3)&  b4 );
2999    a03 =   b3 ^((~b4)&  b0 );
3000    a14 =   b4 ^((~b0)&  b1 );
3001
3002    b4 = ROL64((a40^d0), 18);
3003    b0 = ROL64((a01^d1), 1);
3004    b1 = ROL64((a12^d2), 6);
3005    b2 = ROL64((a23^d3), 25);
3006    b3 = ROL64((a34^d4), 8);
3007    a40 =   b0 ^((~b1)&  b2 );
3008    a01 =   b1 ^((~b2)&  b3 );
3009    a12 =   b2 ^((~b3)&  b4 );
3010    a23 =   b3 ^((~b4)&  b0 );
3011    a34 =   b4 ^((~b0)&  b1 );
3012
3013    b1 = ROL64((a10^d0), 36);
3014    b2 = ROL64((a21^d1), 10);
3015    b3 = ROL64((a32^d2), 15);
3016    b4 = ROL64((a43^d3), 56);
3017    b0 = ROL64((a04^d4), 27);
3018    a10 =   b0 ^((~b1)&  b2 );
3019    a21 =   b1 ^((~b2)&  b3 );
3020    a32 =   b2 ^((~b3)&  b4 );
3021    a43 =   b3 ^((~b4)&  b0 );
3022    a04 =   b4 ^((~b0)&  b1 );
3023
3024    b3 = ROL64((a30^d0), 41);
3025    b4 = ROL64((a41^d1), 2);
3026    b0 = ROL64((a02^d2), 62);
3027    b1 = ROL64((a13^d3), 55);
3028    b2 = ROL64((a24^d4), 39);
3029    a30 =   b0 ^((~b1)&  b2 );
3030    a41 =   b1 ^((~b2)&  b3 );
3031    a02 =   b2 ^((~b3)&  b4 );
3032    a13 =   b3 ^((~b4)&  b0 );
3033    a24 =   b4 ^((~b0)&  b1 );
3034
3035    c0 = a00^a20^a40^a10^a30;
3036    c1 = a11^a31^a01^a21^a41;
3037    c2 = a22^a42^a12^a32^a02;
3038    c3 = a33^a03^a23^a43^a13;
3039    c4 = a44^a14^a34^a04^a24;
3040    d0 = c4^ROL64(c1, 1);
3041    d1 = c0^ROL64(c2, 1);
3042    d2 = c1^ROL64(c3, 1);
3043    d3 = c2^ROL64(c4, 1);
3044    d4 = c3^ROL64(c0, 1);
3045
3046    b0 = (a00^d0);
3047    b1 = ROL64((a31^d1), 44);
3048    b2 = ROL64((a12^d2), 43);
3049    b3 = ROL64((a43^d3), 21);
3050    b4 = ROL64((a24^d4), 14);
3051    a00 =   b0 ^((~b1)&  b2 );
3052    a00 ^= RC[i+1];
3053    a31 =   b1 ^((~b2)&  b3 );
3054    a12 =   b2 ^((~b3)&  b4 );
3055    a43 =   b3 ^((~b4)&  b0 );
3056    a24 =   b4 ^((~b0)&  b1 );
3057
3058    b2 = ROL64((a40^d0), 3);
3059    b3 = ROL64((a21^d1), 45);
3060    b4 = ROL64((a02^d2), 61);
3061    b0 = ROL64((a33^d3), 28);
3062    b1 = ROL64((a14^d4), 20);
3063    a40 =   b0 ^((~b1)&  b2 );
3064    a21 =   b1 ^((~b2)&  b3 );
3065    a02 =   b2 ^((~b3)&  b4 );
3066    a33 =   b3 ^((~b4)&  b0 );
3067    a14 =   b4 ^((~b0)&  b1 );
3068
3069    b4 = ROL64((a30^d0), 18);
3070    b0 = ROL64((a11^d1), 1);
3071    b1 = ROL64((a42^d2), 6);
3072    b2 = ROL64((a23^d3), 25);
3073    b3 = ROL64((a04^d4), 8);
3074    a30 =   b0 ^((~b1)&  b2 );
3075    a11 =   b1 ^((~b2)&  b3 );
3076    a42 =   b2 ^((~b3)&  b4 );
3077    a23 =   b3 ^((~b4)&  b0 );
3078    a04 =   b4 ^((~b0)&  b1 );
3079
3080    b1 = ROL64((a20^d0), 36);
3081    b2 = ROL64((a01^d1), 10);
3082    b3 = ROL64((a32^d2), 15);
3083    b4 = ROL64((a13^d3), 56);
3084    b0 = ROL64((a44^d4), 27);
3085    a20 =   b0 ^((~b1)&  b2 );
3086    a01 =   b1 ^((~b2)&  b3 );
3087    a32 =   b2 ^((~b3)&  b4 );
3088    a13 =   b3 ^((~b4)&  b0 );
3089    a44 =   b4 ^((~b0)&  b1 );
3090
3091    b3 = ROL64((a10^d0), 41);
3092    b4 = ROL64((a41^d1), 2);
3093    b0 = ROL64((a22^d2), 62);
3094    b1 = ROL64((a03^d3), 55);
3095    b2 = ROL64((a34^d4), 39);
3096    a10 =   b0 ^((~b1)&  b2 );
3097    a41 =   b1 ^((~b2)&  b3 );
3098    a22 =   b2 ^((~b3)&  b4 );
3099    a03 =   b3 ^((~b4)&  b0 );
3100    a34 =   b4 ^((~b0)&  b1 );
3101
3102    c0 = a00^a40^a30^a20^a10;
3103    c1 = a31^a21^a11^a01^a41;
3104    c2 = a12^a02^a42^a32^a22;
3105    c3 = a43^a33^a23^a13^a03;
3106    c4 = a24^a14^a04^a44^a34;
3107    d0 = c4^ROL64(c1, 1);
3108    d1 = c0^ROL64(c2, 1);
3109    d2 = c1^ROL64(c3, 1);
3110    d3 = c2^ROL64(c4, 1);
3111    d4 = c3^ROL64(c0, 1);
3112
3113    b0 = (a00^d0);
3114    b1 = ROL64((a21^d1), 44);
3115    b2 = ROL64((a42^d2), 43);
3116    b3 = ROL64((a13^d3), 21);
3117    b4 = ROL64((a34^d4), 14);
3118    a00 =   b0 ^((~b1)&  b2 );
3119    a00 ^= RC[i+2];
3120    a21 =   b1 ^((~b2)&  b3 );
3121    a42 =   b2 ^((~b3)&  b4 );
3122    a13 =   b3 ^((~b4)&  b0 );
3123    a34 =   b4 ^((~b0)&  b1 );
3124
3125    b2 = ROL64((a30^d0), 3);
3126    b3 = ROL64((a01^d1), 45);
3127    b4 = ROL64((a22^d2), 61);
3128    b0 = ROL64((a43^d3), 28);
3129    b1 = ROL64((a14^d4), 20);
3130    a30 =   b0 ^((~b1)&  b2 );
3131    a01 =   b1 ^((~b2)&  b3 );
3132    a22 =   b2 ^((~b3)&  b4 );
3133    a43 =   b3 ^((~b4)&  b0 );
3134    a14 =   b4 ^((~b0)&  b1 );
3135
3136    b4 = ROL64((a10^d0), 18);
3137    b0 = ROL64((a31^d1), 1);
3138    b1 = ROL64((a02^d2), 6);
3139    b2 = ROL64((a23^d3), 25);
3140    b3 = ROL64((a44^d4), 8);
3141    a10 =   b0 ^((~b1)&  b2 );
3142    a31 =   b1 ^((~b2)&  b3 );
3143    a02 =   b2 ^((~b3)&  b4 );
3144    a23 =   b3 ^((~b4)&  b0 );
3145    a44 =   b4 ^((~b0)&  b1 );
3146
3147    b1 = ROL64((a40^d0), 36);
3148    b2 = ROL64((a11^d1), 10);
3149    b3 = ROL64((a32^d2), 15);
3150    b4 = ROL64((a03^d3), 56);
3151    b0 = ROL64((a24^d4), 27);
3152    a40 =   b0 ^((~b1)&  b2 );
3153    a11 =   b1 ^((~b2)&  b3 );
3154    a32 =   b2 ^((~b3)&  b4 );
3155    a03 =   b3 ^((~b4)&  b0 );
3156    a24 =   b4 ^((~b0)&  b1 );
3157
3158    b3 = ROL64((a20^d0), 41);
3159    b4 = ROL64((a41^d1), 2);
3160    b0 = ROL64((a12^d2), 62);
3161    b1 = ROL64((a33^d3), 55);
3162    b2 = ROL64((a04^d4), 39);
3163    a20 =   b0 ^((~b1)&  b2 );
3164    a41 =   b1 ^((~b2)&  b3 );
3165    a12 =   b2 ^((~b3)&  b4 );
3166    a33 =   b3 ^((~b4)&  b0 );
3167    a04 =   b4 ^((~b0)&  b1 );
3168
3169    c0 = a00^a30^a10^a40^a20;
3170    c1 = a21^a01^a31^a11^a41;
3171    c2 = a42^a22^a02^a32^a12;
3172    c3 = a13^a43^a23^a03^a33;
3173    c4 = a34^a14^a44^a24^a04;
3174    d0 = c4^ROL64(c1, 1);
3175    d1 = c0^ROL64(c2, 1);
3176    d2 = c1^ROL64(c3, 1);
3177    d3 = c2^ROL64(c4, 1);
3178    d4 = c3^ROL64(c0, 1);
3179
3180    b0 = (a00^d0);
3181    b1 = ROL64((a01^d1), 44);
3182    b2 = ROL64((a02^d2), 43);
3183    b3 = ROL64((a03^d3), 21);
3184    b4 = ROL64((a04^d4), 14);
3185    a00 =   b0 ^((~b1)&  b2 );
3186    a00 ^= RC[i+3];
3187    a01 =   b1 ^((~b2)&  b3 );
3188    a02 =   b2 ^((~b3)&  b4 );
3189    a03 =   b3 ^((~b4)&  b0 );
3190    a04 =   b4 ^((~b0)&  b1 );
3191
3192    b2 = ROL64((a10^d0), 3);
3193    b3 = ROL64((a11^d1), 45);
3194    b4 = ROL64((a12^d2), 61);
3195    b0 = ROL64((a13^d3), 28);
3196    b1 = ROL64((a14^d4), 20);
3197    a10 =   b0 ^((~b1)&  b2 );
3198    a11 =   b1 ^((~b2)&  b3 );
3199    a12 =   b2 ^((~b3)&  b4 );
3200    a13 =   b3 ^((~b4)&  b0 );
3201    a14 =   b4 ^((~b0)&  b1 );
3202
3203    b4 = ROL64((a20^d0), 18);
3204    b0 = ROL64((a21^d1), 1);
3205    b1 = ROL64((a22^d2), 6);
3206    b2 = ROL64((a23^d3), 25);
3207    b3 = ROL64((a24^d4), 8);
3208    a20 =   b0 ^((~b1)&  b2 );
3209    a21 =   b1 ^((~b2)&  b3 );
3210    a22 =   b2 ^((~b3)&  b4 );
3211    a23 =   b3 ^((~b4)&  b0 );
3212    a24 =   b4 ^((~b0)&  b1 );
3213
3214    b1 = ROL64((a30^d0), 36);
3215    b2 = ROL64((a31^d1), 10);
3216    b3 = ROL64((a32^d2), 15);
3217    b4 = ROL64((a33^d3), 56);
3218    b0 = ROL64((a34^d4), 27);
3219    a30 =   b0 ^((~b1)&  b2 );
3220    a31 =   b1 ^((~b2)&  b3 );
3221    a32 =   b2 ^((~b3)&  b4 );
3222    a33 =   b3 ^((~b4)&  b0 );
3223    a34 =   b4 ^((~b0)&  b1 );
3224
3225    b3 = ROL64((a40^d0), 41);
3226    b4 = ROL64((a41^d1), 2);
3227    b0 = ROL64((a42^d2), 62);
3228    b1 = ROL64((a43^d3), 55);
3229    b2 = ROL64((a44^d4), 39);
3230    a40 =   b0 ^((~b1)&  b2 );
3231    a41 =   b1 ^((~b2)&  b3 );
3232    a42 =   b2 ^((~b3)&  b4 );
3233    a43 =   b3 ^((~b4)&  b0 );
3234    a44 =   b4 ^((~b0)&  b1 );
3235  }
3236}
3237
3238/*
3239** Initialize a new hash.  iSize determines the size of the hash
3240** in bits and should be one of 224, 256, 384, or 512.  Or iSize
3241** can be zero to use the default hash size of 256 bits.
3242*/
3243static void SHA3Init(SHA3Context *p, int iSize){
3244  memset(p, 0, sizeof(*p));
3245  if( iSize>=128 && iSize<=512 ){
3246    p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
3247  }else{
3248    p->nRate = (1600 - 2*256)/8;
3249  }
3250#if SHA3_BYTEORDER==1234
3251  /* Known to be little-endian at compile-time. No-op */
3252#elif SHA3_BYTEORDER==4321
3253  p->ixMask = 7;  /* Big-endian */
3254#else
3255  {
3256    static unsigned int one = 1;
3257    if( 1==*(unsigned char*)&one ){
3258      /* Little endian.  No byte swapping. */
3259      p->ixMask = 0;
3260    }else{
3261      /* Big endian.  Byte swap. */
3262      p->ixMask = 7;
3263    }
3264  }
3265#endif
3266}
3267
3268/*
3269** Make consecutive calls to the SHA3Update function to add new content
3270** to the hash
3271*/
3272static void SHA3Update(
3273  SHA3Context *p,
3274  const unsigned char *aData,
3275  unsigned int nData
3276){
3277  unsigned int i = 0;
3278  if( aData==0 ) return;
3279#if SHA3_BYTEORDER==1234
3280  if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
3281    for(; i+7<nData; i+=8){
3282      p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
3283      p->nLoaded += 8;
3284      if( p->nLoaded>=p->nRate ){
3285        KeccakF1600Step(p);
3286        p->nLoaded = 0;
3287      }
3288    }
3289  }
3290#endif
3291  for(; i<nData; i++){
3292#if SHA3_BYTEORDER==1234
3293    p->u.x[p->nLoaded] ^= aData[i];
3294#elif SHA3_BYTEORDER==4321
3295    p->u.x[p->nLoaded^0x07] ^= aData[i];
3296#else
3297    p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
3298#endif
3299    p->nLoaded++;
3300    if( p->nLoaded==p->nRate ){
3301      KeccakF1600Step(p);
3302      p->nLoaded = 0;
3303    }
3304  }
3305}
3306
3307/*
3308** After all content has been added, invoke SHA3Final() to compute
3309** the final hash.  The function returns a pointer to the binary
3310** hash value.
3311*/
3312static unsigned char *SHA3Final(SHA3Context *p){
3313  unsigned int i;
3314  if( p->nLoaded==p->nRate-1 ){
3315    const unsigned char c1 = 0x86;
3316    SHA3Update(p, &c1, 1);
3317  }else{
3318    const unsigned char c2 = 0x06;
3319    const unsigned char c3 = 0x80;
3320    SHA3Update(p, &c2, 1);
3321    p->nLoaded = p->nRate - 1;
3322    SHA3Update(p, &c3, 1);
3323  }
3324  for(i=0; i<p->nRate; i++){
3325    p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
3326  }
3327  return &p->u.x[p->nRate];
3328}
3329/* End of the hashing logic
3330*****************************************************************************/
3331
3332/*
3333** Implementation of the sha3(X,SIZE) function.
3334**
3335** Return a BLOB which is the SIZE-bit SHA3 hash of X.  The default
3336** size is 256.  If X is a BLOB, it is hashed as is.
3337** For all other non-NULL types of input, X is converted into a UTF-8 string
3338** and the string is hashed without the trailing 0x00 terminator.  The hash
3339** of a NULL value is NULL.
3340*/
3341static void sha3Func(
3342  sqlite3_context *context,
3343  int argc,
3344  sqlite3_value **argv
3345){
3346  SHA3Context cx;
3347  int eType = sqlite3_value_type(argv[0]);
3348  int nByte = sqlite3_value_bytes(argv[0]);
3349  int iSize;
3350  if( argc==1 ){
3351    iSize = 256;
3352  }else{
3353    iSize = sqlite3_value_int(argv[1]);
3354    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3355      sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3356                                    "384 512", -1);
3357      return;
3358    }
3359  }
3360  if( eType==SQLITE_NULL ) return;
3361  SHA3Init(&cx, iSize);
3362  if( eType==SQLITE_BLOB ){
3363    SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
3364  }else{
3365    SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
3366  }
3367  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3368}
3369
3370/* Compute a string using sqlite3_vsnprintf() with a maximum length
3371** of 50 bytes and add it to the hash.
3372*/
3373static void sha3_step_vformat(
3374  SHA3Context *p,                 /* Add content to this context */
3375  const char *zFormat,
3376  ...
3377){
3378  va_list ap;
3379  int n;
3380  char zBuf[50];
3381  va_start(ap, zFormat);
3382  sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
3383  va_end(ap);
3384  n = (int)strlen(zBuf);
3385  SHA3Update(p, (unsigned char*)zBuf, n);
3386}
3387
3388/*
3389** Implementation of the sha3_query(SQL,SIZE) function.
3390**
3391** This function compiles and runs the SQL statement(s) given in the
3392** argument. The results are hashed using a SIZE-bit SHA3.  The default
3393** size is 256.
3394**
3395** The format of the byte stream that is hashed is summarized as follows:
3396**
3397**       S<n>:<sql>
3398**       R
3399**       N
3400**       I<int>
3401**       F<ieee-float>
3402**       B<size>:<bytes>
3403**       T<size>:<text>
3404**
3405** <sql> is the original SQL text for each statement run and <n> is
3406** the size of that text.  The SQL text is UTF-8.  A single R character
3407** occurs before the start of each row.  N means a NULL value.
3408** I mean an 8-byte little-endian integer <int>.  F is a floating point
3409** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
3410** B means blobs of <size> bytes.  T means text rendered as <size>
3411** bytes of UTF-8.  The <n> and <size> values are expressed as an ASCII
3412** text integers.
3413**
3414** For each SQL statement in the X input, there is one S segment.  Each
3415** S segment is followed by zero or more R segments, one for each row in the
3416** result set.  After each R, there are one or more N, I, F, B, or T segments,
3417** one for each column in the result set.  Segments are concatentated directly
3418** with no delimiters of any kind.
3419*/
3420static void sha3QueryFunc(
3421  sqlite3_context *context,
3422  int argc,
3423  sqlite3_value **argv
3424){
3425  sqlite3 *db = sqlite3_context_db_handle(context);
3426  const char *zSql = (const char*)sqlite3_value_text(argv[0]);
3427  sqlite3_stmt *pStmt = 0;
3428  int nCol;                   /* Number of columns in the result set */
3429  int i;                      /* Loop counter */
3430  int rc;
3431  int n;
3432  const char *z;
3433  SHA3Context cx;
3434  int iSize;
3435
3436  if( argc==1 ){
3437    iSize = 256;
3438  }else{
3439    iSize = sqlite3_value_int(argv[1]);
3440    if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
3441      sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
3442                                    "384 512", -1);
3443      return;
3444    }
3445  }
3446  if( zSql==0 ) return;
3447  SHA3Init(&cx, iSize);
3448  while( zSql[0] ){
3449    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
3450    if( rc ){
3451      char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
3452                                   zSql, sqlite3_errmsg(db));
3453      sqlite3_finalize(pStmt);
3454      sqlite3_result_error(context, zMsg, -1);
3455      sqlite3_free(zMsg);
3456      return;
3457    }
3458    if( !sqlite3_stmt_readonly(pStmt) ){
3459      char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
3460      sqlite3_finalize(pStmt);
3461      sqlite3_result_error(context, zMsg, -1);
3462      sqlite3_free(zMsg);
3463      return;
3464    }
3465    nCol = sqlite3_column_count(pStmt);
3466    z = sqlite3_sql(pStmt);
3467    if( z ){
3468      n = (int)strlen(z);
3469      sha3_step_vformat(&cx,"S%d:",n);
3470      SHA3Update(&cx,(unsigned char*)z,n);
3471    }
3472
3473    /* Compute a hash over the result of the query */
3474    while( SQLITE_ROW==sqlite3_step(pStmt) ){
3475      SHA3Update(&cx,(const unsigned char*)"R",1);
3476      for(i=0; i<nCol; i++){
3477        switch( sqlite3_column_type(pStmt,i) ){
3478          case SQLITE_NULL: {
3479            SHA3Update(&cx, (const unsigned char*)"N",1);
3480            break;
3481          }
3482          case SQLITE_INTEGER: {
3483            sqlite3_uint64 u;
3484            int j;
3485            unsigned char x[9];
3486            sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
3487            memcpy(&u, &v, 8);
3488            for(j=8; j>=1; j--){
3489              x[j] = u & 0xff;
3490              u >>= 8;
3491            }
3492            x[0] = 'I';
3493            SHA3Update(&cx, x, 9);
3494            break;
3495          }
3496          case SQLITE_FLOAT: {
3497            sqlite3_uint64 u;
3498            int j;
3499            unsigned char x[9];
3500            double r = sqlite3_column_double(pStmt,i);
3501            memcpy(&u, &r, 8);
3502            for(j=8; j>=1; j--){
3503              x[j] = u & 0xff;
3504              u >>= 8;
3505            }
3506            x[0] = 'F';
3507            SHA3Update(&cx,x,9);
3508            break;
3509          }
3510          case SQLITE_TEXT: {
3511            int n2 = sqlite3_column_bytes(pStmt, i);
3512            const unsigned char *z2 = sqlite3_column_text(pStmt, i);
3513            sha3_step_vformat(&cx,"T%d:",n2);
3514            SHA3Update(&cx, z2, n2);
3515            break;
3516          }
3517          case SQLITE_BLOB: {
3518            int n2 = sqlite3_column_bytes(pStmt, i);
3519            const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
3520            sha3_step_vformat(&cx,"B%d:",n2);
3521            SHA3Update(&cx, z2, n2);
3522            break;
3523          }
3524        }
3525      }
3526    }
3527    sqlite3_finalize(pStmt);
3528  }
3529  sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
3530}
3531
3532
3533#ifdef _WIN32
3534
3535#endif
3536int sqlite3_shathree_init(
3537  sqlite3 *db,
3538  char **pzErrMsg,
3539  const sqlite3_api_routines *pApi
3540){
3541  int rc = SQLITE_OK;
3542  SQLITE_EXTENSION_INIT2(pApi);
3543  (void)pzErrMsg;  /* Unused parameter */
3544  rc = sqlite3_create_function(db, "sha3", 1,
3545                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3546                      0, sha3Func, 0, 0);
3547  if( rc==SQLITE_OK ){
3548    rc = sqlite3_create_function(db, "sha3", 2,
3549                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
3550                      0, sha3Func, 0, 0);
3551  }
3552  if( rc==SQLITE_OK ){
3553    rc = sqlite3_create_function(db, "sha3_query", 1,
3554                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
3555                      0, sha3QueryFunc, 0, 0);
3556  }
3557  if( rc==SQLITE_OK ){
3558    rc = sqlite3_create_function(db, "sha3_query", 2,
3559                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
3560                      0, sha3QueryFunc, 0, 0);
3561  }
3562  return rc;
3563}
3564
3565/************************* End ../ext/misc/shathree.c ********************/
3566/************************* Begin ../ext/misc/uint.c ******************/
3567/*
3568** 2020-04-14
3569**
3570** The author disclaims copyright to this source code.  In place of
3571** a legal notice, here is a blessing:
3572**
3573**    May you do good and not evil.
3574**    May you find forgiveness for yourself and forgive others.
3575**    May you share freely, never taking more than you give.
3576**
3577******************************************************************************
3578**
3579** This SQLite extension implements the UINT collating sequence.
3580**
3581** UINT works like BINARY for text, except that embedded strings
3582** of digits compare in numeric order.
3583**
3584**     *   Leading zeros are handled properly, in the sense that
3585**         they do not mess of the maginitude comparison of embedded
3586**         strings of digits.  "x00123y" is equal to "x123y".
3587**
3588**     *   Only unsigned integers are recognized.  Plus and minus
3589**         signs are ignored.  Decimal points and exponential notation
3590**         are ignored.
3591**
3592**     *   Embedded integers can be of arbitrary length.  Comparison
3593**         is *not* limited integers that can be expressed as a
3594**         64-bit machine integer.
3595*/
3596/* #include "sqlite3ext.h" */
3597SQLITE_EXTENSION_INIT1
3598#include <assert.h>
3599#include <string.h>
3600#include <ctype.h>
3601
3602/*
3603** Compare text in lexicographic order, except strings of digits
3604** compare in numeric order.
3605*/
3606static int uintCollFunc(
3607  void *notUsed,
3608  int nKey1, const void *pKey1,
3609  int nKey2, const void *pKey2
3610){
3611  const unsigned char *zA = (const unsigned char*)pKey1;
3612  const unsigned char *zB = (const unsigned char*)pKey2;
3613  int i=0, j=0, x;
3614  (void)notUsed;
3615  while( i<nKey1 && j<nKey2 ){
3616    x = zA[i] - zB[j];
3617    if( isdigit(zA[i]) ){
3618      int k;
3619      if( !isdigit(zB[j]) ) return x;
3620      while( i<nKey1 && zA[i]=='0' ){ i++; }
3621      while( j<nKey2 && zB[j]=='0' ){ j++; }
3622      k = 0;
3623      while( i+k<nKey1 && isdigit(zA[i+k])
3624             && j+k<nKey2 && isdigit(zB[j+k]) ){
3625        k++;
3626      }
3627      if( i+k<nKey1 && isdigit(zA[i+k]) ){
3628        return +1;
3629      }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
3630        return -1;
3631      }else{
3632        x = memcmp(zA+i, zB+j, k);
3633        if( x ) return x;
3634        i += k;
3635        j += k;
3636      }
3637    }else if( x ){
3638      return x;
3639    }else{
3640      i++;
3641      j++;
3642    }
3643  }
3644  return (nKey1 - i) - (nKey2 - j);
3645}
3646
3647#ifdef _WIN32
3648
3649#endif
3650int sqlite3_uint_init(
3651  sqlite3 *db,
3652  char **pzErrMsg,
3653  const sqlite3_api_routines *pApi
3654){
3655  SQLITE_EXTENSION_INIT2(pApi);
3656  (void)pzErrMsg;  /* Unused parameter */
3657  return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
3658}
3659
3660/************************* End ../ext/misc/uint.c ********************/
3661/************************* Begin ../ext/misc/decimal.c ******************/
3662/*
3663** 2020-06-22
3664**
3665** The author disclaims copyright to this source code.  In place of
3666** a legal notice, here is a blessing:
3667**
3668**    May you do good and not evil.
3669**    May you find forgiveness for yourself and forgive others.
3670**    May you share freely, never taking more than you give.
3671**
3672******************************************************************************
3673**
3674** Routines to implement arbitrary-precision decimal math.
3675**
3676** The focus here is on simplicity and correctness, not performance.
3677*/
3678/* #include "sqlite3ext.h" */
3679SQLITE_EXTENSION_INIT1
3680#include <assert.h>
3681#include <string.h>
3682#include <ctype.h>
3683#include <stdlib.h>
3684
3685/* Mark a function parameter as unused, to suppress nuisance compiler
3686** warnings. */
3687#ifndef UNUSED_PARAMETER
3688# define UNUSED_PARAMETER(X)  (void)(X)
3689#endif
3690
3691
3692/* A decimal object */
3693typedef struct Decimal Decimal;
3694struct Decimal {
3695  char sign;        /* 0 for positive, 1 for negative */
3696  char oom;         /* True if an OOM is encountered */
3697  char isNull;      /* True if holds a NULL rather than a number */
3698  char isInit;      /* True upon initialization */
3699  int nDigit;       /* Total number of digits */
3700  int nFrac;        /* Number of digits to the right of the decimal point */
3701  signed char *a;   /* Array of digits.  Most significant first. */
3702};
3703
3704/*
3705** Release memory held by a Decimal, but do not free the object itself.
3706*/
3707static void decimal_clear(Decimal *p){
3708  sqlite3_free(p->a);
3709}
3710
3711/*
3712** Destroy a Decimal object
3713*/
3714static void decimal_free(Decimal *p){
3715  if( p ){
3716    decimal_clear(p);
3717    sqlite3_free(p);
3718  }
3719}
3720
3721/*
3722** Allocate a new Decimal object initialized to the text in zIn[].
3723** Return NULL if any kind of error occurs.
3724*/
3725static Decimal *decimalNewFromText(const char *zIn, int n){
3726  Decimal *p = 0;
3727  int i;
3728  int iExp = 0;
3729
3730  p = sqlite3_malloc( sizeof(*p) );
3731  if( p==0 ) goto new_from_text_failed;
3732  p->sign = 0;
3733  p->oom = 0;
3734  p->isInit = 1;
3735  p->isNull = 0;
3736  p->nDigit = 0;
3737  p->nFrac = 0;
3738  p->a = sqlite3_malloc64( n+1 );
3739  if( p->a==0 ) goto new_from_text_failed;
3740  for(i=0; isspace(zIn[i]); i++){}
3741  if( zIn[i]=='-' ){
3742    p->sign = 1;
3743    i++;
3744  }else if( zIn[i]=='+' ){
3745    i++;
3746  }
3747  while( i<n && zIn[i]=='0' ) i++;
3748  while( i<n ){
3749    char c = zIn[i];
3750    if( c>='0' && c<='9' ){
3751      p->a[p->nDigit++] = c - '0';
3752    }else if( c=='.' ){
3753      p->nFrac = p->nDigit + 1;
3754    }else if( c=='e' || c=='E' ){
3755      int j = i+1;
3756      int neg = 0;
3757      if( j>=n ) break;
3758      if( zIn[j]=='-' ){
3759        neg = 1;
3760        j++;
3761      }else if( zIn[j]=='+' ){
3762        j++;
3763      }
3764      while( j<n && iExp<1000000 ){
3765        if( zIn[j]>='0' && zIn[j]<='9' ){
3766          iExp = iExp*10 + zIn[j] - '0';
3767        }
3768        j++;
3769      }
3770      if( neg ) iExp = -iExp;
3771      break;
3772    }
3773    i++;
3774  }
3775  if( p->nFrac ){
3776    p->nFrac = p->nDigit - (p->nFrac - 1);
3777  }
3778  if( iExp>0 ){
3779    if( p->nFrac>0 ){
3780      if( iExp<=p->nFrac ){
3781        p->nFrac -= iExp;
3782        iExp = 0;
3783      }else{
3784        iExp -= p->nFrac;
3785        p->nFrac = 0;
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      memset(p->a+p->nDigit, 0, iExp);
3792      p->nDigit += iExp;
3793    }
3794  }else if( iExp<0 ){
3795    int nExtra;
3796    iExp = -iExp;
3797    nExtra = p->nDigit - p->nFrac - 1;
3798    if( nExtra ){
3799      if( nExtra>=iExp ){
3800        p->nFrac += iExp;
3801        iExp  = 0;
3802      }else{
3803        iExp -= nExtra;
3804        p->nFrac = p->nDigit - 1;
3805      }
3806    }
3807    if( iExp>0 ){
3808      p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
3809      if( p->a==0 ) goto new_from_text_failed;
3810      memmove(p->a+iExp, p->a, p->nDigit);
3811      memset(p->a, 0, iExp);
3812      p->nDigit += iExp;
3813      p->nFrac += iExp;
3814    }
3815  }
3816  return p;
3817
3818new_from_text_failed:
3819  if( p ){
3820    if( p->a ) sqlite3_free(p->a);
3821    sqlite3_free(p);
3822  }
3823  return 0;
3824}
3825
3826/* Forward reference */
3827static Decimal *decimalFromDouble(double);
3828
3829/*
3830** Allocate a new Decimal object from an sqlite3_value.  Return a pointer
3831** to the new object, or NULL if there is an error.  If the pCtx argument
3832** is not NULL, then errors are reported on it as well.
3833**
3834** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted
3835** directly into a Decimal.  For SQLITE_FLOAT or for SQLITE_BLOB of length
3836** 8 bytes, the resulting double value is expanded into its decimal equivalent.
3837** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length,
3838** then NULL is returned.
3839*/
3840static Decimal *decimal_new(
3841  sqlite3_context *pCtx,       /* Report error here, if not null */
3842  sqlite3_value *pIn,          /* Construct the decimal object from this */
3843  int bTextOnly                /* Always interpret pIn as text if true */
3844){
3845  Decimal *p = 0;
3846  int eType = sqlite3_value_type(pIn);
3847  if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){
3848    eType = SQLITE_TEXT;
3849  }
3850  switch( eType ){
3851    case SQLITE_TEXT:
3852    case SQLITE_INTEGER: {
3853      const char *zIn = (const char*)sqlite3_value_text(pIn);
3854      int n = sqlite3_value_bytes(pIn);
3855      p = decimalNewFromText(zIn, n);
3856      if( p==0 ) goto new_failed;
3857      break;
3858    }
3859
3860    case SQLITE_FLOAT: {
3861      p = decimalFromDouble(sqlite3_value_double(pIn));
3862      break;
3863    }
3864
3865    case SQLITE_BLOB: {
3866      const unsigned char *x;
3867      unsigned int i;
3868      sqlite3_uint64 v = 0;
3869      double r;
3870
3871      if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break;
3872      x = sqlite3_value_blob(pIn);
3873      for(i=0; i<sizeof(r); i++){
3874        v = (v<<8) | x[i];
3875      }
3876      memcpy(&r, &v, sizeof(r));
3877      p = decimalFromDouble(r);
3878      break;
3879    }
3880
3881    case SQLITE_NULL: {
3882      break;
3883    }
3884  }
3885  return p;
3886
3887new_failed:
3888  if( pCtx ) sqlite3_result_error_nomem(pCtx);
3889  sqlite3_free(p);
3890  return 0;
3891}
3892
3893/*
3894** Make the given Decimal the result.
3895*/
3896static void decimal_result(sqlite3_context *pCtx, Decimal *p){
3897  char *z;
3898  int i, j;
3899  int n;
3900  if( p==0 || p->oom ){
3901    sqlite3_result_error_nomem(pCtx);
3902    return;
3903  }
3904  if( p->isNull ){
3905    sqlite3_result_null(pCtx);
3906    return;
3907  }
3908  z = sqlite3_malloc( p->nDigit+4 );
3909  if( z==0 ){
3910    sqlite3_result_error_nomem(pCtx);
3911    return;
3912  }
3913  i = 0;
3914  if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
3915    p->sign = 0;
3916  }
3917  if( p->sign ){
3918    z[0] = '-';
3919    i = 1;
3920  }
3921  n = p->nDigit - p->nFrac;
3922  if( n<=0 ){
3923    z[i++] = '0';
3924  }
3925  j = 0;
3926  while( n>1 && p->a[j]==0 ){
3927    j++;
3928    n--;
3929  }
3930  while( n>0  ){
3931    z[i++] = p->a[j] + '0';
3932    j++;
3933    n--;
3934  }
3935  if( p->nFrac ){
3936    z[i++] = '.';
3937    do{
3938      z[i++] = p->a[j] + '0';
3939      j++;
3940    }while( j<p->nDigit );
3941  }
3942  z[i] = 0;
3943  sqlite3_result_text(pCtx, z, i, sqlite3_free);
3944}
3945
3946/*
3947** Make the given Decimal the result in an format similar to  '%+#e'.
3948** In other words, show exponential notation with leading and trailing
3949** zeros omitted.
3950*/
3951static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){
3952  char *z;       /* The output buffer */
3953  int i;         /* Loop counter */
3954  int nZero;     /* Number of leading zeros */
3955  int nDigit;    /* Number of digits not counting trailing zeros */
3956  int nFrac;     /* Digits to the right of the decimal point */
3957  int exp;       /* Exponent value */
3958  signed char zero;     /* Zero value */
3959  signed char *a;       /* Array of digits */
3960
3961  if( p==0 || p->oom ){
3962    sqlite3_result_error_nomem(pCtx);
3963    return;
3964  }
3965  if( p->isNull ){
3966    sqlite3_result_null(pCtx);
3967    return;
3968  }
3969  for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){}
3970  for(nZero=0; nZero<nDigit && p->a[nZero]==0; nZero++){}
3971  nFrac = p->nFrac + (nDigit - p->nDigit);
3972  nDigit -= nZero;
3973  z = sqlite3_malloc( nDigit+20 );
3974  if( z==0 ){
3975    sqlite3_result_error_nomem(pCtx);
3976    return;
3977  }
3978  if( nDigit==0 ){
3979    zero = 0;
3980    a = &zero;
3981    nDigit = 1;
3982    nFrac = 0;
3983  }else{
3984    a = &p->a[nZero];
3985  }
3986  if( p->sign && nDigit>0 ){
3987    z[0] = '-';
3988  }else{
3989    z[0] = '+';
3990  }
3991  z[1] = a[0]+'0';
3992  z[2] = '.';
3993  if( nDigit==1 ){
3994    z[3] = '0';
3995    i = 4;
3996  }else{
3997    for(i=1; i<nDigit; i++){
3998      z[2+i] = a[i]+'0';
3999    }
4000    i = nDigit+2;
4001  }
4002  exp = nDigit - nFrac - 1;
4003  sqlite3_snprintf(nDigit+20-i, &z[i], "e%+03d", exp);
4004  sqlite3_result_text(pCtx, z, -1, sqlite3_free);
4005}
4006
4007/*
4008** Compare to Decimal objects.  Return negative, 0, or positive if the
4009** first object is less than, equal to, or greater than the second.
4010**
4011** Preconditions for this routine:
4012**
4013**    pA!=0
4014**    pA->isNull==0
4015**    pB!=0
4016**    pB->isNull==0
4017*/
4018static int decimal_cmp(const Decimal *pA, const Decimal *pB){
4019  int nASig, nBSig, rc, n;
4020  if( pA->sign!=pB->sign ){
4021    return pA->sign ? -1 : +1;
4022  }
4023  if( pA->sign ){
4024    const Decimal *pTemp = pA;
4025    pA = pB;
4026    pB = pTemp;
4027  }
4028  nASig = pA->nDigit - pA->nFrac;
4029  nBSig = pB->nDigit - pB->nFrac;
4030  if( nASig!=nBSig ){
4031    return nASig - nBSig;
4032  }
4033  n = pA->nDigit;
4034  if( n>pB->nDigit ) n = pB->nDigit;
4035  rc = memcmp(pA->a, pB->a, n);
4036  if( rc==0 ){
4037    rc = pA->nDigit - pB->nDigit;
4038  }
4039  return rc;
4040}
4041
4042/*
4043** SQL Function:   decimal_cmp(X, Y)
4044**
4045** Return negative, zero, or positive if X is less then, equal to, or
4046** greater than Y.
4047*/
4048static void decimalCmpFunc(
4049  sqlite3_context *context,
4050  int argc,
4051  sqlite3_value **argv
4052){
4053  Decimal *pA = 0, *pB = 0;
4054  int rc;
4055
4056  UNUSED_PARAMETER(argc);
4057  pA = decimal_new(context, argv[0], 1);
4058  if( pA==0 || pA->isNull ) goto cmp_done;
4059  pB = decimal_new(context, argv[1], 1);
4060  if( pB==0 || pB->isNull ) goto cmp_done;
4061  rc = decimal_cmp(pA, pB);
4062  if( rc<0 ) rc = -1;
4063  else if( rc>0 ) rc = +1;
4064  sqlite3_result_int(context, rc);
4065cmp_done:
4066  decimal_free(pA);
4067  decimal_free(pB);
4068}
4069
4070/*
4071** Expand the Decimal so that it has a least nDigit digits and nFrac
4072** digits to the right of the decimal point.
4073*/
4074static void decimal_expand(Decimal *p, int nDigit, int nFrac){
4075  int nAddSig;
4076  int nAddFrac;
4077  if( p==0 ) return;
4078  nAddFrac = nFrac - p->nFrac;
4079  nAddSig = (nDigit - p->nDigit) - nAddFrac;
4080  if( nAddFrac==0 && nAddSig==0 ) return;
4081  p->a = sqlite3_realloc64(p->a, nDigit+1);
4082  if( p->a==0 ){
4083    p->oom = 1;
4084    return;
4085  }
4086  if( nAddSig ){
4087    memmove(p->a+nAddSig, p->a, p->nDigit);
4088    memset(p->a, 0, nAddSig);
4089    p->nDigit += nAddSig;
4090  }
4091  if( nAddFrac ){
4092    memset(p->a+p->nDigit, 0, nAddFrac);
4093    p->nDigit += nAddFrac;
4094    p->nFrac += nAddFrac;
4095  }
4096}
4097
4098/*
4099** Add the value pB into pA.   A := A + B.
4100**
4101** Both pA and pB might become denormalized by this routine.
4102*/
4103static void decimal_add(Decimal *pA, Decimal *pB){
4104  int nSig, nFrac, nDigit;
4105  int i, rc;
4106  if( pA==0 ){
4107    return;
4108  }
4109  if( pA->oom || pB==0 || pB->oom ){
4110    pA->oom = 1;
4111    return;
4112  }
4113  if( pA->isNull || pB->isNull ){
4114    pA->isNull = 1;
4115    return;
4116  }
4117  nSig = pA->nDigit - pA->nFrac;
4118  if( nSig && pA->a[0]==0 ) nSig--;
4119  if( nSig<pB->nDigit-pB->nFrac ){
4120    nSig = pB->nDigit - pB->nFrac;
4121  }
4122  nFrac = pA->nFrac;
4123  if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
4124  nDigit = nSig + nFrac + 1;
4125  decimal_expand(pA, nDigit, nFrac);
4126  decimal_expand(pB, nDigit, nFrac);
4127  if( pA->oom || pB->oom ){
4128    pA->oom = 1;
4129  }else{
4130    if( pA->sign==pB->sign ){
4131      int carry = 0;
4132      for(i=nDigit-1; i>=0; i--){
4133        int x = pA->a[i] + pB->a[i] + carry;
4134        if( x>=10 ){
4135          carry = 1;
4136          pA->a[i] = x - 10;
4137        }else{
4138          carry = 0;
4139          pA->a[i] = x;
4140        }
4141      }
4142    }else{
4143      signed char *aA, *aB;
4144      int borrow = 0;
4145      rc = memcmp(pA->a, pB->a, nDigit);
4146      if( rc<0 ){
4147        aA = pB->a;
4148        aB = pA->a;
4149        pA->sign = !pA->sign;
4150      }else{
4151        aA = pA->a;
4152        aB = pB->a;
4153      }
4154      for(i=nDigit-1; i>=0; i--){
4155        int x = aA[i] - aB[i] - borrow;
4156        if( x<0 ){
4157          pA->a[i] = x+10;
4158          borrow = 1;
4159        }else{
4160          pA->a[i] = x;
4161          borrow = 0;
4162        }
4163      }
4164    }
4165  }
4166}
4167
4168/*
4169** Multiply A by B.   A := A * B
4170**
4171** All significant digits after the decimal point are retained.
4172** Trailing zeros after the decimal point are omitted as long as
4173** the number of digits after the decimal point is no less than
4174** either the number of digits in either input.
4175*/
4176static void decimalMul(Decimal *pA, Decimal *pB){
4177  signed char *acc = 0;
4178  int i, j, k;
4179  int minFrac;
4180
4181  if( pA==0 || pA->oom || pA->isNull
4182   || pB==0 || pB->oom || pB->isNull
4183  ){
4184    goto mul_end;
4185  }
4186  acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
4187  if( acc==0 ){
4188    pA->oom = 1;
4189    goto mul_end;
4190  }
4191  memset(acc, 0, pA->nDigit + pB->nDigit + 2);
4192  minFrac = pA->nFrac;
4193  if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
4194  for(i=pA->nDigit-1; i>=0; i--){
4195    signed char f = pA->a[i];
4196    int carry = 0, x;
4197    for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
4198      x = acc[k] + f*pB->a[j] + carry;
4199      acc[k] = x%10;
4200      carry = x/10;
4201    }
4202    x = acc[k] + carry;
4203    acc[k] = x%10;
4204    acc[k-1] += x/10;
4205  }
4206  sqlite3_free(pA->a);
4207  pA->a = acc;
4208  acc = 0;
4209  pA->nDigit += pB->nDigit + 2;
4210  pA->nFrac += pB->nFrac;
4211  pA->sign ^= pB->sign;
4212  while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
4213    pA->nFrac--;
4214    pA->nDigit--;
4215  }
4216
4217mul_end:
4218  sqlite3_free(acc);
4219}
4220
4221/*
4222** Create a new Decimal object that contains an integer power of 2.
4223*/
4224static Decimal *decimalPow2(int N){
4225  Decimal *pA = 0;      /* The result to be returned */
4226  Decimal *pX = 0;      /* Multiplier */
4227  if( N<-20000 || N>20000 ) goto pow2_fault;
4228  pA = decimalNewFromText("1.0", 3);
4229  if( pA==0 || pA->oom ) goto pow2_fault;
4230  if( N==0 ) return pA;
4231  if( N>0 ){
4232    pX = decimalNewFromText("2.0", 3);
4233  }else{
4234    N = -N;
4235    pX = decimalNewFromText("0.5", 3);
4236  }
4237  if( pX==0 || pX->oom ) goto pow2_fault;
4238  while( 1 /* Exit by break */ ){
4239    if( N & 1 ){
4240      decimalMul(pA, pX);
4241      if( pA->oom ) goto pow2_fault;
4242    }
4243    N >>= 1;
4244    if( N==0 ) break;
4245    decimalMul(pX, pX);
4246  }
4247  decimal_free(pX);
4248  return pA;
4249
4250pow2_fault:
4251  decimal_free(pA);
4252  decimal_free(pX);
4253  return 0;
4254}
4255
4256/*
4257** Use an IEEE754 binary64 ("double") to generate a new Decimal object.
4258*/
4259static Decimal *decimalFromDouble(double r){
4260  sqlite3_int64 m, a;
4261  int e;
4262  int isNeg;
4263  Decimal *pA;
4264  Decimal *pX;
4265  char zNum[100];
4266  if( r<0.0 ){
4267    isNeg = 1;
4268    r = -r;
4269  }else{
4270    isNeg = 0;
4271  }
4272  memcpy(&a,&r,sizeof(a));
4273  if( a==0 ){
4274    e = 0;
4275    m = 0;
4276  }else{
4277    e = a>>52;
4278    m = a & ((((sqlite3_int64)1)<<52)-1);
4279    if( e==0 ){
4280      m <<= 1;
4281    }else{
4282      m |= ((sqlite3_int64)1)<<52;
4283    }
4284    while( e<1075 && m>0 && (m&1)==0 ){
4285      m >>= 1;
4286      e++;
4287    }
4288    if( isNeg ) m = -m;
4289    e = e - 1075;
4290    if( e>971 ){
4291      return 0;  /* A NaN or an Infinity */
4292    }
4293  }
4294
4295  /* At this point m is the integer significand and e is the exponent */
4296  sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m);
4297  pA = decimalNewFromText(zNum, (int)strlen(zNum));
4298  pX = decimalPow2(e);
4299  decimalMul(pA, pX);
4300  decimal_free(pX);
4301  return pA;
4302}
4303
4304/*
4305** SQL Function:   decimal(X)
4306** OR:             decimal_exp(X)
4307**
4308** Convert input X into decimal and then back into text.
4309**
4310** If X is originally a float, then a full decimal expansion of that floating
4311** point value is done.  Or if X is an 8-byte blob, it is interpreted
4312** as a float and similarly expanded.
4313**
4314** The decimal_exp(X) function returns the result in exponential notation.
4315** decimal(X) returns a complete decimal, without the e+NNN at the end.
4316*/
4317static void decimalFunc(
4318  sqlite3_context *context,
4319  int argc,
4320  sqlite3_value **argv
4321){
4322  Decimal *p =  decimal_new(context, argv[0], 0);
4323  UNUSED_PARAMETER(argc);
4324  if( p ){
4325    if( sqlite3_user_data(context)!=0 ){
4326      decimal_result_sci(context, p);
4327    }else{
4328      decimal_result(context, p);
4329    }
4330    decimal_free(p);
4331  }
4332}
4333
4334/*
4335** Compare text in decimal order.
4336*/
4337static int decimalCollFunc(
4338  void *notUsed,
4339  int nKey1, const void *pKey1,
4340  int nKey2, const void *pKey2
4341){
4342  const unsigned char *zA = (const unsigned char*)pKey1;
4343  const unsigned char *zB = (const unsigned char*)pKey2;
4344  Decimal *pA = decimalNewFromText((const char*)zA, nKey1);
4345  Decimal *pB = decimalNewFromText((const char*)zB, nKey2);
4346  int rc;
4347  UNUSED_PARAMETER(notUsed);
4348  if( pA==0 || pB==0 ){
4349    rc = 0;
4350  }else{
4351    rc = decimal_cmp(pA, pB);
4352  }
4353  decimal_free(pA);
4354  decimal_free(pB);
4355  return rc;
4356}
4357
4358
4359/*
4360** SQL Function:   decimal_add(X, Y)
4361**                 decimal_sub(X, Y)
4362**
4363** Return the sum or difference of X and Y.
4364*/
4365static void decimalAddFunc(
4366  sqlite3_context *context,
4367  int argc,
4368  sqlite3_value **argv
4369){
4370  Decimal *pA = decimal_new(context, argv[0], 1);
4371  Decimal *pB = decimal_new(context, argv[1], 1);
4372  UNUSED_PARAMETER(argc);
4373  decimal_add(pA, pB);
4374  decimal_result(context, pA);
4375  decimal_free(pA);
4376  decimal_free(pB);
4377}
4378static void decimalSubFunc(
4379  sqlite3_context *context,
4380  int argc,
4381  sqlite3_value **argv
4382){
4383  Decimal *pA = decimal_new(context, argv[0], 1);
4384  Decimal *pB = decimal_new(context, argv[1], 1);
4385  UNUSED_PARAMETER(argc);
4386  if( pB ){
4387    pB->sign = !pB->sign;
4388    decimal_add(pA, pB);
4389    decimal_result(context, pA);
4390  }
4391  decimal_free(pA);
4392  decimal_free(pB);
4393}
4394
4395/* Aggregate funcion:   decimal_sum(X)
4396**
4397** Works like sum() except that it uses decimal arithmetic for unlimited
4398** precision.
4399*/
4400static void decimalSumStep(
4401  sqlite3_context *context,
4402  int argc,
4403  sqlite3_value **argv
4404){
4405  Decimal *p;
4406  Decimal *pArg;
4407  UNUSED_PARAMETER(argc);
4408  p = sqlite3_aggregate_context(context, sizeof(*p));
4409  if( p==0 ) return;
4410  if( !p->isInit ){
4411    p->isInit = 1;
4412    p->a = sqlite3_malloc(2);
4413    if( p->a==0 ){
4414      p->oom = 1;
4415    }else{
4416      p->a[0] = 0;
4417    }
4418    p->nDigit = 1;
4419    p->nFrac = 0;
4420  }
4421  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4422  pArg = decimal_new(context, argv[0], 1);
4423  decimal_add(p, pArg);
4424  decimal_free(pArg);
4425}
4426static void decimalSumInverse(
4427  sqlite3_context *context,
4428  int argc,
4429  sqlite3_value **argv
4430){
4431  Decimal *p;
4432  Decimal *pArg;
4433  UNUSED_PARAMETER(argc);
4434  p = sqlite3_aggregate_context(context, sizeof(*p));
4435  if( p==0 ) return;
4436  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4437  pArg = decimal_new(context, argv[0], 1);
4438  if( pArg ) pArg->sign = !pArg->sign;
4439  decimal_add(p, pArg);
4440  decimal_free(pArg);
4441}
4442static void decimalSumValue(sqlite3_context *context){
4443  Decimal *p = sqlite3_aggregate_context(context, 0);
4444  if( p==0 ) return;
4445  decimal_result(context, p);
4446}
4447static void decimalSumFinalize(sqlite3_context *context){
4448  Decimal *p = sqlite3_aggregate_context(context, 0);
4449  if( p==0 ) return;
4450  decimal_result(context, p);
4451  decimal_clear(p);
4452}
4453
4454/*
4455** SQL Function:   decimal_mul(X, Y)
4456**
4457** Return the product of X and Y.
4458*/
4459static void decimalMulFunc(
4460  sqlite3_context *context,
4461  int argc,
4462  sqlite3_value **argv
4463){
4464  Decimal *pA = decimal_new(context, argv[0], 1);
4465  Decimal *pB = decimal_new(context, argv[1], 1);
4466  UNUSED_PARAMETER(argc);
4467  if( pA==0 || pA->oom || pA->isNull
4468   || pB==0 || pB->oom || pB->isNull
4469  ){
4470    goto mul_end;
4471  }
4472  decimalMul(pA, pB);
4473  if( pA->oom ){
4474    goto mul_end;
4475  }
4476  decimal_result(context, pA);
4477
4478mul_end:
4479  decimal_free(pA);
4480  decimal_free(pB);
4481}
4482
4483/*
4484** SQL Function:   decimal_pow2(N)
4485**
4486** Return the N-th power of 2.  N must be an integer.
4487*/
4488static void decimalPow2Func(
4489  sqlite3_context *context,
4490  int argc,
4491  sqlite3_value **argv
4492){
4493  UNUSED_PARAMETER(argc);
4494  if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){
4495    Decimal *pA = decimalPow2(sqlite3_value_int(argv[0]));
4496    decimal_result_sci(context, pA);
4497    decimal_free(pA);
4498  }
4499}
4500
4501#ifdef _WIN32
4502
4503#endif
4504int sqlite3_decimal_init(
4505  sqlite3 *db,
4506  char **pzErrMsg,
4507  const sqlite3_api_routines *pApi
4508){
4509  int rc = SQLITE_OK;
4510  static const struct {
4511    const char *zFuncName;
4512    int nArg;
4513    int iArg;
4514    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
4515  } aFunc[] = {
4516    { "decimal",       1, 0,  decimalFunc        },
4517    { "decimal_exp",   1, 1,  decimalFunc        },
4518    { "decimal_cmp",   2, 0,  decimalCmpFunc     },
4519    { "decimal_add",   2, 0,  decimalAddFunc     },
4520    { "decimal_sub",   2, 0,  decimalSubFunc     },
4521    { "decimal_mul",   2, 0,  decimalMulFunc     },
4522    { "decimal_pow2",  1, 0,  decimalPow2Func    },
4523  };
4524  unsigned int i;
4525  (void)pzErrMsg;  /* Unused parameter */
4526
4527  SQLITE_EXTENSION_INIT2(pApi);
4528
4529  for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){
4530    rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
4531                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
4532                   aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0);
4533  }
4534  if( rc==SQLITE_OK ){
4535    rc = sqlite3_create_window_function(db, "decimal_sum", 1,
4536                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
4537                   decimalSumStep, decimalSumFinalize,
4538                   decimalSumValue, decimalSumInverse, 0);
4539  }
4540  if( rc==SQLITE_OK ){
4541    rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
4542                                  0, decimalCollFunc);
4543  }
4544  return rc;
4545}
4546
4547/************************* End ../ext/misc/decimal.c ********************/
4548#undef sqlite3_base_init
4549#define sqlite3_base_init sqlite3_base64_init
4550/************************* Begin ../ext/misc/base64.c ******************/
4551/*
4552** 2022-11-18
4553**
4554** The author disclaims copyright to this source code.  In place of
4555** a legal notice, here is a blessing:
4556**
4557**    May you do good and not evil.
4558**    May you find forgiveness for yourself and forgive others.
4559**    May you share freely, never taking more than you give.
4560**
4561*************************************************************************
4562**
4563** This is a SQLite extension for converting in either direction
4564** between a (binary) blob and base64 text. Base64 can transit a
4565** sane USASCII channel unmolested. It also plays nicely in CSV or
4566** written as TCL brace-enclosed literals or SQL string literals,
4567** and can be used unmodified in XML-like documents.
4568**
4569** This is an independent implementation of conversions specified in
4570** RFC 4648, done on the above date by the author (Larry Brasfield)
4571** who thereby has the right to put this into the public domain.
4572**
4573** The conversions meet RFC 4648 requirements, provided that this
4574** C source specifies that line-feeds are included in the encoded
4575** data to limit visible line lengths to 72 characters and to
4576** terminate any encoded blob having non-zero length.
4577**
4578** Length limitations are not imposed except that the runtime
4579** SQLite string or blob length limits are respected. Otherwise,
4580** any length binary sequence can be represented and recovered.
4581** Generated base64 sequences, with their line-feeds included,
4582** can be concatenated; the result converted back to binary will
4583** be the concatenation of the represented binary sequences.
4584**
4585** This SQLite3 extension creates a function, base64(x), which
4586** either: converts text x containing base64 to a returned blob;
4587** or converts a blob x to returned text containing base64. An
4588** error will be thrown for other input argument types.
4589**
4590** This code relies on UTF-8 encoding only with respect to the
4591** meaning of the first 128 (7-bit) codes matching that of USASCII.
4592** It will fail miserably if somehow made to try to convert EBCDIC.
4593** Because it is table-driven, it could be enhanced to handle that,
4594** but the world and SQLite have moved on from that anachronism.
4595**
4596** To build the extension:
4597** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4598** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c
4599** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c
4600** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c
4601** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll
4602*/
4603
4604#include <assert.h>
4605
4606/* #include "sqlite3ext.h" */
4607
4608#ifndef deliberate_fall_through
4609/* Quiet some compilers about some of our intentional code. */
4610# if GCC_VERSION>=7000000
4611#  define deliberate_fall_through __attribute__((fallthrough));
4612# else
4613#  define deliberate_fall_through
4614# endif
4615#endif
4616
4617SQLITE_EXTENSION_INIT1;
4618
4619#define PC 0x80 /* pad character */
4620#define WS 0x81 /* whitespace */
4621#define ND 0x82 /* Not above or digit-value */
4622#define PAD_CHAR '='
4623
4624#ifndef U8_TYPEDEF
4625/* typedef unsigned char u8; */
4626#define U8_TYPEDEF
4627#endif
4628
4629/* Decoding table, ASCII (7-bit) value to base 64 digit value or other */
4630static const u8 b64DigitValues[128] = {
4631  /*                             HT LF VT  FF CR       */
4632    ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND,
4633  /*                                                US */
4634    ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND,
4635  /*sp                                  +            / */
4636    WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63,
4637  /* 0  1            5            9            =       */
4638    52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND,
4639  /*    A                                            O */
4640    ND, 0, 1, 2,  3, 4, 5, 6,  7, 8, 9,10, 11,12,13,14,
4641  /* P                               Z                 */
4642    15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND,
4643  /*    a                                            o */
4644    ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
4645  /* p                               z                 */
4646    41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND
4647};
4648
4649static const char b64Numerals[64+1]
4650= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4651
4652#define BX_DV_PROTO(c) \
4653  ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80)
4654#define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80)
4655#define IS_BX_WS(bdp) ((bdp)==WS)
4656#define IS_BX_PAD(bdp) ((bdp)==PC)
4657#define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)])
4658/* Width of base64 lines. Should be an integer multiple of 4. */
4659#define B64_DARK_MAX 72
4660
4661/* Encode a byte buffer into base64 text with linefeeds appended to limit
4662** encoded group lengths to B64_DARK_MAX or to terminate the last group.
4663*/
4664static char* toBase64( u8 *pIn, int nbIn, char *pOut ){
4665  int nCol = 0;
4666  while( nbIn >= 3 ){
4667    /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */
4668    pOut[0] = BX_NUMERAL(pIn[0]>>2);
4669    pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f);
4670    pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6));
4671    pOut[3] = BX_NUMERAL(pIn[2]&0x3f);
4672    pOut += 4;
4673    nbIn -= 3;
4674    pIn += 3;
4675    if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){
4676      *pOut++ = '\n';
4677      nCol = 0;
4678    }
4679  }
4680  if( nbIn > 0 ){
4681    signed char nco = nbIn+1;
4682    int nbe;
4683    unsigned long qv = *pIn++;
4684    for( nbe=1; nbe<3; ++nbe ){
4685      qv <<= 8;
4686      if( nbe<nbIn ) qv |= *pIn++;
4687    }
4688    for( nbe=3; nbe>=0; --nbe ){
4689      char ce = (nbe<nco)? BX_NUMERAL((u8)(qv & 0x3f)) : PAD_CHAR;
4690      qv >>= 6;
4691      pOut[nbe] = ce;
4692    }
4693    pOut += 4;
4694    *pOut++ = '\n';
4695  }
4696  *pOut = 0;
4697  return pOut;
4698}
4699
4700/* Skip over text which is not base64 numeral(s). */
4701static char * skipNonB64( char *s, int nc ){
4702  char c;
4703  while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s;
4704  return s;
4705}
4706
4707/* Decode base64 text into a byte buffer. */
4708static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){
4709  if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
4710  while( ncIn>0 && *pIn!=PAD_CHAR ){
4711    static signed char nboi[] = { 0, 0, 1, 2, 3 };
4712    char *pUse = skipNonB64(pIn, ncIn);
4713    unsigned long qv = 0L;
4714    int nti, nbo, nac;
4715    ncIn -= (pUse - pIn);
4716    pIn = pUse;
4717    nti = (ncIn>4)? 4 : ncIn;
4718    ncIn -= nti;
4719    nbo = nboi[nti];
4720    if( nbo==0 ) break;
4721    for( nac=0; nac<4; ++nac ){
4722      char c = (nac<nti)? *pIn++ : b64Numerals[0];
4723      u8 bdp = BX_DV_PROTO(c);
4724      switch( bdp ){
4725      case ND:
4726        /*  Treat dark non-digits as pad, but they terminate decode too. */
4727        ncIn = 0;
4728        deliberate_fall_through;
4729      case WS:
4730        /* Treat whitespace as pad and terminate this group.*/
4731        nti = nac;
4732        deliberate_fall_through;
4733      case PC:
4734        bdp = 0;
4735        --nbo;
4736        deliberate_fall_through;
4737      default: /* bdp is the digit value. */
4738        qv = qv<<6 | bdp;
4739        break;
4740      }
4741    }
4742    switch( nbo ){
4743    case 3:
4744      pOut[2] = (qv) & 0xff;
4745    case 2:
4746      pOut[1] = (qv>>8) & 0xff;
4747    case 1:
4748      pOut[0] = (qv>>16) & 0xff;
4749    }
4750    pOut += nbo;
4751  }
4752  return pOut;
4753}
4754
4755/* This function does the work for the SQLite base64(x) UDF. */
4756static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){
4757  int nb, nc, nv = sqlite3_value_bytes(av[0]);
4758  int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
4759                            SQLITE_LIMIT_LENGTH, -1);
4760  char *cBuf;
4761  u8 *bBuf;
4762  assert(na==1);
4763  switch( sqlite3_value_type(av[0]) ){
4764  case SQLITE_BLOB:
4765    nb = nv;
4766    nc = 4*(nv+2/3); /* quads needed */
4767    nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */
4768    if( nvMax < nc ){
4769      sqlite3_result_error(context, "blob expanded to base64 too big", -1);
4770      return;
4771    }
4772    bBuf = (u8*)sqlite3_value_blob(av[0]);
4773    if( !bBuf ){
4774      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4775        goto memFail;
4776      }
4777      sqlite3_result_text(context,"",-1,SQLITE_STATIC);
4778      break;
4779    }
4780    cBuf = sqlite3_malloc(nc);
4781    if( !cBuf ) goto memFail;
4782    nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf);
4783    sqlite3_result_text(context, cBuf, nc, sqlite3_free);
4784    break;
4785  case SQLITE_TEXT:
4786    nc = nv;
4787    nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */
4788    if( nvMax < nb ){
4789      sqlite3_result_error(context, "blob from base64 may be too big", -1);
4790      return;
4791    }else if( nb<1 ){
4792      nb = 1;
4793    }
4794    cBuf = (char *)sqlite3_value_text(av[0]);
4795    if( !cBuf ){
4796      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
4797        goto memFail;
4798      }
4799      sqlite3_result_zeroblob(context, 0);
4800      break;
4801    }
4802    bBuf = sqlite3_malloc(nb);
4803    if( !bBuf ) goto memFail;
4804    nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf);
4805    sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
4806    break;
4807  default:
4808    sqlite3_result_error(context, "base64 accepts only blob or text", -1);
4809    return;
4810  }
4811  return;
4812 memFail:
4813  sqlite3_result_error(context, "base64 OOM", -1);
4814}
4815
4816/*
4817** Establish linkage to running SQLite library.
4818*/
4819#ifndef SQLITE_SHELL_EXTFUNCS
4820#ifdef _WIN32
4821
4822#endif
4823int sqlite3_base_init
4824#else
4825static int sqlite3_base64_init
4826#endif
4827(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
4828  SQLITE_EXTENSION_INIT2(pApi);
4829  (void)pzErr;
4830  return sqlite3_create_function
4831    (db, "base64", 1,
4832     SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
4833     0, base64, 0, 0);
4834}
4835
4836/*
4837** Define some macros to allow this extension to be built into the shell
4838** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
4839** allows shell.c, as distributed, to have this extension built in.
4840*/
4841#define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0)
4842#define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
4843
4844/************************* End ../ext/misc/base64.c ********************/
4845#undef sqlite3_base_init
4846#define sqlite3_base_init sqlite3_base85_init
4847#define OMIT_BASE85_CHECKER
4848/************************* Begin ../ext/misc/base85.c ******************/
4849/*
4850** 2022-11-16
4851**
4852** The author disclaims copyright to this source code.  In place of
4853** a legal notice, here is a blessing:
4854**
4855**    May you do good and not evil.
4856**    May you find forgiveness for yourself and forgive others.
4857**    May you share freely, never taking more than you give.
4858**
4859*************************************************************************
4860**
4861** This is a utility for converting binary to base85 or vice-versa.
4862** It can be built as a standalone program or an SQLite3 extension.
4863**
4864** Much like base64 representations, base85 can be sent through a
4865** sane USASCII channel unmolested. It also plays nicely in CSV or
4866** written as TCL brace-enclosed literals or SQL string literals.
4867** It is not suited for unmodified use in XML-like documents.
4868**
4869** The encoding used resembles Ascii85, but was devised by the author
4870** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85
4871** variant sources existed, in the 1984 timeframe on a VAX mainframe.
4872** Further, this is an independent implementation of a base85 system.
4873** Hence, the author has rightfully put this into the public domain.
4874**
4875** Base85 numerals are taken from the set of 7-bit USASCII codes,
4876** excluding control characters and Space ! " ' ( ) { | } ~ Del
4877** in code order representing digit values 0 to 84 (base 10.)
4878**
4879** Groups of 4 bytes, interpreted as big-endian 32-bit values,
4880** are represented as 5-digit base85 numbers with MS to LS digit
4881** order. Groups of 1-3 bytes are represented with 2-4 digits,
4882** still big-endian but 8-24 bit values. (Using big-endian yields
4883** the simplest transition to byte groups smaller than 4 bytes.
4884** These byte groups can also be considered base-256 numbers.)
4885** Groups of 0 bytes are represented with 0 digits and vice-versa.
4886** No pad characters are used; Encoded base85 numeral sequence
4887** (aka "group") length maps 1-to-1 to the decoded binary length.
4888**
4889** Any character not in the base85 numeral set delimits groups.
4890** When base85 is streamed or stored in containers of indefinite
4891** size, newline is used to separate it into sub-sequences of no
4892** more than 80 digits so that fgets() can be used to read it.
4893**
4894** Length limitations are not imposed except that the runtime
4895** SQLite string or blob length limits are respected. Otherwise,
4896** any length binary sequence can be represented and recovered.
4897** Base85 sequences can be concatenated by separating them with
4898** a non-base85 character; the conversion to binary will then
4899** be the concatenation of the represented binary sequences.
4900
4901** The standalone program either converts base85 on stdin to create
4902** a binary file or converts a binary file to base85 on stdout.
4903** Read or make it blurt its help for invocation details.
4904**
4905** The SQLite3 extension creates a function, base85(x), which will
4906** either convert text base85 to a blob or a blob to text base85
4907** and return the result (or throw an error for other types.)
4908** Unless built with OMIT_BASE85_CHECKER defined, it also creates a
4909** function, is_base85(t), which returns 1 iff the text t contains
4910** nothing other than base85 numerals and whitespace, or 0 otherwise.
4911**
4912** To build the extension:
4913** Set shell variable SQDIR=<your favorite SQLite checkout directory>
4914** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted.
4915** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c
4916** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c
4917** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c
4918** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll
4919**
4920** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg.
4921** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85
4922** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c
4923** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c
4924*/
4925
4926#include <stdio.h>
4927#include <memory.h>
4928#include <string.h>
4929#include <assert.h>
4930#ifndef OMIT_BASE85_CHECKER
4931# include <ctype.h>
4932#endif
4933
4934#ifndef BASE85_STANDALONE
4935
4936/* # include "sqlite3ext.h" */
4937
4938SQLITE_EXTENSION_INIT1;
4939
4940#else
4941
4942# ifdef _WIN32
4943#  include <io.h>
4944#  include <fcntl.h>
4945# else
4946#  define setmode(fd,m)
4947# endif
4948
4949static char *zHelp =
4950  "Usage: base85 <dirFlag> <binFile>\n"
4951  " <dirFlag> is either -r to read or -w to write <binFile>,\n"
4952  "   content to be converted to/from base85 on stdout/stdin.\n"
4953  " <binFile> names a binary file to be rendered or created.\n"
4954  "   Or, the name '-' refers to the stdin or stdout stream.\n"
4955  ;
4956
4957static void sayHelp(){
4958  printf("%s", zHelp);
4959}
4960#endif
4961
4962#ifndef U8_TYPEDEF
4963/* typedef unsigned char u8; */
4964#define U8_TYPEDEF
4965#endif
4966
4967/* Classify c according to interval within USASCII set w.r.t. base85
4968 * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not.
4969 */
4970#define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z'))
4971
4972/* Provide digitValue to b85Numeral offset as a function of above class. */
4973static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 };
4974#define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)]
4975
4976/* Say whether c is a base85 numeral. */
4977#define IS_B85( c ) (B85_CLASS(c) & 1)
4978
4979#if 0 /* Not used, */
4980static u8 base85DigitValue( char c ){
4981  u8 dv = (u8)(c - '#');
4982  if( dv>87 ) return 0xff;
4983  return (dv > 3)? dv-3 : dv;
4984}
4985#endif
4986
4987/* Width of base64 lines. Should be an integer multiple of 5. */
4988#define B85_DARK_MAX 80
4989
4990
4991static char * skipNonB85( char *s, int nc ){
4992  char c;
4993  while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s;
4994  return s;
4995}
4996
4997/* Convert small integer, known to be in 0..84 inclusive, to base85 numeral.
4998 * Do not use the macro form with argument expression having a side-effect.*/
4999#if 0
5000static char base85Numeral( u8 b ){
5001  return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*');
5002}
5003#else
5004# define base85Numeral( dn )\
5005  ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*')))
5006#endif
5007
5008static char *putcs(char *pc, char *s){
5009  char c;
5010  while( (c = *s++)!=0 ) *pc++ = c;
5011  return pc;
5012}
5013
5014/* Encode a byte buffer into base85 text. If pSep!=0, it's a C string
5015** to be appended to encoded groups to limit their length to B85_DARK_MAX
5016** or to terminate the last group (to aid concatenation.)
5017*/
5018static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){
5019  int nCol = 0;
5020  while( nbIn >= 4 ){
5021    int nco = 5;
5022    unsigned long qbv = (((unsigned long)pIn[0])<<24) |
5023                        (pIn[1]<<16) | (pIn[2]<<8) | pIn[3];
5024    while( nco > 0 ){
5025      unsigned nqv = (unsigned)(qbv/85UL);
5026      unsigned char dv = qbv - 85UL*nqv;
5027      qbv = nqv;
5028      pOut[--nco] = base85Numeral(dv);
5029    }
5030    nbIn -= 4;
5031    pIn += 4;
5032    pOut += 5;
5033    if( pSep && (nCol += 5)>=B85_DARK_MAX ){
5034      pOut = putcs(pOut, pSep);
5035      nCol = 0;
5036    }
5037  }
5038  if( nbIn > 0 ){
5039    int nco = nbIn + 1;
5040    unsigned long qv = *pIn++;
5041    int nbe = 1;
5042    while( nbe++ < nbIn ){
5043      qv = (qv<<8) | *pIn++;
5044    }
5045    nCol += nco;
5046    while( nco > 0 ){
5047      u8 dv = (u8)(qv % 85);
5048      qv /= 85;
5049      pOut[--nco] = base85Numeral(dv);
5050    }
5051    pOut += (nbIn+1);
5052  }
5053  if( pSep && nCol>0 ) pOut = putcs(pOut, pSep);
5054  *pOut = 0;
5055  return pOut;
5056}
5057
5058/* Decode base85 text into a byte buffer. */
5059static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){
5060  if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn;
5061  while( ncIn>0 ){
5062    static signed char nboi[] = { 0, 0, 1, 2, 3, 4 };
5063    char *pUse = skipNonB85(pIn, ncIn);
5064    unsigned long qv = 0L;
5065    int nti, nbo;
5066    ncIn -= (pUse - pIn);
5067    pIn = pUse;
5068    nti = (ncIn>5)? 5 : ncIn;
5069    nbo = nboi[nti];
5070    if( nbo==0 ) break;
5071    while( nti>0 ){
5072      char c = *pIn++;
5073      u8 cdo = B85_DNOS(c);
5074      --ncIn;
5075      if( cdo==0 ) break;
5076      qv = 85 * qv + (c - cdo);
5077      --nti;
5078    }
5079    nbo -= nti; /* Adjust for early (non-digit) end of group. */
5080    switch( nbo ){
5081    case 4:
5082      *pOut++ = (qv >> 24)&0xff;
5083    case 3:
5084      *pOut++ = (qv >> 16)&0xff;
5085    case 2:
5086      *pOut++ = (qv >> 8)&0xff;
5087    case 1:
5088      *pOut++ = qv&0xff;
5089    case 0:
5090      break;
5091    }
5092  }
5093  return pOut;
5094}
5095
5096#ifndef OMIT_BASE85_CHECKER
5097/* Say whether input char sequence is all (base85 and/or whitespace).*/
5098static int allBase85( char *p, int len ){
5099  char c;
5100  while( len-- > 0 && (c = *p++) != 0 ){
5101    if( !IS_B85(c) && !isspace(c) ) return 0;
5102  }
5103  return 1;
5104}
5105#endif
5106
5107#ifndef BASE85_STANDALONE
5108
5109# ifndef OMIT_BASE85_CHECKER
5110/* This function does the work for the SQLite is_base85(t) UDF. */
5111static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5112  assert(na==1);
5113  switch( sqlite3_value_type(av[0]) ){
5114  case SQLITE_TEXT:
5115    {
5116      int rv = allBase85( (char *)sqlite3_value_text(av[0]),
5117                          sqlite3_value_bytes(av[0]) );
5118      sqlite3_result_int(context, rv);
5119    }
5120    break;
5121  case SQLITE_NULL:
5122    sqlite3_result_null(context);
5123    break;
5124  default:
5125    sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1);
5126    return;
5127  }
5128}
5129# endif
5130
5131/* This function does the work for the SQLite base85(x) UDF. */
5132static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){
5133  int nb, nc, nv = sqlite3_value_bytes(av[0]);
5134  int nvMax = sqlite3_limit(sqlite3_context_db_handle(context),
5135                            SQLITE_LIMIT_LENGTH, -1);
5136  char *cBuf;
5137  u8 *bBuf;
5138  assert(na==1);
5139  switch( sqlite3_value_type(av[0]) ){
5140  case SQLITE_BLOB:
5141    nb = nv;
5142    /*    ulongs    tail   newlines  tailenc+nul*/
5143    nc = 5*(nv/4) + nv%4 + nv/64+1 + 2;
5144    if( nvMax < nc ){
5145      sqlite3_result_error(context, "blob expanded to base85 too big", -1);
5146      return;
5147    }
5148    bBuf = (u8*)sqlite3_value_blob(av[0]);
5149    if( !bBuf ){
5150      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5151        goto memFail;
5152      }
5153      sqlite3_result_text(context,"",-1,SQLITE_STATIC);
5154      break;
5155    }
5156    cBuf = sqlite3_malloc(nc);
5157    if( !cBuf ) goto memFail;
5158    nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf);
5159    sqlite3_result_text(context, cBuf, nc, sqlite3_free);
5160    break;
5161  case SQLITE_TEXT:
5162    nc = nv;
5163    nb = 4*(nv/5) + nv%5; /* may overestimate */
5164    if( nvMax < nb ){
5165      sqlite3_result_error(context, "blob from base85 may be too big", -1);
5166      return;
5167    }else if( nb<1 ){
5168      nb = 1;
5169    }
5170    cBuf = (char *)sqlite3_value_text(av[0]);
5171    if( !cBuf ){
5172      if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){
5173        goto memFail;
5174      }
5175      sqlite3_result_zeroblob(context, 0);
5176      break;
5177    }
5178    bBuf = sqlite3_malloc(nb);
5179    if( !bBuf ) goto memFail;
5180    nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf);
5181    sqlite3_result_blob(context, bBuf, nb, sqlite3_free);
5182    break;
5183  default:
5184    sqlite3_result_error(context, "base85 accepts only blob or text.", -1);
5185    return;
5186  }
5187  return;
5188 memFail:
5189  sqlite3_result_error(context, "base85 OOM", -1);
5190}
5191
5192/*
5193** Establish linkage to running SQLite library.
5194*/
5195#ifndef SQLITE_SHELL_EXTFUNCS
5196#ifdef _WIN32
5197
5198#endif
5199int sqlite3_base_init
5200#else
5201static int sqlite3_base85_init
5202#endif
5203(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){
5204  SQLITE_EXTENSION_INIT2(pApi);
5205  (void)pzErr;
5206# ifndef OMIT_BASE85_CHECKER
5207  {
5208    int rc = sqlite3_create_function
5209      (db, "is_base85", 1,
5210       SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8,
5211       0, is_base85, 0, 0);
5212    if( rc!=SQLITE_OK ) return rc;
5213  }
5214# endif
5215  return sqlite3_create_function
5216    (db, "base85", 1,
5217     SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8,
5218     0, base85, 0, 0);
5219}
5220
5221/*
5222** Define some macros to allow this extension to be built into the shell
5223** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This
5224** allows shell.c, as distributed, to have this extension built in.
5225*/
5226# define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0)
5227# define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */
5228
5229#else /* standalone program */
5230
5231int main(int na, char *av[]){
5232  int cin;
5233  int rc = 0;
5234  u8 bBuf[4*(B85_DARK_MAX/5)];
5235  char cBuf[5*(sizeof(bBuf)/4)+2];
5236  size_t nio;
5237# ifndef OMIT_BASE85_CHECKER
5238  int b85Clean = 1;
5239# endif
5240  char rw;
5241  FILE *fb = 0, *foc = 0;
5242  char fmode[3] = "xb";
5243  if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){
5244    sayHelp();
5245    return 0;
5246  }
5247  fmode[0] = rw;
5248  if( av[2][0]=='-' && av[2][1]==0 ){
5249    switch( rw ){
5250    case 'r':
5251      fb = stdin;
5252      setmode(fileno(stdin), O_BINARY);
5253      break;
5254    case 'w':
5255      fb = stdout;
5256      setmode(fileno(stdout), O_BINARY);
5257      break;
5258    }
5259  }else{
5260    fb = fopen(av[2], fmode);
5261    foc = fb;
5262  }
5263  if( !fb ){
5264    fprintf(stderr, "Cannot open %s for %c\n", av[2], rw);
5265    rc = 1;
5266  }else{
5267    switch( rw ){
5268    case 'r':
5269      while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){
5270        toBase85( bBuf, (int)nio, cBuf, 0 );
5271        fprintf(stdout, "%s\n", cBuf);
5272      }
5273      break;
5274    case 'w':
5275      while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){
5276        int nc = strlen(cBuf);
5277        size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf;
5278        if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1;
5279# ifndef OMIT_BASE85_CHECKER
5280        b85Clean &= allBase85( cBuf, nc );
5281# endif
5282      }
5283      break;
5284    default:
5285      sayHelp();
5286      rc = 1;
5287    }
5288    if( foc ) fclose(foc);
5289  }
5290# ifndef OMIT_BASE85_CHECKER
5291  if( !b85Clean ){
5292    fprintf(stderr, "Base85 input had non-base85 dark or control content.\n");
5293  }
5294# endif
5295  return rc;
5296}
5297
5298#endif
5299
5300/************************* End ../ext/misc/base85.c ********************/
5301/************************* Begin ../ext/misc/ieee754.c ******************/
5302/*
5303** 2013-04-17
5304**
5305** The author disclaims copyright to this source code.  In place of
5306** a legal notice, here is a blessing:
5307**
5308**    May you do good and not evil.
5309**    May you find forgiveness for yourself and forgive others.
5310**    May you share freely, never taking more than you give.
5311**
5312******************************************************************************
5313**
5314** This SQLite extension implements functions for the exact display
5315** and input of IEEE754 Binary64 floating-point numbers.
5316**
5317**   ieee754(X)
5318**   ieee754(Y,Z)
5319**
5320** In the first form, the value X should be a floating-point number.
5321** The function will return a string of the form 'ieee754(Y,Z)' where
5322** Y and Z are integers such that X==Y*pow(2,Z).
5323**
5324** In the second form, Y and Z are integers which are the mantissa and
5325** base-2 exponent of a new floating point number.  The function returns
5326** a floating-point value equal to Y*pow(2,Z).
5327**
5328** Examples:
5329**
5330**     ieee754(2.0)             ->     'ieee754(2,0)'
5331**     ieee754(45.25)           ->     'ieee754(181,-2)'
5332**     ieee754(2, 0)            ->     2.0
5333**     ieee754(181, -2)         ->     45.25
5334**
5335** Two additional functions break apart the one-argument ieee754()
5336** result into separate integer values:
5337**
5338**     ieee754_mantissa(45.25)  ->     181
5339**     ieee754_exponent(45.25)  ->     -2
5340**
5341** These functions convert binary64 numbers into blobs and back again.
5342**
5343**     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
5344**     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
5345**
5346** In all single-argument functions, if the argument is an 8-byte blob
5347** then that blob is interpreted as a big-endian binary64 value.
5348**
5349**
5350** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
5351** -----------------------------------------------
5352**
5353** This extension in combination with the separate 'decimal' extension
5354** can be used to compute the exact decimal representation of binary64
5355** values.  To begin, first compute a table of exponent values:
5356**
5357**    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
5358**    WITH RECURSIVE c(x,v) AS (
5359**      VALUES(0,'1')
5360**      UNION ALL
5361**      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
5362**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5363**    WITH RECURSIVE c(x,v) AS (
5364**      VALUES(-1,'0.5')
5365**      UNION ALL
5366**      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
5367**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
5368**
5369** Then, to compute the exact decimal representation of a floating
5370** point value (the value 47.49 is used in the example) do:
5371**
5372**    WITH c(n) AS (VALUES(47.49))
5373**          ---------------^^^^^---- Replace with whatever you want
5374**    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
5375**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
5376**
5377** Here is a query to show various boundry values for the binary64
5378** number format:
5379**
5380**    WITH c(name,bin) AS (VALUES
5381**       ('minimum positive value',        x'0000000000000001'),
5382**       ('maximum subnormal value',       x'000fffffffffffff'),
5383**       ('mininum positive nornal value', x'0010000000000000'),
5384**       ('maximum value',                 x'7fefffffffffffff'))
5385**    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
5386**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
5387**
5388*/
5389/* #include "sqlite3ext.h" */
5390SQLITE_EXTENSION_INIT1
5391#include <assert.h>
5392#include <string.h>
5393
5394/* Mark a function parameter as unused, to suppress nuisance compiler
5395** warnings. */
5396#ifndef UNUSED_PARAMETER
5397# define UNUSED_PARAMETER(X)  (void)(X)
5398#endif
5399
5400/*
5401** Implementation of the ieee754() function
5402*/
5403static void ieee754func(
5404  sqlite3_context *context,
5405  int argc,
5406  sqlite3_value **argv
5407){
5408  if( argc==1 ){
5409    sqlite3_int64 m, a;
5410    double r;
5411    int e;
5412    int isNeg;
5413    char zResult[100];
5414    assert( sizeof(m)==sizeof(r) );
5415    if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5416     && sqlite3_value_bytes(argv[0])==sizeof(r)
5417    ){
5418      const unsigned char *x = sqlite3_value_blob(argv[0]);
5419      unsigned int i;
5420      sqlite3_uint64 v = 0;
5421      for(i=0; i<sizeof(r); i++){
5422        v = (v<<8) | x[i];
5423      }
5424      memcpy(&r, &v, sizeof(r));
5425    }else{
5426      r = sqlite3_value_double(argv[0]);
5427    }
5428    if( r<0.0 ){
5429      isNeg = 1;
5430      r = -r;
5431    }else{
5432      isNeg = 0;
5433    }
5434    memcpy(&a,&r,sizeof(a));
5435    if( a==0 ){
5436      e = 0;
5437      m = 0;
5438    }else{
5439      e = a>>52;
5440      m = a & ((((sqlite3_int64)1)<<52)-1);
5441      if( e==0 ){
5442        m <<= 1;
5443      }else{
5444        m |= ((sqlite3_int64)1)<<52;
5445      }
5446      while( e<1075 && m>0 && (m&1)==0 ){
5447        m >>= 1;
5448        e++;
5449      }
5450      if( isNeg ) m = -m;
5451    }
5452    switch( *(int*)sqlite3_user_data(context) ){
5453      case 0:
5454        sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
5455                         m, e-1075);
5456        sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
5457        break;
5458      case 1:
5459        sqlite3_result_int64(context, m);
5460        break;
5461      case 2:
5462        sqlite3_result_int(context, e-1075);
5463        break;
5464    }
5465  }else{
5466    sqlite3_int64 m, e, a;
5467    double r;
5468    int isNeg = 0;
5469    m = sqlite3_value_int64(argv[0]);
5470    e = sqlite3_value_int64(argv[1]);
5471
5472    /* Limit the range of e.  Ticket 22dea1cfdb9151e4 2021-03-02 */
5473    if( e>10000 ){
5474      e = 10000;
5475    }else if( e<-10000 ){
5476      e = -10000;
5477    }
5478
5479    if( m<0 ){
5480      isNeg = 1;
5481      m = -m;
5482      if( m<0 ) return;
5483    }else if( m==0 && e>-1000 && e<1000 ){
5484      sqlite3_result_double(context, 0.0);
5485      return;
5486    }
5487    while( (m>>32)&0xffe00000 ){
5488      m >>= 1;
5489      e++;
5490    }
5491    while( m!=0 && ((m>>32)&0xfff00000)==0 ){
5492      m <<= 1;
5493      e--;
5494    }
5495    e += 1075;
5496    if( e<=0 ){
5497      /* Subnormal */
5498      if( 1-e >= 64 ){
5499        m = 0;
5500      }else{
5501        m >>= 1-e;
5502      }
5503      e = 0;
5504    }else if( e>0x7ff ){
5505      e = 0x7ff;
5506    }
5507    a = m & ((((sqlite3_int64)1)<<52)-1);
5508    a |= e<<52;
5509    if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
5510    memcpy(&r, &a, sizeof(r));
5511    sqlite3_result_double(context, r);
5512  }
5513}
5514
5515/*
5516** Functions to convert between blobs and floats.
5517*/
5518static void ieee754func_from_blob(
5519  sqlite3_context *context,
5520  int argc,
5521  sqlite3_value **argv
5522){
5523  UNUSED_PARAMETER(argc);
5524  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
5525   && sqlite3_value_bytes(argv[0])==sizeof(double)
5526  ){
5527    double r;
5528    const unsigned char *x = sqlite3_value_blob(argv[0]);
5529    unsigned int i;
5530    sqlite3_uint64 v = 0;
5531    for(i=0; i<sizeof(r); i++){
5532      v = (v<<8) | x[i];
5533    }
5534    memcpy(&r, &v, sizeof(r));
5535    sqlite3_result_double(context, r);
5536  }
5537}
5538static void ieee754func_to_blob(
5539  sqlite3_context *context,
5540  int argc,
5541  sqlite3_value **argv
5542){
5543  UNUSED_PARAMETER(argc);
5544  if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
5545   || sqlite3_value_type(argv[0])==SQLITE_INTEGER
5546  ){
5547    double r = sqlite3_value_double(argv[0]);
5548    sqlite3_uint64 v;
5549    unsigned char a[sizeof(r)];
5550    unsigned int i;
5551    memcpy(&v, &r, sizeof(r));
5552    for(i=1; i<=sizeof(r); i++){
5553      a[sizeof(r)-i] = v&0xff;
5554      v >>= 8;
5555    }
5556    sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
5557  }
5558}
5559
5560/*
5561** SQL Function:   ieee754_inc(r,N)
5562**
5563** Move the floating point value r by N quantums and return the new
5564** values.
5565**
5566** Behind the scenes: this routine merely casts r into a 64-bit unsigned
5567** integer, adds N, then casts the value back into float.
5568**
5569** Example:  To find the smallest positive number:
5570**
5571**     SELECT ieee754_inc(0.0,+1);
5572*/
5573static void ieee754inc(
5574  sqlite3_context *context,
5575  int argc,
5576  sqlite3_value **argv
5577){
5578  double r;
5579  sqlite3_int64 N;
5580  sqlite3_uint64 m1, m2;
5581  double r2;
5582  UNUSED_PARAMETER(argc);
5583  r = sqlite3_value_double(argv[0]);
5584  N = sqlite3_value_int64(argv[1]);
5585  memcpy(&m1, &r, 8);
5586  m2 = m1 + N;
5587  memcpy(&r2, &m2, 8);
5588  sqlite3_result_double(context, r2);
5589}
5590
5591
5592#ifdef _WIN32
5593
5594#endif
5595int sqlite3_ieee_init(
5596  sqlite3 *db,
5597  char **pzErrMsg,
5598  const sqlite3_api_routines *pApi
5599){
5600  static const struct {
5601    char *zFName;
5602    int nArg;
5603    int iAux;
5604    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
5605  } aFunc[] = {
5606    { "ieee754",           1,   0, ieee754func },
5607    { "ieee754",           2,   0, ieee754func },
5608    { "ieee754_mantissa",  1,   1, ieee754func },
5609    { "ieee754_exponent",  1,   2, ieee754func },
5610    { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
5611    { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
5612    { "ieee754_inc",       2,   0, ieee754inc  },
5613  };
5614  unsigned int i;
5615  int rc = SQLITE_OK;
5616  SQLITE_EXTENSION_INIT2(pApi);
5617  (void)pzErrMsg;  /* Unused parameter */
5618  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
5619    rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,
5620                               SQLITE_UTF8|SQLITE_INNOCUOUS,
5621                               (void*)&aFunc[i].iAux,
5622                               aFunc[i].xFunc, 0, 0);
5623  }
5624  return rc;
5625}
5626
5627/************************* End ../ext/misc/ieee754.c ********************/
5628/************************* Begin ../ext/misc/series.c ******************/
5629/*
5630** 2015-08-18, 2023-04-28
5631**
5632** The author disclaims copyright to this source code.  In place of
5633** a legal notice, here is a blessing:
5634**
5635**    May you do good and not evil.
5636**    May you find forgiveness for yourself and forgive others.
5637**    May you share freely, never taking more than you give.
5638**
5639*************************************************************************
5640**
5641** This file demonstrates how to create a table-valued-function using
5642** a virtual table.  This demo implements the generate_series() function
5643** which gives the same results as the eponymous function in PostgreSQL,
5644** within the limitation that its arguments are signed 64-bit integers.
5645**
5646** Considering its equivalents to generate_series(start,stop,step): A
5647** value V[n] sequence is produced for integer n ascending from 0 where
5648**  ( V[n] == start + n * step  &&  sgn(V[n] - stop) * sgn(step) >= 0 )
5649** for each produced value (independent of production time ordering.)
5650**
5651** All parameters must be either integer or convertable to integer.
5652** The start parameter is required.
5653** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff)
5654** The step parameter defaults to 1 and 0 is treated as 1.
5655**
5656** Examples:
5657**
5658**      SELECT * FROM generate_series(0,100,5);
5659**
5660** The query above returns integers from 0 through 100 counting by steps
5661** of 5.
5662**
5663**      SELECT * FROM generate_series(0,100);
5664**
5665** Integers from 0 through 100 with a step size of 1.
5666**
5667**      SELECT * FROM generate_series(20) LIMIT 10;
5668**
5669** Integers 20 through 29.
5670**
5671**      SELECT * FROM generate_series(0,-100,-5);
5672**
5673** Integers 0 -5 -10 ... -100.
5674**
5675**      SELECT * FROM generate_series(0,-1);
5676**
5677** Empty sequence.
5678**
5679** HOW IT WORKS
5680**
5681** The generate_series "function" is really a virtual table with the
5682** following schema:
5683**
5684**     CREATE TABLE generate_series(
5685**       value,
5686**       start HIDDEN,
5687**       stop HIDDEN,
5688**       step HIDDEN
5689**     );
5690**
5691** The virtual table also has a rowid, logically equivalent to n+1 where
5692** "n" is the ascending integer in the aforesaid production definition.
5693**
5694** Function arguments in queries against this virtual table are translated
5695** into equality constraints against successive hidden columns.  In other
5696** words, the following pairs of queries are equivalent to each other:
5697**
5698**    SELECT * FROM generate_series(0,100,5);
5699**    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
5700**
5701**    SELECT * FROM generate_series(0,100);
5702**    SELECT * FROM generate_series WHERE start=0 AND stop=100;
5703**
5704**    SELECT * FROM generate_series(20) LIMIT 10;
5705**    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
5706**
5707** The generate_series virtual table implementation leaves the xCreate method
5708** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
5709** TABLE command with "generate_series" as the USING argument.  Instead, there
5710** is a single generate_series virtual table that is always available without
5711** having to be created first.
5712**
5713** The xBestIndex method looks for equality constraints against the hidden
5714** start, stop, and step columns, and if present, it uses those constraints
5715** to bound the sequence of generated values.  If the equality constraints
5716** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
5717** xBestIndex returns a small cost when both start and stop are available,
5718** and a very large cost if either start or stop are unavailable.  This
5719** encourages the query planner to order joins such that the bounds of the
5720** series are well-defined.
5721*/
5722/* #include "sqlite3ext.h" */
5723SQLITE_EXTENSION_INIT1
5724#include <assert.h>
5725#include <string.h>
5726#include <limits.h>
5727
5728#ifndef SQLITE_OMIT_VIRTUALTABLE
5729/*
5730** Return that member of a generate_series(...) sequence whose 0-based
5731** index is ix. The 0th member is given by smBase. The sequence members
5732** progress per ix increment by smStep.
5733*/
5734static sqlite3_int64 genSeqMember(
5735  sqlite3_int64 smBase,
5736  sqlite3_int64 smStep,
5737  sqlite3_uint64 ix
5738){
5739  static const sqlite3_uint64 mxI64 =
5740      ((sqlite3_uint64)0x7fffffff)<<32 | 0xffffffff;
5741  if( ix>=mxI64 ){
5742    /* Get ix into signed i64 range. */
5743    ix -= mxI64;
5744    /* With 2's complement ALU, this next can be 1 step, but is split into
5745     * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */
5746    smBase += (mxI64/2) * smStep;
5747    smBase += (mxI64 - mxI64/2) * smStep;
5748  }
5749  /* Under UBSAN (or on 1's complement machines), must do this last term
5750   * in steps to avoid the dreaded (and harmless) signed multiply overlow. */
5751  if( ix>=2 ){
5752    sqlite3_int64 ix2 = (sqlite3_int64)ix/2;
5753    smBase += ix2*smStep;
5754    ix -= ix2;
5755  }
5756  return smBase + ((sqlite3_int64)ix)*smStep;
5757}
5758
5759/* typedef unsigned char u8; */
5760
5761typedef struct SequenceSpec {
5762  sqlite3_int64 iBase;         /* Starting value ("start") */
5763  sqlite3_int64 iTerm;         /* Given terminal value ("stop") */
5764  sqlite3_int64 iStep;         /* Increment ("step") */
5765  sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */
5766  sqlite3_uint64 uSeqIndexNow; /* Current index during generation */
5767  sqlite3_int64 iValueNow;     /* Current value during generation */
5768  u8 isNotEOF;                 /* Sequence generation not exhausted */
5769  u8 isReversing;              /* Sequence is being reverse generated */
5770} SequenceSpec;
5771
5772/*
5773** Prepare a SequenceSpec for use in generating an integer series
5774** given initialized iBase, iTerm and iStep values. Sequence is
5775** initialized per given isReversing. Other members are computed.
5776*/
5777static void setupSequence( SequenceSpec *pss ){
5778  int bSameSigns;
5779  pss->uSeqIndexMax = 0;
5780  pss->isNotEOF = 0;
5781  bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0);
5782  if( pss->iTerm < pss->iBase ){
5783    sqlite3_uint64 nuspan = 0;
5784    if( bSameSigns ){
5785      nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm);
5786    }else{
5787      /* Under UBSAN (or on 1's complement machines), must do this in steps.
5788       * In this clause, iBase>=0 and iTerm<0 . */
5789      nuspan = 1;
5790      nuspan += pss->iBase;
5791      nuspan += -(pss->iTerm+1);
5792    }
5793    if( pss->iStep<0 ){
5794      pss->isNotEOF = 1;
5795      if( nuspan==ULONG_MAX ){
5796        pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1;
5797      }else if( pss->iStep>LLONG_MIN ){
5798        pss->uSeqIndexMax = nuspan/-pss->iStep;
5799      }
5800    }
5801  }else if( pss->iTerm > pss->iBase ){
5802    sqlite3_uint64 puspan = 0;
5803    if( bSameSigns ){
5804      puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase);
5805    }else{
5806      /* Under UBSAN (or on 1's complement machines), must do this in steps.
5807       * In this clause, iTerm>=0 and iBase<0 . */
5808      puspan = 1;
5809      puspan += pss->iTerm;
5810      puspan += -(pss->iBase+1);
5811    }
5812    if( pss->iStep>0 ){
5813      pss->isNotEOF = 1;
5814      pss->uSeqIndexMax = puspan/pss->iStep;
5815    }
5816  }else if( pss->iTerm == pss->iBase ){
5817      pss->isNotEOF = 1;
5818      pss->uSeqIndexMax = 0;
5819  }
5820  pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0;
5821  pss->iValueNow = (pss->isReversing)
5822    ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax)
5823    : pss->iBase;
5824}
5825
5826/*
5827** Progress sequence generator to yield next value, if any.
5828** Leave its state to either yield next value or be at EOF.
5829** Return whether there is a next value, or 0 at EOF.
5830*/
5831static int progressSequence( SequenceSpec *pss ){
5832  if( !pss->isNotEOF ) return 0;
5833  if( pss->isReversing ){
5834    if( pss->uSeqIndexNow > 0 ){
5835      pss->uSeqIndexNow--;
5836      pss->iValueNow -= pss->iStep;
5837    }else{
5838      pss->isNotEOF = 0;
5839    }
5840  }else{
5841    if( pss->uSeqIndexNow < pss->uSeqIndexMax ){
5842      pss->uSeqIndexNow++;
5843      pss->iValueNow += pss->iStep;
5844    }else{
5845      pss->isNotEOF = 0;
5846    }
5847  }
5848  return pss->isNotEOF;
5849}
5850
5851/* series_cursor is a subclass of sqlite3_vtab_cursor which will
5852** serve as the underlying representation of a cursor that scans
5853** over rows of the result
5854*/
5855typedef struct series_cursor series_cursor;
5856struct series_cursor {
5857  sqlite3_vtab_cursor base;  /* Base class - must be first */
5858  SequenceSpec ss;           /* (this) Derived class data */
5859};
5860
5861/*
5862** The seriesConnect() method is invoked to create a new
5863** series_vtab that describes the generate_series virtual table.
5864**
5865** Think of this routine as the constructor for series_vtab objects.
5866**
5867** All this routine needs to do is:
5868**
5869**    (1) Allocate the series_vtab object and initialize all fields.
5870**
5871**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
5872**        result set of queries against generate_series will look like.
5873*/
5874static int seriesConnect(
5875  sqlite3 *db,
5876  void *pUnused,
5877  int argcUnused, const char *const*argvUnused,
5878  sqlite3_vtab **ppVtab,
5879  char **pzErrUnused
5880){
5881  sqlite3_vtab *pNew;
5882  int rc;
5883
5884/* Column numbers */
5885#define SERIES_COLUMN_VALUE 0
5886#define SERIES_COLUMN_START 1
5887#define SERIES_COLUMN_STOP  2
5888#define SERIES_COLUMN_STEP  3
5889
5890  (void)pUnused;
5891  (void)argcUnused;
5892  (void)argvUnused;
5893  (void)pzErrUnused;
5894  rc = sqlite3_declare_vtab(db,
5895     "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
5896  if( rc==SQLITE_OK ){
5897    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
5898    if( pNew==0 ) return SQLITE_NOMEM;
5899    memset(pNew, 0, sizeof(*pNew));
5900    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
5901  }
5902  return rc;
5903}
5904
5905/*
5906** This method is the destructor for series_cursor objects.
5907*/
5908static int seriesDisconnect(sqlite3_vtab *pVtab){
5909  sqlite3_free(pVtab);
5910  return SQLITE_OK;
5911}
5912
5913/*
5914** Constructor for a new series_cursor object.
5915*/
5916static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
5917  series_cursor *pCur;
5918  (void)pUnused;
5919  pCur = sqlite3_malloc( sizeof(*pCur) );
5920  if( pCur==0 ) return SQLITE_NOMEM;
5921  memset(pCur, 0, sizeof(*pCur));
5922  *ppCursor = &pCur->base;
5923  return SQLITE_OK;
5924}
5925
5926/*
5927** Destructor for a series_cursor.
5928*/
5929static int seriesClose(sqlite3_vtab_cursor *cur){
5930  sqlite3_free(cur);
5931  return SQLITE_OK;
5932}
5933
5934
5935/*
5936** Advance a series_cursor to its next row of output.
5937*/
5938static int seriesNext(sqlite3_vtab_cursor *cur){
5939  series_cursor *pCur = (series_cursor*)cur;
5940  progressSequence( & pCur->ss );
5941  return SQLITE_OK;
5942}
5943
5944/*
5945** Return values of columns for the row at which the series_cursor
5946** is currently pointing.
5947*/
5948static int seriesColumn(
5949  sqlite3_vtab_cursor *cur,   /* The cursor */
5950  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
5951  int i                       /* Which column to return */
5952){
5953  series_cursor *pCur = (series_cursor*)cur;
5954  sqlite3_int64 x = 0;
5955  switch( i ){
5956    case SERIES_COLUMN_START:  x = pCur->ss.iBase; break;
5957    case SERIES_COLUMN_STOP:   x = pCur->ss.iTerm; break;
5958    case SERIES_COLUMN_STEP:   x = pCur->ss.iStep;   break;
5959    default:                   x = pCur->ss.iValueNow;  break;
5960  }
5961  sqlite3_result_int64(ctx, x);
5962  return SQLITE_OK;
5963}
5964
5965#ifndef LARGEST_UINT64
5966#define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32))
5967#endif
5968
5969/*
5970** Return the rowid for the current row, logically equivalent to n+1 where
5971** "n" is the ascending integer in the aforesaid production definition.
5972*/
5973static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
5974  series_cursor *pCur = (series_cursor*)cur;
5975  sqlite3_uint64 n = pCur->ss.uSeqIndexNow;
5976  *pRowid = (sqlite3_int64)((n<LARGEST_UINT64)? n+1 : 0);
5977  return SQLITE_OK;
5978}
5979
5980/*
5981** Return TRUE if the cursor has been moved off of the last
5982** row of output.
5983*/
5984static int seriesEof(sqlite3_vtab_cursor *cur){
5985  series_cursor *pCur = (series_cursor*)cur;
5986  return !pCur->ss.isNotEOF;
5987}
5988
5989/* True to cause run-time checking of the start=, stop=, and/or step=
5990** parameters.  The only reason to do this is for testing the
5991** constraint checking logic for virtual tables in the SQLite core.
5992*/
5993#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
5994# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
5995#endif
5996
5997/*
5998** This method is called to "rewind" the series_cursor object back
5999** to the first row of output.  This method is always called at least
6000** once prior to any call to seriesColumn() or seriesRowid() or
6001** seriesEof().
6002**
6003** The query plan selected by seriesBestIndex is passed in the idxNum
6004** parameter.  (idxStr is not used in this implementation.)  idxNum
6005** is a bitmask showing which constraints are available:
6006**
6007**   0x01:    start=VALUE
6008**   0x02:    stop=VALUE
6009**   0x04:    step=VALUE
6010**   0x08:    descending order
6011**   0x10:    ascending order
6012**   0x20:    LIMIT  VALUE
6013**   0x40:    OFFSET  VALUE
6014**
6015** This routine should initialize the cursor and position it so that it
6016** is pointing at the first row, or pointing off the end of the table
6017** (so that seriesEof() will return true) if the table is empty.
6018*/
6019static int seriesFilter(
6020  sqlite3_vtab_cursor *pVtabCursor,
6021  int idxNum, const char *idxStrUnused,
6022  int argc, sqlite3_value **argv
6023){
6024  series_cursor *pCur = (series_cursor *)pVtabCursor;
6025  int i = 0;
6026  (void)idxStrUnused;
6027  if( idxNum & 0x01 ){
6028    pCur->ss.iBase = sqlite3_value_int64(argv[i++]);
6029  }else{
6030    pCur->ss.iBase = 0;
6031  }
6032  if( idxNum & 0x02 ){
6033    pCur->ss.iTerm = sqlite3_value_int64(argv[i++]);
6034  }else{
6035    pCur->ss.iTerm = 0xffffffff;
6036  }
6037  if( idxNum & 0x04 ){
6038    pCur->ss.iStep = sqlite3_value_int64(argv[i++]);
6039    if( pCur->ss.iStep==0 ){
6040      pCur->ss.iStep = 1;
6041    }else if( pCur->ss.iStep<0 ){
6042      if( (idxNum & 0x10)==0 ) idxNum |= 0x08;
6043    }
6044  }else{
6045    pCur->ss.iStep = 1;
6046  }
6047  if( idxNum & 0x20 ){
6048    sqlite3_int64 iLimit = sqlite3_value_int64(argv[i++]);
6049    sqlite3_int64 iTerm;
6050    if( idxNum & 0x40 ){
6051      sqlite3_int64 iOffset = sqlite3_value_int64(argv[i++]);
6052      if( iOffset>0 ){
6053        pCur->ss.iBase += pCur->ss.iStep*iOffset;
6054      }
6055    }
6056    if( iLimit>=0 ){
6057      iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep;
6058      if( pCur->ss.iStep<0 ){
6059        if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6060      }else{
6061        if( iTerm<pCur->ss.iTerm ) pCur->ss.iTerm = iTerm;
6062      }
6063    }
6064  }
6065  for(i=0; i<argc; i++){
6066    if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
6067      /* If any of the constraints have a NULL value, then return no rows.
6068      ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
6069      pCur->ss.iBase = 1;
6070      pCur->ss.iTerm = 0;
6071      pCur->ss.iStep = 1;
6072      break;
6073    }
6074  }
6075  if( idxNum & 0x08 ){
6076    pCur->ss.isReversing = pCur->ss.iStep > 0;
6077  }else{
6078    pCur->ss.isReversing = pCur->ss.iStep < 0;
6079  }
6080  setupSequence( &pCur->ss );
6081  return SQLITE_OK;
6082}
6083
6084/*
6085** SQLite will invoke this method one or more times while planning a query
6086** that uses the generate_series virtual table.  This routine needs to create
6087** a query plan for each invocation and compute an estimated cost for that
6088** plan.
6089**
6090** In this implementation idxNum is used to represent the
6091** query plan.  idxStr is unused.
6092**
6093** The query plan is represented by bits in idxNum:
6094**
6095**   0x01  start = $value  -- constraint exists
6096**   0x02  stop = $value   -- constraint exists
6097**   0x04  step = $value   -- constraint exists
6098**   0x08  output is in descending order
6099**   0x10  output is in ascending order
6100**   0x20  LIMIT $value    -- constraint exists
6101**   0x40  OFFSET $value   -- constraint exists
6102*/
6103static int seriesBestIndex(
6104  sqlite3_vtab *pVTab,
6105  sqlite3_index_info *pIdxInfo
6106){
6107  int i, j;              /* Loop over constraints */
6108  int idxNum = 0;        /* The query plan bitmask */
6109#ifndef ZERO_ARGUMENT_GENERATE_SERIES
6110  int bStartSeen = 0;    /* EQ constraint seen on the START column */
6111#endif
6112  int unusableMask = 0;  /* Mask of unusable constraints */
6113  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
6114  int aIdx[5];           /* Constraints on start, stop, step, LIMIT, OFFSET */
6115  const struct sqlite3_index_constraint *pConstraint;
6116
6117  /* This implementation assumes that the start, stop, and step columns
6118  ** are the last three columns in the virtual table. */
6119  assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
6120  assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
6121
6122  aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = -1;
6123  pConstraint = pIdxInfo->aConstraint;
6124  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
6125    int iCol;    /* 0 for start, 1 for stop, 2 for step */
6126    int iMask;   /* bitmask for those column */
6127    int op = pConstraint->op;
6128    if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
6129     && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
6130    ){
6131      if( pConstraint->usable==0 ){
6132        /* do nothing */
6133      }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
6134        aIdx[3] = i;
6135        idxNum |= 0x20;
6136      }else{
6137        assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
6138        aIdx[4] = i;
6139        idxNum |= 0x40;
6140      }
6141      continue;
6142    }
6143    if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
6144    iCol = pConstraint->iColumn - SERIES_COLUMN_START;
6145    assert( iCol>=0 && iCol<=2 );
6146    iMask = 1 << iCol;
6147#ifndef ZERO_ARGUMENT_GENERATE_SERIES
6148    if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
6149      bStartSeen = 1;
6150    }
6151#endif
6152    if( pConstraint->usable==0 ){
6153      unusableMask |=  iMask;
6154      continue;
6155    }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
6156      idxNum |= iMask;
6157      aIdx[iCol] = i;
6158    }
6159  }
6160  if( aIdx[3]==0 ){
6161    /* Ignore OFFSET if LIMIT is omitted */
6162    idxNum &= ~0x60;
6163    aIdx[4] = 0;
6164  }
6165  for(i=0; i<5; i++){
6166    if( (j = aIdx[i])>=0 ){
6167      pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
6168      pIdxInfo->aConstraintUsage[j].omit =
6169         !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
6170    }
6171  }
6172  /* The current generate_column() implementation requires at least one
6173  ** argument (the START value).  Legacy versions assumed START=0 if the
6174  ** first argument was omitted.  Compile with -DZERO_ARGUMENT_GENERATE_SERIES
6175  ** to obtain the legacy behavior */
6176#ifndef ZERO_ARGUMENT_GENERATE_SERIES
6177  if( !bStartSeen ){
6178    sqlite3_free(pVTab->zErrMsg);
6179    pVTab->zErrMsg = sqlite3_mprintf(
6180        "first argument to \"generate_series()\" missing or unusable");
6181    return SQLITE_ERROR;
6182  }
6183#endif
6184  if( (unusableMask & ~idxNum)!=0 ){
6185    /* The start, stop, and step columns are inputs.  Therefore if there
6186    ** are unusable constraints on any of start, stop, or step then
6187    ** this plan is unusable */
6188    return SQLITE_CONSTRAINT;
6189  }
6190  if( (idxNum & 0x03)==0x03 ){
6191    /* Both start= and stop= boundaries are available.  This is the
6192    ** the preferred case */
6193    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
6194    pIdxInfo->estimatedRows = 1000;
6195    if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){
6196      if( pIdxInfo->aOrderBy[0].desc ){
6197        idxNum |= 0x08;
6198      }else{
6199        idxNum |= 0x10;
6200      }
6201      pIdxInfo->orderByConsumed = 1;
6202    }
6203  }else if( (idxNum & 0x21)==0x21 ){
6204    /* We have start= and LIMIT */
6205    pIdxInfo->estimatedRows = 2500;
6206  }else{
6207    /* If either boundary is missing, we have to generate a huge span
6208    ** of numbers.  Make this case very expensive so that the query
6209    ** planner will work hard to avoid it. */
6210    pIdxInfo->estimatedRows = 2147483647;
6211  }
6212  pIdxInfo->idxNum = idxNum;
6213  return SQLITE_OK;
6214}
6215
6216/*
6217** This following structure defines all the methods for the
6218** generate_series virtual table.
6219*/
6220static sqlite3_module seriesModule = {
6221  0,                         /* iVersion */
6222  0,                         /* xCreate */
6223  seriesConnect,             /* xConnect */
6224  seriesBestIndex,           /* xBestIndex */
6225  seriesDisconnect,          /* xDisconnect */
6226  0,                         /* xDestroy */
6227  seriesOpen,                /* xOpen - open a cursor */
6228  seriesClose,               /* xClose - close a cursor */
6229  seriesFilter,              /* xFilter - configure scan constraints */
6230  seriesNext,                /* xNext - advance a cursor */
6231  seriesEof,                 /* xEof - check for end of scan */
6232  seriesColumn,              /* xColumn - read data */
6233  seriesRowid,               /* xRowid - read data */
6234  0,                         /* xUpdate */
6235  0,                         /* xBegin */
6236  0,                         /* xSync */
6237  0,                         /* xCommit */
6238  0,                         /* xRollback */
6239  0,                         /* xFindMethod */
6240  0,                         /* xRename */
6241  0,                         /* xSavepoint */
6242  0,                         /* xRelease */
6243  0,                         /* xRollbackTo */
6244  0,                         /* xShadowName */
6245  0                          /* xIntegrity */
6246};
6247
6248#endif /* SQLITE_OMIT_VIRTUALTABLE */
6249
6250#ifdef _WIN32
6251
6252#endif
6253int sqlite3_series_init(
6254  sqlite3 *db,
6255  char **pzErrMsg,
6256  const sqlite3_api_routines *pApi
6257){
6258  int rc = SQLITE_OK;
6259  SQLITE_EXTENSION_INIT2(pApi);
6260#ifndef SQLITE_OMIT_VIRTUALTABLE
6261  if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
6262    *pzErrMsg = sqlite3_mprintf(
6263        "generate_series() requires SQLite 3.8.12 or later");
6264    return SQLITE_ERROR;
6265  }
6266  rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
6267#endif
6268  return rc;
6269}
6270
6271/************************* End ../ext/misc/series.c ********************/
6272/************************* Begin ../ext/misc/regexp.c ******************/
6273/*
6274** 2012-11-13
6275**
6276** The author disclaims copyright to this source code.  In place of
6277** a legal notice, here is a blessing:
6278**
6279**    May you do good and not evil.
6280**    May you find forgiveness for yourself and forgive others.
6281**    May you share freely, never taking more than you give.
6282**
6283******************************************************************************
6284**
6285** The code in this file implements a compact but reasonably
6286** efficient regular-expression matcher for posix extended regular
6287** expressions against UTF8 text.
6288**
6289** This file is an SQLite extension.  It registers a single function
6290** named "regexp(A,B)" where A is the regular expression and B is the
6291** string to be matched.  By registering this function, SQLite will also
6292** then implement the "B regexp A" operator.  Note that with the function
6293** the regular expression comes first, but with the operator it comes
6294** second.
6295**
6296**  The following regular expression syntax is supported:
6297**
6298**     X*      zero or more occurrences of X
6299**     X+      one or more occurrences of X
6300**     X?      zero or one occurrences of X
6301**     X{p,q}  between p and q occurrences of X
6302**     (X)     match X
6303**     X|Y     X or Y
6304**     ^X      X occurring at the beginning of the string
6305**     X$      X occurring at the end of the string
6306**     .       Match any single character
6307**     \c      Character c where c is one of \{}()[]|*+?.
6308**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
6309**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
6310**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
6311**     [abc]   Any single character from the set abc
6312**     [^abc]  Any single character not in the set abc
6313**     [a-z]   Any single character in the range a-z
6314**     [^a-z]  Any single character not in the range a-z
6315**     \b      Word boundary
6316**     \w      Word character.  [A-Za-z0-9_]
6317**     \W      Non-word character
6318**     \d      Digit
6319**     \D      Non-digit
6320**     \s      Whitespace character
6321**     \S      Non-whitespace character
6322**
6323** A nondeterministic finite automaton (NFA) is used for matching, so the
6324** performance is bounded by O(N*M) where N is the size of the regular
6325** expression and M is the size of the input string.  The matcher never
6326** exhibits exponential behavior.  Note that the X{p,q} operator expands
6327** to p copies of X following by q-p copies of X? and that the size of the
6328** regular expression in the O(N*M) performance bound is computed after
6329** this expansion.
6330*/
6331#include <string.h>
6332#include <stdlib.h>
6333/* #include "sqlite3ext.h" */
6334SQLITE_EXTENSION_INIT1
6335
6336/*
6337** The following #defines change the names of some functions implemented in
6338** this file to prevent name collisions with C-library functions of the
6339** same name.
6340*/
6341#define re_match   sqlite3re_match
6342#define re_compile sqlite3re_compile
6343#define re_free    sqlite3re_free
6344
6345/* The end-of-input character */
6346#define RE_EOF            0    /* End of input */
6347#define RE_START  0xfffffff    /* Start of input - larger than an UTF-8 */
6348
6349/* The NFA is implemented as sequence of opcodes taken from the following
6350** set.  Each opcode has a single integer argument.
6351*/
6352#define RE_OP_MATCH       1    /* Match the one character in the argument */
6353#define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
6354#define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
6355#define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
6356#define RE_OP_GOTO        5    /* Jump to opcode at iArg */
6357#define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
6358#define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
6359#define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
6360#define RE_OP_CC_VALUE    9    /* Single value in a character class */
6361#define RE_OP_CC_RANGE   10    /* Range of values in a character class */
6362#define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
6363#define RE_OP_NOTWORD    12    /* Not a perl word character */
6364#define RE_OP_DIGIT      13    /* digit:  [0-9] */
6365#define RE_OP_NOTDIGIT   14    /* Not a digit */
6366#define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
6367#define RE_OP_NOTSPACE   16    /* Not a digit */
6368#define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */
6369#define RE_OP_ATSTART    18    /* Currently at the start of the string */
6370
6371#if defined(SQLITE_DEBUG)
6372/* Opcode names used for symbolic debugging */
6373static const char *ReOpName[] = {
6374  "EOF",
6375  "MATCH",
6376  "ANY",
6377  "ANYSTAR",
6378  "FORK",
6379  "GOTO",
6380  "ACCEPT",
6381  "CC_INC",
6382  "CC_EXC",
6383  "CC_VALUE",
6384  "CC_RANGE",
6385  "WORD",
6386  "NOTWORD",
6387  "DIGIT",
6388  "NOTDIGIT",
6389  "SPACE",
6390  "NOTSPACE",
6391  "BOUNDARY",
6392  "ATSTART",
6393};
6394#endif /* SQLITE_DEBUG */
6395
6396
6397/* Each opcode is a "state" in the NFA */
6398typedef unsigned short ReStateNumber;
6399
6400/* Because this is an NFA and not a DFA, multiple states can be active at
6401** once.  An instance of the following object records all active states in
6402** the NFA.  The implementation is optimized for the common case where the
6403** number of actives states is small.
6404*/
6405typedef struct ReStateSet {
6406  unsigned nState;            /* Number of current states */
6407  ReStateNumber *aState;      /* Current states */
6408} ReStateSet;
6409
6410/* An input string read one character at a time.
6411*/
6412typedef struct ReInput ReInput;
6413struct ReInput {
6414  const unsigned char *z;  /* All text */
6415  int i;                   /* Next byte to read */
6416  int mx;                  /* EOF when i>=mx */
6417};
6418
6419/* A compiled NFA (or an NFA that is in the process of being compiled) is
6420** an instance of the following object.
6421*/
6422typedef struct ReCompiled ReCompiled;
6423struct ReCompiled {
6424  ReInput sIn;                /* Regular expression text */
6425  const char *zErr;           /* Error message to return */
6426  char *aOp;                  /* Operators for the virtual machine */
6427  int *aArg;                  /* Arguments to each operator */
6428  unsigned (*xNextChar)(ReInput*);  /* Next character function */
6429  unsigned char zInit[12];    /* Initial text to match */
6430  int nInit;                  /* Number of bytes in zInit */
6431  unsigned nState;            /* Number of entries in aOp[] and aArg[] */
6432  unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
6433};
6434
6435/* Add a state to the given state set if it is not already there */
6436static void re_add_state(ReStateSet *pSet, int newState){
6437  unsigned i;
6438  for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
6439  pSet->aState[pSet->nState++] = (ReStateNumber)newState;
6440}
6441
6442/* Extract the next unicode character from *pzIn and return it.  Advance
6443** *pzIn to the first byte past the end of the character returned.  To
6444** be clear:  this routine converts utf8 to unicode.  This routine is
6445** optimized for the common case where the next character is a single byte.
6446*/
6447static unsigned re_next_char(ReInput *p){
6448  unsigned c;
6449  if( p->i>=p->mx ) return 0;
6450  c = p->z[p->i++];
6451  if( c>=0x80 ){
6452    if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
6453      c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
6454      if( c<0x80 ) c = 0xfffd;
6455    }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
6456           && (p->z[p->i+1]&0xc0)==0x80 ){
6457      c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
6458      p->i += 2;
6459      if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
6460    }else if( (c&0xf8)==0xf0 && p->i+2<p->mx && (p->z[p->i]&0xc0)==0x80
6461           && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
6462      c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
6463                       | (p->z[p->i+2]&0x3f);
6464      p->i += 3;
6465      if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
6466    }else{
6467      c = 0xfffd;
6468    }
6469  }
6470  return c;
6471}
6472static unsigned re_next_char_nocase(ReInput *p){
6473  unsigned c = re_next_char(p);
6474  if( c>='A' && c<='Z' ) c += 'a' - 'A';
6475  return c;
6476}
6477
6478/* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
6479static int re_word_char(int c){
6480  return (c>='0' && c<='9') || (c>='a' && c<='z')
6481      || (c>='A' && c<='Z') || c=='_';
6482}
6483
6484/* Return true if c is a "digit" character:  [0-9] */
6485static int re_digit_char(int c){
6486  return (c>='0' && c<='9');
6487}
6488
6489/* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
6490static int re_space_char(int c){
6491  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
6492}
6493
6494/* Run a compiled regular expression on the zero-terminated input
6495** string zIn[].  Return true on a match and false if there is no match.
6496*/
6497static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){
6498  ReStateSet aStateSet[2], *pThis, *pNext;
6499  ReStateNumber aSpace[100];
6500  ReStateNumber *pToFree;
6501  unsigned int i = 0;
6502  unsigned int iSwap = 0;
6503  int c = RE_START;
6504  int cPrev = 0;
6505  int rc = 0;
6506  ReInput in;
6507
6508  in.z = zIn;
6509  in.i = 0;
6510  in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);
6511
6512  /* Look for the initial prefix match, if there is one. */
6513  if( pRe->nInit ){
6514    unsigned char x = pRe->zInit[0];
6515    while( in.i+pRe->nInit<=in.mx
6516     && (zIn[in.i]!=x ||
6517         strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
6518    ){
6519      in.i++;
6520    }
6521    if( in.i+pRe->nInit>in.mx ) return 0;
6522    c = RE_START-1;
6523  }
6524
6525  if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
6526    pToFree = 0;
6527    aStateSet[0].aState = aSpace;
6528  }else{
6529    pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState );
6530    if( pToFree==0 ) return -1;
6531    aStateSet[0].aState = pToFree;
6532  }
6533  aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
6534  pNext = &aStateSet[1];
6535  pNext->nState = 0;
6536  re_add_state(pNext, 0);
6537  while( c!=RE_EOF && pNext->nState>0 ){
6538    cPrev = c;
6539    c = pRe->xNextChar(&in);
6540    pThis = pNext;
6541    pNext = &aStateSet[iSwap];
6542    iSwap = 1 - iSwap;
6543    pNext->nState = 0;
6544    for(i=0; i<pThis->nState; i++){
6545      int x = pThis->aState[i];
6546      switch( pRe->aOp[x] ){
6547        case RE_OP_MATCH: {
6548          if( pRe->aArg[x]==c ) re_add_state(pNext, x+1);
6549          break;
6550        }
6551        case RE_OP_ATSTART: {
6552          if( cPrev==RE_START ) re_add_state(pThis, x+1);
6553          break;
6554        }
6555        case RE_OP_ANY: {
6556          if( c!=0 ) re_add_state(pNext, x+1);
6557          break;
6558        }
6559        case RE_OP_WORD: {
6560          if( re_word_char(c) ) re_add_state(pNext, x+1);
6561          break;
6562        }
6563        case RE_OP_NOTWORD: {
6564          if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1);
6565          break;
6566        }
6567        case RE_OP_DIGIT: {
6568          if( re_digit_char(c) ) re_add_state(pNext, x+1);
6569          break;
6570        }
6571        case RE_OP_NOTDIGIT: {
6572          if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1);
6573          break;
6574        }
6575        case RE_OP_SPACE: {
6576          if( re_space_char(c) ) re_add_state(pNext, x+1);
6577          break;
6578        }
6579        case RE_OP_NOTSPACE: {
6580          if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1);
6581          break;
6582        }
6583        case RE_OP_BOUNDARY: {
6584          if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1);
6585          break;
6586        }
6587        case RE_OP_ANYSTAR: {
6588          re_add_state(pNext, x);
6589          re_add_state(pThis, x+1);
6590          break;
6591        }
6592        case RE_OP_FORK: {
6593          re_add_state(pThis, x+pRe->aArg[x]);
6594          re_add_state(pThis, x+1);
6595          break;
6596        }
6597        case RE_OP_GOTO: {
6598          re_add_state(pThis, x+pRe->aArg[x]);
6599          break;
6600        }
6601        case RE_OP_ACCEPT: {
6602          rc = 1;
6603          goto re_match_end;
6604        }
6605        case RE_OP_CC_EXC: {
6606          if( c==0 ) break;
6607          /* fall-through */ goto re_op_cc_inc;
6608        }
6609        case RE_OP_CC_INC: re_op_cc_inc: {
6610          int j = 1;
6611          int n = pRe->aArg[x];
6612          int hit = 0;
6613          for(j=1; j>0 && j<n; j++){
6614            if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
6615              if( pRe->aArg[x+j]==c ){
6616                hit = 1;
6617                j = -1;
6618              }
6619            }else{
6620              if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
6621                hit = 1;
6622                j = -1;
6623              }else{
6624                j++;
6625              }
6626            }
6627          }
6628          if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
6629          if( hit ) re_add_state(pNext, x+n);
6630          break;
6631        }
6632      }
6633    }
6634  }
6635  for(i=0; i<pNext->nState; i++){
6636    int x = pNext->aState[i];
6637    while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x];
6638    if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; }
6639  }
6640re_match_end:
6641  sqlite3_free(pToFree);
6642  return rc;
6643}
6644
6645/* Resize the opcode and argument arrays for an RE under construction.
6646*/
6647static int re_resize(ReCompiled *p, int N){
6648  char *aOp;
6649  int *aArg;
6650  aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0]));
6651  if( aOp==0 ) return 1;
6652  p->aOp = aOp;
6653  aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0]));
6654  if( aArg==0 ) return 1;
6655  p->aArg = aArg;
6656  p->nAlloc = N;
6657  return 0;
6658}
6659
6660/* Insert a new opcode and argument into an RE under construction.  The
6661** insertion point is just prior to existing opcode iBefore.
6662*/
6663static int re_insert(ReCompiled *p, int iBefore, int op, int arg){
6664  int i;
6665  if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0;
6666  for(i=p->nState; i>iBefore; i--){
6667    p->aOp[i] = p->aOp[i-1];
6668    p->aArg[i] = p->aArg[i-1];
6669  }
6670  p->nState++;
6671  p->aOp[iBefore] = (char)op;
6672  p->aArg[iBefore] = arg;
6673  return iBefore;
6674}
6675
6676/* Append a new opcode and argument to the end of the RE under construction.
6677*/
6678static int re_append(ReCompiled *p, int op, int arg){
6679  return re_insert(p, p->nState, op, arg);
6680}
6681
6682/* Make a copy of N opcodes starting at iStart onto the end of the RE
6683** under construction.
6684*/
6685static void re_copy(ReCompiled *p, int iStart, int N){
6686  if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return;
6687  memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
6688  memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
6689  p->nState += N;
6690}
6691
6692/* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
6693** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
6694** c is not a hex digit *pV is unchanged.
6695*/
6696static int re_hex(int c, int *pV){
6697  if( c>='0' && c<='9' ){
6698    c -= '0';
6699  }else if( c>='a' && c<='f' ){
6700    c -= 'a' - 10;
6701  }else if( c>='A' && c<='F' ){
6702    c -= 'A' - 10;
6703  }else{
6704    return 0;
6705  }
6706  *pV = (*pV)*16 + (c & 0xff);
6707  return 1;
6708}
6709
6710/* A backslash character has been seen, read the next character and
6711** return its interpretation.
6712*/
6713static unsigned re_esc_char(ReCompiled *p){
6714  static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
6715  static const char zTrans[] = "\a\f\n\r\t\v";
6716  int i, v = 0;
6717  char c;
6718  if( p->sIn.i>=p->sIn.mx ) return 0;
6719  c = p->sIn.z[p->sIn.i];
6720  if( c=='u' && p->sIn.i+4<p->sIn.mx ){
6721    const unsigned char *zIn = p->sIn.z + p->sIn.i;
6722    if( re_hex(zIn[1],&v)
6723     && re_hex(zIn[2],&v)
6724     && re_hex(zIn[3],&v)
6725     && re_hex(zIn[4],&v)
6726    ){
6727      p->sIn.i += 5;
6728      return v;
6729    }
6730  }
6731  if( c=='x' && p->sIn.i+2<p->sIn.mx ){
6732    const unsigned char *zIn = p->sIn.z + p->sIn.i;
6733    if( re_hex(zIn[1],&v)
6734     && re_hex(zIn[2],&v)
6735    ){
6736      p->sIn.i += 3;
6737      return v;
6738    }
6739  }
6740  for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
6741  if( zEsc[i] ){
6742    if( i<6 ) c = zTrans[i];
6743    p->sIn.i++;
6744  }else{
6745    p->zErr = "unknown \\ escape";
6746  }
6747  return c;
6748}
6749
6750/* Forward declaration */
6751static const char *re_subcompile_string(ReCompiled*);
6752
6753/* Peek at the next byte of input */
6754static unsigned char rePeek(ReCompiled *p){
6755  return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
6756}
6757
6758/* Compile RE text into a sequence of opcodes.  Continue up to the
6759** first unmatched ")" character, then return.  If an error is found,
6760** return a pointer to the error message string.
6761*/
6762static const char *re_subcompile_re(ReCompiled *p){
6763  const char *zErr;
6764  int iStart, iEnd, iGoto;
6765  iStart = p->nState;
6766  zErr = re_subcompile_string(p);
6767  if( zErr ) return zErr;
6768  while( rePeek(p)=='|' ){
6769    iEnd = p->nState;
6770    re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
6771    iGoto = re_append(p, RE_OP_GOTO, 0);
6772    p->sIn.i++;
6773    zErr = re_subcompile_string(p);
6774    if( zErr ) return zErr;
6775    p->aArg[iGoto] = p->nState - iGoto;
6776  }
6777  return 0;
6778}
6779
6780/* Compile an element of regular expression text (anything that can be
6781** an operand to the "|" operator).  Return NULL on success or a pointer
6782** to the error message if there is a problem.
6783*/
6784static const char *re_subcompile_string(ReCompiled *p){
6785  int iPrev = -1;
6786  int iStart;
6787  unsigned c;
6788  const char *zErr;
6789  while( (c = p->xNextChar(&p->sIn))!=0 ){
6790    iStart = p->nState;
6791    switch( c ){
6792      case '|':
6793      case ')': {
6794        p->sIn.i--;
6795        return 0;
6796      }
6797      case '(': {
6798        zErr = re_subcompile_re(p);
6799        if( zErr ) return zErr;
6800        if( rePeek(p)!=')' ) return "unmatched '('";
6801        p->sIn.i++;
6802        break;
6803      }
6804      case '.': {
6805        if( rePeek(p)=='*' ){
6806          re_append(p, RE_OP_ANYSTAR, 0);
6807          p->sIn.i++;
6808        }else{
6809          re_append(p, RE_OP_ANY, 0);
6810        }
6811        break;
6812      }
6813      case '*': {
6814        if( iPrev<0 ) return "'*' without operand";
6815        re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
6816        re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
6817        break;
6818      }
6819      case '+': {
6820        if( iPrev<0 ) return "'+' without operand";
6821        re_append(p, RE_OP_FORK, iPrev - p->nState);
6822        break;
6823      }
6824      case '?': {
6825        if( iPrev<0 ) return "'?' without operand";
6826        re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
6827        break;
6828      }
6829      case '$': {
6830        re_append(p, RE_OP_MATCH, RE_EOF);
6831        break;
6832      }
6833      case '^': {
6834        re_append(p, RE_OP_ATSTART, 0);
6835        break;
6836      }
6837      case '{': {
6838        int m = 0, n = 0;
6839        int sz, j;
6840        if( iPrev<0 ) return "'{m,n}' without operand";
6841        while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
6842        n = m;
6843        if( c==',' ){
6844          p->sIn.i++;
6845          n = 0;
6846          while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
6847        }
6848        if( c!='}' ) return "unmatched '{'";
6849        if( n>0 && n<m ) return "n less than m in '{m,n}'";
6850        p->sIn.i++;
6851        sz = p->nState - iPrev;
6852        if( m==0 ){
6853          if( n==0 ) return "both m and n are zero in '{m,n}'";
6854          re_insert(p, iPrev, RE_OP_FORK, sz+1);
6855          iPrev++;
6856          n--;
6857        }else{
6858          for(j=1; j<m; j++) re_copy(p, iPrev, sz);
6859        }
6860        for(j=m; j<n; j++){
6861          re_append(p, RE_OP_FORK, sz+1);
6862          re_copy(p, iPrev, sz);
6863        }
6864        if( n==0 && m>0 ){
6865          re_append(p, RE_OP_FORK, -sz);
6866        }
6867        break;
6868      }
6869      case '[': {
6870        unsigned int iFirst = p->nState;
6871        if( rePeek(p)=='^' ){
6872          re_append(p, RE_OP_CC_EXC, 0);
6873          p->sIn.i++;
6874        }else{
6875          re_append(p, RE_OP_CC_INC, 0);
6876        }
6877        while( (c = p->xNextChar(&p->sIn))!=0 ){
6878          if( c=='[' && rePeek(p)==':' ){
6879            return "POSIX character classes not supported";
6880          }
6881          if( c=='\\' ) c = re_esc_char(p);
6882          if( rePeek(p)=='-' ){
6883            re_append(p, RE_OP_CC_RANGE, c);
6884            p->sIn.i++;
6885            c = p->xNextChar(&p->sIn);
6886            if( c=='\\' ) c = re_esc_char(p);
6887            re_append(p, RE_OP_CC_RANGE, c);
6888          }else{
6889            re_append(p, RE_OP_CC_VALUE, c);
6890          }
6891          if( rePeek(p)==']' ){ p->sIn.i++; break; }
6892        }
6893        if( c==0 ) return "unclosed '['";
6894        if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst;
6895        break;
6896      }
6897      case '\\': {
6898        int specialOp = 0;
6899        switch( rePeek(p) ){
6900          case 'b': specialOp = RE_OP_BOUNDARY;   break;
6901          case 'd': specialOp = RE_OP_DIGIT;      break;
6902          case 'D': specialOp = RE_OP_NOTDIGIT;   break;
6903          case 's': specialOp = RE_OP_SPACE;      break;
6904          case 'S': specialOp = RE_OP_NOTSPACE;   break;
6905          case 'w': specialOp = RE_OP_WORD;       break;
6906          case 'W': specialOp = RE_OP_NOTWORD;    break;
6907        }
6908        if( specialOp ){
6909          p->sIn.i++;
6910          re_append(p, specialOp, 0);
6911        }else{
6912          c = re_esc_char(p);
6913          re_append(p, RE_OP_MATCH, c);
6914        }
6915        break;
6916      }
6917      default: {
6918        re_append(p, RE_OP_MATCH, c);
6919        break;
6920      }
6921    }
6922    iPrev = iStart;
6923  }
6924  return 0;
6925}
6926
6927/* Free and reclaim all the memory used by a previously compiled
6928** regular expression.  Applications should invoke this routine once
6929** for every call to re_compile() to avoid memory leaks.
6930*/
6931static void re_free(ReCompiled *pRe){
6932  if( pRe ){
6933    sqlite3_free(pRe->aOp);
6934    sqlite3_free(pRe->aArg);
6935    sqlite3_free(pRe);
6936  }
6937}
6938
6939/*
6940** Compile a textual regular expression in zIn[] into a compiled regular
6941** expression suitable for us by re_match() and return a pointer to the
6942** compiled regular expression in *ppRe.  Return NULL on success or an
6943** error message if something goes wrong.
6944*/
6945static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){
6946  ReCompiled *pRe;
6947  const char *zErr;
6948  int i, j;
6949
6950  *ppRe = 0;
6951  pRe = sqlite3_malloc( sizeof(*pRe) );
6952  if( pRe==0 ){
6953    return "out of memory";
6954  }
6955  memset(pRe, 0, sizeof(*pRe));
6956  pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char;
6957  if( re_resize(pRe, 30) ){
6958    re_free(pRe);
6959    return "out of memory";
6960  }
6961  if( zIn[0]=='^' ){
6962    zIn++;
6963  }else{
6964    re_append(pRe, RE_OP_ANYSTAR, 0);
6965  }
6966  pRe->sIn.z = (unsigned char*)zIn;
6967  pRe->sIn.i = 0;
6968  pRe->sIn.mx = (int)strlen(zIn);
6969  zErr = re_subcompile_re(pRe);
6970  if( zErr ){
6971    re_free(pRe);
6972    return zErr;
6973  }
6974  if( pRe->sIn.i>=pRe->sIn.mx ){
6975    re_append(pRe, RE_OP_ACCEPT, 0);
6976    *ppRe = pRe;
6977  }else{
6978    re_free(pRe);
6979    return "unrecognized character";
6980  }
6981
6982  /* The following is a performance optimization.  If the regex begins with
6983  ** ".*" (if the input regex lacks an initial "^") and afterwards there are
6984  ** one or more matching characters, enter those matching characters into
6985  ** zInit[].  The re_match() routine can then search ahead in the input
6986  ** string looking for the initial match without having to run the whole
6987  ** regex engine over the string.  Do not worry about trying to match
6988  ** unicode characters beyond plane 0 - those are very rare and this is
6989  ** just an optimization. */
6990  if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){
6991    for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
6992      unsigned x = pRe->aArg[i];
6993      if( x<=0x7f ){
6994        pRe->zInit[j++] = (unsigned char)x;
6995      }else if( x<=0x7ff ){
6996        pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6));
6997        pRe->zInit[j++] = 0x80 | (x&0x3f);
6998      }else if( x<=0xffff ){
6999        pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12));
7000        pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
7001        pRe->zInit[j++] = 0x80 | (x&0x3f);
7002      }else{
7003        break;
7004      }
7005    }
7006    if( j>0 && pRe->zInit[j-1]==0 ) j--;
7007    pRe->nInit = j;
7008  }
7009  return pRe->zErr;
7010}
7011
7012/*
7013** Implementation of the regexp() SQL function.  This function implements
7014** the build-in REGEXP operator.  The first argument to the function is the
7015** pattern and the second argument is the string.  So, the SQL statements:
7016**
7017**       A REGEXP B
7018**
7019** is implemented as regexp(B,A).
7020*/
7021static void re_sql_func(
7022  sqlite3_context *context,
7023  int argc,
7024  sqlite3_value **argv
7025){
7026  ReCompiled *pRe;          /* Compiled regular expression */
7027  const char *zPattern;     /* The regular expression */
7028  const unsigned char *zStr;/* String being searched */
7029  const char *zErr;         /* Compile error message */
7030  int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */
7031
7032  (void)argc;  /* Unused */
7033  pRe = sqlite3_get_auxdata(context, 0);
7034  if( pRe==0 ){
7035    zPattern = (const char*)sqlite3_value_text(argv[0]);
7036    if( zPattern==0 ) return;
7037    zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7038    if( zErr ){
7039      re_free(pRe);
7040      sqlite3_result_error(context, zErr, -1);
7041      return;
7042    }
7043    if( pRe==0 ){
7044      sqlite3_result_error_nomem(context);
7045      return;
7046    }
7047    setAux = 1;
7048  }
7049  zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
7050  if( zStr!=0 ){
7051    sqlite3_result_int(context, re_match(pRe, zStr, -1));
7052  }
7053  if( setAux ){
7054    sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free);
7055  }
7056}
7057
7058#if defined(SQLITE_DEBUG)
7059/*
7060** This function is used for testing and debugging only.  It is only available
7061** if the SQLITE_DEBUG compile-time option is used.
7062**
7063** Compile a regular expression and then convert the compiled expression into
7064** text and return that text.
7065*/
7066static void re_bytecode_func(
7067  sqlite3_context *context,
7068  int argc,
7069  sqlite3_value **argv
7070){
7071  const char *zPattern;
7072  const char *zErr;
7073  ReCompiled *pRe;
7074  sqlite3_str *pStr;
7075  int i;
7076  int n;
7077  char *z;
7078  (void)argc;
7079
7080  zPattern = (const char*)sqlite3_value_text(argv[0]);
7081  if( zPattern==0 ) return;
7082  zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0);
7083  if( zErr ){
7084    re_free(pRe);
7085    sqlite3_result_error(context, zErr, -1);
7086    return;
7087  }
7088  if( pRe==0 ){
7089    sqlite3_result_error_nomem(context);
7090    return;
7091  }
7092  pStr = sqlite3_str_new(0);
7093  if( pStr==0 ) goto re_bytecode_func_err;
7094  if( pRe->nInit>0 ){
7095    sqlite3_str_appendf(pStr, "INIT     ");
7096    for(i=0; i<pRe->nInit; i++){
7097      sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]);
7098    }
7099    sqlite3_str_appendf(pStr, "\n");
7100  }
7101  for(i=0; (unsigned)i<pRe->nState; i++){
7102    sqlite3_str_appendf(pStr, "%-8s %4d\n",
7103         ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]);
7104  }
7105  n = sqlite3_str_length(pStr);
7106  z = sqlite3_str_finish(pStr);
7107  if( n==0 ){
7108    sqlite3_free(z);
7109  }else{
7110    sqlite3_result_text(context, z, n-1, sqlite3_free);
7111  }
7112
7113re_bytecode_func_err:
7114  re_free(pRe);
7115}
7116
7117#endif /* SQLITE_DEBUG */
7118
7119
7120/*
7121** Invoke this routine to register the regexp() function with the
7122** SQLite database connection.
7123*/
7124#ifdef _WIN32
7125
7126#endif
7127int sqlite3_regexp_init(
7128  sqlite3 *db,
7129  char **pzErrMsg,
7130  const sqlite3_api_routines *pApi
7131){
7132  int rc = SQLITE_OK;
7133  SQLITE_EXTENSION_INIT2(pApi);
7134  (void)pzErrMsg;  /* Unused */
7135  rc = sqlite3_create_function(db, "regexp", 2,
7136                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7137                            0, re_sql_func, 0, 0);
7138  if( rc==SQLITE_OK ){
7139    /* The regexpi(PATTERN,STRING) function is a case-insensitive version
7140    ** of regexp(PATTERN,STRING). */
7141    rc = sqlite3_create_function(db, "regexpi", 2,
7142                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7143                            (void*)db, re_sql_func, 0, 0);
7144#if defined(SQLITE_DEBUG)
7145    if( rc==SQLITE_OK ){
7146      rc = sqlite3_create_function(db, "regexp_bytecode", 1,
7147                            SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
7148                            0, re_bytecode_func, 0, 0);
7149    }
7150#endif /* SQLITE_DEBUG */
7151  }
7152  return rc;
7153}
7154
7155/************************* End ../ext/misc/regexp.c ********************/
7156#ifndef SQLITE_SHELL_FIDDLE
7157/************************* Begin ../ext/misc/fileio.c ******************/
7158/*
7159** 2014-06-13
7160**
7161** The author disclaims copyright to this source code.  In place of
7162** a legal notice, here is a blessing:
7163**
7164**    May you do good and not evil.
7165**    May you find forgiveness for yourself and forgive others.
7166**    May you share freely, never taking more than you give.
7167**
7168******************************************************************************
7169**
7170** This SQLite extension implements SQL functions readfile() and
7171** writefile(), and eponymous virtual type "fsdir".
7172**
7173** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
7174**
7175**   If neither of the optional arguments is present, then this UDF
7176**   function writes blob DATA to file FILE. If successful, the number
7177**   of bytes written is returned. If an error occurs, NULL is returned.
7178**
7179**   If the first option argument - MODE - is present, then it must
7180**   be passed an integer value that corresponds to a POSIX mode
7181**   value (file type + permissions, as returned in the stat.st_mode
7182**   field by the stat() system call). Three types of files may
7183**   be written/created:
7184**
7185**     regular files:  (mode & 0170000)==0100000
7186**     symbolic links: (mode & 0170000)==0120000
7187**     directories:    (mode & 0170000)==0040000
7188**
7189**   For a directory, the DATA is ignored. For a symbolic link, it is
7190**   interpreted as text and used as the target of the link. For a
7191**   regular file, it is interpreted as a blob and written into the
7192**   named file. Regardless of the type of file, its permissions are
7193**   set to (mode & 0777) before returning.
7194**
7195**   If the optional MTIME argument is present, then it is interpreted
7196**   as an integer - the number of seconds since the unix epoch. The
7197**   modification-time of the target file is set to this value before
7198**   returning.
7199**
7200**   If three or more arguments are passed to this function and an
7201**   error is encountered, an exception is raised.
7202**
7203** READFILE(FILE):
7204**
7205**   Read and return the contents of file FILE (type blob) from disk.
7206**
7207** FSDIR:
7208**
7209**   Used as follows:
7210**
7211**     SELECT * FROM fsdir($path [, $dir]);
7212**
7213**   Parameter $path is an absolute or relative pathname. If the file that it
7214**   refers to does not exist, it is an error. If the path refers to a regular
7215**   file or symbolic link, it returns a single row. Or, if the path refers
7216**   to a directory, it returns one row for the directory, and one row for each
7217**   file within the hierarchy rooted at $path.
7218**
7219**   Each row has the following columns:
7220**
7221**     name:  Path to file or directory (text value).
7222**     mode:  Value of stat.st_mode for directory entry (an integer).
7223**     mtime: Value of stat.st_mtime for directory entry (an integer).
7224**     data:  For a regular file, a blob containing the file data. For a
7225**            symlink, a text value containing the text of the link. For a
7226**            directory, NULL.
7227**
7228**   If a non-NULL value is specified for the optional $dir parameter and
7229**   $path is a relative path, then $path is interpreted relative to $dir.
7230**   And the paths returned in the "name" column of the table are also
7231**   relative to directory $dir.
7232**
7233** Notes on building this extension for Windows:
7234**   Unless linked statically with the SQLite library, a preprocessor
7235**   symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone
7236**   DLL form of this extension for WIN32. See its use below for details.
7237*/
7238/* #include "sqlite3ext.h" */
7239SQLITE_EXTENSION_INIT1
7240#include <stdio.h>
7241#include <string.h>
7242#include <assert.h>
7243
7244#include <sys/types.h>
7245#include <sys/stat.h>
7246#include <fcntl.h>
7247#if !defined(_WIN32) && !defined(WIN32)
7248#  include <unistd.h>
7249#  include <dirent.h>
7250#  include <utime.h>
7251#  include <sys/time.h>
7252#else
7253#  include "windows.h"
7254#  include <io.h>
7255#  include <direct.h>
7256/* #  include "test_windirent.h" */
7257#  define dirent DIRENT
7258#  ifndef chmod
7259#    define chmod _chmod
7260#  endif
7261#  ifndef stat
7262#    define stat _stat
7263#  endif
7264#  define mkdir(path,mode) _mkdir(path)
7265#  define lstat(path,buf) stat(path,buf)
7266#endif
7267#include <time.h>
7268#include <errno.h>
7269
7270
7271/*
7272** Structure of the fsdir() table-valued function
7273*/
7274                 /*    0    1    2     3    4           5             */
7275#define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
7276#define FSDIR_COLUMN_NAME     0     /* Name of the file */
7277#define FSDIR_COLUMN_MODE     1     /* Access mode */
7278#define FSDIR_COLUMN_MTIME    2     /* Last modification time */
7279#define FSDIR_COLUMN_DATA     3     /* File content */
7280#define FSDIR_COLUMN_PATH     4     /* Path to top of search */
7281#define FSDIR_COLUMN_DIR      5     /* Path is relative to this directory */
7282
7283
7284/*
7285** Set the result stored by context ctx to a blob containing the
7286** contents of file zName.  Or, leave the result unchanged (NULL)
7287** if the file does not exist or is unreadable.
7288**
7289** If the file exceeds the SQLite blob size limit, through an
7290** SQLITE_TOOBIG error.
7291**
7292** Throw an SQLITE_IOERR if there are difficulties pulling the file
7293** off of disk.
7294*/
7295static void readFileContents(sqlite3_context *ctx, const char *zName){
7296  FILE *in;
7297  sqlite3_int64 nIn;
7298  void *pBuf;
7299  sqlite3 *db;
7300  int mxBlob;
7301
7302  in = fopen(zName, "rb");
7303  if( in==0 ){
7304    /* File does not exist or is unreadable. Leave the result set to NULL. */
7305    return;
7306  }
7307  fseek(in, 0, SEEK_END);
7308  nIn = ftell(in);
7309  rewind(in);
7310  db = sqlite3_context_db_handle(ctx);
7311  mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1);
7312  if( nIn>mxBlob ){
7313    sqlite3_result_error_code(ctx, SQLITE_TOOBIG);
7314    fclose(in);
7315    return;
7316  }
7317  pBuf = sqlite3_malloc64( nIn ? nIn : 1 );
7318  if( pBuf==0 ){
7319    sqlite3_result_error_nomem(ctx);
7320    fclose(in);
7321    return;
7322  }
7323  if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){
7324    sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free);
7325  }else{
7326    sqlite3_result_error_code(ctx, SQLITE_IOERR);
7327    sqlite3_free(pBuf);
7328  }
7329  fclose(in);
7330}
7331
7332/*
7333** Implementation of the "readfile(X)" SQL function.  The entire content
7334** of the file named X is read and returned as a BLOB.  NULL is returned
7335** if the file does not exist or is unreadable.
7336*/
7337static void readfileFunc(
7338  sqlite3_context *context,
7339  int argc,
7340  sqlite3_value **argv
7341){
7342  const char *zName;
7343  (void)(argc);  /* Unused parameter */
7344  zName = (const char*)sqlite3_value_text(argv[0]);
7345  if( zName==0 ) return;
7346  readFileContents(context, zName);
7347}
7348
7349/*
7350** Set the error message contained in context ctx to the results of
7351** vprintf(zFmt, ...).
7352*/
7353static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
7354  char *zMsg = 0;
7355  va_list ap;
7356  va_start(ap, zFmt);
7357  zMsg = sqlite3_vmprintf(zFmt, ap);
7358  sqlite3_result_error(ctx, zMsg, -1);
7359  sqlite3_free(zMsg);
7360  va_end(ap);
7361}
7362
7363#if defined(_WIN32)
7364/*
7365** This function is designed to convert a Win32 FILETIME structure into the
7366** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
7367*/
7368static sqlite3_uint64 fileTimeToUnixTime(
7369  LPFILETIME pFileTime
7370){
7371  SYSTEMTIME epochSystemTime;
7372  ULARGE_INTEGER epochIntervals;
7373  FILETIME epochFileTime;
7374  ULARGE_INTEGER fileIntervals;
7375
7376  memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
7377  epochSystemTime.wYear = 1970;
7378  epochSystemTime.wMonth = 1;
7379  epochSystemTime.wDay = 1;
7380  SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
7381  epochIntervals.LowPart = epochFileTime.dwLowDateTime;
7382  epochIntervals.HighPart = epochFileTime.dwHighDateTime;
7383
7384  fileIntervals.LowPart = pFileTime->dwLowDateTime;
7385  fileIntervals.HighPart = pFileTime->dwHighDateTime;
7386
7387  return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
7388}
7389
7390
7391#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
7392#  /* To allow a standalone DLL, use this next replacement function: */
7393#  undef sqlite3_win32_utf8_to_unicode
7394#  define sqlite3_win32_utf8_to_unicode utf8_to_utf16
7395#
7396LPWSTR utf8_to_utf16(const char *z){
7397  int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0);
7398  LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR));
7399  if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) )
7400    return rv;
7401  sqlite3_free(rv);
7402  return 0;
7403}
7404#endif
7405
7406/*
7407** This function attempts to normalize the time values found in the stat()
7408** buffer to UTC.  This is necessary on Win32, where the runtime library
7409** appears to return these values as local times.
7410*/
7411static void statTimesToUtc(
7412  const char *zPath,
7413  struct stat *pStatBuf
7414){
7415  HANDLE hFindFile;
7416  WIN32_FIND_DATAW fd;
7417  LPWSTR zUnicodeName;
7418  extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7419  zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
7420  if( zUnicodeName ){
7421    memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
7422    hFindFile = FindFirstFileW(zUnicodeName, &fd);
7423    if( hFindFile!=NULL ){
7424      pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
7425      pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
7426      pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
7427      FindClose(hFindFile);
7428    }
7429    sqlite3_free(zUnicodeName);
7430  }
7431}
7432#endif
7433
7434/*
7435** This function is used in place of stat().  On Windows, special handling
7436** is required in order for the included time to be returned as UTC.  On all
7437** other systems, this function simply calls stat().
7438*/
7439static int fileStat(
7440  const char *zPath,
7441  struct stat *pStatBuf
7442){
7443#if defined(_WIN32)
7444  int rc = stat(zPath, pStatBuf);
7445  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7446  return rc;
7447#else
7448  return stat(zPath, pStatBuf);
7449#endif
7450}
7451
7452/*
7453** This function is used in place of lstat().  On Windows, special handling
7454** is required in order for the included time to be returned as UTC.  On all
7455** other systems, this function simply calls lstat().
7456*/
7457static int fileLinkStat(
7458  const char *zPath,
7459  struct stat *pStatBuf
7460){
7461#if defined(_WIN32)
7462  int rc = lstat(zPath, pStatBuf);
7463  if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
7464  return rc;
7465#else
7466  return lstat(zPath, pStatBuf);
7467#endif
7468}
7469
7470/*
7471** Argument zFile is the name of a file that will be created and/or written
7472** by SQL function writefile(). This function ensures that the directory
7473** zFile will be written to exists, creating it if required. The permissions
7474** for any path components created by this function are set in accordance
7475** with the current umask.
7476**
7477** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
7478** SQLITE_OK is returned if the directory is successfully created, or
7479** SQLITE_ERROR otherwise.
7480*/
7481static int makeDirectory(
7482  const char *zFile
7483){
7484  char *zCopy = sqlite3_mprintf("%s", zFile);
7485  int rc = SQLITE_OK;
7486
7487  if( zCopy==0 ){
7488    rc = SQLITE_NOMEM;
7489  }else{
7490    int nCopy = (int)strlen(zCopy);
7491    int i = 1;
7492
7493    while( rc==SQLITE_OK ){
7494      struct stat sStat;
7495      int rc2;
7496
7497      for(; zCopy[i]!='/' && i<nCopy; i++);
7498      if( i==nCopy ) break;
7499      zCopy[i] = '\0';
7500
7501      rc2 = fileStat(zCopy, &sStat);
7502      if( rc2!=0 ){
7503        if( mkdir(zCopy, 0777) ) rc = SQLITE_ERROR;
7504      }else{
7505        if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
7506      }
7507      zCopy[i] = '/';
7508      i++;
7509    }
7510
7511    sqlite3_free(zCopy);
7512  }
7513
7514  return rc;
7515}
7516
7517/*
7518** This function does the work for the writefile() UDF. Refer to
7519** header comments at the top of this file for details.
7520*/
7521static int writeFile(
7522  sqlite3_context *pCtx,          /* Context to return bytes written in */
7523  const char *zFile,              /* File to write */
7524  sqlite3_value *pData,           /* Data to write */
7525  mode_t mode,                    /* MODE parameter passed to writefile() */
7526  sqlite3_int64 mtime             /* MTIME parameter (or -1 to not set time) */
7527){
7528  if( zFile==0 ) return 1;
7529#if !defined(_WIN32) && !defined(WIN32)
7530  if( S_ISLNK(mode) ){
7531    const char *zTo = (const char*)sqlite3_value_text(pData);
7532    if( zTo==0 ) return 1;
7533    unlink(zFile);
7534    if( symlink(zTo, zFile)<0 ) return 1;
7535  }else
7536#endif
7537  {
7538    if( S_ISDIR(mode) ){
7539      if( mkdir(zFile, mode) ){
7540        /* The mkdir() call to create the directory failed. This might not
7541        ** be an error though - if there is already a directory at the same
7542        ** path and either the permissions already match or can be changed
7543        ** to do so using chmod(), it is not an error.  */
7544        struct stat sStat;
7545        if( errno!=EEXIST
7546         || 0!=fileStat(zFile, &sStat)
7547         || !S_ISDIR(sStat.st_mode)
7548         || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
7549        ){
7550          return 1;
7551        }
7552      }
7553    }else{
7554      sqlite3_int64 nWrite = 0;
7555      const char *z;
7556      int rc = 0;
7557      FILE *out = fopen(zFile, "wb");
7558      if( out==0 ) return 1;
7559      z = (const char*)sqlite3_value_blob(pData);
7560      if( z ){
7561        sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
7562        nWrite = sqlite3_value_bytes(pData);
7563        if( nWrite!=n ){
7564          rc = 1;
7565        }
7566      }
7567      fclose(out);
7568      if( rc==0 && mode && chmod(zFile, mode & 0777) ){
7569        rc = 1;
7570      }
7571      if( rc ) return 2;
7572      sqlite3_result_int64(pCtx, nWrite);
7573    }
7574  }
7575
7576  if( mtime>=0 ){
7577#if defined(_WIN32)
7578#if !SQLITE_OS_WINRT
7579    /* Windows */
7580    FILETIME lastAccess;
7581    FILETIME lastWrite;
7582    SYSTEMTIME currentTime;
7583    LONGLONG intervals;
7584    HANDLE hFile;
7585    LPWSTR zUnicodeName;
7586    extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
7587
7588    GetSystemTime(&currentTime);
7589    SystemTimeToFileTime(&currentTime, &lastAccess);
7590    intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
7591    lastWrite.dwLowDateTime = (DWORD)intervals;
7592    lastWrite.dwHighDateTime = intervals >> 32;
7593    zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
7594    if( zUnicodeName==0 ){
7595      return 1;
7596    }
7597    hFile = CreateFileW(
7598      zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
7599      FILE_FLAG_BACKUP_SEMANTICS, NULL
7600    );
7601    sqlite3_free(zUnicodeName);
7602    if( hFile!=INVALID_HANDLE_VALUE ){
7603      BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
7604      CloseHandle(hFile);
7605      return !bResult;
7606    }else{
7607      return 1;
7608    }
7609#endif
7610#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
7611    /* Recent unix */
7612    struct timespec times[2];
7613    times[0].tv_nsec = times[1].tv_nsec = 0;
7614    times[0].tv_sec = time(0);
7615    times[1].tv_sec = mtime;
7616    if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
7617      return 1;
7618    }
7619#else
7620    /* Legacy unix.
7621    **
7622    ** Do not use utimes() on a symbolic link - it sees through the link and
7623    ** modifies the timestamps on the target. Or fails if the target does
7624    ** not exist.  */
7625    if( 0==S_ISLNK(mode) ){
7626      struct timeval times[2];
7627      times[0].tv_usec = times[1].tv_usec = 0;
7628      times[0].tv_sec = time(0);
7629      times[1].tv_sec = mtime;
7630      if( utimes(zFile, times) ){
7631        return 1;
7632      }
7633    }
7634#endif
7635  }
7636
7637  return 0;
7638}
7639
7640/*
7641** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
7642** Refer to header comments at the top of this file for details.
7643*/
7644static void writefileFunc(
7645  sqlite3_context *context,
7646  int argc,
7647  sqlite3_value **argv
7648){
7649  const char *zFile;
7650  mode_t mode = 0;
7651  int res;
7652  sqlite3_int64 mtime = -1;
7653
7654  if( argc<2 || argc>4 ){
7655    sqlite3_result_error(context,
7656        "wrong number of arguments to function writefile()", -1
7657    );
7658    return;
7659  }
7660
7661  zFile = (const char*)sqlite3_value_text(argv[0]);
7662  if( zFile==0 ) return;
7663  if( argc>=3 ){
7664    mode = (mode_t)sqlite3_value_int(argv[2]);
7665  }
7666  if( argc==4 ){
7667    mtime = sqlite3_value_int64(argv[3]);
7668  }
7669
7670  res = writeFile(context, zFile, argv[1], mode, mtime);
7671  if( res==1 && errno==ENOENT ){
7672    if( makeDirectory(zFile)==SQLITE_OK ){
7673      res = writeFile(context, zFile, argv[1], mode, mtime);
7674    }
7675  }
7676
7677  if( argc>2 && res!=0 ){
7678    if( S_ISLNK(mode) ){
7679      ctxErrorMsg(context, "failed to create symlink: %s", zFile);
7680    }else if( S_ISDIR(mode) ){
7681      ctxErrorMsg(context, "failed to create directory: %s", zFile);
7682    }else{
7683      ctxErrorMsg(context, "failed to write file: %s", zFile);
7684    }
7685  }
7686}
7687
7688/*
7689** SQL function:   lsmode(MODE)
7690**
7691** Given a numberic st_mode from stat(), convert it into a human-readable
7692** text string in the style of "ls -l".
7693*/
7694static void lsModeFunc(
7695  sqlite3_context *context,
7696  int argc,
7697  sqlite3_value **argv
7698){
7699  int i;
7700  int iMode = sqlite3_value_int(argv[0]);
7701  char z[16];
7702  (void)argc;
7703  if( S_ISLNK(iMode) ){
7704    z[0] = 'l';
7705  }else if( S_ISREG(iMode) ){
7706    z[0] = '-';
7707  }else if( S_ISDIR(iMode) ){
7708    z[0] = 'd';
7709  }else{
7710    z[0] = '?';
7711  }
7712  for(i=0; i<3; i++){
7713    int m = (iMode >> ((2-i)*3));
7714    char *a = &z[1 + i*3];
7715    a[0] = (m & 0x4) ? 'r' : '-';
7716    a[1] = (m & 0x2) ? 'w' : '-';
7717    a[2] = (m & 0x1) ? 'x' : '-';
7718  }
7719  z[10] = '\0';
7720  sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7721}
7722
7723#ifndef SQLITE_OMIT_VIRTUALTABLE
7724
7725/*
7726** Cursor type for recursively iterating through a directory structure.
7727*/
7728typedef struct fsdir_cursor fsdir_cursor;
7729typedef struct FsdirLevel FsdirLevel;
7730
7731struct FsdirLevel {
7732  DIR *pDir;                 /* From opendir() */
7733  char *zDir;                /* Name of directory (nul-terminated) */
7734};
7735
7736struct fsdir_cursor {
7737  sqlite3_vtab_cursor base;  /* Base class - must be first */
7738
7739  int nLvl;                  /* Number of entries in aLvl[] array */
7740  int iLvl;                  /* Index of current entry */
7741  FsdirLevel *aLvl;          /* Hierarchy of directories being traversed */
7742
7743  const char *zBase;
7744  int nBase;
7745
7746  struct stat sStat;         /* Current lstat() results */
7747  char *zPath;               /* Path to current entry */
7748  sqlite3_int64 iRowid;      /* Current rowid */
7749};
7750
7751typedef struct fsdir_tab fsdir_tab;
7752struct fsdir_tab {
7753  sqlite3_vtab base;         /* Base class - must be first */
7754};
7755
7756/*
7757** Construct a new fsdir virtual table object.
7758*/
7759static int fsdirConnect(
7760  sqlite3 *db,
7761  void *pAux,
7762  int argc, const char *const*argv,
7763  sqlite3_vtab **ppVtab,
7764  char **pzErr
7765){
7766  fsdir_tab *pNew = 0;
7767  int rc;
7768  (void)pAux;
7769  (void)argc;
7770  (void)argv;
7771  (void)pzErr;
7772  rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
7773  if( rc==SQLITE_OK ){
7774    pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
7775    if( pNew==0 ) return SQLITE_NOMEM;
7776    memset(pNew, 0, sizeof(*pNew));
7777    sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
7778  }
7779  *ppVtab = (sqlite3_vtab*)pNew;
7780  return rc;
7781}
7782
7783/*
7784** This method is the destructor for fsdir vtab objects.
7785*/
7786static int fsdirDisconnect(sqlite3_vtab *pVtab){
7787  sqlite3_free(pVtab);
7788  return SQLITE_OK;
7789}
7790
7791/*
7792** Constructor for a new fsdir_cursor object.
7793*/
7794static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
7795  fsdir_cursor *pCur;
7796  (void)p;
7797  pCur = sqlite3_malloc( sizeof(*pCur) );
7798  if( pCur==0 ) return SQLITE_NOMEM;
7799  memset(pCur, 0, sizeof(*pCur));
7800  pCur->iLvl = -1;
7801  *ppCursor = &pCur->base;
7802  return SQLITE_OK;
7803}
7804
7805/*
7806** Reset a cursor back to the state it was in when first returned
7807** by fsdirOpen().
7808*/
7809static void fsdirResetCursor(fsdir_cursor *pCur){
7810  int i;
7811  for(i=0; i<=pCur->iLvl; i++){
7812    FsdirLevel *pLvl = &pCur->aLvl[i];
7813    if( pLvl->pDir ) closedir(pLvl->pDir);
7814    sqlite3_free(pLvl->zDir);
7815  }
7816  sqlite3_free(pCur->zPath);
7817  sqlite3_free(pCur->aLvl);
7818  pCur->aLvl = 0;
7819  pCur->zPath = 0;
7820  pCur->zBase = 0;
7821  pCur->nBase = 0;
7822  pCur->nLvl = 0;
7823  pCur->iLvl = -1;
7824  pCur->iRowid = 1;
7825}
7826
7827/*
7828** Destructor for an fsdir_cursor.
7829*/
7830static int fsdirClose(sqlite3_vtab_cursor *cur){
7831  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7832
7833  fsdirResetCursor(pCur);
7834  sqlite3_free(pCur);
7835  return SQLITE_OK;
7836}
7837
7838/*
7839** Set the error message for the virtual table associated with cursor
7840** pCur to the results of vprintf(zFmt, ...).
7841*/
7842static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
7843  va_list ap;
7844  va_start(ap, zFmt);
7845  pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
7846  va_end(ap);
7847}
7848
7849
7850/*
7851** Advance an fsdir_cursor to its next row of output.
7852*/
7853static int fsdirNext(sqlite3_vtab_cursor *cur){
7854  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7855  mode_t m = pCur->sStat.st_mode;
7856
7857  pCur->iRowid++;
7858  if( S_ISDIR(m) ){
7859    /* Descend into this directory */
7860    int iNew = pCur->iLvl + 1;
7861    FsdirLevel *pLvl;
7862    if( iNew>=pCur->nLvl ){
7863      int nNew = iNew+1;
7864      sqlite3_int64 nByte = nNew*sizeof(FsdirLevel);
7865      FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte);
7866      if( aNew==0 ) return SQLITE_NOMEM;
7867      memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
7868      pCur->aLvl = aNew;
7869      pCur->nLvl = nNew;
7870    }
7871    pCur->iLvl = iNew;
7872    pLvl = &pCur->aLvl[iNew];
7873
7874    pLvl->zDir = pCur->zPath;
7875    pCur->zPath = 0;
7876    pLvl->pDir = opendir(pLvl->zDir);
7877    if( pLvl->pDir==0 ){
7878      fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
7879      return SQLITE_ERROR;
7880    }
7881  }
7882
7883  while( pCur->iLvl>=0 ){
7884    FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
7885    struct dirent *pEntry = readdir(pLvl->pDir);
7886    if( pEntry ){
7887      if( pEntry->d_name[0]=='.' ){
7888       if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
7889       if( pEntry->d_name[1]=='\0' ) continue;
7890      }
7891      sqlite3_free(pCur->zPath);
7892      pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
7893      if( pCur->zPath==0 ) return SQLITE_NOMEM;
7894      if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
7895        fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
7896        return SQLITE_ERROR;
7897      }
7898      return SQLITE_OK;
7899    }
7900    closedir(pLvl->pDir);
7901    sqlite3_free(pLvl->zDir);
7902    pLvl->pDir = 0;
7903    pLvl->zDir = 0;
7904    pCur->iLvl--;
7905  }
7906
7907  /* EOF */
7908  sqlite3_free(pCur->zPath);
7909  pCur->zPath = 0;
7910  return SQLITE_OK;
7911}
7912
7913/*
7914** Return values of columns for the row at which the series_cursor
7915** is currently pointing.
7916*/
7917static int fsdirColumn(
7918  sqlite3_vtab_cursor *cur,   /* The cursor */
7919  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
7920  int i                       /* Which column to return */
7921){
7922  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7923  switch( i ){
7924    case FSDIR_COLUMN_NAME: {
7925      sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
7926      break;
7927    }
7928
7929    case FSDIR_COLUMN_MODE:
7930      sqlite3_result_int64(ctx, pCur->sStat.st_mode);
7931      break;
7932
7933    case FSDIR_COLUMN_MTIME:
7934      sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
7935      break;
7936
7937    case FSDIR_COLUMN_DATA: {
7938      mode_t m = pCur->sStat.st_mode;
7939      if( S_ISDIR(m) ){
7940        sqlite3_result_null(ctx);
7941#if !defined(_WIN32) && !defined(WIN32)
7942      }else if( S_ISLNK(m) ){
7943        char aStatic[64];
7944        char *aBuf = aStatic;
7945        sqlite3_int64 nBuf = 64;
7946        int n;
7947
7948        while( 1 ){
7949          n = readlink(pCur->zPath, aBuf, nBuf);
7950          if( n<nBuf ) break;
7951          if( aBuf!=aStatic ) sqlite3_free(aBuf);
7952          nBuf = nBuf*2;
7953          aBuf = sqlite3_malloc64(nBuf);
7954          if( aBuf==0 ){
7955            sqlite3_result_error_nomem(ctx);
7956            return SQLITE_NOMEM;
7957          }
7958        }
7959
7960        sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
7961        if( aBuf!=aStatic ) sqlite3_free(aBuf);
7962#endif
7963      }else{
7964        readFileContents(ctx, pCur->zPath);
7965      }
7966    }
7967    case FSDIR_COLUMN_PATH:
7968    default: {
7969      /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters.
7970      ** always return their values as NULL */
7971      break;
7972    }
7973  }
7974  return SQLITE_OK;
7975}
7976
7977/*
7978** Return the rowid for the current row. In this implementation, the
7979** first row returned is assigned rowid value 1, and each subsequent
7980** row a value 1 more than that of the previous.
7981*/
7982static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7983  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7984  *pRowid = pCur->iRowid;
7985  return SQLITE_OK;
7986}
7987
7988/*
7989** Return TRUE if the cursor has been moved off of the last
7990** row of output.
7991*/
7992static int fsdirEof(sqlite3_vtab_cursor *cur){
7993  fsdir_cursor *pCur = (fsdir_cursor*)cur;
7994  return (pCur->zPath==0);
7995}
7996
7997/*
7998** xFilter callback.
7999**
8000** idxNum==1   PATH parameter only
8001** idxNum==2   Both PATH and DIR supplied
8002*/
8003static int fsdirFilter(
8004  sqlite3_vtab_cursor *cur,
8005  int idxNum, const char *idxStr,
8006  int argc, sqlite3_value **argv
8007){
8008  const char *zDir = 0;
8009  fsdir_cursor *pCur = (fsdir_cursor*)cur;
8010  (void)idxStr;
8011  fsdirResetCursor(pCur);
8012
8013  if( idxNum==0 ){
8014    fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
8015    return SQLITE_ERROR;
8016  }
8017
8018  assert( argc==idxNum && (argc==1 || argc==2) );
8019  zDir = (const char*)sqlite3_value_text(argv[0]);
8020  if( zDir==0 ){
8021    fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
8022    return SQLITE_ERROR;
8023  }
8024  if( argc==2 ){
8025    pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
8026  }
8027  if( pCur->zBase ){
8028    pCur->nBase = (int)strlen(pCur->zBase)+1;
8029    pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
8030  }else{
8031    pCur->zPath = sqlite3_mprintf("%s", zDir);
8032  }
8033
8034  if( pCur->zPath==0 ){
8035    return SQLITE_NOMEM;
8036  }
8037  if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
8038    fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
8039    return SQLITE_ERROR;
8040  }
8041
8042  return SQLITE_OK;
8043}
8044
8045/*
8046** SQLite will invoke this method one or more times while planning a query
8047** that uses the generate_series virtual table.  This routine needs to create
8048** a query plan for each invocation and compute an estimated cost for that
8049** plan.
8050**
8051** In this implementation idxNum is used to represent the
8052** query plan.  idxStr is unused.
8053**
8054** The query plan is represented by values of idxNum:
8055**
8056**  (1)  The path value is supplied by argv[0]
8057**  (2)  Path is in argv[0] and dir is in argv[1]
8058*/
8059static int fsdirBestIndex(
8060  sqlite3_vtab *tab,
8061  sqlite3_index_info *pIdxInfo
8062){
8063  int i;                 /* Loop over constraints */
8064  int idxPath = -1;      /* Index in pIdxInfo->aConstraint of PATH= */
8065  int idxDir = -1;       /* Index in pIdxInfo->aConstraint of DIR= */
8066  int seenPath = 0;      /* True if an unusable PATH= constraint is seen */
8067  int seenDir = 0;       /* True if an unusable DIR= constraint is seen */
8068  const struct sqlite3_index_constraint *pConstraint;
8069
8070  (void)tab;
8071  pConstraint = pIdxInfo->aConstraint;
8072  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8073    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8074    switch( pConstraint->iColumn ){
8075      case FSDIR_COLUMN_PATH: {
8076        if( pConstraint->usable ){
8077          idxPath = i;
8078          seenPath = 0;
8079        }else if( idxPath<0 ){
8080          seenPath = 1;
8081        }
8082        break;
8083      }
8084      case FSDIR_COLUMN_DIR: {
8085        if( pConstraint->usable ){
8086          idxDir = i;
8087          seenDir = 0;
8088        }else if( idxDir<0 ){
8089          seenDir = 1;
8090        }
8091        break;
8092      }
8093    }
8094  }
8095  if( seenPath || seenDir ){
8096    /* If input parameters are unusable, disallow this plan */
8097    return SQLITE_CONSTRAINT;
8098  }
8099
8100  if( idxPath<0 ){
8101    pIdxInfo->idxNum = 0;
8102    /* The pIdxInfo->estimatedCost should have been initialized to a huge
8103    ** number.  Leave it unchanged. */
8104    pIdxInfo->estimatedRows = 0x7fffffff;
8105  }else{
8106    pIdxInfo->aConstraintUsage[idxPath].omit = 1;
8107    pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1;
8108    if( idxDir>=0 ){
8109      pIdxInfo->aConstraintUsage[idxDir].omit = 1;
8110      pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2;
8111      pIdxInfo->idxNum = 2;
8112      pIdxInfo->estimatedCost = 10.0;
8113    }else{
8114      pIdxInfo->idxNum = 1;
8115      pIdxInfo->estimatedCost = 100.0;
8116    }
8117  }
8118
8119  return SQLITE_OK;
8120}
8121
8122/*
8123** Register the "fsdir" virtual table.
8124*/
8125static int fsdirRegister(sqlite3 *db){
8126  static sqlite3_module fsdirModule = {
8127    0,                         /* iVersion */
8128    0,                         /* xCreate */
8129    fsdirConnect,              /* xConnect */
8130    fsdirBestIndex,            /* xBestIndex */
8131    fsdirDisconnect,           /* xDisconnect */
8132    0,                         /* xDestroy */
8133    fsdirOpen,                 /* xOpen - open a cursor */
8134    fsdirClose,                /* xClose - close a cursor */
8135    fsdirFilter,               /* xFilter - configure scan constraints */
8136    fsdirNext,                 /* xNext - advance a cursor */
8137    fsdirEof,                  /* xEof - check for end of scan */
8138    fsdirColumn,               /* xColumn - read data */
8139    fsdirRowid,                /* xRowid - read data */
8140    0,                         /* xUpdate */
8141    0,                         /* xBegin */
8142    0,                         /* xSync */
8143    0,                         /* xCommit */
8144    0,                         /* xRollback */
8145    0,                         /* xFindMethod */
8146    0,                         /* xRename */
8147    0,                         /* xSavepoint */
8148    0,                         /* xRelease */
8149    0,                         /* xRollbackTo */
8150    0,                         /* xShadowName */
8151    0                          /* xIntegrity */
8152  };
8153
8154  int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
8155  return rc;
8156}
8157#else         /* SQLITE_OMIT_VIRTUALTABLE */
8158# define fsdirRegister(x) SQLITE_OK
8159#endif
8160
8161#ifdef _WIN32
8162
8163#endif
8164int sqlite3_fileio_init(
8165  sqlite3 *db,
8166  char **pzErrMsg,
8167  const sqlite3_api_routines *pApi
8168){
8169  int rc = SQLITE_OK;
8170  SQLITE_EXTENSION_INIT2(pApi);
8171  (void)pzErrMsg;  /* Unused parameter */
8172  rc = sqlite3_create_function(db, "readfile", 1,
8173                               SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8174                               readfileFunc, 0, 0);
8175  if( rc==SQLITE_OK ){
8176    rc = sqlite3_create_function(db, "writefile", -1,
8177                                 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
8178                                 writefileFunc, 0, 0);
8179  }
8180  if( rc==SQLITE_OK ){
8181    rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
8182                                 lsModeFunc, 0, 0);
8183  }
8184  if( rc==SQLITE_OK ){
8185    rc = fsdirRegister(db);
8186  }
8187  return rc;
8188}
8189
8190#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32))
8191/* To allow a standalone DLL, make test_windirent.c use the same
8192 * redefined SQLite API calls as the above extension code does.
8193 * Just pull in this .c to accomplish this. As a beneficial side
8194 * effect, this extension becomes a single translation unit. */
8195#  include "test_windirent.c"
8196#endif
8197
8198/************************* End ../ext/misc/fileio.c ********************/
8199/************************* Begin ../ext/misc/completion.c ******************/
8200/*
8201** 2017-07-10
8202**
8203** The author disclaims copyright to this source code.  In place of
8204** a legal notice, here is a blessing:
8205**
8206**    May you do good and not evil.
8207**    May you find forgiveness for yourself and forgive others.
8208**    May you share freely, never taking more than you give.
8209**
8210*************************************************************************
8211**
8212** This file implements an eponymous virtual table that returns suggested
8213** completions for a partial SQL input.
8214**
8215** Suggested usage:
8216**
8217**     SELECT DISTINCT candidate COLLATE nocase
8218**       FROM completion($prefix,$wholeline)
8219**      ORDER BY 1;
8220**
8221** The two query parameters are optional.  $prefix is the text of the
8222** current word being typed and that is to be completed.  $wholeline is
8223** the complete input line, used for context.
8224**
8225** The raw completion() table might return the same candidate multiple
8226** times, for example if the same column name is used to two or more
8227** tables.  And the candidates are returned in an arbitrary order.  Hence,
8228** the DISTINCT and ORDER BY are recommended.
8229**
8230** This virtual table operates at the speed of human typing, and so there
8231** is no attempt to make it fast.  Even a slow implementation will be much
8232** faster than any human can type.
8233**
8234*/
8235/* #include "sqlite3ext.h" */
8236SQLITE_EXTENSION_INIT1
8237#include <assert.h>
8238#include <string.h>
8239#include <ctype.h>
8240
8241#ifndef SQLITE_OMIT_VIRTUALTABLE
8242
8243/* completion_vtab is a subclass of sqlite3_vtab which will
8244** serve as the underlying representation of a completion virtual table
8245*/
8246typedef struct completion_vtab completion_vtab;
8247struct completion_vtab {
8248  sqlite3_vtab base;  /* Base class - must be first */
8249  sqlite3 *db;        /* Database connection for this completion vtab */
8250};
8251
8252/* completion_cursor is a subclass of sqlite3_vtab_cursor which will
8253** serve as the underlying representation of a cursor that scans
8254** over rows of the result
8255*/
8256typedef struct completion_cursor completion_cursor;
8257struct completion_cursor {
8258  sqlite3_vtab_cursor base;  /* Base class - must be first */
8259  sqlite3 *db;               /* Database connection for this cursor */
8260  int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
8261  char *zPrefix;             /* The prefix for the word we want to complete */
8262  char *zLine;               /* The whole that we want to complete */
8263  const char *zCurrentRow;   /* Current output row */
8264  int szRow;                 /* Length of the zCurrentRow string */
8265  sqlite3_stmt *pStmt;       /* Current statement */
8266  sqlite3_int64 iRowid;      /* The rowid */
8267  int ePhase;                /* Current phase */
8268  int j;                     /* inter-phase counter */
8269};
8270
8271/* Values for ePhase:
8272*/
8273#define COMPLETION_FIRST_PHASE   1
8274#define COMPLETION_KEYWORDS      1
8275#define COMPLETION_PRAGMAS       2
8276#define COMPLETION_FUNCTIONS     3
8277#define COMPLETION_COLLATIONS    4
8278#define COMPLETION_INDEXES       5
8279#define COMPLETION_TRIGGERS      6
8280#define COMPLETION_DATABASES     7
8281#define COMPLETION_TABLES        8    /* Also VIEWs and TRIGGERs */
8282#define COMPLETION_COLUMNS       9
8283#define COMPLETION_MODULES       10
8284#define COMPLETION_EOF           11
8285
8286/*
8287** The completionConnect() method is invoked to create a new
8288** completion_vtab that describes the completion virtual table.
8289**
8290** Think of this routine as the constructor for completion_vtab objects.
8291**
8292** All this routine needs to do is:
8293**
8294**    (1) Allocate the completion_vtab object and initialize all fields.
8295**
8296**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
8297**        result set of queries against completion will look like.
8298*/
8299static int completionConnect(
8300  sqlite3 *db,
8301  void *pAux,
8302  int argc, const char *const*argv,
8303  sqlite3_vtab **ppVtab,
8304  char **pzErr
8305){
8306  completion_vtab *pNew;
8307  int rc;
8308
8309  (void)(pAux);    /* Unused parameter */
8310  (void)(argc);    /* Unused parameter */
8311  (void)(argv);    /* Unused parameter */
8312  (void)(pzErr);   /* Unused parameter */
8313
8314/* Column numbers */
8315#define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
8316#define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
8317#define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
8318#define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
8319
8320  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
8321  rc = sqlite3_declare_vtab(db,
8322      "CREATE TABLE x("
8323      "  candidate TEXT,"
8324      "  prefix TEXT HIDDEN,"
8325      "  wholeline TEXT HIDDEN,"
8326      "  phase INT HIDDEN"        /* Used for debugging only */
8327      ")");
8328  if( rc==SQLITE_OK ){
8329    pNew = sqlite3_malloc( sizeof(*pNew) );
8330    *ppVtab = (sqlite3_vtab*)pNew;
8331    if( pNew==0 ) return SQLITE_NOMEM;
8332    memset(pNew, 0, sizeof(*pNew));
8333    pNew->db = db;
8334  }
8335  return rc;
8336}
8337
8338/*
8339** This method is the destructor for completion_cursor objects.
8340*/
8341static int completionDisconnect(sqlite3_vtab *pVtab){
8342  sqlite3_free(pVtab);
8343  return SQLITE_OK;
8344}
8345
8346/*
8347** Constructor for a new completion_cursor object.
8348*/
8349static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
8350  completion_cursor *pCur;
8351  pCur = sqlite3_malloc( sizeof(*pCur) );
8352  if( pCur==0 ) return SQLITE_NOMEM;
8353  memset(pCur, 0, sizeof(*pCur));
8354  pCur->db = ((completion_vtab*)p)->db;
8355  *ppCursor = &pCur->base;
8356  return SQLITE_OK;
8357}
8358
8359/*
8360** Reset the completion_cursor.
8361*/
8362static void completionCursorReset(completion_cursor *pCur){
8363  sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
8364  sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
8365  sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
8366  pCur->j = 0;
8367}
8368
8369/*
8370** Destructor for a completion_cursor.
8371*/
8372static int completionClose(sqlite3_vtab_cursor *cur){
8373  completionCursorReset((completion_cursor*)cur);
8374  sqlite3_free(cur);
8375  return SQLITE_OK;
8376}
8377
8378/*
8379** Advance a completion_cursor to its next row of output.
8380**
8381** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
8382** record the current state of the scan.  This routine sets ->zCurrentRow
8383** to the current row of output and then returns.  If no more rows remain,
8384** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
8385** table that has reached the end of its scan.
8386**
8387** The current implementation just lists potential identifiers and
8388** keywords and filters them by zPrefix.  Future enhancements should
8389** take zLine into account to try to restrict the set of identifiers and
8390** keywords based on what would be legal at the current point of input.
8391*/
8392static int completionNext(sqlite3_vtab_cursor *cur){
8393  completion_cursor *pCur = (completion_cursor*)cur;
8394  int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
8395  int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
8396  pCur->iRowid++;
8397  while( pCur->ePhase!=COMPLETION_EOF ){
8398    switch( pCur->ePhase ){
8399      case COMPLETION_KEYWORDS: {
8400        if( pCur->j >= sqlite3_keyword_count() ){
8401          pCur->zCurrentRow = 0;
8402          pCur->ePhase = COMPLETION_DATABASES;
8403        }else{
8404          sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
8405        }
8406        iCol = -1;
8407        break;
8408      }
8409      case COMPLETION_DATABASES: {
8410        if( pCur->pStmt==0 ){
8411          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
8412                             &pCur->pStmt, 0);
8413        }
8414        iCol = 1;
8415        eNextPhase = COMPLETION_TABLES;
8416        break;
8417      }
8418      case COMPLETION_TABLES: {
8419        if( pCur->pStmt==0 ){
8420          sqlite3_stmt *pS2;
8421          char *zSql = 0;
8422          const char *zSep = "";
8423          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8424          while( sqlite3_step(pS2)==SQLITE_ROW ){
8425            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8426            zSql = sqlite3_mprintf(
8427               "%z%s"
8428               "SELECT name FROM \"%w\".sqlite_schema",
8429               zSql, zSep, zDb
8430            );
8431            if( zSql==0 ) return SQLITE_NOMEM;
8432            zSep = " UNION ";
8433          }
8434          sqlite3_finalize(pS2);
8435          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8436          sqlite3_free(zSql);
8437        }
8438        iCol = 0;
8439        eNextPhase = COMPLETION_COLUMNS;
8440        break;
8441      }
8442      case COMPLETION_COLUMNS: {
8443        if( pCur->pStmt==0 ){
8444          sqlite3_stmt *pS2;
8445          char *zSql = 0;
8446          const char *zSep = "";
8447          sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
8448          while( sqlite3_step(pS2)==SQLITE_ROW ){
8449            const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
8450            zSql = sqlite3_mprintf(
8451               "%z%s"
8452               "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
8453                       " JOIN pragma_table_info(sm.name,%Q) AS pti"
8454               " WHERE sm.type='table'",
8455               zSql, zSep, zDb, zDb
8456            );
8457            if( zSql==0 ) return SQLITE_NOMEM;
8458            zSep = " UNION ";
8459          }
8460          sqlite3_finalize(pS2);
8461          sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
8462          sqlite3_free(zSql);
8463        }
8464        iCol = 0;
8465        eNextPhase = COMPLETION_EOF;
8466        break;
8467      }
8468    }
8469    if( iCol<0 ){
8470      /* This case is when the phase presets zCurrentRow */
8471      if( pCur->zCurrentRow==0 ) continue;
8472    }else{
8473      if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
8474        /* Extract the next row of content */
8475        pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
8476        pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
8477      }else{
8478        /* When all rows are finished, advance to the next phase */
8479        sqlite3_finalize(pCur->pStmt);
8480        pCur->pStmt = 0;
8481        pCur->ePhase = eNextPhase;
8482        continue;
8483      }
8484    }
8485    if( pCur->nPrefix==0 ) break;
8486    if( pCur->nPrefix<=pCur->szRow
8487     && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
8488    ){
8489      break;
8490    }
8491  }
8492
8493  return SQLITE_OK;
8494}
8495
8496/*
8497** Return values of columns for the row at which the completion_cursor
8498** is currently pointing.
8499*/
8500static int completionColumn(
8501  sqlite3_vtab_cursor *cur,   /* The cursor */
8502  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
8503  int i                       /* Which column to return */
8504){
8505  completion_cursor *pCur = (completion_cursor*)cur;
8506  switch( i ){
8507    case COMPLETION_COLUMN_CANDIDATE: {
8508      sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
8509      break;
8510    }
8511    case COMPLETION_COLUMN_PREFIX: {
8512      sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
8513      break;
8514    }
8515    case COMPLETION_COLUMN_WHOLELINE: {
8516      sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
8517      break;
8518    }
8519    case COMPLETION_COLUMN_PHASE: {
8520      sqlite3_result_int(ctx, pCur->ePhase);
8521      break;
8522    }
8523  }
8524  return SQLITE_OK;
8525}
8526
8527/*
8528** Return the rowid for the current row.  In this implementation, the
8529** rowid is the same as the output value.
8530*/
8531static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
8532  completion_cursor *pCur = (completion_cursor*)cur;
8533  *pRowid = pCur->iRowid;
8534  return SQLITE_OK;
8535}
8536
8537/*
8538** Return TRUE if the cursor has been moved off of the last
8539** row of output.
8540*/
8541static int completionEof(sqlite3_vtab_cursor *cur){
8542  completion_cursor *pCur = (completion_cursor*)cur;
8543  return pCur->ePhase >= COMPLETION_EOF;
8544}
8545
8546/*
8547** This method is called to "rewind" the completion_cursor object back
8548** to the first row of output.  This method is always called at least
8549** once prior to any call to completionColumn() or completionRowid() or
8550** completionEof().
8551*/
8552static int completionFilter(
8553  sqlite3_vtab_cursor *pVtabCursor,
8554  int idxNum, const char *idxStr,
8555  int argc, sqlite3_value **argv
8556){
8557  completion_cursor *pCur = (completion_cursor *)pVtabCursor;
8558  int iArg = 0;
8559  (void)(idxStr);   /* Unused parameter */
8560  (void)(argc);     /* Unused parameter */
8561  completionCursorReset(pCur);
8562  if( idxNum & 1 ){
8563    pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
8564    if( pCur->nPrefix>0 ){
8565      pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8566      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8567    }
8568    iArg = 1;
8569  }
8570  if( idxNum & 2 ){
8571    pCur->nLine = sqlite3_value_bytes(argv[iArg]);
8572    if( pCur->nLine>0 ){
8573      pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
8574      if( pCur->zLine==0 ) return SQLITE_NOMEM;
8575    }
8576  }
8577  if( pCur->zLine!=0 && pCur->zPrefix==0 ){
8578    int i = pCur->nLine;
8579    while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
8580      i--;
8581    }
8582    pCur->nPrefix = pCur->nLine - i;
8583    if( pCur->nPrefix>0 ){
8584      pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
8585      if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
8586    }
8587  }
8588  pCur->iRowid = 0;
8589  pCur->ePhase = COMPLETION_FIRST_PHASE;
8590  return completionNext(pVtabCursor);
8591}
8592
8593/*
8594** SQLite will invoke this method one or more times while planning a query
8595** that uses the completion virtual table.  This routine needs to create
8596** a query plan for each invocation and compute an estimated cost for that
8597** plan.
8598**
8599** There are two hidden parameters that act as arguments to the table-valued
8600** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
8601** is available and bit 1 is set if "wholeline" is available.
8602*/
8603static int completionBestIndex(
8604  sqlite3_vtab *tab,
8605  sqlite3_index_info *pIdxInfo
8606){
8607  int i;                 /* Loop over constraints */
8608  int idxNum = 0;        /* The query plan bitmask */
8609  int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
8610  int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
8611  int nArg = 0;          /* Number of arguments that completeFilter() expects */
8612  const struct sqlite3_index_constraint *pConstraint;
8613
8614  (void)(tab);    /* Unused parameter */
8615  pConstraint = pIdxInfo->aConstraint;
8616  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
8617    if( pConstraint->usable==0 ) continue;
8618    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
8619    switch( pConstraint->iColumn ){
8620      case COMPLETION_COLUMN_PREFIX:
8621        prefixIdx = i;
8622        idxNum |= 1;
8623        break;
8624      case COMPLETION_COLUMN_WHOLELINE:
8625        wholelineIdx = i;
8626        idxNum |= 2;
8627        break;
8628    }
8629  }
8630  if( prefixIdx>=0 ){
8631    pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
8632    pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
8633  }
8634  if( wholelineIdx>=0 ){
8635    pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
8636    pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
8637  }
8638  pIdxInfo->idxNum = idxNum;
8639  pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
8640  pIdxInfo->estimatedRows = 500 - 100*nArg;
8641  return SQLITE_OK;
8642}
8643
8644/*
8645** This following structure defines all the methods for the
8646** completion virtual table.
8647*/
8648static sqlite3_module completionModule = {
8649  0,                         /* iVersion */
8650  0,                         /* xCreate */
8651  completionConnect,         /* xConnect */
8652  completionBestIndex,       /* xBestIndex */
8653  completionDisconnect,      /* xDisconnect */
8654  0,                         /* xDestroy */
8655  completionOpen,            /* xOpen - open a cursor */
8656  completionClose,           /* xClose - close a cursor */
8657  completionFilter,          /* xFilter - configure scan constraints */
8658  completionNext,            /* xNext - advance a cursor */
8659  completionEof,             /* xEof - check for end of scan */
8660  completionColumn,          /* xColumn - read data */
8661  completionRowid,           /* xRowid - read data */
8662  0,                         /* xUpdate */
8663  0,                         /* xBegin */
8664  0,                         /* xSync */
8665  0,                         /* xCommit */
8666  0,                         /* xRollback */
8667  0,                         /* xFindMethod */
8668  0,                         /* xRename */
8669  0,                         /* xSavepoint */
8670  0,                         /* xRelease */
8671  0,                         /* xRollbackTo */
8672  0,                         /* xShadowName */
8673  0                          /* xIntegrity */
8674};
8675
8676#endif /* SQLITE_OMIT_VIRTUALTABLE */
8677
8678int sqlite3CompletionVtabInit(sqlite3 *db){
8679  int rc = SQLITE_OK;
8680#ifndef SQLITE_OMIT_VIRTUALTABLE
8681  rc = sqlite3_create_module(db, "completion", &completionModule, 0);
8682#endif
8683  return rc;
8684}
8685
8686#ifdef _WIN32
8687
8688#endif
8689int sqlite3_completion_init(
8690  sqlite3 *db,
8691  char **pzErrMsg,
8692  const sqlite3_api_routines *pApi
8693){
8694  int rc = SQLITE_OK;
8695  SQLITE_EXTENSION_INIT2(pApi);
8696  (void)(pzErrMsg);  /* Unused parameter */
8697#ifndef SQLITE_OMIT_VIRTUALTABLE
8698  rc = sqlite3CompletionVtabInit(db);
8699#endif
8700  return rc;
8701}
8702
8703/************************* End ../ext/misc/completion.c ********************/
8704/************************* Begin ../ext/misc/appendvfs.c ******************/
8705/*
8706** 2017-10-20
8707**
8708** The author disclaims copyright to this source code.  In place of
8709** a legal notice, here is a blessing:
8710**
8711**    May you do good and not evil.
8712**    May you find forgiveness for yourself and forgive others.
8713**    May you share freely, never taking more than you give.
8714**
8715******************************************************************************
8716**
8717** This file implements a VFS shim that allows an SQLite database to be
8718** appended onto the end of some other file, such as an executable.
8719**
8720** A special record must appear at the end of the file that identifies the
8721** file as an appended database and provides the offset to the first page
8722** of the exposed content. (Or, it is the length of the content prefix.)
8723** For best performance page 1 should be located at a disk page boundary,
8724** though that is not required.
8725**
8726** When opening a database using this VFS, the connection might treat
8727** the file as an ordinary SQLite database, or it might treat it as a
8728** database appended onto some other file.  The decision is made by
8729** applying the following rules in order:
8730**
8731**  (1)  An empty file is an ordinary database.
8732**
8733**  (2)  If the file ends with the appendvfs trailer string
8734**       "Start-Of-SQLite3-NNNNNNNN" that file is an appended database.
8735**
8736**  (3)  If the file begins with the standard SQLite prefix string
8737**       "SQLite format 3", that file is an ordinary database.
8738**
8739**  (4)  If none of the above apply and the SQLITE_OPEN_CREATE flag is
8740**       set, then a new database is appended to the already existing file.
8741**
8742**  (5)  Otherwise, SQLITE_CANTOPEN is returned.
8743**
8744** To avoid unnecessary complications with the PENDING_BYTE, the size of
8745** the file containing the database is limited to 1GiB. (1073741824 bytes)
8746** This VFS will not read or write past the 1GiB mark.  This restriction
8747** might be lifted in future versions.  For now, if you need a larger
8748** database, then keep it in a separate file.
8749**
8750** If the file being opened is a plain database (not an appended one), then
8751** this shim is a pass-through into the default underlying VFS. (rule 3)
8752**/
8753/* #include "sqlite3ext.h" */
8754SQLITE_EXTENSION_INIT1
8755#include <string.h>
8756#include <assert.h>
8757
8758/* The append mark at the end of the database is:
8759**
8760**     Start-Of-SQLite3-NNNNNNNN
8761**     123456789 123456789 12345
8762**
8763** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
8764** the offset to page 1, and also the length of the prefix content.
8765*/
8766#define APND_MARK_PREFIX     "Start-Of-SQLite3-"
8767#define APND_MARK_PREFIX_SZ  17
8768#define APND_MARK_FOS_SZ      8
8769#define APND_MARK_SIZE       (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ)
8770
8771/*
8772** Maximum size of the combined prefix + database + append-mark.  This
8773** must be less than 0x40000000 to avoid locking issues on Windows.
8774*/
8775#define APND_MAX_SIZE  (0x40000000)
8776
8777/*
8778** Try to align the database to an even multiple of APND_ROUNDUP bytes.
8779*/
8780#ifndef APND_ROUNDUP
8781#define APND_ROUNDUP 4096
8782#endif
8783#define APND_ALIGN_MASK         ((sqlite3_int64)(APND_ROUNDUP-1))
8784#define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK)
8785
8786/*
8787** Forward declaration of objects used by this utility
8788*/
8789typedef struct sqlite3_vfs ApndVfs;
8790typedef struct ApndFile ApndFile;
8791
8792/* Access to a lower-level VFS that (might) implement dynamic loading,
8793** access to randomness, etc.
8794*/
8795#define ORIGVFS(p)  ((sqlite3_vfs*)((p)->pAppData))
8796#define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
8797
8798/* An open appendvfs file
8799**
8800** An instance of this structure describes the appended database file.
8801** A separate sqlite3_file object is always appended. The appended
8802** sqlite3_file object (which can be accessed using ORIGFILE()) describes
8803** the entire file, including the prefix, the database, and the
8804** append-mark.
8805**
8806** The structure of an AppendVFS database is like this:
8807**
8808**   +-------------+---------+----------+-------------+
8809**   | prefix-file | padding | database | append-mark |
8810**   +-------------+---------+----------+-------------+
8811**                           ^          ^
8812**                           |          |
8813**                         iPgOne      iMark
8814**
8815**
8816** "prefix file" -  file onto which the database has been appended.
8817** "padding"     -  zero or more bytes inserted so that "database"
8818**                  starts on an APND_ROUNDUP boundary
8819** "database"    -  The SQLite database file
8820** "append-mark" -  The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates
8821**                  the offset from the start of prefix-file to the start
8822**                  of "database".
8823**
8824** The size of the database is iMark - iPgOne.
8825**
8826** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value
8827** of iPgOne stored as a big-ending 64-bit integer.
8828**
8829** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE).
8830** Or, iMark is -1 to indicate that it has not yet been written.
8831*/
8832struct ApndFile {
8833  sqlite3_file base;        /* Subclass.  MUST BE FIRST! */
8834  sqlite3_int64 iPgOne;     /* Offset to the start of the database */
8835  sqlite3_int64 iMark;      /* Offset of the append mark.  -1 if unwritten */
8836  /* Always followed by another sqlite3_file that describes the whole file */
8837};
8838
8839/*
8840** Methods for ApndFile
8841*/
8842static int apndClose(sqlite3_file*);
8843static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
8844static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
8845static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
8846static int apndSync(sqlite3_file*, int flags);
8847static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
8848static int apndLock(sqlite3_file*, int);
8849static int apndUnlock(sqlite3_file*, int);
8850static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
8851static int apndFileControl(sqlite3_file*, int op, void *pArg);
8852static int apndSectorSize(sqlite3_file*);
8853static int apndDeviceCharacteristics(sqlite3_file*);
8854static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
8855static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
8856static void apndShmBarrier(sqlite3_file*);
8857static int apndShmUnmap(sqlite3_file*, int deleteFlag);
8858static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
8859static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
8860
8861/*
8862** Methods for ApndVfs
8863*/
8864static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
8865static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
8866static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
8867static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
8868static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
8869static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
8870static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
8871static void apndDlClose(sqlite3_vfs*, void*);
8872static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
8873static int apndSleep(sqlite3_vfs*, int microseconds);
8874static int apndCurrentTime(sqlite3_vfs*, double*);
8875static int apndGetLastError(sqlite3_vfs*, int, char *);
8876static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
8877static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
8878static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
8879static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
8880
8881static sqlite3_vfs apnd_vfs = {
8882  3,                            /* iVersion (set when registered) */
8883  0,                            /* szOsFile (set when registered) */
8884  1024,                         /* mxPathname */
8885  0,                            /* pNext */
8886  "apndvfs",                    /* zName */
8887  0,                            /* pAppData (set when registered) */
8888  apndOpen,                     /* xOpen */
8889  apndDelete,                   /* xDelete */
8890  apndAccess,                   /* xAccess */
8891  apndFullPathname,             /* xFullPathname */
8892  apndDlOpen,                   /* xDlOpen */
8893  apndDlError,                  /* xDlError */
8894  apndDlSym,                    /* xDlSym */
8895  apndDlClose,                  /* xDlClose */
8896  apndRandomness,               /* xRandomness */
8897  apndSleep,                    /* xSleep */
8898  apndCurrentTime,              /* xCurrentTime */
8899  apndGetLastError,             /* xGetLastError */
8900  apndCurrentTimeInt64,         /* xCurrentTimeInt64 */
8901  apndSetSystemCall,            /* xSetSystemCall */
8902  apndGetSystemCall,            /* xGetSystemCall */
8903  apndNextSystemCall            /* xNextSystemCall */
8904};
8905
8906static const sqlite3_io_methods apnd_io_methods = {
8907  3,                              /* iVersion */
8908  apndClose,                      /* xClose */
8909  apndRead,                       /* xRead */
8910  apndWrite,                      /* xWrite */
8911  apndTruncate,                   /* xTruncate */
8912  apndSync,                       /* xSync */
8913  apndFileSize,                   /* xFileSize */
8914  apndLock,                       /* xLock */
8915  apndUnlock,                     /* xUnlock */
8916  apndCheckReservedLock,          /* xCheckReservedLock */
8917  apndFileControl,                /* xFileControl */
8918  apndSectorSize,                 /* xSectorSize */
8919  apndDeviceCharacteristics,      /* xDeviceCharacteristics */
8920  apndShmMap,                     /* xShmMap */
8921  apndShmLock,                    /* xShmLock */
8922  apndShmBarrier,                 /* xShmBarrier */
8923  apndShmUnmap,                   /* xShmUnmap */
8924  apndFetch,                      /* xFetch */
8925  apndUnfetch                     /* xUnfetch */
8926};
8927
8928/*
8929** Close an apnd-file.
8930*/
8931static int apndClose(sqlite3_file *pFile){
8932  pFile = ORIGFILE(pFile);
8933  return pFile->pMethods->xClose(pFile);
8934}
8935
8936/*
8937** Read data from an apnd-file.
8938*/
8939static int apndRead(
8940  sqlite3_file *pFile,
8941  void *zBuf,
8942  int iAmt,
8943  sqlite_int64 iOfst
8944){
8945  ApndFile *paf = (ApndFile *)pFile;
8946  pFile = ORIGFILE(pFile);
8947  return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8948}
8949
8950/*
8951** Add the append-mark onto what should become the end of the file.
8952*  If and only if this succeeds, internal ApndFile.iMark is updated.
8953*  Parameter iWriteEnd is the appendvfs-relative offset of the new mark.
8954*/
8955static int apndWriteMark(
8956  ApndFile *paf,
8957  sqlite3_file *pFile,
8958  sqlite_int64 iWriteEnd
8959){
8960  sqlite_int64 iPgOne = paf->iPgOne;
8961  unsigned char a[APND_MARK_SIZE];
8962  int i = APND_MARK_FOS_SZ;
8963  int rc;
8964  assert(pFile == ORIGFILE(paf));
8965  memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
8966  while( --i >= 0 ){
8967    a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff);
8968    iPgOne >>= 8;
8969  }
8970  iWriteEnd += paf->iPgOne;
8971  if( SQLITE_OK==(rc = pFile->pMethods->xWrite
8972                  (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){
8973    paf->iMark = iWriteEnd;
8974  }
8975  return rc;
8976}
8977
8978/*
8979** Write data to an apnd-file.
8980*/
8981static int apndWrite(
8982  sqlite3_file *pFile,
8983  const void *zBuf,
8984  int iAmt,
8985  sqlite_int64 iOfst
8986){
8987  ApndFile *paf = (ApndFile *)pFile;
8988  sqlite_int64 iWriteEnd = iOfst + iAmt;
8989  if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL;
8990  pFile = ORIGFILE(pFile);
8991  /* If append-mark is absent or will be overwritten, write it. */
8992  if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){
8993    int rc = apndWriteMark(paf, pFile, iWriteEnd);
8994    if( SQLITE_OK!=rc ) return rc;
8995  }
8996  return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst);
8997}
8998
8999/*
9000** Truncate an apnd-file.
9001*/
9002static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
9003  ApndFile *paf = (ApndFile *)pFile;
9004  pFile = ORIGFILE(pFile);
9005  /* The append mark goes out first so truncate failure does not lose it. */
9006  if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR;
9007  /* Truncate underlying file just past append mark */
9008  return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE);
9009}
9010
9011/*
9012** Sync an apnd-file.
9013*/
9014static int apndSync(sqlite3_file *pFile, int flags){
9015  pFile = ORIGFILE(pFile);
9016  return pFile->pMethods->xSync(pFile, flags);
9017}
9018
9019/*
9020** Return the current file-size of an apnd-file.
9021** If the append mark is not yet there, the file-size is 0.
9022*/
9023static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
9024  ApndFile *paf = (ApndFile *)pFile;
9025  *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0;
9026  return SQLITE_OK;
9027}
9028
9029/*
9030** Lock an apnd-file.
9031*/
9032static int apndLock(sqlite3_file *pFile, int eLock){
9033  pFile = ORIGFILE(pFile);
9034  return pFile->pMethods->xLock(pFile, eLock);
9035}
9036
9037/*
9038** Unlock an apnd-file.
9039*/
9040static int apndUnlock(sqlite3_file *pFile, int eLock){
9041  pFile = ORIGFILE(pFile);
9042  return pFile->pMethods->xUnlock(pFile, eLock);
9043}
9044
9045/*
9046** Check if another file-handle holds a RESERVED lock on an apnd-file.
9047*/
9048static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
9049  pFile = ORIGFILE(pFile);
9050  return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
9051}
9052
9053/*
9054** File control method. For custom operations on an apnd-file.
9055*/
9056static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
9057  ApndFile *paf = (ApndFile *)pFile;
9058  int rc;
9059  pFile = ORIGFILE(pFile);
9060  if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne;
9061  rc = pFile->pMethods->xFileControl(pFile, op, pArg);
9062  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
9063    *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg);
9064  }
9065  return rc;
9066}
9067
9068/*
9069** Return the sector-size in bytes for an apnd-file.
9070*/
9071static int apndSectorSize(sqlite3_file *pFile){
9072  pFile = ORIGFILE(pFile);
9073  return pFile->pMethods->xSectorSize(pFile);
9074}
9075
9076/*
9077** Return the device characteristic flags supported by an apnd-file.
9078*/
9079static int apndDeviceCharacteristics(sqlite3_file *pFile){
9080  pFile = ORIGFILE(pFile);
9081  return pFile->pMethods->xDeviceCharacteristics(pFile);
9082}
9083
9084/* Create a shared memory file mapping */
9085static int apndShmMap(
9086  sqlite3_file *pFile,
9087  int iPg,
9088  int pgsz,
9089  int bExtend,
9090  void volatile **pp
9091){
9092  pFile = ORIGFILE(pFile);
9093  return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
9094}
9095
9096/* Perform locking on a shared-memory segment */
9097static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
9098  pFile = ORIGFILE(pFile);
9099  return pFile->pMethods->xShmLock(pFile,offset,n,flags);
9100}
9101
9102/* Memory barrier operation on shared memory */
9103static void apndShmBarrier(sqlite3_file *pFile){
9104  pFile = ORIGFILE(pFile);
9105  pFile->pMethods->xShmBarrier(pFile);
9106}
9107
9108/* Unmap a shared memory segment */
9109static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
9110  pFile = ORIGFILE(pFile);
9111  return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
9112}
9113
9114/* Fetch a page of a memory-mapped file */
9115static int apndFetch(
9116  sqlite3_file *pFile,
9117  sqlite3_int64 iOfst,
9118  int iAmt,
9119  void **pp
9120){
9121  ApndFile *p = (ApndFile *)pFile;
9122  if( p->iMark < 0 || iOfst+iAmt > p->iMark ){
9123    return SQLITE_IOERR; /* Cannot read what is not yet there. */
9124  }
9125  pFile = ORIGFILE(pFile);
9126  return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
9127}
9128
9129/* Release a memory-mapped page */
9130static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
9131  ApndFile *p = (ApndFile *)pFile;
9132  pFile = ORIGFILE(pFile);
9133  return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
9134}
9135
9136/*
9137** Try to read the append-mark off the end of a file.  Return the
9138** start of the appended database if the append-mark is present.
9139** If there is no valid append-mark, return -1;
9140**
9141** An append-mark is only valid if the NNNNNNNN start-of-database offset
9142** indicates that the appended database contains at least one page.  The
9143** start-of-database value must be a multiple of 512.
9144*/
9145static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
9146  int rc, i;
9147  sqlite3_int64 iMark;
9148  int msbs = 8 * (APND_MARK_FOS_SZ-1);
9149  unsigned char a[APND_MARK_SIZE];
9150
9151  if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1;
9152  rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
9153  if( rc ) return -1;
9154  if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
9155  iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs;
9156  for(i=1; i<8; i++){
9157    msbs -= 8;
9158    iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<msbs;
9159  }
9160  if( iMark > (sz - APND_MARK_SIZE - 512) ) return -1;
9161  if( iMark & 0x1ff ) return -1;
9162  return iMark;
9163}
9164
9165static const char apvfsSqliteHdr[] = "SQLite format 3";
9166/*
9167** Check to see if the file is an appendvfs SQLite database file.
9168** Return true iff it is such. Parameter sz is the file's size.
9169*/
9170static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){
9171  int rc;
9172  char zHdr[16];
9173  sqlite3_int64 iMark = apndReadMark(sz, pFile);
9174  if( iMark>=0 ){
9175    /* If file has the correct end-marker, the expected odd size, and the
9176    ** SQLite DB type marker where the end-marker puts it, then it
9177    ** is an appendvfs database.
9178    */
9179    rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark);
9180    if( SQLITE_OK==rc
9181     && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0
9182     && (sz & 0x1ff) == APND_MARK_SIZE
9183     && sz>=512+APND_MARK_SIZE
9184    ){
9185      return 1; /* It's an appendvfs database */
9186    }
9187  }
9188  return 0;
9189}
9190
9191/*
9192** Check to see if the file is an ordinary SQLite database file.
9193** Return true iff so. Parameter sz is the file's size.
9194*/
9195static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
9196  char zHdr[16];
9197  if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */
9198   || (sz & 0x1ff) != 0
9199   || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0)
9200   || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0
9201  ){
9202    return 0;
9203  }else{
9204    return 1;
9205  }
9206}
9207
9208/*
9209** Open an apnd file handle.
9210*/
9211static int apndOpen(
9212  sqlite3_vfs *pApndVfs,
9213  const char *zName,
9214  sqlite3_file *pFile,
9215  int flags,
9216  int *pOutFlags
9217){
9218  ApndFile *pApndFile = (ApndFile*)pFile;
9219  sqlite3_file *pBaseFile = ORIGFILE(pFile);
9220  sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs);
9221  int rc;
9222  sqlite3_int64 sz = 0;
9223  if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
9224    /* The appendvfs is not to be used for transient or temporary databases.
9225    ** Just use the base VFS open to initialize the given file object and
9226    ** open the underlying file. (Appendvfs is then unused for this file.)
9227    */
9228    return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags);
9229  }
9230  memset(pApndFile, 0, sizeof(ApndFile));
9231  pFile->pMethods = &apnd_io_methods;
9232  pApndFile->iMark = -1;    /* Append mark not yet written */
9233
9234  rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags);
9235  if( rc==SQLITE_OK ){
9236    rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz);
9237    if( rc ){
9238      pBaseFile->pMethods->xClose(pBaseFile);
9239    }
9240  }
9241  if( rc ){
9242    pFile->pMethods = 0;
9243    return rc;
9244  }
9245  if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){
9246    /* The file being opened appears to be just an ordinary DB. Copy
9247    ** the base dispatch-table so this instance mimics the base VFS.
9248    */
9249    memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile);
9250    return SQLITE_OK;
9251  }
9252  pApndFile->iPgOne = apndReadMark(sz, pFile);
9253  if( pApndFile->iPgOne>=0 ){
9254    pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */
9255    return SQLITE_OK;
9256  }
9257  if( (flags & SQLITE_OPEN_CREATE)==0 ){
9258    pBaseFile->pMethods->xClose(pBaseFile);
9259    rc = SQLITE_CANTOPEN;
9260    pFile->pMethods = 0;
9261  }else{
9262    /* Round newly added appendvfs location to #define'd page boundary.
9263    ** Note that nothing has yet been written to the underlying file.
9264    ** The append mark will be written along with first content write.
9265    ** Until then, paf->iMark value indicates it is not yet written.
9266    */
9267    pApndFile->iPgOne = APND_START_ROUNDUP(sz);
9268  }
9269  return rc;
9270}
9271
9272/*
9273** Delete an apnd file.
9274** For an appendvfs, this could mean delete the appendvfs portion,
9275** leaving the appendee as it was before it gained an appendvfs.
9276** For now, this code deletes the underlying file too.
9277*/
9278static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
9279  return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
9280}
9281
9282/*
9283** All other VFS methods are pass-thrus.
9284*/
9285static int apndAccess(
9286  sqlite3_vfs *pVfs,
9287  const char *zPath,
9288  int flags,
9289  int *pResOut
9290){
9291  return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
9292}
9293static int apndFullPathname(
9294  sqlite3_vfs *pVfs,
9295  const char *zPath,
9296  int nOut,
9297  char *zOut
9298){
9299  return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
9300}
9301static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
9302  return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
9303}
9304static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
9305  ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
9306}
9307static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
9308  return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
9309}
9310static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
9311  ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
9312}
9313static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
9314  return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
9315}
9316static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
9317  return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
9318}
9319static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
9320  return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
9321}
9322static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
9323  return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
9324}
9325static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
9326  return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
9327}
9328static int apndSetSystemCall(
9329  sqlite3_vfs *pVfs,
9330  const char *zName,
9331  sqlite3_syscall_ptr pCall
9332){
9333  return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
9334}
9335static sqlite3_syscall_ptr apndGetSystemCall(
9336  sqlite3_vfs *pVfs,
9337  const char *zName
9338){
9339  return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
9340}
9341static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
9342  return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
9343}
9344
9345
9346#ifdef _WIN32
9347
9348#endif
9349/*
9350** This routine is called when the extension is loaded.
9351** Register the new VFS.
9352*/
9353int sqlite3_appendvfs_init(
9354  sqlite3 *db,
9355  char **pzErrMsg,
9356  const sqlite3_api_routines *pApi
9357){
9358  int rc = SQLITE_OK;
9359  sqlite3_vfs *pOrig;
9360  SQLITE_EXTENSION_INIT2(pApi);
9361  (void)pzErrMsg;
9362  (void)db;
9363  pOrig = sqlite3_vfs_find(0);
9364  if( pOrig==0 ) return SQLITE_ERROR;
9365  apnd_vfs.iVersion = pOrig->iVersion;
9366  apnd_vfs.pAppData = pOrig;
9367  apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
9368  rc = sqlite3_vfs_register(&apnd_vfs, 0);
9369#ifdef APPENDVFS_TEST
9370  if( rc==SQLITE_OK ){
9371    rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
9372  }
9373#endif
9374  if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
9375  return rc;
9376}
9377
9378/************************* End ../ext/misc/appendvfs.c ********************/
9379#endif
9380#ifdef SQLITE_HAVE_ZLIB
9381/************************* Begin ../ext/misc/zipfile.c ******************/
9382/*
9383** 2017-12-26
9384**
9385** The author disclaims copyright to this source code.  In place of
9386** a legal notice, here is a blessing:
9387**
9388**    May you do good and not evil.
9389**    May you find forgiveness for yourself and forgive others.
9390**    May you share freely, never taking more than you give.
9391**
9392******************************************************************************
9393**
9394** This file implements a virtual table for reading and writing ZIP archive
9395** files.
9396**
9397** Usage example:
9398**
9399**     SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
9400**
9401** Current limitations:
9402**
9403**    *  No support for encryption
9404**    *  No support for ZIP archives spanning multiple files
9405**    *  No support for zip64 extensions
9406**    *  Only the "inflate/deflate" (zlib) compression method is supported
9407*/
9408/* #include "sqlite3ext.h" */
9409SQLITE_EXTENSION_INIT1
9410#include <stdio.h>
9411#include <string.h>
9412#include <assert.h>
9413#include <stdint.h>
9414
9415#include <zlib.h>
9416
9417#ifndef SQLITE_OMIT_VIRTUALTABLE
9418
9419#ifndef SQLITE_AMALGAMATION
9420
9421#ifndef UINT32_TYPE
9422# ifdef HAVE_UINT32_T
9423#  define UINT32_TYPE uint32_t
9424# else
9425#  define UINT32_TYPE unsigned int
9426# endif
9427#endif
9428#ifndef UINT16_TYPE
9429# ifdef HAVE_UINT16_T
9430#  define UINT16_TYPE uint16_t
9431# else
9432#  define UINT16_TYPE unsigned short int
9433# endif
9434#endif
9435/* typedef sqlite3_int64 i64; */
9436/* typedef unsigned char u8; */
9437/* typedef UINT32_TYPE u32;           // 4-byte unsigned integer // */
9438/* typedef UINT16_TYPE u16;           // 2-byte unsigned integer // */
9439#define MIN(a,b) ((a)<(b) ? (a) : (b))
9440
9441#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
9442# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
9443#endif
9444#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
9445# define ALWAYS(X)      (1)
9446# define NEVER(X)       (0)
9447#elif !defined(NDEBUG)
9448# define ALWAYS(X)      ((X)?1:(assert(0),0))
9449# define NEVER(X)       ((X)?(assert(0),1):0)
9450#else
9451# define ALWAYS(X)      (X)
9452# define NEVER(X)       (X)
9453#endif
9454
9455#endif   /* SQLITE_AMALGAMATION */
9456
9457/*
9458** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
9459**
9460** In some ways it would be better to obtain these values from system
9461** header files. But, the dependency is undesirable and (a) these
9462** have been stable for decades, (b) the values are part of POSIX and
9463** are also made explicit in [man stat], and (c) are part of the
9464** file format for zip archives.
9465*/
9466#ifndef S_IFDIR
9467# define S_IFDIR 0040000
9468#endif
9469#ifndef S_IFREG
9470# define S_IFREG 0100000
9471#endif
9472#ifndef S_IFLNK
9473# define S_IFLNK 0120000
9474#endif
9475
9476static const char ZIPFILE_SCHEMA[] =
9477  "CREATE TABLE y("
9478    "name PRIMARY KEY,"  /* 0: Name of file in zip archive */
9479    "mode,"              /* 1: POSIX mode for file */
9480    "mtime,"             /* 2: Last modification time (secs since 1970)*/
9481    "sz,"                /* 3: Size of object */
9482    "rawdata,"           /* 4: Raw data */
9483    "data,"              /* 5: Uncompressed data */
9484    "method,"            /* 6: Compression method (integer) */
9485    "z HIDDEN"           /* 7: Name of zip file */
9486  ") WITHOUT ROWID;";
9487
9488#define ZIPFILE_F_COLUMN_IDX 7    /* Index of column "file" in the above */
9489#define ZIPFILE_BUFFER_SIZE (64*1024)
9490
9491
9492/*
9493** Magic numbers used to read and write zip files.
9494**
9495** ZIPFILE_NEWENTRY_MADEBY:
9496**   Use this value for the "version-made-by" field in new zip file
9497**   entries. The upper byte indicates "unix", and the lower byte
9498**   indicates that the zip file matches pkzip specification 3.0.
9499**   This is what info-zip seems to do.
9500**
9501** ZIPFILE_NEWENTRY_REQUIRED:
9502**   Value for "version-required-to-extract" field of new entries.
9503**   Version 2.0 is required to support folders and deflate compression.
9504**
9505** ZIPFILE_NEWENTRY_FLAGS:
9506**   Value for "general-purpose-bit-flags" field of new entries. Bit
9507**   11 means "utf-8 filename and comment".
9508**
9509** ZIPFILE_SIGNATURE_CDS:
9510**   First 4 bytes of a valid CDS record.
9511**
9512** ZIPFILE_SIGNATURE_LFH:
9513**   First 4 bytes of a valid LFH record.
9514**
9515** ZIPFILE_SIGNATURE_EOCD
9516**   First 4 bytes of a valid EOCD record.
9517*/
9518#define ZIPFILE_EXTRA_TIMESTAMP   0x5455
9519#define ZIPFILE_NEWENTRY_MADEBY   ((3<<8) + 30)
9520#define ZIPFILE_NEWENTRY_REQUIRED 20
9521#define ZIPFILE_NEWENTRY_FLAGS    0x800
9522#define ZIPFILE_SIGNATURE_CDS     0x02014b50
9523#define ZIPFILE_SIGNATURE_LFH     0x04034b50
9524#define ZIPFILE_SIGNATURE_EOCD    0x06054b50
9525
9526/*
9527** The sizes of the fixed-size part of each of the three main data
9528** structures in a zip archive.
9529*/
9530#define ZIPFILE_LFH_FIXED_SZ      30
9531#define ZIPFILE_EOCD_FIXED_SZ     22
9532#define ZIPFILE_CDS_FIXED_SZ      46
9533
9534/*
9535*** 4.3.16  End of central directory record:
9536***
9537***   end of central dir signature    4 bytes  (0x06054b50)
9538***   number of this disk             2 bytes
9539***   number of the disk with the
9540***   start of the central directory  2 bytes
9541***   total number of entries in the
9542***   central directory on this disk  2 bytes
9543***   total number of entries in
9544***   the central directory           2 bytes
9545***   size of the central directory   4 bytes
9546***   offset of start of central
9547***   directory with respect to
9548***   the starting disk number        4 bytes
9549***   .ZIP file comment length        2 bytes
9550***   .ZIP file comment       (variable size)
9551*/
9552typedef struct ZipfileEOCD ZipfileEOCD;
9553struct ZipfileEOCD {
9554  u16 iDisk;
9555  u16 iFirstDisk;
9556  u16 nEntry;
9557  u16 nEntryTotal;
9558  u32 nSize;
9559  u32 iOffset;
9560};
9561
9562/*
9563*** 4.3.12  Central directory structure:
9564***
9565*** ...
9566***
9567***   central file header signature   4 bytes  (0x02014b50)
9568***   version made by                 2 bytes
9569***   version needed to extract       2 bytes
9570***   general purpose bit flag        2 bytes
9571***   compression method              2 bytes
9572***   last mod file time              2 bytes
9573***   last mod file date              2 bytes
9574***   crc-32                          4 bytes
9575***   compressed size                 4 bytes
9576***   uncompressed size               4 bytes
9577***   file name length                2 bytes
9578***   extra field length              2 bytes
9579***   file comment length             2 bytes
9580***   disk number start               2 bytes
9581***   internal file attributes        2 bytes
9582***   external file attributes        4 bytes
9583***   relative offset of local header 4 bytes
9584*/
9585typedef struct ZipfileCDS ZipfileCDS;
9586struct ZipfileCDS {
9587  u16 iVersionMadeBy;
9588  u16 iVersionExtract;
9589  u16 flags;
9590  u16 iCompression;
9591  u16 mTime;
9592  u16 mDate;
9593  u32 crc32;
9594  u32 szCompressed;
9595  u32 szUncompressed;
9596  u16 nFile;
9597  u16 nExtra;
9598  u16 nComment;
9599  u16 iDiskStart;
9600  u16 iInternalAttr;
9601  u32 iExternalAttr;
9602  u32 iOffset;
9603  char *zFile;                    /* Filename (sqlite3_malloc()) */
9604};
9605
9606/*
9607*** 4.3.7  Local file header:
9608***
9609***   local file header signature     4 bytes  (0x04034b50)
9610***   version needed to extract       2 bytes
9611***   general purpose bit flag        2 bytes
9612***   compression method              2 bytes
9613***   last mod file time              2 bytes
9614***   last mod file date              2 bytes
9615***   crc-32                          4 bytes
9616***   compressed size                 4 bytes
9617***   uncompressed size               4 bytes
9618***   file name length                2 bytes
9619***   extra field length              2 bytes
9620***
9621*/
9622typedef struct ZipfileLFH ZipfileLFH;
9623struct ZipfileLFH {
9624  u16 iVersionExtract;
9625  u16 flags;
9626  u16 iCompression;
9627  u16 mTime;
9628  u16 mDate;
9629  u32 crc32;
9630  u32 szCompressed;
9631  u32 szUncompressed;
9632  u16 nFile;
9633  u16 nExtra;
9634};
9635
9636typedef struct ZipfileEntry ZipfileEntry;
9637struct ZipfileEntry {
9638  ZipfileCDS cds;            /* Parsed CDS record */
9639  u32 mUnixTime;             /* Modification time, in UNIX format */
9640  u8 *aExtra;                /* cds.nExtra+cds.nComment bytes of extra data */
9641  i64 iDataOff;              /* Offset to data in file (if aData==0) */
9642  u8 *aData;                 /* cds.szCompressed bytes of compressed data */
9643  ZipfileEntry *pNext;       /* Next element in in-memory CDS */
9644};
9645
9646/*
9647** Cursor type for zipfile tables.
9648*/
9649typedef struct ZipfileCsr ZipfileCsr;
9650struct ZipfileCsr {
9651  sqlite3_vtab_cursor base;  /* Base class - must be first */
9652  i64 iId;                   /* Cursor ID */
9653  u8 bEof;                   /* True when at EOF */
9654  u8 bNoop;                  /* If next xNext() call is no-op */
9655
9656  /* Used outside of write transactions */
9657  FILE *pFile;               /* Zip file */
9658  i64 iNextOff;              /* Offset of next record in central directory */
9659  ZipfileEOCD eocd;          /* Parse of central directory record */
9660
9661  ZipfileEntry *pFreeEntry;  /* Free this list when cursor is closed or reset */
9662  ZipfileEntry *pCurrent;    /* Current entry */
9663  ZipfileCsr *pCsrNext;      /* Next cursor on same virtual table */
9664};
9665
9666typedef struct ZipfileTab ZipfileTab;
9667struct ZipfileTab {
9668  sqlite3_vtab base;         /* Base class - must be first */
9669  char *zFile;               /* Zip file this table accesses (may be NULL) */
9670  sqlite3 *db;               /* Host database connection */
9671  u8 *aBuffer;               /* Temporary buffer used for various tasks */
9672
9673  ZipfileCsr *pCsrList;      /* List of cursors */
9674  i64 iNextCsrid;
9675
9676  /* The following are used by write transactions only */
9677  ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
9678  ZipfileEntry *pLastEntry;  /* Last element in pFirstEntry list */
9679  FILE *pWriteFd;            /* File handle open on zip archive */
9680  i64 szCurrent;             /* Current size of zip archive */
9681  i64 szOrig;                /* Size of archive at start of transaction */
9682};
9683
9684/*
9685** Set the error message contained in context ctx to the results of
9686** vprintf(zFmt, ...).
9687*/
9688static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
9689  char *zMsg = 0;
9690  va_list ap;
9691  va_start(ap, zFmt);
9692  zMsg = sqlite3_vmprintf(zFmt, ap);
9693  sqlite3_result_error(ctx, zMsg, -1);
9694  sqlite3_free(zMsg);
9695  va_end(ap);
9696}
9697
9698/*
9699** If string zIn is quoted, dequote it in place. Otherwise, if the string
9700** is not quoted, do nothing.
9701*/
9702static void zipfileDequote(char *zIn){
9703  char q = zIn[0];
9704  if( q=='"' || q=='\'' || q=='`' || q=='[' ){
9705    int iIn = 1;
9706    int iOut = 0;
9707    if( q=='[' ) q = ']';
9708    while( ALWAYS(zIn[iIn]) ){
9709      char c = zIn[iIn++];
9710      if( c==q && zIn[iIn++]!=q ) break;
9711      zIn[iOut++] = c;
9712    }
9713    zIn[iOut] = '\0';
9714  }
9715}
9716
9717/*
9718** Construct a new ZipfileTab virtual table object.
9719**
9720**   argv[0]   -> module name  ("zipfile")
9721**   argv[1]   -> database name
9722**   argv[2]   -> table name
9723**   argv[...] -> "column name" and other module argument fields.
9724*/
9725static int zipfileConnect(
9726  sqlite3 *db,
9727  void *pAux,
9728  int argc, const char *const*argv,
9729  sqlite3_vtab **ppVtab,
9730  char **pzErr
9731){
9732  int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
9733  int nFile = 0;
9734  const char *zFile = 0;
9735  ZipfileTab *pNew = 0;
9736  int rc;
9737  (void)pAux;
9738
9739  /* If the table name is not "zipfile", require that the argument be
9740  ** specified. This stops zipfile tables from being created as:
9741  **
9742  **   CREATE VIRTUAL TABLE zzz USING zipfile();
9743  **
9744  ** It does not prevent:
9745  **
9746  **   CREATE VIRTUAL TABLE zipfile USING zipfile();
9747  */
9748  assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
9749  if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
9750    *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
9751    return SQLITE_ERROR;
9752  }
9753
9754  if( argc>3 ){
9755    zFile = argv[3];
9756    nFile = (int)strlen(zFile)+1;
9757  }
9758
9759  rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
9760  if( rc==SQLITE_OK ){
9761    pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile);
9762    if( pNew==0 ) return SQLITE_NOMEM;
9763    memset(pNew, 0, nByte+nFile);
9764    pNew->db = db;
9765    pNew->aBuffer = (u8*)&pNew[1];
9766    if( zFile ){
9767      pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
9768      memcpy(pNew->zFile, zFile, nFile);
9769      zipfileDequote(pNew->zFile);
9770    }
9771  }
9772  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
9773  *ppVtab = (sqlite3_vtab*)pNew;
9774  return rc;
9775}
9776
9777/*
9778** Free the ZipfileEntry structure indicated by the only argument.
9779*/
9780static void zipfileEntryFree(ZipfileEntry *p){
9781  if( p ){
9782    sqlite3_free(p->cds.zFile);
9783    sqlite3_free(p);
9784  }
9785}
9786
9787/*
9788** Release resources that should be freed at the end of a write
9789** transaction.
9790*/
9791static void zipfileCleanupTransaction(ZipfileTab *pTab){
9792  ZipfileEntry *pEntry;
9793  ZipfileEntry *pNext;
9794
9795  if( pTab->pWriteFd ){
9796    fclose(pTab->pWriteFd);
9797    pTab->pWriteFd = 0;
9798  }
9799  for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
9800    pNext = pEntry->pNext;
9801    zipfileEntryFree(pEntry);
9802  }
9803  pTab->pFirstEntry = 0;
9804  pTab->pLastEntry = 0;
9805  pTab->szCurrent = 0;
9806  pTab->szOrig = 0;
9807}
9808
9809/*
9810** This method is the destructor for zipfile vtab objects.
9811*/
9812static int zipfileDisconnect(sqlite3_vtab *pVtab){
9813  zipfileCleanupTransaction((ZipfileTab*)pVtab);
9814  sqlite3_free(pVtab);
9815  return SQLITE_OK;
9816}
9817
9818/*
9819** Constructor for a new ZipfileCsr object.
9820*/
9821static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
9822  ZipfileTab *pTab = (ZipfileTab*)p;
9823  ZipfileCsr *pCsr;
9824  pCsr = sqlite3_malloc(sizeof(*pCsr));
9825  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
9826  if( pCsr==0 ){
9827    return SQLITE_NOMEM;
9828  }
9829  memset(pCsr, 0, sizeof(*pCsr));
9830  pCsr->iId = ++pTab->iNextCsrid;
9831  pCsr->pCsrNext = pTab->pCsrList;
9832  pTab->pCsrList = pCsr;
9833  return SQLITE_OK;
9834}
9835
9836/*
9837** Reset a cursor back to the state it was in when first returned
9838** by zipfileOpen().
9839*/
9840static void zipfileResetCursor(ZipfileCsr *pCsr){
9841  ZipfileEntry *p;
9842  ZipfileEntry *pNext;
9843
9844  pCsr->bEof = 0;
9845  if( pCsr->pFile ){
9846    fclose(pCsr->pFile);
9847    pCsr->pFile = 0;
9848    zipfileEntryFree(pCsr->pCurrent);
9849    pCsr->pCurrent = 0;
9850  }
9851
9852  for(p=pCsr->pFreeEntry; p; p=pNext){
9853    pNext = p->pNext;
9854    zipfileEntryFree(p);
9855  }
9856}
9857
9858/*
9859** Destructor for an ZipfileCsr.
9860*/
9861static int zipfileClose(sqlite3_vtab_cursor *cur){
9862  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
9863  ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
9864  ZipfileCsr **pp;
9865  zipfileResetCursor(pCsr);
9866
9867  /* Remove this cursor from the ZipfileTab.pCsrList list. */
9868  for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
9869  *pp = pCsr->pCsrNext;
9870
9871  sqlite3_free(pCsr);
9872  return SQLITE_OK;
9873}
9874
9875/*
9876** Set the error message for the virtual table associated with cursor
9877** pCsr to the results of vprintf(zFmt, ...).
9878*/
9879static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
9880  va_list ap;
9881  va_start(ap, zFmt);
9882  sqlite3_free(pTab->base.zErrMsg);
9883  pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
9884  va_end(ap);
9885}
9886static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
9887  va_list ap;
9888  va_start(ap, zFmt);
9889  sqlite3_free(pCsr->base.pVtab->zErrMsg);
9890  pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
9891  va_end(ap);
9892}
9893
9894/*
9895** Read nRead bytes of data from offset iOff of file pFile into buffer
9896** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
9897** otherwise.
9898**
9899** If an error does occur, output variable (*pzErrmsg) may be set to point
9900** to an English language error message. It is the responsibility of the
9901** caller to eventually free this buffer using
9902** sqlite3_free().
9903*/
9904static int zipfileReadData(
9905  FILE *pFile,                    /* Read from this file */
9906  u8 *aRead,                      /* Read into this buffer */
9907  int nRead,                      /* Number of bytes to read */
9908  i64 iOff,                       /* Offset to read from */
9909  char **pzErrmsg                 /* OUT: Error message (from sqlite3_malloc) */
9910){
9911  size_t n;
9912  fseek(pFile, (long)iOff, SEEK_SET);
9913  n = fread(aRead, 1, nRead, pFile);
9914  if( (int)n!=nRead ){
9915    *pzErrmsg = sqlite3_mprintf("error in fread()");
9916    return SQLITE_ERROR;
9917  }
9918  return SQLITE_OK;
9919}
9920
9921static int zipfileAppendData(
9922  ZipfileTab *pTab,
9923  const u8 *aWrite,
9924  int nWrite
9925){
9926  if( nWrite>0 ){
9927    size_t n = nWrite;
9928    fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
9929    n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
9930    if( (int)n!=nWrite ){
9931      pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
9932      return SQLITE_ERROR;
9933    }
9934    pTab->szCurrent += nWrite;
9935  }
9936  return SQLITE_OK;
9937}
9938
9939/*
9940** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
9941*/
9942static u16 zipfileGetU16(const u8 *aBuf){
9943  return (aBuf[1] << 8) + aBuf[0];
9944}
9945
9946/*
9947** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
9948*/
9949static u32 zipfileGetU32(const u8 *aBuf){
9950  if( aBuf==0 ) return 0;
9951  return ((u32)(aBuf[3]) << 24)
9952       + ((u32)(aBuf[2]) << 16)
9953       + ((u32)(aBuf[1]) <<  8)
9954       + ((u32)(aBuf[0]) <<  0);
9955}
9956
9957/*
9958** Write a 16-bit little endiate integer into buffer aBuf.
9959*/
9960static void zipfilePutU16(u8 *aBuf, u16 val){
9961  aBuf[0] = val & 0xFF;
9962  aBuf[1] = (val>>8) & 0xFF;
9963}
9964
9965/*
9966** Write a 32-bit little endiate integer into buffer aBuf.
9967*/
9968static void zipfilePutU32(u8 *aBuf, u32 val){
9969  aBuf[0] = val & 0xFF;
9970  aBuf[1] = (val>>8) & 0xFF;
9971  aBuf[2] = (val>>16) & 0xFF;
9972  aBuf[3] = (val>>24) & 0xFF;
9973}
9974
9975#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
9976#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
9977
9978#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
9979#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
9980
9981/*
9982** Magic numbers used to read CDS records.
9983*/
9984#define ZIPFILE_CDS_NFILE_OFF        28
9985#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
9986
9987/*
9988** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
9989** if the record is not well-formed, or SQLITE_OK otherwise.
9990*/
9991static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
9992  u8 *aRead = aBuf;
9993  u32 sig = zipfileRead32(aRead);
9994  int rc = SQLITE_OK;
9995  if( sig!=ZIPFILE_SIGNATURE_CDS ){
9996    rc = SQLITE_ERROR;
9997  }else{
9998    pCDS->iVersionMadeBy = zipfileRead16(aRead);
9999    pCDS->iVersionExtract = zipfileRead16(aRead);
10000    pCDS->flags = zipfileRead16(aRead);
10001    pCDS->iCompression = zipfileRead16(aRead);
10002    pCDS->mTime = zipfileRead16(aRead);
10003    pCDS->mDate = zipfileRead16(aRead);
10004    pCDS->crc32 = zipfileRead32(aRead);
10005    pCDS->szCompressed = zipfileRead32(aRead);
10006    pCDS->szUncompressed = zipfileRead32(aRead);
10007    assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
10008    pCDS->nFile = zipfileRead16(aRead);
10009    pCDS->nExtra = zipfileRead16(aRead);
10010    pCDS->nComment = zipfileRead16(aRead);
10011    pCDS->iDiskStart = zipfileRead16(aRead);
10012    pCDS->iInternalAttr = zipfileRead16(aRead);
10013    pCDS->iExternalAttr = zipfileRead32(aRead);
10014    pCDS->iOffset = zipfileRead32(aRead);
10015    assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
10016  }
10017
10018  return rc;
10019}
10020
10021/*
10022** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
10023** if the record is not well-formed, or SQLITE_OK otherwise.
10024*/
10025static int zipfileReadLFH(
10026  u8 *aBuffer,
10027  ZipfileLFH *pLFH
10028){
10029  u8 *aRead = aBuffer;
10030  int rc = SQLITE_OK;
10031
10032  u32 sig = zipfileRead32(aRead);
10033  if( sig!=ZIPFILE_SIGNATURE_LFH ){
10034    rc = SQLITE_ERROR;
10035  }else{
10036    pLFH->iVersionExtract = zipfileRead16(aRead);
10037    pLFH->flags = zipfileRead16(aRead);
10038    pLFH->iCompression = zipfileRead16(aRead);
10039    pLFH->mTime = zipfileRead16(aRead);
10040    pLFH->mDate = zipfileRead16(aRead);
10041    pLFH->crc32 = zipfileRead32(aRead);
10042    pLFH->szCompressed = zipfileRead32(aRead);
10043    pLFH->szUncompressed = zipfileRead32(aRead);
10044    pLFH->nFile = zipfileRead16(aRead);
10045    pLFH->nExtra = zipfileRead16(aRead);
10046  }
10047  return rc;
10048}
10049
10050
10051/*
10052** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
10053** Scan through this buffer to find an "extra-timestamp" field. If one
10054** exists, extract the 32-bit modification-timestamp from it and store
10055** the value in output parameter *pmTime.
10056**
10057** Zero is returned if no extra-timestamp record could be found (and so
10058** *pmTime is left unchanged), or non-zero otherwise.
10059**
10060** The general format of an extra field is:
10061**
10062**   Header ID    2 bytes
10063**   Data Size    2 bytes
10064**   Data         N bytes
10065*/
10066static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
10067  int ret = 0;
10068  u8 *p = aExtra;
10069  u8 *pEnd = &aExtra[nExtra];
10070
10071  while( p<pEnd ){
10072    u16 id = zipfileRead16(p);
10073    u16 nByte = zipfileRead16(p);
10074
10075    switch( id ){
10076      case ZIPFILE_EXTRA_TIMESTAMP: {
10077        u8 b = p[0];
10078        if( b & 0x01 ){     /* 0x01 -> modtime is present */
10079          *pmTime = zipfileGetU32(&p[1]);
10080          ret = 1;
10081        }
10082        break;
10083      }
10084    }
10085
10086    p += nByte;
10087  }
10088  return ret;
10089}
10090
10091/*
10092** Convert the standard MS-DOS timestamp stored in the mTime and mDate
10093** fields of the CDS structure passed as the only argument to a 32-bit
10094** UNIX seconds-since-the-epoch timestamp. Return the result.
10095**
10096** "Standard" MS-DOS time format:
10097**
10098**   File modification time:
10099**     Bits 00-04: seconds divided by 2
10100**     Bits 05-10: minute
10101**     Bits 11-15: hour
10102**   File modification date:
10103**     Bits 00-04: day
10104**     Bits 05-08: month (1-12)
10105**     Bits 09-15: years from 1980
10106**
10107** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
10108*/
10109static u32 zipfileMtime(ZipfileCDS *pCDS){
10110  int Y,M,D,X1,X2,A,B,sec,min,hr;
10111  i64 JDsec;
10112  Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
10113  M = ((pCDS->mDate >> 5) & 0x0F);
10114  D = (pCDS->mDate & 0x1F);
10115  sec = (pCDS->mTime & 0x1F)*2;
10116  min = (pCDS->mTime >> 5) & 0x3F;
10117  hr = (pCDS->mTime >> 11) & 0x1F;
10118  if( M<=2 ){
10119    Y--;
10120    M += 12;
10121  }
10122  X1 = 36525*(Y+4716)/100;
10123  X2 = 306001*(M+1)/10000;
10124  A = Y/100;
10125  B = 2 - A + (A/4);
10126  JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec;
10127  return (u32)(JDsec - (i64)24405875*(i64)8640);
10128}
10129
10130/*
10131** The opposite of zipfileMtime(). This function populates the mTime and
10132** mDate fields of the CDS structure passed as the first argument according
10133** to the UNIX timestamp value passed as the second.
10134*/
10135static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
10136  /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
10137  i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
10138
10139  int A, B, C, D, E;
10140  int yr, mon, day;
10141  int hr, min, sec;
10142
10143  A = (int)((JD - 1867216.25)/36524.25);
10144  A = (int)(JD + 1 + A - (A/4));
10145  B = A + 1524;
10146  C = (int)((B - 122.1)/365.25);
10147  D = (36525*(C&32767))/100;
10148  E = (int)((B-D)/30.6001);
10149
10150  day = B - D - (int)(30.6001*E);
10151  mon = (E<14 ? E-1 : E-13);
10152  yr = mon>2 ? C-4716 : C-4715;
10153
10154  hr = (mUnixTime % (24*60*60)) / (60*60);
10155  min = (mUnixTime % (60*60)) / 60;
10156  sec = (mUnixTime % 60);
10157
10158  if( yr>=1980 ){
10159    pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
10160    pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
10161  }else{
10162    pCds->mDate = pCds->mTime = 0;
10163  }
10164
10165  assert( mUnixTime<315507600
10166       || mUnixTime==zipfileMtime(pCds)
10167       || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
10168       /* || (mUnixTime % 2) */
10169  );
10170}
10171
10172/*
10173** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
10174** size) containing an entire zip archive image. Or, if aBlob is NULL,
10175** then pFile is a file-handle open on a zip file. In either case, this
10176** function creates a ZipfileEntry object based on the zip archive entry
10177** for which the CDS record is at offset iOff.
10178**
10179** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
10180** the new object. Otherwise, an SQLite error code is returned and the
10181** final value of (*ppEntry) undefined.
10182*/
10183static int zipfileGetEntry(
10184  ZipfileTab *pTab,               /* Store any error message here */
10185  const u8 *aBlob,                /* Pointer to in-memory file image */
10186  int nBlob,                      /* Size of aBlob[] in bytes */
10187  FILE *pFile,                    /* If aBlob==0, read from this file */
10188  i64 iOff,                       /* Offset of CDS record */
10189  ZipfileEntry **ppEntry          /* OUT: Pointer to new object */
10190){
10191  u8 *aRead;
10192  char **pzErr = &pTab->base.zErrMsg;
10193  int rc = SQLITE_OK;
10194  (void)nBlob;
10195
10196  if( aBlob==0 ){
10197    aRead = pTab->aBuffer;
10198    rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
10199  }else{
10200    aRead = (u8*)&aBlob[iOff];
10201  }
10202
10203  if( rc==SQLITE_OK ){
10204    sqlite3_int64 nAlloc;
10205    ZipfileEntry *pNew;
10206
10207    int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
10208    int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
10209    nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
10210
10211    nAlloc = sizeof(ZipfileEntry) + nExtra;
10212    if( aBlob ){
10213      nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
10214    }
10215
10216    pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc);
10217    if( pNew==0 ){
10218      rc = SQLITE_NOMEM;
10219    }else{
10220      memset(pNew, 0, sizeof(ZipfileEntry));
10221      rc = zipfileReadCDS(aRead, &pNew->cds);
10222      if( rc!=SQLITE_OK ){
10223        *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
10224      }else if( aBlob==0 ){
10225        rc = zipfileReadData(
10226            pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
10227        );
10228      }else{
10229        aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
10230      }
10231    }
10232
10233    if( rc==SQLITE_OK ){
10234      u32 *pt = &pNew->mUnixTime;
10235      pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
10236      pNew->aExtra = (u8*)&pNew[1];
10237      memcpy(pNew->aExtra, &aRead[nFile], nExtra);
10238      if( pNew->cds.zFile==0 ){
10239        rc = SQLITE_NOMEM;
10240      }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
10241        pNew->mUnixTime = zipfileMtime(&pNew->cds);
10242      }
10243    }
10244
10245    if( rc==SQLITE_OK ){
10246      static const int szFix = ZIPFILE_LFH_FIXED_SZ;
10247      ZipfileLFH lfh;
10248      if( pFile ){
10249        rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
10250      }else{
10251        aRead = (u8*)&aBlob[pNew->cds.iOffset];
10252      }
10253
10254      if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh);
10255      if( rc==SQLITE_OK ){
10256        pNew->iDataOff =  pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
10257        pNew->iDataOff += lfh.nFile + lfh.nExtra;
10258        if( aBlob && pNew->cds.szCompressed ){
10259          pNew->aData = &pNew->aExtra[nExtra];
10260          memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
10261        }
10262      }else{
10263        *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
10264            (int)pNew->cds.iOffset
10265        );
10266      }
10267    }
10268
10269    if( rc!=SQLITE_OK ){
10270      zipfileEntryFree(pNew);
10271    }else{
10272      *ppEntry = pNew;
10273    }
10274  }
10275
10276  return rc;
10277}
10278
10279/*
10280** Advance an ZipfileCsr to its next row of output.
10281*/
10282static int zipfileNext(sqlite3_vtab_cursor *cur){
10283  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10284  int rc = SQLITE_OK;
10285
10286  if( pCsr->pFile ){
10287    i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
10288    zipfileEntryFree(pCsr->pCurrent);
10289    pCsr->pCurrent = 0;
10290    if( pCsr->iNextOff>=iEof ){
10291      pCsr->bEof = 1;
10292    }else{
10293      ZipfileEntry *p = 0;
10294      ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
10295      rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
10296      if( rc==SQLITE_OK ){
10297        pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
10298        pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
10299      }
10300      pCsr->pCurrent = p;
10301    }
10302  }else{
10303    if( !pCsr->bNoop ){
10304      pCsr->pCurrent = pCsr->pCurrent->pNext;
10305    }
10306    if( pCsr->pCurrent==0 ){
10307      pCsr->bEof = 1;
10308    }
10309  }
10310
10311  pCsr->bNoop = 0;
10312  return rc;
10313}
10314
10315static void zipfileFree(void *p) {
10316  sqlite3_free(p);
10317}
10318
10319/*
10320** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
10321** size is nOut bytes. This function uncompresses the data and sets the
10322** return value in context pCtx to the result (a blob).
10323**
10324** If an error occurs, an error code is left in pCtx instead.
10325*/
10326static void zipfileInflate(
10327  sqlite3_context *pCtx,          /* Store result here */
10328  const u8 *aIn,                  /* Compressed data */
10329  int nIn,                        /* Size of buffer aIn[] in bytes */
10330  int nOut                        /* Expected output size */
10331){
10332  u8 *aRes = sqlite3_malloc(nOut);
10333  if( aRes==0 ){
10334    sqlite3_result_error_nomem(pCtx);
10335  }else{
10336    int err;
10337    z_stream str;
10338    memset(&str, 0, sizeof(str));
10339
10340    str.next_in = (Byte*)aIn;
10341    str.avail_in = nIn;
10342    str.next_out = (Byte*)aRes;
10343    str.avail_out = nOut;
10344
10345    err = inflateInit2(&str, -15);
10346    if( err!=Z_OK ){
10347      zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
10348    }else{
10349      err = inflate(&str, Z_NO_FLUSH);
10350      if( err!=Z_STREAM_END ){
10351        zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
10352      }else{
10353        sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
10354        aRes = 0;
10355      }
10356    }
10357    sqlite3_free(aRes);
10358    inflateEnd(&str);
10359  }
10360}
10361
10362/*
10363** Buffer aIn (size nIn bytes) contains uncompressed data. This function
10364** compresses it and sets (*ppOut) to point to a buffer containing the
10365** compressed data. The caller is responsible for eventually calling
10366** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
10367** is set to the size of buffer (*ppOut) in bytes.
10368**
10369** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
10370** code is returned and an error message left in virtual-table handle
10371** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
10372** case.
10373*/
10374static int zipfileDeflate(
10375  const u8 *aIn, int nIn,         /* Input */
10376  u8 **ppOut, int *pnOut,         /* Output */
10377  char **pzErr                    /* OUT: Error message */
10378){
10379  int rc = SQLITE_OK;
10380  sqlite3_int64 nAlloc;
10381  z_stream str;
10382  u8 *aOut;
10383
10384  memset(&str, 0, sizeof(str));
10385  str.next_in = (Bytef*)aIn;
10386  str.avail_in = nIn;
10387  deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
10388
10389  nAlloc = deflateBound(&str, nIn);
10390  aOut = (u8*)sqlite3_malloc64(nAlloc);
10391  if( aOut==0 ){
10392    rc = SQLITE_NOMEM;
10393  }else{
10394    int res;
10395    str.next_out = aOut;
10396    str.avail_out = nAlloc;
10397    res = deflate(&str, Z_FINISH);
10398    if( res==Z_STREAM_END ){
10399      *ppOut = aOut;
10400      *pnOut = (int)str.total_out;
10401    }else{
10402      sqlite3_free(aOut);
10403      *pzErr = sqlite3_mprintf("zipfile: deflate() error");
10404      rc = SQLITE_ERROR;
10405    }
10406    deflateEnd(&str);
10407  }
10408
10409  return rc;
10410}
10411
10412
10413/*
10414** Return values of columns for the row at which the series_cursor
10415** is currently pointing.
10416*/
10417static int zipfileColumn(
10418  sqlite3_vtab_cursor *cur,   /* The cursor */
10419  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
10420  int i                       /* Which column to return */
10421){
10422  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10423  ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
10424  int rc = SQLITE_OK;
10425  switch( i ){
10426    case 0:   /* name */
10427      sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
10428      break;
10429    case 1:   /* mode */
10430      /* TODO: Whether or not the following is correct surely depends on
10431      ** the platform on which the archive was created.  */
10432      sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
10433      break;
10434    case 2: { /* mtime */
10435      sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
10436      break;
10437    }
10438    case 3: { /* sz */
10439      if( sqlite3_vtab_nochange(ctx)==0 ){
10440        sqlite3_result_int64(ctx, pCDS->szUncompressed);
10441      }
10442      break;
10443    }
10444    case 4:   /* rawdata */
10445      if( sqlite3_vtab_nochange(ctx) ) break;
10446    case 5: { /* data */
10447      if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
10448        int sz = pCDS->szCompressed;
10449        int szFinal = pCDS->szUncompressed;
10450        if( szFinal>0 ){
10451          u8 *aBuf;
10452          u8 *aFree = 0;
10453          if( pCsr->pCurrent->aData ){
10454            aBuf = pCsr->pCurrent->aData;
10455          }else{
10456            aBuf = aFree = sqlite3_malloc64(sz);
10457            if( aBuf==0 ){
10458              rc = SQLITE_NOMEM;
10459            }else{
10460              FILE *pFile = pCsr->pFile;
10461              if( pFile==0 ){
10462                pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
10463              }
10464              rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
10465                  &pCsr->base.pVtab->zErrMsg
10466              );
10467            }
10468          }
10469          if( rc==SQLITE_OK ){
10470            if( i==5 && pCDS->iCompression ){
10471              zipfileInflate(ctx, aBuf, sz, szFinal);
10472            }else{
10473              sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
10474            }
10475          }
10476          sqlite3_free(aFree);
10477        }else{
10478          /* Figure out if this is a directory or a zero-sized file. Consider
10479          ** it to be a directory either if the mode suggests so, or if
10480          ** the final character in the name is '/'.  */
10481          u32 mode = pCDS->iExternalAttr >> 16;
10482          if( !(mode & S_IFDIR)
10483           && pCDS->nFile>=1
10484           && pCDS->zFile[pCDS->nFile-1]!='/'
10485          ){
10486            sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
10487          }
10488        }
10489      }
10490      break;
10491    }
10492    case 6:   /* method */
10493      sqlite3_result_int(ctx, pCDS->iCompression);
10494      break;
10495    default:  /* z */
10496      assert( i==7 );
10497      sqlite3_result_int64(ctx, pCsr->iId);
10498      break;
10499  }
10500
10501  return rc;
10502}
10503
10504/*
10505** Return TRUE if the cursor is at EOF.
10506*/
10507static int zipfileEof(sqlite3_vtab_cursor *cur){
10508  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10509  return pCsr->bEof;
10510}
10511
10512/*
10513** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
10514** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
10515** is guaranteed to be a file-handle open on a zip file.
10516**
10517** This function attempts to locate the EOCD record within the zip archive
10518** and populate *pEOCD with the results of decoding it. SQLITE_OK is
10519** returned if successful. Otherwise, an SQLite error code is returned and
10520** an English language error message may be left in virtual-table pTab.
10521*/
10522static int zipfileReadEOCD(
10523  ZipfileTab *pTab,               /* Return errors here */
10524  const u8 *aBlob,                /* Pointer to in-memory file image */
10525  int nBlob,                      /* Size of aBlob[] in bytes */
10526  FILE *pFile,                    /* Read from this file if aBlob==0 */
10527  ZipfileEOCD *pEOCD              /* Object to populate */
10528){
10529  u8 *aRead = pTab->aBuffer;      /* Temporary buffer */
10530  int nRead;                      /* Bytes to read from file */
10531  int rc = SQLITE_OK;
10532
10533  memset(pEOCD, 0, sizeof(ZipfileEOCD));
10534  if( aBlob==0 ){
10535    i64 iOff;                     /* Offset to read from */
10536    i64 szFile;                   /* Total size of file in bytes */
10537    fseek(pFile, 0, SEEK_END);
10538    szFile = (i64)ftell(pFile);
10539    if( szFile==0 ){
10540      return SQLITE_OK;
10541    }
10542    nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
10543    iOff = szFile - nRead;
10544    rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
10545  }else{
10546    nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
10547    aRead = (u8*)&aBlob[nBlob-nRead];
10548  }
10549
10550  if( rc==SQLITE_OK ){
10551    int i;
10552
10553    /* Scan backwards looking for the signature bytes */
10554    for(i=nRead-20; i>=0; i--){
10555      if( aRead[i]==0x50 && aRead[i+1]==0x4b
10556       && aRead[i+2]==0x05 && aRead[i+3]==0x06
10557      ){
10558        break;
10559      }
10560    }
10561    if( i<0 ){
10562      pTab->base.zErrMsg = sqlite3_mprintf(
10563          "cannot find end of central directory record"
10564      );
10565      return SQLITE_ERROR;
10566    }
10567
10568    aRead += i+4;
10569    pEOCD->iDisk = zipfileRead16(aRead);
10570    pEOCD->iFirstDisk = zipfileRead16(aRead);
10571    pEOCD->nEntry = zipfileRead16(aRead);
10572    pEOCD->nEntryTotal = zipfileRead16(aRead);
10573    pEOCD->nSize = zipfileRead32(aRead);
10574    pEOCD->iOffset = zipfileRead32(aRead);
10575  }
10576
10577  return rc;
10578}
10579
10580/*
10581** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
10582** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
10583** to the end of the list. Otherwise, it is added to the list immediately
10584** before pBefore (which is guaranteed to be a part of said list).
10585*/
10586static void zipfileAddEntry(
10587  ZipfileTab *pTab,
10588  ZipfileEntry *pBefore,
10589  ZipfileEntry *pNew
10590){
10591  assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
10592  assert( pNew->pNext==0 );
10593  if( pBefore==0 ){
10594    if( pTab->pFirstEntry==0 ){
10595      pTab->pFirstEntry = pTab->pLastEntry = pNew;
10596    }else{
10597      assert( pTab->pLastEntry->pNext==0 );
10598      pTab->pLastEntry->pNext = pNew;
10599      pTab->pLastEntry = pNew;
10600    }
10601  }else{
10602    ZipfileEntry **pp;
10603    for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
10604    pNew->pNext = pBefore;
10605    *pp = pNew;
10606  }
10607}
10608
10609static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
10610  ZipfileEOCD eocd;
10611  int rc;
10612  int i;
10613  i64 iOff;
10614
10615  rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
10616  iOff = eocd.iOffset;
10617  for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
10618    ZipfileEntry *pNew = 0;
10619    rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
10620
10621    if( rc==SQLITE_OK ){
10622      zipfileAddEntry(pTab, 0, pNew);
10623      iOff += ZIPFILE_CDS_FIXED_SZ;
10624      iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
10625    }
10626  }
10627  return rc;
10628}
10629
10630/*
10631** xFilter callback.
10632*/
10633static int zipfileFilter(
10634  sqlite3_vtab_cursor *cur,
10635  int idxNum, const char *idxStr,
10636  int argc, sqlite3_value **argv
10637){
10638  ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
10639  ZipfileCsr *pCsr = (ZipfileCsr*)cur;
10640  const char *zFile = 0;          /* Zip file to scan */
10641  int rc = SQLITE_OK;             /* Return Code */
10642  int bInMemory = 0;              /* True for an in-memory zipfile */
10643
10644  (void)idxStr;
10645  (void)argc;
10646
10647  zipfileResetCursor(pCsr);
10648
10649  if( pTab->zFile ){
10650    zFile = pTab->zFile;
10651  }else if( idxNum==0 ){
10652    zipfileCursorErr(pCsr, "zipfile() function requires an argument");
10653    return SQLITE_ERROR;
10654  }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
10655    static const u8 aEmptyBlob = 0;
10656    const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
10657    int nBlob = sqlite3_value_bytes(argv[0]);
10658    assert( pTab->pFirstEntry==0 );
10659    if( aBlob==0 ){
10660      aBlob = &aEmptyBlob;
10661      nBlob = 0;
10662    }
10663    rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
10664    pCsr->pFreeEntry = pTab->pFirstEntry;
10665    pTab->pFirstEntry = pTab->pLastEntry = 0;
10666    if( rc!=SQLITE_OK ) return rc;
10667    bInMemory = 1;
10668  }else{
10669    zFile = (const char*)sqlite3_value_text(argv[0]);
10670  }
10671
10672  if( 0==pTab->pWriteFd && 0==bInMemory ){
10673    pCsr->pFile = zFile ? fopen(zFile, "rb") : 0;
10674    if( pCsr->pFile==0 ){
10675      zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
10676      rc = SQLITE_ERROR;
10677    }else{
10678      rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
10679      if( rc==SQLITE_OK ){
10680        if( pCsr->eocd.nEntry==0 ){
10681          pCsr->bEof = 1;
10682        }else{
10683          pCsr->iNextOff = pCsr->eocd.iOffset;
10684          rc = zipfileNext(cur);
10685        }
10686      }
10687    }
10688  }else{
10689    pCsr->bNoop = 1;
10690    pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
10691    rc = zipfileNext(cur);
10692  }
10693
10694  return rc;
10695}
10696
10697/*
10698** xBestIndex callback.
10699*/
10700static int zipfileBestIndex(
10701  sqlite3_vtab *tab,
10702  sqlite3_index_info *pIdxInfo
10703){
10704  int i;
10705  int idx = -1;
10706  int unusable = 0;
10707  (void)tab;
10708
10709  for(i=0; i<pIdxInfo->nConstraint; i++){
10710    const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
10711    if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
10712    if( pCons->usable==0 ){
10713      unusable = 1;
10714    }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
10715      idx = i;
10716    }
10717  }
10718  pIdxInfo->estimatedCost = 1000.0;
10719  if( idx>=0 ){
10720    pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
10721    pIdxInfo->aConstraintUsage[idx].omit = 1;
10722    pIdxInfo->idxNum = 1;
10723  }else if( unusable ){
10724    return SQLITE_CONSTRAINT;
10725  }
10726  return SQLITE_OK;
10727}
10728
10729static ZipfileEntry *zipfileNewEntry(const char *zPath){
10730  ZipfileEntry *pNew;
10731  pNew = sqlite3_malloc(sizeof(ZipfileEntry));
10732  if( pNew ){
10733    memset(pNew, 0, sizeof(ZipfileEntry));
10734    pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
10735    if( pNew->cds.zFile==0 ){
10736      sqlite3_free(pNew);
10737      pNew = 0;
10738    }
10739  }
10740  return pNew;
10741}
10742
10743static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
10744  ZipfileCDS *pCds = &pEntry->cds;
10745  u8 *a = aBuf;
10746
10747  pCds->nExtra = 9;
10748
10749  /* Write the LFH itself */
10750  zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
10751  zipfileWrite16(a, pCds->iVersionExtract);
10752  zipfileWrite16(a, pCds->flags);
10753  zipfileWrite16(a, pCds->iCompression);
10754  zipfileWrite16(a, pCds->mTime);
10755  zipfileWrite16(a, pCds->mDate);
10756  zipfileWrite32(a, pCds->crc32);
10757  zipfileWrite32(a, pCds->szCompressed);
10758  zipfileWrite32(a, pCds->szUncompressed);
10759  zipfileWrite16(a, (u16)pCds->nFile);
10760  zipfileWrite16(a, pCds->nExtra);
10761  assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
10762
10763  /* Add the file name */
10764  memcpy(a, pCds->zFile, (int)pCds->nFile);
10765  a += (int)pCds->nFile;
10766
10767  /* The "extra" data */
10768  zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
10769  zipfileWrite16(a, 5);
10770  *a++ = 0x01;
10771  zipfileWrite32(a, pEntry->mUnixTime);
10772
10773  return a-aBuf;
10774}
10775
10776static int zipfileAppendEntry(
10777  ZipfileTab *pTab,
10778  ZipfileEntry *pEntry,
10779  const u8 *pData,
10780  int nData
10781){
10782  u8 *aBuf = pTab->aBuffer;
10783  int nBuf;
10784  int rc;
10785
10786  nBuf = zipfileSerializeLFH(pEntry, aBuf);
10787  rc = zipfileAppendData(pTab, aBuf, nBuf);
10788  if( rc==SQLITE_OK ){
10789    pEntry->iDataOff = pTab->szCurrent;
10790    rc = zipfileAppendData(pTab, pData, nData);
10791  }
10792
10793  return rc;
10794}
10795
10796static int zipfileGetMode(
10797  sqlite3_value *pVal,
10798  int bIsDir,                     /* If true, default to directory */
10799  u32 *pMode,                     /* OUT: Mode value */
10800  char **pzErr                    /* OUT: Error message */
10801){
10802  const char *z = (const char*)sqlite3_value_text(pVal);
10803  u32 mode = 0;
10804  if( z==0 ){
10805    mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
10806  }else if( z[0]>='0' && z[0]<='9' ){
10807    mode = (unsigned int)sqlite3_value_int(pVal);
10808  }else{
10809    const char zTemplate[11] = "-rwxrwxrwx";
10810    int i;
10811    if( strlen(z)!=10 ) goto parse_error;
10812    switch( z[0] ){
10813      case '-': mode |= S_IFREG; break;
10814      case 'd': mode |= S_IFDIR; break;
10815      case 'l': mode |= S_IFLNK; break;
10816      default: goto parse_error;
10817    }
10818    for(i=1; i<10; i++){
10819      if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
10820      else if( z[i]!='-' ) goto parse_error;
10821    }
10822  }
10823  if( ((mode & S_IFDIR)==0)==bIsDir ){
10824    /* The "mode" attribute is a directory, but data has been specified.
10825    ** Or vice-versa - no data but "mode" is a file or symlink.  */
10826    *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
10827    return SQLITE_CONSTRAINT;
10828  }
10829  *pMode = mode;
10830  return SQLITE_OK;
10831
10832 parse_error:
10833  *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
10834  return SQLITE_ERROR;
10835}
10836
10837/*
10838** Both (const char*) arguments point to nul-terminated strings. Argument
10839** nB is the value of strlen(zB). This function returns 0 if the strings are
10840** identical, ignoring any trailing '/' character in either path.  */
10841static int zipfileComparePath(const char *zA, const char *zB, int nB){
10842  int nA = (int)strlen(zA);
10843  if( nA>0 && zA[nA-1]=='/' ) nA--;
10844  if( nB>0 && zB[nB-1]=='/' ) nB--;
10845  if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
10846  return 1;
10847}
10848
10849static int zipfileBegin(sqlite3_vtab *pVtab){
10850  ZipfileTab *pTab = (ZipfileTab*)pVtab;
10851  int rc = SQLITE_OK;
10852
10853  assert( pTab->pWriteFd==0 );
10854  if( pTab->zFile==0 || pTab->zFile[0]==0 ){
10855    pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
10856    return SQLITE_ERROR;
10857  }
10858
10859  /* Open a write fd on the file. Also load the entire central directory
10860  ** structure into memory. During the transaction any new file data is
10861  ** appended to the archive file, but the central directory is accumulated
10862  ** in main-memory until the transaction is committed.  */
10863  pTab->pWriteFd = fopen(pTab->zFile, "ab+");
10864  if( pTab->pWriteFd==0 ){
10865    pTab->base.zErrMsg = sqlite3_mprintf(
10866        "zipfile: failed to open file %s for writing", pTab->zFile
10867        );
10868    rc = SQLITE_ERROR;
10869  }else{
10870    fseek(pTab->pWriteFd, 0, SEEK_END);
10871    pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
10872    rc = zipfileLoadDirectory(pTab, 0, 0);
10873  }
10874
10875  if( rc!=SQLITE_OK ){
10876    zipfileCleanupTransaction(pTab);
10877  }
10878
10879  return rc;
10880}
10881
10882/*
10883** Return the current time as a 32-bit timestamp in UNIX epoch format (like
10884** time(2)).
10885*/
10886static u32 zipfileTime(void){
10887  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
10888  u32 ret;
10889  if( pVfs==0 ) return 0;
10890  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
10891    i64 ms;
10892    pVfs->xCurrentTimeInt64(pVfs, &ms);
10893    ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
10894  }else{
10895    double day;
10896    pVfs->xCurrentTime(pVfs, &day);
10897    ret = (u32)((day - 2440587.5) * 86400);
10898  }
10899  return ret;
10900}
10901
10902/*
10903** Return a 32-bit timestamp in UNIX epoch format.
10904**
10905** If the value passed as the only argument is either NULL or an SQL NULL,
10906** return the current time. Otherwise, return the value stored in (*pVal)
10907** cast to a 32-bit unsigned integer.
10908*/
10909static u32 zipfileGetTime(sqlite3_value *pVal){
10910  if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
10911    return zipfileTime();
10912  }
10913  return (u32)sqlite3_value_int64(pVal);
10914}
10915
10916/*
10917** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
10918** linked list.  Remove it from the list and free the object.
10919*/
10920static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
10921  if( pOld ){
10922    if( pTab->pFirstEntry==pOld ){
10923      pTab->pFirstEntry = pOld->pNext;
10924      if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0;
10925    }else{
10926      ZipfileEntry *p;
10927      for(p=pTab->pFirstEntry; p; p=p->pNext){
10928        if( p->pNext==pOld ){
10929          p->pNext = pOld->pNext;
10930          if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p;
10931          break;
10932        }
10933      }
10934    }
10935    zipfileEntryFree(pOld);
10936  }
10937}
10938
10939/*
10940** xUpdate method.
10941*/
10942static int zipfileUpdate(
10943  sqlite3_vtab *pVtab,
10944  int nVal,
10945  sqlite3_value **apVal,
10946  sqlite_int64 *pRowid
10947){
10948  ZipfileTab *pTab = (ZipfileTab*)pVtab;
10949  int rc = SQLITE_OK;             /* Return Code */
10950  ZipfileEntry *pNew = 0;         /* New in-memory CDS entry */
10951
10952  u32 mode = 0;                   /* Mode for new entry */
10953  u32 mTime = 0;                  /* Modification time for new entry */
10954  i64 sz = 0;                     /* Uncompressed size */
10955  const char *zPath = 0;          /* Path for new entry */
10956  int nPath = 0;                  /* strlen(zPath) */
10957  const u8 *pData = 0;            /* Pointer to buffer containing content */
10958  int nData = 0;                  /* Size of pData buffer in bytes */
10959  int iMethod = 0;                /* Compression method for new entry */
10960  u8 *pFree = 0;                  /* Free this */
10961  char *zFree = 0;                /* Also free this */
10962  ZipfileEntry *pOld = 0;
10963  ZipfileEntry *pOld2 = 0;
10964  int bUpdate = 0;                /* True for an update that modifies "name" */
10965  int bIsDir = 0;
10966  u32 iCrc32 = 0;
10967
10968  (void)pRowid;
10969
10970  if( pTab->pWriteFd==0 ){
10971    rc = zipfileBegin(pVtab);
10972    if( rc!=SQLITE_OK ) return rc;
10973  }
10974
10975  /* If this is a DELETE or UPDATE, find the archive entry to delete. */
10976  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
10977    const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
10978    int nDelete = (int)strlen(zDelete);
10979    if( nVal>1 ){
10980      const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
10981      if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
10982        bUpdate = 1;
10983      }
10984    }
10985    for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
10986      if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
10987        break;
10988      }
10989      assert( pOld->pNext );
10990    }
10991  }
10992
10993  if( nVal>1 ){
10994    /* Check that "sz" and "rawdata" are both NULL: */
10995    if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
10996      zipfileTableErr(pTab, "sz must be NULL");
10997      rc = SQLITE_CONSTRAINT;
10998    }
10999    if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
11000      zipfileTableErr(pTab, "rawdata must be NULL");
11001      rc = SQLITE_CONSTRAINT;
11002    }
11003
11004    if( rc==SQLITE_OK ){
11005      if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
11006        /* data=NULL. A directory */
11007        bIsDir = 1;
11008      }else{
11009        /* Value specified for "data", and possibly "method". This must be
11010        ** a regular file or a symlink. */
11011        const u8 *aIn = sqlite3_value_blob(apVal[7]);
11012        int nIn = sqlite3_value_bytes(apVal[7]);
11013        int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
11014
11015        iMethod = sqlite3_value_int(apVal[8]);
11016        sz = nIn;
11017        pData = aIn;
11018        nData = nIn;
11019        if( iMethod!=0 && iMethod!=8 ){
11020          zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
11021          rc = SQLITE_CONSTRAINT;
11022        }else{
11023          if( bAuto || iMethod ){
11024            int nCmp;
11025            rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
11026            if( rc==SQLITE_OK ){
11027              if( iMethod || nCmp<nIn ){
11028                iMethod = 8;
11029                pData = pFree;
11030                nData = nCmp;
11031              }
11032            }
11033          }
11034          iCrc32 = crc32(0, aIn, nIn);
11035        }
11036      }
11037    }
11038
11039    if( rc==SQLITE_OK ){
11040      rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
11041    }
11042
11043    if( rc==SQLITE_OK ){
11044      zPath = (const char*)sqlite3_value_text(apVal[2]);
11045      if( zPath==0 ) zPath = "";
11046      nPath = (int)strlen(zPath);
11047      mTime = zipfileGetTime(apVal[4]);
11048    }
11049
11050    if( rc==SQLITE_OK && bIsDir ){
11051      /* For a directory, check that the last character in the path is a
11052      ** '/'. This appears to be required for compatibility with info-zip
11053      ** (the unzip command on unix). It does not create directories
11054      ** otherwise.  */
11055      if( nPath<=0 || zPath[nPath-1]!='/' ){
11056        zFree = sqlite3_mprintf("%s/", zPath);
11057        zPath = (const char*)zFree;
11058        if( zFree==0 ){
11059          rc = SQLITE_NOMEM;
11060          nPath = 0;
11061        }else{
11062          nPath = (int)strlen(zPath);
11063        }
11064      }
11065    }
11066
11067    /* Check that we're not inserting a duplicate entry -OR- updating an
11068    ** entry with a path, thereby making it into a duplicate. */
11069    if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
11070      ZipfileEntry *p;
11071      for(p=pTab->pFirstEntry; p; p=p->pNext){
11072        if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
11073          switch( sqlite3_vtab_on_conflict(pTab->db) ){
11074            case SQLITE_IGNORE: {
11075              goto zipfile_update_done;
11076            }
11077            case SQLITE_REPLACE: {
11078              pOld2 = p;
11079              break;
11080            }
11081            default: {
11082              zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
11083              rc = SQLITE_CONSTRAINT;
11084              break;
11085            }
11086          }
11087          break;
11088        }
11089      }
11090    }
11091
11092    if( rc==SQLITE_OK ){
11093      /* Create the new CDS record. */
11094      pNew = zipfileNewEntry(zPath);
11095      if( pNew==0 ){
11096        rc = SQLITE_NOMEM;
11097      }else{
11098        pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11099        pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11100        pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11101        pNew->cds.iCompression = (u16)iMethod;
11102        zipfileMtimeToDos(&pNew->cds, mTime);
11103        pNew->cds.crc32 = iCrc32;
11104        pNew->cds.szCompressed = nData;
11105        pNew->cds.szUncompressed = (u32)sz;
11106        pNew->cds.iExternalAttr = (mode<<16);
11107        pNew->cds.iOffset = (u32)pTab->szCurrent;
11108        pNew->cds.nFile = (u16)nPath;
11109        pNew->mUnixTime = (u32)mTime;
11110        rc = zipfileAppendEntry(pTab, pNew, pData, nData);
11111        zipfileAddEntry(pTab, pOld, pNew);
11112      }
11113    }
11114  }
11115
11116  if( rc==SQLITE_OK && (pOld || pOld2) ){
11117    ZipfileCsr *pCsr;
11118    for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11119      if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
11120        pCsr->pCurrent = pCsr->pCurrent->pNext;
11121        pCsr->bNoop = 1;
11122      }
11123    }
11124
11125    zipfileRemoveEntryFromList(pTab, pOld);
11126    zipfileRemoveEntryFromList(pTab, pOld2);
11127  }
11128
11129zipfile_update_done:
11130  sqlite3_free(pFree);
11131  sqlite3_free(zFree);
11132  return rc;
11133}
11134
11135static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
11136  u8 *a = aBuf;
11137  zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
11138  zipfileWrite16(a, p->iDisk);
11139  zipfileWrite16(a, p->iFirstDisk);
11140  zipfileWrite16(a, p->nEntry);
11141  zipfileWrite16(a, p->nEntryTotal);
11142  zipfileWrite32(a, p->nSize);
11143  zipfileWrite32(a, p->iOffset);
11144  zipfileWrite16(a, 0);        /* Size of trailing comment in bytes*/
11145
11146  return a-aBuf;
11147}
11148
11149static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
11150  int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
11151  assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
11152  return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
11153}
11154
11155/*
11156** Serialize the CDS structure into buffer aBuf[]. Return the number
11157** of bytes written.
11158*/
11159static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
11160  u8 *a = aBuf;
11161  ZipfileCDS *pCDS = &pEntry->cds;
11162
11163  if( pEntry->aExtra==0 ){
11164    pCDS->nExtra = 9;
11165  }
11166
11167  zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
11168  zipfileWrite16(a, pCDS->iVersionMadeBy);
11169  zipfileWrite16(a, pCDS->iVersionExtract);
11170  zipfileWrite16(a, pCDS->flags);
11171  zipfileWrite16(a, pCDS->iCompression);
11172  zipfileWrite16(a, pCDS->mTime);
11173  zipfileWrite16(a, pCDS->mDate);
11174  zipfileWrite32(a, pCDS->crc32);
11175  zipfileWrite32(a, pCDS->szCompressed);
11176  zipfileWrite32(a, pCDS->szUncompressed);
11177  assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
11178  zipfileWrite16(a, pCDS->nFile);
11179  zipfileWrite16(a, pCDS->nExtra);
11180  zipfileWrite16(a, pCDS->nComment);
11181  zipfileWrite16(a, pCDS->iDiskStart);
11182  zipfileWrite16(a, pCDS->iInternalAttr);
11183  zipfileWrite32(a, pCDS->iExternalAttr);
11184  zipfileWrite32(a, pCDS->iOffset);
11185
11186  memcpy(a, pCDS->zFile, pCDS->nFile);
11187  a += pCDS->nFile;
11188
11189  if( pEntry->aExtra ){
11190    int n = (int)pCDS->nExtra + (int)pCDS->nComment;
11191    memcpy(a, pEntry->aExtra, n);
11192    a += n;
11193  }else{
11194    assert( pCDS->nExtra==9 );
11195    zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
11196    zipfileWrite16(a, 5);
11197    *a++ = 0x01;
11198    zipfileWrite32(a, pEntry->mUnixTime);
11199  }
11200
11201  return a-aBuf;
11202}
11203
11204static int zipfileCommit(sqlite3_vtab *pVtab){
11205  ZipfileTab *pTab = (ZipfileTab*)pVtab;
11206  int rc = SQLITE_OK;
11207  if( pTab->pWriteFd ){
11208    i64 iOffset = pTab->szCurrent;
11209    ZipfileEntry *p;
11210    ZipfileEOCD eocd;
11211    int nEntry = 0;
11212
11213    /* Write out all entries */
11214    for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
11215      int n = zipfileSerializeCDS(p, pTab->aBuffer);
11216      rc = zipfileAppendData(pTab, pTab->aBuffer, n);
11217      nEntry++;
11218    }
11219
11220    /* Write out the EOCD record */
11221    eocd.iDisk = 0;
11222    eocd.iFirstDisk = 0;
11223    eocd.nEntry = (u16)nEntry;
11224    eocd.nEntryTotal = (u16)nEntry;
11225    eocd.nSize = (u32)(pTab->szCurrent - iOffset);
11226    eocd.iOffset = (u32)iOffset;
11227    rc = zipfileAppendEOCD(pTab, &eocd);
11228
11229    zipfileCleanupTransaction(pTab);
11230  }
11231  return rc;
11232}
11233
11234static int zipfileRollback(sqlite3_vtab *pVtab){
11235  return zipfileCommit(pVtab);
11236}
11237
11238static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
11239  ZipfileCsr *pCsr;
11240  for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
11241    if( iId==pCsr->iId ) break;
11242  }
11243  return pCsr;
11244}
11245
11246static void zipfileFunctionCds(
11247  sqlite3_context *context,
11248  int argc,
11249  sqlite3_value **argv
11250){
11251  ZipfileCsr *pCsr;
11252  ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
11253  assert( argc>0 );
11254
11255  pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
11256  if( pCsr ){
11257    ZipfileCDS *p = &pCsr->pCurrent->cds;
11258    char *zRes = sqlite3_mprintf("{"
11259        "\"version-made-by\" : %u, "
11260        "\"version-to-extract\" : %u, "
11261        "\"flags\" : %u, "
11262        "\"compression\" : %u, "
11263        "\"time\" : %u, "
11264        "\"date\" : %u, "
11265        "\"crc32\" : %u, "
11266        "\"compressed-size\" : %u, "
11267        "\"uncompressed-size\" : %u, "
11268        "\"file-name-length\" : %u, "
11269        "\"extra-field-length\" : %u, "
11270        "\"file-comment-length\" : %u, "
11271        "\"disk-number-start\" : %u, "
11272        "\"internal-attr\" : %u, "
11273        "\"external-attr\" : %u, "
11274        "\"offset\" : %u }",
11275        (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
11276        (u32)p->flags, (u32)p->iCompression,
11277        (u32)p->mTime, (u32)p->mDate,
11278        (u32)p->crc32, (u32)p->szCompressed,
11279        (u32)p->szUncompressed, (u32)p->nFile,
11280        (u32)p->nExtra, (u32)p->nComment,
11281        (u32)p->iDiskStart, (u32)p->iInternalAttr,
11282        (u32)p->iExternalAttr, (u32)p->iOffset
11283    );
11284
11285    if( zRes==0 ){
11286      sqlite3_result_error_nomem(context);
11287    }else{
11288      sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
11289      sqlite3_free(zRes);
11290    }
11291  }
11292}
11293
11294/*
11295** xFindFunction method.
11296*/
11297static int zipfileFindFunction(
11298  sqlite3_vtab *pVtab,            /* Virtual table handle */
11299  int nArg,                       /* Number of SQL function arguments */
11300  const char *zName,              /* Name of SQL function */
11301  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
11302  void **ppArg                    /* OUT: User data for *pxFunc */
11303){
11304  (void)nArg;
11305  if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
11306    *pxFunc = zipfileFunctionCds;
11307    *ppArg = (void*)pVtab;
11308    return 1;
11309  }
11310  return 0;
11311}
11312
11313typedef struct ZipfileBuffer ZipfileBuffer;
11314struct ZipfileBuffer {
11315  u8 *a;                          /* Pointer to buffer */
11316  int n;                          /* Size of buffer in bytes */
11317  int nAlloc;                     /* Byte allocated at a[] */
11318};
11319
11320typedef struct ZipfileCtx ZipfileCtx;
11321struct ZipfileCtx {
11322  int nEntry;
11323  ZipfileBuffer body;
11324  ZipfileBuffer cds;
11325};
11326
11327static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
11328  if( pBuf->n+nByte>pBuf->nAlloc ){
11329    u8 *aNew;
11330    sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512;
11331    int nReq = pBuf->n + nByte;
11332
11333    while( nNew<nReq ) nNew = nNew*2;
11334    aNew = sqlite3_realloc64(pBuf->a, nNew);
11335    if( aNew==0 ) return SQLITE_NOMEM;
11336    pBuf->a = aNew;
11337    pBuf->nAlloc = (int)nNew;
11338  }
11339  return SQLITE_OK;
11340}
11341
11342/*
11343** xStep() callback for the zipfile() aggregate. This can be called in
11344** any of the following ways:
11345**
11346**   SELECT zipfile(name,data) ...
11347**   SELECT zipfile(name,mode,mtime,data) ...
11348**   SELECT zipfile(name,mode,mtime,data,method) ...
11349*/
11350static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
11351  ZipfileCtx *p;                  /* Aggregate function context */
11352  ZipfileEntry e;                 /* New entry to add to zip archive */
11353
11354  sqlite3_value *pName = 0;
11355  sqlite3_value *pMode = 0;
11356  sqlite3_value *pMtime = 0;
11357  sqlite3_value *pData = 0;
11358  sqlite3_value *pMethod = 0;
11359
11360  int bIsDir = 0;
11361  u32 mode;
11362  int rc = SQLITE_OK;
11363  char *zErr = 0;
11364
11365  int iMethod = -1;               /* Compression method to use (0 or 8) */
11366
11367  const u8 *aData = 0;            /* Possibly compressed data for new entry */
11368  int nData = 0;                  /* Size of aData[] in bytes */
11369  int szUncompressed = 0;         /* Size of data before compression */
11370  u8 *aFree = 0;                  /* Free this before returning */
11371  u32 iCrc32 = 0;                 /* crc32 of uncompressed data */
11372
11373  char *zName = 0;                /* Path (name) of new entry */
11374  int nName = 0;                  /* Size of zName in bytes */
11375  char *zFree = 0;                /* Free this before returning */
11376  int nByte;
11377
11378  memset(&e, 0, sizeof(e));
11379  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11380  if( p==0 ) return;
11381
11382  /* Martial the arguments into stack variables */
11383  if( nVal!=2 && nVal!=4 && nVal!=5 ){
11384    zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
11385    rc = SQLITE_ERROR;
11386    goto zipfile_step_out;
11387  }
11388  pName = apVal[0];
11389  if( nVal==2 ){
11390    pData = apVal[1];
11391  }else{
11392    pMode = apVal[1];
11393    pMtime = apVal[2];
11394    pData = apVal[3];
11395    if( nVal==5 ){
11396      pMethod = apVal[4];
11397    }
11398  }
11399
11400  /* Check that the 'name' parameter looks ok. */
11401  zName = (char*)sqlite3_value_text(pName);
11402  nName = sqlite3_value_bytes(pName);
11403  if( zName==0 ){
11404    zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
11405    rc = SQLITE_ERROR;
11406    goto zipfile_step_out;
11407  }
11408
11409  /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
11410  ** deflate compression) or NULL (choose automatically).  */
11411  if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
11412    iMethod = (int)sqlite3_value_int64(pMethod);
11413    if( iMethod!=0 && iMethod!=8 ){
11414      zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
11415      rc = SQLITE_ERROR;
11416      goto zipfile_step_out;
11417    }
11418  }
11419
11420  /* Now inspect the data. If this is NULL, then the new entry must be a
11421  ** directory.  Otherwise, figure out whether or not the data should
11422  ** be deflated or simply stored in the zip archive. */
11423  if( sqlite3_value_type(pData)==SQLITE_NULL ){
11424    bIsDir = 1;
11425    iMethod = 0;
11426  }else{
11427    aData = sqlite3_value_blob(pData);
11428    szUncompressed = nData = sqlite3_value_bytes(pData);
11429    iCrc32 = crc32(0, aData, nData);
11430    if( iMethod<0 || iMethod==8 ){
11431      int nOut = 0;
11432      rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
11433      if( rc!=SQLITE_OK ){
11434        goto zipfile_step_out;
11435      }
11436      if( iMethod==8 || nOut<nData ){
11437        aData = aFree;
11438        nData = nOut;
11439        iMethod = 8;
11440      }else{
11441        iMethod = 0;
11442      }
11443    }
11444  }
11445
11446  /* Decode the "mode" argument. */
11447  rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
11448  if( rc ) goto zipfile_step_out;
11449
11450  /* Decode the "mtime" argument. */
11451  e.mUnixTime = zipfileGetTime(pMtime);
11452
11453  /* If this is a directory entry, ensure that there is exactly one '/'
11454  ** at the end of the path. Or, if this is not a directory and the path
11455  ** ends in '/' it is an error. */
11456  if( bIsDir==0 ){
11457    if( nName>0 && zName[nName-1]=='/' ){
11458      zErr = sqlite3_mprintf("non-directory name must not end with /");
11459      rc = SQLITE_ERROR;
11460      goto zipfile_step_out;
11461    }
11462  }else{
11463    if( nName==0 || zName[nName-1]!='/' ){
11464      zName = zFree = sqlite3_mprintf("%s/", zName);
11465      if( zName==0 ){
11466        rc = SQLITE_NOMEM;
11467        goto zipfile_step_out;
11468      }
11469      nName = (int)strlen(zName);
11470    }else{
11471      while( nName>1 && zName[nName-2]=='/' ) nName--;
11472    }
11473  }
11474
11475  /* Assemble the ZipfileEntry object for the new zip archive entry */
11476  e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
11477  e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
11478  e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
11479  e.cds.iCompression = (u16)iMethod;
11480  zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
11481  e.cds.crc32 = iCrc32;
11482  e.cds.szCompressed = nData;
11483  e.cds.szUncompressed = szUncompressed;
11484  e.cds.iExternalAttr = (mode<<16);
11485  e.cds.iOffset = p->body.n;
11486  e.cds.nFile = (u16)nName;
11487  e.cds.zFile = zName;
11488
11489  /* Append the LFH to the body of the new archive */
11490  nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
11491  if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
11492  p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
11493
11494  /* Append the data to the body of the new archive */
11495  if( nData>0 ){
11496    if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
11497    memcpy(&p->body.a[p->body.n], aData, nData);
11498    p->body.n += nData;
11499  }
11500
11501  /* Append the CDS record to the directory of the new archive */
11502  nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
11503  if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
11504  p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
11505
11506  /* Increment the count of entries in the archive */
11507  p->nEntry++;
11508
11509 zipfile_step_out:
11510  sqlite3_free(aFree);
11511  sqlite3_free(zFree);
11512  if( rc ){
11513    if( zErr ){
11514      sqlite3_result_error(pCtx, zErr, -1);
11515    }else{
11516      sqlite3_result_error_code(pCtx, rc);
11517    }
11518  }
11519  sqlite3_free(zErr);
11520}
11521
11522/*
11523** xFinalize() callback for zipfile aggregate function.
11524*/
11525static void zipfileFinal(sqlite3_context *pCtx){
11526  ZipfileCtx *p;
11527  ZipfileEOCD eocd;
11528  sqlite3_int64 nZip;
11529  u8 *aZip;
11530
11531  p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
11532  if( p==0 ) return;
11533  if( p->nEntry>0 ){
11534    memset(&eocd, 0, sizeof(eocd));
11535    eocd.nEntry = (u16)p->nEntry;
11536    eocd.nEntryTotal = (u16)p->nEntry;
11537    eocd.nSize = p->cds.n;
11538    eocd.iOffset = p->body.n;
11539
11540    nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
11541    aZip = (u8*)sqlite3_malloc64(nZip);
11542    if( aZip==0 ){
11543      sqlite3_result_error_nomem(pCtx);
11544    }else{
11545      memcpy(aZip, p->body.a, p->body.n);
11546      memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
11547      zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
11548      sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree);
11549    }
11550  }
11551
11552  sqlite3_free(p->body.a);
11553  sqlite3_free(p->cds.a);
11554}
11555
11556
11557/*
11558** Register the "zipfile" virtual table.
11559*/
11560static int zipfileRegister(sqlite3 *db){
11561  static sqlite3_module zipfileModule = {
11562    1,                         /* iVersion */
11563    zipfileConnect,            /* xCreate */
11564    zipfileConnect,            /* xConnect */
11565    zipfileBestIndex,          /* xBestIndex */
11566    zipfileDisconnect,         /* xDisconnect */
11567    zipfileDisconnect,         /* xDestroy */
11568    zipfileOpen,               /* xOpen - open a cursor */
11569    zipfileClose,              /* xClose - close a cursor */
11570    zipfileFilter,             /* xFilter - configure scan constraints */
11571    zipfileNext,               /* xNext - advance a cursor */
11572    zipfileEof,                /* xEof - check for end of scan */
11573    zipfileColumn,             /* xColumn - read data */
11574    0,                         /* xRowid - read data */
11575    zipfileUpdate,             /* xUpdate */
11576    zipfileBegin,              /* xBegin */
11577    0,                         /* xSync */
11578    zipfileCommit,             /* xCommit */
11579    zipfileRollback,           /* xRollback */
11580    zipfileFindFunction,       /* xFindMethod */
11581    0,                         /* xRename */
11582    0,                         /* xSavepoint */
11583    0,                         /* xRelease */
11584    0,                         /* xRollback */
11585    0,                         /* xShadowName */
11586    0                          /* xIntegrity */
11587  };
11588
11589  int rc = sqlite3_create_module(db, "zipfile"  , &zipfileModule, 0);
11590  if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
11591  if( rc==SQLITE_OK ){
11592    rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
11593        zipfileStep, zipfileFinal
11594    );
11595  }
11596  assert( sizeof(i64)==8 );
11597  assert( sizeof(u32)==4 );
11598  assert( sizeof(u16)==2 );
11599  assert( sizeof(u8)==1 );
11600  return rc;
11601}
11602#else         /* SQLITE_OMIT_VIRTUALTABLE */
11603# define zipfileRegister(x) SQLITE_OK
11604#endif
11605
11606#ifdef _WIN32
11607
11608#endif
11609int sqlite3_zipfile_init(
11610  sqlite3 *db,
11611  char **pzErrMsg,
11612  const sqlite3_api_routines *pApi
11613){
11614  SQLITE_EXTENSION_INIT2(pApi);
11615  (void)pzErrMsg;  /* Unused parameter */
11616  return zipfileRegister(db);
11617}
11618
11619/************************* End ../ext/misc/zipfile.c ********************/
11620/************************* Begin ../ext/misc/sqlar.c ******************/
11621/*
11622** 2017-12-17
11623**
11624** The author disclaims copyright to this source code.  In place of
11625** a legal notice, here is a blessing:
11626**
11627**    May you do good and not evil.
11628**    May you find forgiveness for yourself and forgive others.
11629**    May you share freely, never taking more than you give.
11630**
11631******************************************************************************
11632**
11633** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
11634** for working with sqlar archives and used by the shell tool's built-in
11635** sqlar support.
11636*/
11637/* #include "sqlite3ext.h" */
11638SQLITE_EXTENSION_INIT1
11639#include <zlib.h>
11640#include <assert.h>
11641
11642/*
11643** Implementation of the "sqlar_compress(X)" SQL function.
11644**
11645** If the type of X is SQLITE_BLOB, and compressing that blob using
11646** zlib utility function compress() yields a smaller blob, return the
11647** compressed blob. Otherwise, return a copy of X.
11648**
11649** SQLar uses the "zlib format" for compressed content.  The zlib format
11650** contains a two-byte identification header and a four-byte checksum at
11651** the end.  This is different from ZIP which uses the raw deflate format.
11652**
11653** Future enhancements to SQLar might add support for new compression formats.
11654** If so, those new formats will be identified by alternative headers in the
11655** compressed data.
11656*/
11657static void sqlarCompressFunc(
11658  sqlite3_context *context,
11659  int argc,
11660  sqlite3_value **argv
11661){
11662  assert( argc==1 );
11663  if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
11664    const Bytef *pData = sqlite3_value_blob(argv[0]);
11665    uLong nData = sqlite3_value_bytes(argv[0]);
11666    uLongf nOut = compressBound(nData);
11667    Bytef *pOut;
11668
11669    pOut = (Bytef*)sqlite3_malloc(nOut);
11670    if( pOut==0 ){
11671      sqlite3_result_error_nomem(context);
11672      return;
11673    }else{
11674      if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
11675        sqlite3_result_error(context, "error in compress()", -1);
11676      }else if( nOut<nData ){
11677        sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
11678      }else{
11679        sqlite3_result_value(context, argv[0]);
11680      }
11681      sqlite3_free(pOut);
11682    }
11683  }else{
11684    sqlite3_result_value(context, argv[0]);
11685  }
11686}
11687
11688/*
11689** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
11690**
11691** Parameter SZ is interpreted as an integer. If it is less than or
11692** equal to zero, then this function returns a copy of X. Or, if
11693** SZ is equal to the size of X when interpreted as a blob, also
11694** return a copy of X. Otherwise, decompress blob X using zlib
11695** utility function uncompress() and return the results (another
11696** blob).
11697*/
11698static void sqlarUncompressFunc(
11699  sqlite3_context *context,
11700  int argc,
11701  sqlite3_value **argv
11702){
11703  uLong nData;
11704  sqlite3_int64 sz;
11705
11706  assert( argc==2 );
11707  sz = sqlite3_value_int(argv[1]);
11708
11709  if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
11710    sqlite3_result_value(context, argv[0]);
11711  }else{
11712    uLongf szf = sz;
11713    const Bytef *pData= sqlite3_value_blob(argv[0]);
11714    Bytef *pOut = sqlite3_malloc(sz);
11715    if( pOut==0 ){
11716      sqlite3_result_error_nomem(context);
11717    }else if( Z_OK!=uncompress(pOut, &szf, pData, nData) ){
11718      sqlite3_result_error(context, "error in uncompress()", -1);
11719    }else{
11720      sqlite3_result_blob(context, pOut, szf, SQLITE_TRANSIENT);
11721    }
11722    sqlite3_free(pOut);
11723  }
11724}
11725
11726#ifdef _WIN32
11727
11728#endif
11729int sqlite3_sqlar_init(
11730  sqlite3 *db,
11731  char **pzErrMsg,
11732  const sqlite3_api_routines *pApi
11733){
11734  int rc = SQLITE_OK;
11735  SQLITE_EXTENSION_INIT2(pApi);
11736  (void)pzErrMsg;  /* Unused parameter */
11737  rc = sqlite3_create_function(db, "sqlar_compress", 1,
11738                               SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11739                               sqlarCompressFunc, 0, 0);
11740  if( rc==SQLITE_OK ){
11741    rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
11742                                 SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
11743                                 sqlarUncompressFunc, 0, 0);
11744  }
11745  return rc;
11746}
11747
11748/************************* End ../ext/misc/sqlar.c ********************/
11749#endif
11750/************************* Begin ../ext/expert/sqlite3expert.h ******************/
11751/*
11752** 2017 April 07
11753**
11754** The author disclaims copyright to this source code.  In place of
11755** a legal notice, here is a blessing:
11756**
11757**    May you do good and not evil.
11758**    May you find forgiveness for yourself and forgive others.
11759**    May you share freely, never taking more than you give.
11760**
11761*************************************************************************
11762*/
11763#if !defined(SQLITEEXPERT_H)
11764#define SQLITEEXPERT_H 1
11765/* #include "sqlite3.h" */
11766
11767typedef struct sqlite3expert sqlite3expert;
11768
11769/*
11770** Create a new sqlite3expert object.
11771**
11772** If successful, a pointer to the new object is returned and (*pzErr) set
11773** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
11774** an English-language error message. In this case it is the responsibility
11775** of the caller to eventually free the error message buffer using
11776** sqlite3_free().
11777*/
11778sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
11779
11780/*
11781** Configure an sqlite3expert object.
11782**
11783** EXPERT_CONFIG_SAMPLE:
11784**   By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
11785**   each candidate index. This involves scanning and sorting the entire
11786**   contents of each user database table once for each candidate index
11787**   associated with the table. For large databases, this can be
11788**   prohibitively slow. This option allows the sqlite3expert object to
11789**   be configured so that sqlite_stat1 data is instead generated based on a
11790**   subset of each table, or so that no sqlite_stat1 data is used at all.
11791**
11792**   A single integer argument is passed to this option. If the value is less
11793**   than or equal to zero, then no sqlite_stat1 data is generated or used by
11794**   the analysis - indexes are recommended based on the database schema only.
11795**   Or, if the value is 100 or greater, complete sqlite_stat1 data is
11796**   generated for each candidate index (this is the default). Finally, if the
11797**   value falls between 0 and 100, then it represents the percentage of user
11798**   table rows that should be considered when generating sqlite_stat1 data.
11799**
11800**   Examples:
11801**
11802**     // Do not generate any sqlite_stat1 data
11803**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
11804**
11805**     // Generate sqlite_stat1 data based on 10% of the rows in each table.
11806**     sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
11807*/
11808int sqlite3_expert_config(sqlite3expert *p, int op, ...);
11809
11810#define EXPERT_CONFIG_SAMPLE 1    /* int */
11811
11812/*
11813** Specify zero or more SQL statements to be included in the analysis.
11814**
11815** Buffer zSql must contain zero or more complete SQL statements. This
11816** function parses all statements contained in the buffer and adds them
11817** to the internal list of statements to analyze. If successful, SQLITE_OK
11818** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
11819** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
11820** may be set to point to an English language error message. In this case
11821** the caller is responsible for eventually freeing the error message buffer
11822** using sqlite3_free().
11823**
11824** If an error does occur while processing one of the statements in the
11825** buffer passed as the second argument, none of the statements in the
11826** buffer are added to the analysis.
11827**
11828** This function must be called before sqlite3_expert_analyze(). If a call
11829** to this function is made on an sqlite3expert object that has already
11830** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
11831** immediately and no statements are added to the analysis.
11832*/
11833int sqlite3_expert_sql(
11834  sqlite3expert *p,               /* From a successful sqlite3_expert_new() */
11835  const char *zSql,               /* SQL statement(s) to add */
11836  char **pzErr                    /* OUT: Error message (if any) */
11837);
11838
11839
11840/*
11841** This function is called after the sqlite3expert object has been configured
11842** with all SQL statements using sqlite3_expert_sql() to actually perform
11843** the analysis. Once this function has been called, it is not possible to
11844** add further SQL statements to the analysis.
11845**
11846** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
11847** an error occurs, an SQLite error code is returned and (*pzErr) set to
11848** point to a buffer containing an English language error message. In this
11849** case it is the responsibility of the caller to eventually free the buffer
11850** using sqlite3_free().
11851**
11852** If an error does occur within this function, the sqlite3expert object
11853** is no longer useful for any purpose. At that point it is no longer
11854** possible to add further SQL statements to the object or to re-attempt
11855** the analysis. The sqlite3expert object must still be freed using a call
11856** sqlite3_expert_destroy().
11857*/
11858int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
11859
11860/*
11861** Return the total number of statements loaded using sqlite3_expert_sql().
11862** The total number of SQL statements may be different from the total number
11863** to calls to sqlite3_expert_sql().
11864*/
11865int sqlite3_expert_count(sqlite3expert*);
11866
11867/*
11868** Return a component of the report.
11869**
11870** This function is called after sqlite3_expert_analyze() to extract the
11871** results of the analysis. Each call to this function returns either a
11872** NULL pointer or a pointer to a buffer containing a nul-terminated string.
11873** The value passed as the third argument must be one of the EXPERT_REPORT_*
11874** #define constants defined below.
11875**
11876** For some EXPERT_REPORT_* parameters, the buffer returned contains
11877** information relating to a specific SQL statement. In these cases that
11878** SQL statement is identified by the value passed as the second argument.
11879** SQL statements are numbered from 0 in the order in which they are parsed.
11880** If an out-of-range value (less than zero or equal to or greater than the
11881** value returned by sqlite3_expert_count()) is passed as the second argument
11882** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
11883**
11884** EXPERT_REPORT_SQL:
11885**   Return the text of SQL statement iStmt.
11886**
11887** EXPERT_REPORT_INDEXES:
11888**   Return a buffer containing the CREATE INDEX statements for all recommended
11889**   indexes for statement iStmt. If there are no new recommeded indexes, NULL
11890**   is returned.
11891**
11892** EXPERT_REPORT_PLAN:
11893**   Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
11894**   iStmt after the proposed indexes have been added to the database schema.
11895**
11896** EXPERT_REPORT_CANDIDATES:
11897**   Return a pointer to a buffer containing the CREATE INDEX statements
11898**   for all indexes that were tested (for all SQL statements). The iStmt
11899**   parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
11900*/
11901const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
11902
11903/*
11904** Values for the third argument passed to sqlite3_expert_report().
11905*/
11906#define EXPERT_REPORT_SQL        1
11907#define EXPERT_REPORT_INDEXES    2
11908#define EXPERT_REPORT_PLAN       3
11909#define EXPERT_REPORT_CANDIDATES 4
11910
11911/*
11912** Free an (sqlite3expert*) handle and all associated resources. There
11913** should be one call to this function for each successful call to
11914** sqlite3-expert_new().
11915*/
11916void sqlite3_expert_destroy(sqlite3expert*);
11917
11918#endif  /* !defined(SQLITEEXPERT_H) */
11919
11920/************************* End ../ext/expert/sqlite3expert.h ********************/
11921/************************* Begin ../ext/expert/sqlite3expert.c ******************/
11922/*
11923** 2017 April 09
11924**
11925** The author disclaims copyright to this source code.  In place of
11926** a legal notice, here is a blessing:
11927**
11928**    May you do good and not evil.
11929**    May you find forgiveness for yourself and forgive others.
11930**    May you share freely, never taking more than you give.
11931**
11932*************************************************************************
11933*/
11934/* #include "sqlite3expert.h" */
11935#include <assert.h>
11936#include <string.h>
11937#include <stdio.h>
11938
11939#if !defined(SQLITE_AMALGAMATION)
11940#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11941# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
11942#endif
11943#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
11944# define ALWAYS(X)      (1)
11945# define NEVER(X)       (0)
11946#elif !defined(NDEBUG)
11947# define ALWAYS(X)      ((X)?1:(assert(0),0))
11948# define NEVER(X)       ((X)?(assert(0),1):0)
11949#else
11950# define ALWAYS(X)      (X)
11951# define NEVER(X)       (X)
11952#endif
11953#endif /* !defined(SQLITE_AMALGAMATION) */
11954
11955
11956#ifndef SQLITE_OMIT_VIRTUALTABLE
11957
11958/* typedef sqlite3_int64 i64; */
11959/* typedef sqlite3_uint64 u64; */
11960
11961typedef struct IdxColumn IdxColumn;
11962typedef struct IdxConstraint IdxConstraint;
11963typedef struct IdxScan IdxScan;
11964typedef struct IdxStatement IdxStatement;
11965typedef struct IdxTable IdxTable;
11966typedef struct IdxWrite IdxWrite;
11967
11968#define STRLEN  (int)strlen
11969
11970/*
11971** A temp table name that we assume no user database will actually use.
11972** If this assumption proves incorrect triggers on the table with the
11973** conflicting name will be ignored.
11974*/
11975#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
11976
11977/*
11978** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
11979** any other type of single-ended range constraint on a column).
11980**
11981** pLink:
11982**   Used to temporarily link IdxConstraint objects into lists while
11983**   creating candidate indexes.
11984*/
11985struct IdxConstraint {
11986  char *zColl;                    /* Collation sequence */
11987  int bRange;                     /* True for range, false for eq */
11988  int iCol;                       /* Constrained table column */
11989  int bFlag;                      /* Used by idxFindCompatible() */
11990  int bDesc;                      /* True if ORDER BY <expr> DESC */
11991  IdxConstraint *pNext;           /* Next constraint in pEq or pRange list */
11992  IdxConstraint *pLink;           /* See above */
11993};
11994
11995/*
11996** A single scan of a single table.
11997*/
11998struct IdxScan {
11999  IdxTable *pTab;                 /* Associated table object */
12000  int iDb;                        /* Database containing table zTable */
12001  i64 covering;                   /* Mask of columns required for cov. index */
12002  IdxConstraint *pOrder;          /* ORDER BY columns */
12003  IdxConstraint *pEq;             /* List of == constraints */
12004  IdxConstraint *pRange;          /* List of < constraints */
12005  IdxScan *pNextScan;             /* Next IdxScan object for same analysis */
12006};
12007
12008/*
12009** Information regarding a single database table. Extracted from
12010** "PRAGMA table_info" by function idxGetTableInfo().
12011*/
12012struct IdxColumn {
12013  char *zName;
12014  char *zColl;
12015  int iPk;
12016};
12017struct IdxTable {
12018  int nCol;
12019  char *zName;                    /* Table name */
12020  IdxColumn *aCol;
12021  IdxTable *pNext;                /* Next table in linked list of all tables */
12022};
12023
12024/*
12025** An object of the following type is created for each unique table/write-op
12026** seen. The objects are stored in a singly-linked list beginning at
12027** sqlite3expert.pWrite.
12028*/
12029struct IdxWrite {
12030  IdxTable *pTab;
12031  int eOp;                        /* SQLITE_UPDATE, DELETE or INSERT */
12032  IdxWrite *pNext;
12033};
12034
12035/*
12036** Each statement being analyzed is represented by an instance of this
12037** structure.
12038*/
12039struct IdxStatement {
12040  int iId;                        /* Statement number */
12041  char *zSql;                     /* SQL statement */
12042  char *zIdx;                     /* Indexes */
12043  char *zEQP;                     /* Plan */
12044  IdxStatement *pNext;
12045};
12046
12047
12048/*
12049** A hash table for storing strings. With space for a payload string
12050** with each entry. Methods are:
12051**
12052**   idxHashInit()
12053**   idxHashClear()
12054**   idxHashAdd()
12055**   idxHashSearch()
12056*/
12057#define IDX_HASH_SIZE 1023
12058typedef struct IdxHashEntry IdxHashEntry;
12059typedef struct IdxHash IdxHash;
12060struct IdxHashEntry {
12061  char *zKey;                     /* nul-terminated key */
12062  char *zVal;                     /* nul-terminated value string */
12063  char *zVal2;                    /* nul-terminated value string 2 */
12064  IdxHashEntry *pHashNext;        /* Next entry in same hash bucket */
12065  IdxHashEntry *pNext;            /* Next entry in hash */
12066};
12067struct IdxHash {
12068  IdxHashEntry *pFirst;
12069  IdxHashEntry *aHash[IDX_HASH_SIZE];
12070};
12071
12072/*
12073** sqlite3expert object.
12074*/
12075struct sqlite3expert {
12076  int iSample;                    /* Percentage of tables to sample for stat1 */
12077  sqlite3 *db;                    /* User database */
12078  sqlite3 *dbm;                   /* In-memory db for this analysis */
12079  sqlite3 *dbv;                   /* Vtab schema for this analysis */
12080  IdxTable *pTable;               /* List of all IdxTable objects */
12081  IdxScan *pScan;                 /* List of scan objects */
12082  IdxWrite *pWrite;               /* List of write objects */
12083  IdxStatement *pStatement;       /* List of IdxStatement objects */
12084  int bRun;                       /* True once analysis has run */
12085  char **pzErrmsg;
12086  int rc;                         /* Error code from whereinfo hook */
12087  IdxHash hIdx;                   /* Hash containing all candidate indexes */
12088  char *zCandidates;              /* For EXPERT_REPORT_CANDIDATES */
12089};
12090
12091
12092/*
12093** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
12094** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
12095*/
12096static void *idxMalloc(int *pRc, int nByte){
12097  void *pRet;
12098  assert( *pRc==SQLITE_OK );
12099  assert( nByte>0 );
12100  pRet = sqlite3_malloc(nByte);
12101  if( pRet ){
12102    memset(pRet, 0, nByte);
12103  }else{
12104    *pRc = SQLITE_NOMEM;
12105  }
12106  return pRet;
12107}
12108
12109/*
12110** Initialize an IdxHash hash table.
12111*/
12112static void idxHashInit(IdxHash *pHash){
12113  memset(pHash, 0, sizeof(IdxHash));
12114}
12115
12116/*
12117** Reset an IdxHash hash table.
12118*/
12119static void idxHashClear(IdxHash *pHash){
12120  int i;
12121  for(i=0; i<IDX_HASH_SIZE; i++){
12122    IdxHashEntry *pEntry;
12123    IdxHashEntry *pNext;
12124    for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
12125      pNext = pEntry->pHashNext;
12126      sqlite3_free(pEntry->zVal2);
12127      sqlite3_free(pEntry);
12128    }
12129  }
12130  memset(pHash, 0, sizeof(IdxHash));
12131}
12132
12133/*
12134** Return the index of the hash bucket that the string specified by the
12135** arguments to this function belongs.
12136*/
12137static int idxHashString(const char *z, int n){
12138  unsigned int ret = 0;
12139  int i;
12140  for(i=0; i<n; i++){
12141    ret += (ret<<3) + (unsigned char)(z[i]);
12142  }
12143  return (int)(ret % IDX_HASH_SIZE);
12144}
12145
12146/*
12147** If zKey is already present in the hash table, return non-zero and do
12148** nothing. Otherwise, add an entry with key zKey and payload string zVal to
12149** the hash table passed as the second argument.
12150*/
12151static int idxHashAdd(
12152  int *pRc,
12153  IdxHash *pHash,
12154  const char *zKey,
12155  const char *zVal
12156){
12157  int nKey = STRLEN(zKey);
12158  int iHash = idxHashString(zKey, nKey);
12159  int nVal = (zVal ? STRLEN(zVal) : 0);
12160  IdxHashEntry *pEntry;
12161  assert( iHash>=0 );
12162  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12163    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12164      return 1;
12165    }
12166  }
12167  pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
12168  if( pEntry ){
12169    pEntry->zKey = (char*)&pEntry[1];
12170    memcpy(pEntry->zKey, zKey, nKey);
12171    if( zVal ){
12172      pEntry->zVal = &pEntry->zKey[nKey+1];
12173      memcpy(pEntry->zVal, zVal, nVal);
12174    }
12175    pEntry->pHashNext = pHash->aHash[iHash];
12176    pHash->aHash[iHash] = pEntry;
12177
12178    pEntry->pNext = pHash->pFirst;
12179    pHash->pFirst = pEntry;
12180  }
12181  return 0;
12182}
12183
12184/*
12185** If zKey/nKey is present in the hash table, return a pointer to the
12186** hash-entry object.
12187*/
12188static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
12189  int iHash;
12190  IdxHashEntry *pEntry;
12191  if( nKey<0 ) nKey = STRLEN(zKey);
12192  iHash = idxHashString(zKey, nKey);
12193  assert( iHash>=0 );
12194  for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
12195    if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
12196      return pEntry;
12197    }
12198  }
12199  return 0;
12200}
12201
12202/*
12203** If the hash table contains an entry with a key equal to the string
12204** passed as the final two arguments to this function, return a pointer
12205** to the payload string. Otherwise, if zKey/nKey is not present in the
12206** hash table, return NULL.
12207*/
12208static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
12209  IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
12210  if( pEntry ) return pEntry->zVal;
12211  return 0;
12212}
12213
12214/*
12215** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
12216** variable to point to a copy of nul-terminated string zColl.
12217*/
12218static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
12219  IdxConstraint *pNew;
12220  int nColl = STRLEN(zColl);
12221
12222  assert( *pRc==SQLITE_OK );
12223  pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
12224  if( pNew ){
12225    pNew->zColl = (char*)&pNew[1];
12226    memcpy(pNew->zColl, zColl, nColl+1);
12227  }
12228  return pNew;
12229}
12230
12231/*
12232** An error associated with database handle db has just occurred. Pass
12233** the error message to callback function xOut.
12234*/
12235static void idxDatabaseError(
12236  sqlite3 *db,                    /* Database handle */
12237  char **pzErrmsg                 /* Write error here */
12238){
12239  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
12240}
12241
12242/*
12243** Prepare an SQL statement.
12244*/
12245static int idxPrepareStmt(
12246  sqlite3 *db,                    /* Database handle to compile against */
12247  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12248  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12249  const char *zSql                /* SQL statement to compile */
12250){
12251  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12252  if( rc!=SQLITE_OK ){
12253    *ppStmt = 0;
12254    idxDatabaseError(db, pzErrmsg);
12255  }
12256  return rc;
12257}
12258
12259/*
12260** Prepare an SQL statement using the results of a printf() formatting.
12261*/
12262static int idxPrintfPrepareStmt(
12263  sqlite3 *db,                    /* Database handle to compile against */
12264  sqlite3_stmt **ppStmt,          /* OUT: Compiled SQL statement */
12265  char **pzErrmsg,                /* OUT: sqlite3_malloc()ed error message */
12266  const char *zFmt,               /* printf() format of SQL statement */
12267  ...                             /* Trailing printf() arguments */
12268){
12269  va_list ap;
12270  int rc;
12271  char *zSql;
12272  va_start(ap, zFmt);
12273  zSql = sqlite3_vmprintf(zFmt, ap);
12274  if( zSql==0 ){
12275    rc = SQLITE_NOMEM;
12276  }else{
12277    rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
12278    sqlite3_free(zSql);
12279  }
12280  va_end(ap);
12281  return rc;
12282}
12283
12284
12285/*************************************************************************
12286** Beginning of virtual table implementation.
12287*/
12288typedef struct ExpertVtab ExpertVtab;
12289struct ExpertVtab {
12290  sqlite3_vtab base;
12291  IdxTable *pTab;
12292  sqlite3expert *pExpert;
12293};
12294
12295typedef struct ExpertCsr ExpertCsr;
12296struct ExpertCsr {
12297  sqlite3_vtab_cursor base;
12298  sqlite3_stmt *pData;
12299};
12300
12301static char *expertDequote(const char *zIn){
12302  int n = STRLEN(zIn);
12303  char *zRet = sqlite3_malloc(n);
12304
12305  assert( zIn[0]=='\'' );
12306  assert( zIn[n-1]=='\'' );
12307
12308  if( zRet ){
12309    int iOut = 0;
12310    int iIn = 0;
12311    for(iIn=1; iIn<(n-1); iIn++){
12312      if( zIn[iIn]=='\'' ){
12313        assert( zIn[iIn+1]=='\'' );
12314        iIn++;
12315      }
12316      zRet[iOut++] = zIn[iIn];
12317    }
12318    zRet[iOut] = '\0';
12319  }
12320
12321  return zRet;
12322}
12323
12324/*
12325** This function is the implementation of both the xConnect and xCreate
12326** methods of the r-tree virtual table.
12327**
12328**   argv[0]   -> module name
12329**   argv[1]   -> database name
12330**   argv[2]   -> table name
12331**   argv[...] -> column names...
12332*/
12333static int expertConnect(
12334  sqlite3 *db,
12335  void *pAux,
12336  int argc, const char *const*argv,
12337  sqlite3_vtab **ppVtab,
12338  char **pzErr
12339){
12340  sqlite3expert *pExpert = (sqlite3expert*)pAux;
12341  ExpertVtab *p = 0;
12342  int rc;
12343
12344  if( argc!=4 ){
12345    *pzErr = sqlite3_mprintf("internal error!");
12346    rc = SQLITE_ERROR;
12347  }else{
12348    char *zCreateTable = expertDequote(argv[3]);
12349    if( zCreateTable ){
12350      rc = sqlite3_declare_vtab(db, zCreateTable);
12351      if( rc==SQLITE_OK ){
12352        p = idxMalloc(&rc, sizeof(ExpertVtab));
12353      }
12354      if( rc==SQLITE_OK ){
12355        p->pExpert = pExpert;
12356        p->pTab = pExpert->pTable;
12357        assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
12358      }
12359      sqlite3_free(zCreateTable);
12360    }else{
12361      rc = SQLITE_NOMEM;
12362    }
12363  }
12364
12365  *ppVtab = (sqlite3_vtab*)p;
12366  return rc;
12367}
12368
12369static int expertDisconnect(sqlite3_vtab *pVtab){
12370  ExpertVtab *p = (ExpertVtab*)pVtab;
12371  sqlite3_free(p);
12372  return SQLITE_OK;
12373}
12374
12375static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
12376  ExpertVtab *p = (ExpertVtab*)pVtab;
12377  int rc = SQLITE_OK;
12378  int n = 0;
12379  IdxScan *pScan;
12380  const int opmask =
12381    SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
12382    SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
12383    SQLITE_INDEX_CONSTRAINT_LE;
12384
12385  pScan = idxMalloc(&rc, sizeof(IdxScan));
12386  if( pScan ){
12387    int i;
12388
12389    /* Link the new scan object into the list */
12390    pScan->pTab = p->pTab;
12391    pScan->pNextScan = p->pExpert->pScan;
12392    p->pExpert->pScan = pScan;
12393
12394    /* Add the constraints to the IdxScan object */
12395    for(i=0; i<pIdxInfo->nConstraint; i++){
12396      struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
12397      if( pCons->usable
12398       && pCons->iColumn>=0
12399       && p->pTab->aCol[pCons->iColumn].iPk==0
12400       && (pCons->op & opmask)
12401      ){
12402        IdxConstraint *pNew;
12403        const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
12404        pNew = idxNewConstraint(&rc, zColl);
12405        if( pNew ){
12406          pNew->iCol = pCons->iColumn;
12407          if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
12408            pNew->pNext = pScan->pEq;
12409            pScan->pEq = pNew;
12410          }else{
12411            pNew->bRange = 1;
12412            pNew->pNext = pScan->pRange;
12413            pScan->pRange = pNew;
12414          }
12415        }
12416        n++;
12417        pIdxInfo->aConstraintUsage[i].argvIndex = n;
12418      }
12419    }
12420
12421    /* Add the ORDER BY to the IdxScan object */
12422    for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
12423      int iCol = pIdxInfo->aOrderBy[i].iColumn;
12424      if( iCol>=0 ){
12425        IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
12426        if( pNew ){
12427          pNew->iCol = iCol;
12428          pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
12429          pNew->pNext = pScan->pOrder;
12430          pNew->pLink = pScan->pOrder;
12431          pScan->pOrder = pNew;
12432          n++;
12433        }
12434      }
12435    }
12436  }
12437
12438  pIdxInfo->estimatedCost = 1000000.0 / (n+1);
12439  return rc;
12440}
12441
12442static int expertUpdate(
12443  sqlite3_vtab *pVtab,
12444  int nData,
12445  sqlite3_value **azData,
12446  sqlite_int64 *pRowid
12447){
12448  (void)pVtab;
12449  (void)nData;
12450  (void)azData;
12451  (void)pRowid;
12452  return SQLITE_OK;
12453}
12454
12455/*
12456** Virtual table module xOpen method.
12457*/
12458static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
12459  int rc = SQLITE_OK;
12460  ExpertCsr *pCsr;
12461  (void)pVTab;
12462  pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
12463  *ppCursor = (sqlite3_vtab_cursor*)pCsr;
12464  return rc;
12465}
12466
12467/*
12468** Virtual table module xClose method.
12469*/
12470static int expertClose(sqlite3_vtab_cursor *cur){
12471  ExpertCsr *pCsr = (ExpertCsr*)cur;
12472  sqlite3_finalize(pCsr->pData);
12473  sqlite3_free(pCsr);
12474  return SQLITE_OK;
12475}
12476
12477/*
12478** Virtual table module xEof method.
12479**
12480** Return non-zero if the cursor does not currently point to a valid
12481** record (i.e if the scan has finished), or zero otherwise.
12482*/
12483static int expertEof(sqlite3_vtab_cursor *cur){
12484  ExpertCsr *pCsr = (ExpertCsr*)cur;
12485  return pCsr->pData==0;
12486}
12487
12488/*
12489** Virtual table module xNext method.
12490*/
12491static int expertNext(sqlite3_vtab_cursor *cur){
12492  ExpertCsr *pCsr = (ExpertCsr*)cur;
12493  int rc = SQLITE_OK;
12494
12495  assert( pCsr->pData );
12496  rc = sqlite3_step(pCsr->pData);
12497  if( rc!=SQLITE_ROW ){
12498    rc = sqlite3_finalize(pCsr->pData);
12499    pCsr->pData = 0;
12500  }else{
12501    rc = SQLITE_OK;
12502  }
12503
12504  return rc;
12505}
12506
12507/*
12508** Virtual table module xRowid method.
12509*/
12510static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
12511  (void)cur;
12512  *pRowid = 0;
12513  return SQLITE_OK;
12514}
12515
12516/*
12517** Virtual table module xColumn method.
12518*/
12519static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
12520  ExpertCsr *pCsr = (ExpertCsr*)cur;
12521  sqlite3_value *pVal;
12522  pVal = sqlite3_column_value(pCsr->pData, i);
12523  if( pVal ){
12524    sqlite3_result_value(ctx, pVal);
12525  }
12526  return SQLITE_OK;
12527}
12528
12529/*
12530** Virtual table module xFilter method.
12531*/
12532static int expertFilter(
12533  sqlite3_vtab_cursor *cur,
12534  int idxNum, const char *idxStr,
12535  int argc, sqlite3_value **argv
12536){
12537  ExpertCsr *pCsr = (ExpertCsr*)cur;
12538  ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
12539  sqlite3expert *pExpert = pVtab->pExpert;
12540  int rc;
12541
12542  (void)idxNum;
12543  (void)idxStr;
12544  (void)argc;
12545  (void)argv;
12546  rc = sqlite3_finalize(pCsr->pData);
12547  pCsr->pData = 0;
12548  if( rc==SQLITE_OK ){
12549    rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
12550        "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
12551    );
12552  }
12553
12554  if( rc==SQLITE_OK ){
12555    rc = expertNext(cur);
12556  }
12557  return rc;
12558}
12559
12560static int idxRegisterVtab(sqlite3expert *p){
12561  static sqlite3_module expertModule = {
12562    2,                            /* iVersion */
12563    expertConnect,                /* xCreate - create a table */
12564    expertConnect,                /* xConnect - connect to an existing table */
12565    expertBestIndex,              /* xBestIndex - Determine search strategy */
12566    expertDisconnect,             /* xDisconnect - Disconnect from a table */
12567    expertDisconnect,             /* xDestroy - Drop a table */
12568    expertOpen,                   /* xOpen - open a cursor */
12569    expertClose,                  /* xClose - close a cursor */
12570    expertFilter,                 /* xFilter - configure scan constraints */
12571    expertNext,                   /* xNext - advance a cursor */
12572    expertEof,                    /* xEof */
12573    expertColumn,                 /* xColumn - read data */
12574    expertRowid,                  /* xRowid - read data */
12575    expertUpdate,                 /* xUpdate - write data */
12576    0,                            /* xBegin - begin transaction */
12577    0,                            /* xSync - sync transaction */
12578    0,                            /* xCommit - commit transaction */
12579    0,                            /* xRollback - rollback transaction */
12580    0,                            /* xFindFunction - function overloading */
12581    0,                            /* xRename - rename the table */
12582    0,                            /* xSavepoint */
12583    0,                            /* xRelease */
12584    0,                            /* xRollbackTo */
12585    0,                            /* xShadowName */
12586    0,                            /* xIntegrity */
12587  };
12588
12589  return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
12590}
12591/*
12592** End of virtual table implementation.
12593*************************************************************************/
12594/*
12595** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
12596** is called, set it to the return value of sqlite3_finalize() before
12597** returning. Otherwise, discard the sqlite3_finalize() return value.
12598*/
12599static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
12600  int rc = sqlite3_finalize(pStmt);
12601  if( *pRc==SQLITE_OK ) *pRc = rc;
12602}
12603
12604/*
12605** Attempt to allocate an IdxTable structure corresponding to table zTab
12606** in the main database of connection db. If successful, set (*ppOut) to
12607** point to the new object and return SQLITE_OK. Otherwise, return an
12608** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
12609** set to point to an error string.
12610**
12611** It is the responsibility of the caller to eventually free either the
12612** IdxTable object or error message using sqlite3_free().
12613*/
12614static int idxGetTableInfo(
12615  sqlite3 *db,                    /* Database connection to read details from */
12616  const char *zTab,               /* Table name */
12617  IdxTable **ppOut,               /* OUT: New object (if successful) */
12618  char **pzErrmsg                 /* OUT: Error message (if not) */
12619){
12620  sqlite3_stmt *p1 = 0;
12621  int nCol = 0;
12622  int nTab;
12623  int nByte;
12624  IdxTable *pNew = 0;
12625  int rc, rc2;
12626  char *pCsr = 0;
12627  int nPk = 0;
12628
12629  *ppOut = 0;
12630  if( zTab==0 ) return SQLITE_ERROR;
12631  nTab = STRLEN(zTab);
12632  nByte = sizeof(IdxTable) + nTab + 1;
12633  rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
12634  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12635    const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12636    const char *zColSeq = 0;
12637    if( zCol==0 ){
12638      rc = SQLITE_ERROR;
12639      break;
12640    }
12641    nByte += 1 + STRLEN(zCol);
12642    rc = sqlite3_table_column_metadata(
12643        db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12644    );
12645    if( zColSeq==0 ) zColSeq = "binary";
12646    nByte += 1 + STRLEN(zColSeq);
12647    nCol++;
12648    nPk += (sqlite3_column_int(p1, 5)>0);
12649  }
12650  rc2 = sqlite3_reset(p1);
12651  if( rc==SQLITE_OK ) rc = rc2;
12652
12653  nByte += sizeof(IdxColumn) * nCol;
12654  if( rc==SQLITE_OK ){
12655    pNew = idxMalloc(&rc, nByte);
12656  }
12657  if( rc==SQLITE_OK ){
12658    pNew->aCol = (IdxColumn*)&pNew[1];
12659    pNew->nCol = nCol;
12660    pCsr = (char*)&pNew->aCol[nCol];
12661  }
12662
12663  nCol = 0;
12664  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
12665    const char *zCol = (const char*)sqlite3_column_text(p1, 1);
12666    const char *zColSeq = 0;
12667    int nCopy;
12668    if( zCol==0 ) continue;
12669    nCopy = STRLEN(zCol) + 1;
12670    pNew->aCol[nCol].zName = pCsr;
12671    pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
12672    memcpy(pCsr, zCol, nCopy);
12673    pCsr += nCopy;
12674
12675    rc = sqlite3_table_column_metadata(
12676        db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
12677    );
12678    if( rc==SQLITE_OK ){
12679      if( zColSeq==0 ) zColSeq = "binary";
12680      nCopy = STRLEN(zColSeq) + 1;
12681      pNew->aCol[nCol].zColl = pCsr;
12682      memcpy(pCsr, zColSeq, nCopy);
12683      pCsr += nCopy;
12684    }
12685
12686    nCol++;
12687  }
12688  idxFinalize(&rc, p1);
12689
12690  if( rc!=SQLITE_OK ){
12691    sqlite3_free(pNew);
12692    pNew = 0;
12693  }else if( ALWAYS(pNew!=0) ){
12694    pNew->zName = pCsr;
12695    if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
12696  }
12697
12698  *ppOut = pNew;
12699  return rc;
12700}
12701
12702/*
12703** This function is a no-op if *pRc is set to anything other than
12704** SQLITE_OK when it is called.
12705**
12706** If *pRc is initially set to SQLITE_OK, then the text specified by
12707** the printf() style arguments is appended to zIn and the result returned
12708** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
12709** zIn before returning.
12710*/
12711static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
12712  va_list ap;
12713  char *zAppend = 0;
12714  char *zRet = 0;
12715  int nIn = zIn ? STRLEN(zIn) : 0;
12716  int nAppend = 0;
12717  va_start(ap, zFmt);
12718  if( *pRc==SQLITE_OK ){
12719    zAppend = sqlite3_vmprintf(zFmt, ap);
12720    if( zAppend ){
12721      nAppend = STRLEN(zAppend);
12722      zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
12723    }
12724    if( zAppend && zRet ){
12725      if( nIn ) memcpy(zRet, zIn, nIn);
12726      memcpy(&zRet[nIn], zAppend, nAppend+1);
12727    }else{
12728      sqlite3_free(zRet);
12729      zRet = 0;
12730      *pRc = SQLITE_NOMEM;
12731    }
12732    sqlite3_free(zAppend);
12733    sqlite3_free(zIn);
12734  }
12735  va_end(ap);
12736  return zRet;
12737}
12738
12739/*
12740** Return true if zId must be quoted in order to use it as an SQL
12741** identifier, or false otherwise.
12742*/
12743static int idxIdentifierRequiresQuotes(const char *zId){
12744  int i;
12745  int nId = STRLEN(zId);
12746
12747  if( sqlite3_keyword_check(zId, nId) ) return 1;
12748
12749  for(i=0; zId[i]; i++){
12750    if( !(zId[i]=='_')
12751     && !(zId[i]>='0' && zId[i]<='9')
12752     && !(zId[i]>='a' && zId[i]<='z')
12753     && !(zId[i]>='A' && zId[i]<='Z')
12754    ){
12755      return 1;
12756    }
12757  }
12758  return 0;
12759}
12760
12761/*
12762** This function appends an index column definition suitable for constraint
12763** pCons to the string passed as zIn and returns the result.
12764*/
12765static char *idxAppendColDefn(
12766  int *pRc,                       /* IN/OUT: Error code */
12767  char *zIn,                      /* Column defn accumulated so far */
12768  IdxTable *pTab,                 /* Table index will be created on */
12769  IdxConstraint *pCons
12770){
12771  char *zRet = zIn;
12772  IdxColumn *p = &pTab->aCol[pCons->iCol];
12773  if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
12774
12775  if( idxIdentifierRequiresQuotes(p->zName) ){
12776    zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
12777  }else{
12778    zRet = idxAppendText(pRc, zRet, "%s", p->zName);
12779  }
12780
12781  if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
12782    if( idxIdentifierRequiresQuotes(pCons->zColl) ){
12783      zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
12784    }else{
12785      zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
12786    }
12787  }
12788
12789  if( pCons->bDesc ){
12790    zRet = idxAppendText(pRc, zRet, " DESC");
12791  }
12792  return zRet;
12793}
12794
12795/*
12796** Search database dbm for an index compatible with the one idxCreateFromCons()
12797** would create from arguments pScan, pEq and pTail. If no error occurs and
12798** such an index is found, return non-zero. Or, if no such index is found,
12799** return zero.
12800**
12801** If an error occurs, set *pRc to an SQLite error code and return zero.
12802*/
12803static int idxFindCompatible(
12804  int *pRc,                       /* OUT: Error code */
12805  sqlite3* dbm,                   /* Database to search */
12806  IdxScan *pScan,                 /* Scan for table to search for index on */
12807  IdxConstraint *pEq,             /* List of == constraints */
12808  IdxConstraint *pTail            /* List of range constraints */
12809){
12810  const char *zTbl = pScan->pTab->zName;
12811  sqlite3_stmt *pIdxList = 0;
12812  IdxConstraint *pIter;
12813  int nEq = 0;                    /* Number of elements in pEq */
12814  int rc;
12815
12816  /* Count the elements in list pEq */
12817  for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
12818
12819  rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
12820  while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
12821    int bMatch = 1;
12822    IdxConstraint *pT = pTail;
12823    sqlite3_stmt *pInfo = 0;
12824    const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
12825    if( zIdx==0 ) continue;
12826
12827    /* Zero the IdxConstraint.bFlag values in the pEq list */
12828    for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
12829
12830    rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
12831    while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
12832      int iIdx = sqlite3_column_int(pInfo, 0);
12833      int iCol = sqlite3_column_int(pInfo, 1);
12834      const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
12835
12836      if( iIdx<nEq ){
12837        for(pIter=pEq; pIter; pIter=pIter->pLink){
12838          if( pIter->bFlag ) continue;
12839          if( pIter->iCol!=iCol ) continue;
12840          if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
12841          pIter->bFlag = 1;
12842          break;
12843        }
12844        if( pIter==0 ){
12845          bMatch = 0;
12846          break;
12847        }
12848      }else{
12849        if( pT ){
12850          if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
12851            bMatch = 0;
12852            break;
12853          }
12854          pT = pT->pLink;
12855        }
12856      }
12857    }
12858    idxFinalize(&rc, pInfo);
12859
12860    if( rc==SQLITE_OK && bMatch ){
12861      sqlite3_finalize(pIdxList);
12862      return 1;
12863    }
12864  }
12865  idxFinalize(&rc, pIdxList);
12866
12867  *pRc = rc;
12868  return 0;
12869}
12870
12871/* Callback for sqlite3_exec() with query with leading count(*) column.
12872 * The first argument is expected to be an int*, referent to be incremented
12873 * if that leading column is not exactly '0'.
12874 */
12875static int countNonzeros(void* pCount, int nc,
12876                         char* azResults[], char* azColumns[]){
12877  (void)azColumns;  /* Suppress unused parameter warning */
12878  if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
12879    *((int *)pCount) += 1;
12880  }
12881  return 0;
12882}
12883
12884static int idxCreateFromCons(
12885  sqlite3expert *p,
12886  IdxScan *pScan,
12887  IdxConstraint *pEq,
12888  IdxConstraint *pTail
12889){
12890  sqlite3 *dbm = p->dbm;
12891  int rc = SQLITE_OK;
12892  if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
12893    IdxTable *pTab = pScan->pTab;
12894    char *zCols = 0;
12895    char *zIdx = 0;
12896    IdxConstraint *pCons;
12897    unsigned int h = 0;
12898    const char *zFmt;
12899
12900    for(pCons=pEq; pCons; pCons=pCons->pLink){
12901      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12902    }
12903    for(pCons=pTail; pCons; pCons=pCons->pLink){
12904      zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
12905    }
12906
12907    if( rc==SQLITE_OK ){
12908      /* Hash the list of columns to come up with a name for the index */
12909      const char *zTable = pScan->pTab->zName;
12910      int quoteTable = idxIdentifierRequiresQuotes(zTable);
12911      char *zName = 0;          /* Index name */
12912      int collisions = 0;
12913      do{
12914        int i;
12915        char *zFind;
12916        for(i=0; zCols[i]; i++){
12917          h += ((h<<3) + zCols[i]);
12918        }
12919        sqlite3_free(zName);
12920        zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
12921        if( zName==0 ) break;
12922        /* Is is unique among table, view and index names? */
12923        zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
12924          " AND type in ('index','table','view')";
12925        zFind = sqlite3_mprintf(zFmt, zName);
12926        i = 0;
12927        rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
12928        assert(rc==SQLITE_OK);
12929        sqlite3_free(zFind);
12930        if( i==0 ){
12931          collisions = 0;
12932          break;
12933        }
12934        ++collisions;
12935      }while( collisions<50 && zName!=0 );
12936      if( collisions ){
12937        /* This return means "Gave up trying to find a unique index name." */
12938        rc = SQLITE_BUSY_TIMEOUT;
12939      }else if( zName==0 ){
12940        rc = SQLITE_NOMEM;
12941      }else{
12942        if( quoteTable ){
12943          zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
12944        }else{
12945          zFmt = "CREATE INDEX %s ON %s(%s)";
12946        }
12947        zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
12948        if( !zIdx ){
12949          rc = SQLITE_NOMEM;
12950        }else{
12951          rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
12952          if( rc!=SQLITE_OK ){
12953            rc = SQLITE_BUSY_TIMEOUT;
12954          }else{
12955            idxHashAdd(&rc, &p->hIdx, zName, zIdx);
12956          }
12957        }
12958        sqlite3_free(zName);
12959        sqlite3_free(zIdx);
12960      }
12961    }
12962
12963    sqlite3_free(zCols);
12964  }
12965  return rc;
12966}
12967
12968/*
12969** Return true if list pList (linked by IdxConstraint.pLink) contains
12970** a constraint compatible with *p. Otherwise return false.
12971*/
12972static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
12973  IdxConstraint *pCmp;
12974  for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
12975    if( p->iCol==pCmp->iCol ) return 1;
12976  }
12977  return 0;
12978}
12979
12980static int idxCreateFromWhere(
12981  sqlite3expert *p,
12982  IdxScan *pScan,                 /* Create indexes for this scan */
12983  IdxConstraint *pTail            /* range/ORDER BY constraints for inclusion */
12984){
12985  IdxConstraint *p1 = 0;
12986  IdxConstraint *pCon;
12987  int rc;
12988
12989  /* Gather up all the == constraints. */
12990  for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
12991    if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
12992      pCon->pLink = p1;
12993      p1 = pCon;
12994    }
12995  }
12996
12997  /* Create an index using the == constraints collected above. And the
12998  ** range constraint/ORDER BY terms passed in by the caller, if any. */
12999  rc = idxCreateFromCons(p, pScan, p1, pTail);
13000
13001  /* If no range/ORDER BY passed by the caller, create a version of the
13002  ** index for each range constraint.  */
13003  if( pTail==0 ){
13004    for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
13005      assert( pCon->pLink==0 );
13006      if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
13007        rc = idxCreateFromCons(p, pScan, p1, pCon);
13008      }
13009    }
13010  }
13011
13012  return rc;
13013}
13014
13015/*
13016** Create candidate indexes in database [dbm] based on the data in
13017** linked-list pScan.
13018*/
13019static int idxCreateCandidates(sqlite3expert *p){
13020  int rc = SQLITE_OK;
13021  IdxScan *pIter;
13022
13023  for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
13024    rc = idxCreateFromWhere(p, pIter, 0);
13025    if( rc==SQLITE_OK && pIter->pOrder ){
13026      rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
13027    }
13028  }
13029
13030  return rc;
13031}
13032
13033/*
13034** Free all elements of the linked list starting at pConstraint.
13035*/
13036static void idxConstraintFree(IdxConstraint *pConstraint){
13037  IdxConstraint *pNext;
13038  IdxConstraint *p;
13039
13040  for(p=pConstraint; p; p=pNext){
13041    pNext = p->pNext;
13042    sqlite3_free(p);
13043  }
13044}
13045
13046/*
13047** Free all elements of the linked list starting from pScan up until pLast
13048** (pLast is not freed).
13049*/
13050static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
13051  IdxScan *p;
13052  IdxScan *pNext;
13053  for(p=pScan; p!=pLast; p=pNext){
13054    pNext = p->pNextScan;
13055    idxConstraintFree(p->pOrder);
13056    idxConstraintFree(p->pEq);
13057    idxConstraintFree(p->pRange);
13058    sqlite3_free(p);
13059  }
13060}
13061
13062/*
13063** Free all elements of the linked list starting from pStatement up
13064** until pLast (pLast is not freed).
13065*/
13066static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
13067  IdxStatement *p;
13068  IdxStatement *pNext;
13069  for(p=pStatement; p!=pLast; p=pNext){
13070    pNext = p->pNext;
13071    sqlite3_free(p->zEQP);
13072    sqlite3_free(p->zIdx);
13073    sqlite3_free(p);
13074  }
13075}
13076
13077/*
13078** Free the linked list of IdxTable objects starting at pTab.
13079*/
13080static void idxTableFree(IdxTable *pTab){
13081  IdxTable *pIter;
13082  IdxTable *pNext;
13083  for(pIter=pTab; pIter; pIter=pNext){
13084    pNext = pIter->pNext;
13085    sqlite3_free(pIter);
13086  }
13087}
13088
13089/*
13090** Free the linked list of IdxWrite objects starting at pTab.
13091*/
13092static void idxWriteFree(IdxWrite *pTab){
13093  IdxWrite *pIter;
13094  IdxWrite *pNext;
13095  for(pIter=pTab; pIter; pIter=pNext){
13096    pNext = pIter->pNext;
13097    sqlite3_free(pIter);
13098  }
13099}
13100
13101
13102
13103/*
13104** This function is called after candidate indexes have been created. It
13105** runs all the queries to see which indexes they prefer, and populates
13106** IdxStatement.zIdx and IdxStatement.zEQP with the results.
13107*/
13108static int idxFindIndexes(
13109  sqlite3expert *p,
13110  char **pzErr                         /* OUT: Error message (sqlite3_malloc) */
13111){
13112  IdxStatement *pStmt;
13113  sqlite3 *dbm = p->dbm;
13114  int rc = SQLITE_OK;
13115
13116  IdxHash hIdx;
13117  idxHashInit(&hIdx);
13118
13119  for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
13120    IdxHashEntry *pEntry;
13121    sqlite3_stmt *pExplain = 0;
13122    idxHashClear(&hIdx);
13123    rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
13124        "EXPLAIN QUERY PLAN %s", pStmt->zSql
13125    );
13126    while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
13127      /* int iId = sqlite3_column_int(pExplain, 0); */
13128      /* int iParent = sqlite3_column_int(pExplain, 1); */
13129      /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
13130      const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
13131      int nDetail;
13132      int i;
13133
13134      if( !zDetail ) continue;
13135      nDetail = STRLEN(zDetail);
13136
13137      for(i=0; i<nDetail; i++){
13138        const char *zIdx = 0;
13139        if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
13140          zIdx = &zDetail[i+13];
13141        }else if( i+22<nDetail
13142            && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
13143        ){
13144          zIdx = &zDetail[i+22];
13145        }
13146        if( zIdx ){
13147          const char *zSql;
13148          int nIdx = 0;
13149          while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
13150            nIdx++;
13151          }
13152          zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
13153          if( zSql ){
13154            idxHashAdd(&rc, &hIdx, zSql, 0);
13155            if( rc ) goto find_indexes_out;
13156          }
13157          break;
13158        }
13159      }
13160
13161      if( zDetail[0]!='-' ){
13162        pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
13163      }
13164    }
13165
13166    for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13167      pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
13168    }
13169
13170    idxFinalize(&rc, pExplain);
13171  }
13172
13173 find_indexes_out:
13174  idxHashClear(&hIdx);
13175  return rc;
13176}
13177
13178static int idxAuthCallback(
13179  void *pCtx,
13180  int eOp,
13181  const char *z3,
13182  const char *z4,
13183  const char *zDb,
13184  const char *zTrigger
13185){
13186  int rc = SQLITE_OK;
13187  (void)z4;
13188  (void)zTrigger;
13189  if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
13190    if( sqlite3_stricmp(zDb, "main")==0 ){
13191      sqlite3expert *p = (sqlite3expert*)pCtx;
13192      IdxTable *pTab;
13193      for(pTab=p->pTable; pTab; pTab=pTab->pNext){
13194        if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
13195      }
13196      if( pTab ){
13197        IdxWrite *pWrite;
13198        for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
13199          if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
13200        }
13201        if( pWrite==0 ){
13202          pWrite = idxMalloc(&rc, sizeof(IdxWrite));
13203          if( rc==SQLITE_OK ){
13204            pWrite->pTab = pTab;
13205            pWrite->eOp = eOp;
13206            pWrite->pNext = p->pWrite;
13207            p->pWrite = pWrite;
13208          }
13209        }
13210      }
13211    }
13212  }
13213  return rc;
13214}
13215
13216static int idxProcessOneTrigger(
13217  sqlite3expert *p,
13218  IdxWrite *pWrite,
13219  char **pzErr
13220){
13221  static const char *zInt = UNIQUE_TABLE_NAME;
13222  static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
13223  IdxTable *pTab = pWrite->pTab;
13224  const char *zTab = pTab->zName;
13225  const char *zSql =
13226    "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
13227    "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
13228    "ORDER BY type;";
13229  sqlite3_stmt *pSelect = 0;
13230  int rc = SQLITE_OK;
13231  char *zWrite = 0;
13232
13233  /* Create the table and its triggers in the temp schema */
13234  rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
13235  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
13236    const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
13237    if( zCreate==0 ) continue;
13238    rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
13239  }
13240  idxFinalize(&rc, pSelect);
13241
13242  /* Rename the table in the temp schema to zInt */
13243  if( rc==SQLITE_OK ){
13244    char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
13245    if( z==0 ){
13246      rc = SQLITE_NOMEM;
13247    }else{
13248      rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
13249      sqlite3_free(z);
13250    }
13251  }
13252
13253  switch( pWrite->eOp ){
13254    case SQLITE_INSERT: {
13255      int i;
13256      zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
13257      for(i=0; i<pTab->nCol; i++){
13258        zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
13259      }
13260      zWrite = idxAppendText(&rc, zWrite, ")");
13261      break;
13262    }
13263    case SQLITE_UPDATE: {
13264      int i;
13265      zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
13266      for(i=0; i<pTab->nCol; i++){
13267        zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
13268            pTab->aCol[i].zName
13269        );
13270      }
13271      break;
13272    }
13273    default: {
13274      assert( pWrite->eOp==SQLITE_DELETE );
13275      if( rc==SQLITE_OK ){
13276        zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
13277        if( zWrite==0 ) rc = SQLITE_NOMEM;
13278      }
13279    }
13280  }
13281
13282  if( rc==SQLITE_OK ){
13283    sqlite3_stmt *pX = 0;
13284    rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
13285    idxFinalize(&rc, pX);
13286    if( rc!=SQLITE_OK ){
13287      idxDatabaseError(p->dbv, pzErr);
13288    }
13289  }
13290  sqlite3_free(zWrite);
13291
13292  if( rc==SQLITE_OK ){
13293    rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
13294  }
13295
13296  return rc;
13297}
13298
13299static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
13300  int rc = SQLITE_OK;
13301  IdxWrite *pEnd = 0;
13302  IdxWrite *pFirst = p->pWrite;
13303
13304  while( rc==SQLITE_OK && pFirst!=pEnd ){
13305    IdxWrite *pIter;
13306    for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
13307      rc = idxProcessOneTrigger(p, pIter, pzErr);
13308    }
13309    pEnd = pFirst;
13310    pFirst = p->pWrite;
13311  }
13312
13313  return rc;
13314}
13315
13316
13317static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
13318  int rc = idxRegisterVtab(p);
13319  sqlite3_stmt *pSchema = 0;
13320
13321  /* For each table in the main db schema:
13322  **
13323  **   1) Add an entry to the p->pTable list, and
13324  **   2) Create the equivalent virtual table in dbv.
13325  */
13326  rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
13327      "SELECT type, name, sql, 1 FROM sqlite_schema "
13328      "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
13329      " UNION ALL "
13330      "SELECT type, name, sql, 2 FROM sqlite_schema "
13331      "WHERE type = 'trigger'"
13332      "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
13333      "ORDER BY 4, 1"
13334  );
13335  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
13336    const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
13337    const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
13338    const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
13339
13340    if( zType==0 || zName==0 ) continue;
13341    if( zType[0]=='v' || zType[1]=='r' ){
13342      if( zSql ) rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
13343    }else{
13344      IdxTable *pTab;
13345      rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
13346      if( rc==SQLITE_OK ){
13347        int i;
13348        char *zInner = 0;
13349        char *zOuter = 0;
13350        pTab->pNext = p->pTable;
13351        p->pTable = pTab;
13352
13353        /* The statement the vtab will pass to sqlite3_declare_vtab() */
13354        zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
13355        for(i=0; i<pTab->nCol; i++){
13356          zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
13357              (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
13358          );
13359        }
13360        zInner = idxAppendText(&rc, zInner, ")");
13361
13362        /* The CVT statement to create the vtab */
13363        zOuter = idxAppendText(&rc, 0,
13364            "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
13365        );
13366        if( rc==SQLITE_OK ){
13367          rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
13368        }
13369        sqlite3_free(zInner);
13370        sqlite3_free(zOuter);
13371      }
13372    }
13373  }
13374  idxFinalize(&rc, pSchema);
13375  return rc;
13376}
13377
13378struct IdxSampleCtx {
13379  int iTarget;
13380  double target;                  /* Target nRet/nRow value */
13381  double nRow;                    /* Number of rows seen */
13382  double nRet;                    /* Number of rows returned */
13383};
13384
13385static void idxSampleFunc(
13386  sqlite3_context *pCtx,
13387  int argc,
13388  sqlite3_value **argv
13389){
13390  struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
13391  int bRet;
13392
13393  (void)argv;
13394  assert( argc==0 );
13395  if( p->nRow==0.0 ){
13396    bRet = 1;
13397  }else{
13398    bRet = (p->nRet / p->nRow) <= p->target;
13399    if( bRet==0 ){
13400      unsigned short rnd;
13401      sqlite3_randomness(2, (void*)&rnd);
13402      bRet = ((int)rnd % 100) <= p->iTarget;
13403    }
13404  }
13405
13406  sqlite3_result_int(pCtx, bRet);
13407  p->nRow += 1.0;
13408  p->nRet += (double)bRet;
13409}
13410
13411struct IdxRemCtx {
13412  int nSlot;
13413  struct IdxRemSlot {
13414    int eType;                    /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
13415    i64 iVal;                     /* SQLITE_INTEGER value */
13416    double rVal;                  /* SQLITE_FLOAT value */
13417    int nByte;                    /* Bytes of space allocated at z */
13418    int n;                        /* Size of buffer z */
13419    char *z;                      /* SQLITE_TEXT/BLOB value */
13420  } aSlot[1];
13421};
13422
13423/*
13424** Implementation of scalar function rem().
13425*/
13426static void idxRemFunc(
13427  sqlite3_context *pCtx,
13428  int argc,
13429  sqlite3_value **argv
13430){
13431  struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
13432  struct IdxRemSlot *pSlot;
13433  int iSlot;
13434  assert( argc==2 );
13435
13436  iSlot = sqlite3_value_int(argv[0]);
13437  assert( iSlot<=p->nSlot );
13438  pSlot = &p->aSlot[iSlot];
13439
13440  switch( pSlot->eType ){
13441    case SQLITE_NULL:
13442      /* no-op */
13443      break;
13444
13445    case SQLITE_INTEGER:
13446      sqlite3_result_int64(pCtx, pSlot->iVal);
13447      break;
13448
13449    case SQLITE_FLOAT:
13450      sqlite3_result_double(pCtx, pSlot->rVal);
13451      break;
13452
13453    case SQLITE_BLOB:
13454      sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13455      break;
13456
13457    case SQLITE_TEXT:
13458      sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
13459      break;
13460  }
13461
13462  pSlot->eType = sqlite3_value_type(argv[1]);
13463  switch( pSlot->eType ){
13464    case SQLITE_NULL:
13465      /* no-op */
13466      break;
13467
13468    case SQLITE_INTEGER:
13469      pSlot->iVal = sqlite3_value_int64(argv[1]);
13470      break;
13471
13472    case SQLITE_FLOAT:
13473      pSlot->rVal = sqlite3_value_double(argv[1]);
13474      break;
13475
13476    case SQLITE_BLOB:
13477    case SQLITE_TEXT: {
13478      int nByte = sqlite3_value_bytes(argv[1]);
13479      const void *pData = 0;
13480      if( nByte>pSlot->nByte ){
13481        char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
13482        if( zNew==0 ){
13483          sqlite3_result_error_nomem(pCtx);
13484          return;
13485        }
13486        pSlot->nByte = nByte*2;
13487        pSlot->z = zNew;
13488      }
13489      pSlot->n = nByte;
13490      if( pSlot->eType==SQLITE_BLOB ){
13491        pData = sqlite3_value_blob(argv[1]);
13492        if( pData ) memcpy(pSlot->z, pData, nByte);
13493      }else{
13494        pData = sqlite3_value_text(argv[1]);
13495        memcpy(pSlot->z, pData, nByte);
13496      }
13497      break;
13498    }
13499  }
13500}
13501
13502static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
13503  int rc = SQLITE_OK;
13504  const char *zMax =
13505    "SELECT max(i.seqno) FROM "
13506    "  sqlite_schema AS s, "
13507    "  pragma_index_list(s.name) AS l, "
13508    "  pragma_index_info(l.name) AS i "
13509    "WHERE s.type = 'table'";
13510  sqlite3_stmt *pMax = 0;
13511
13512  *pnMax = 0;
13513  rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
13514  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
13515    *pnMax = sqlite3_column_int(pMax, 0) + 1;
13516  }
13517  idxFinalize(&rc, pMax);
13518
13519  return rc;
13520}
13521
13522static int idxPopulateOneStat1(
13523  sqlite3expert *p,
13524  sqlite3_stmt *pIndexXInfo,
13525  sqlite3_stmt *pWriteStat,
13526  const char *zTab,
13527  const char *zIdx,
13528  char **pzErr
13529){
13530  char *zCols = 0;
13531  char *zOrder = 0;
13532  char *zQuery = 0;
13533  int nCol = 0;
13534  int i;
13535  sqlite3_stmt *pQuery = 0;
13536  int *aStat = 0;
13537  int rc = SQLITE_OK;
13538
13539  assert( p->iSample>0 );
13540
13541  /* Formulate the query text */
13542  sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
13543  while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
13544    const char *zComma = zCols==0 ? "" : ", ";
13545    const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
13546    const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
13547    zCols = idxAppendText(&rc, zCols,
13548        "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
13549    );
13550    zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
13551  }
13552  sqlite3_reset(pIndexXInfo);
13553  if( rc==SQLITE_OK ){
13554    if( p->iSample==100 ){
13555      zQuery = sqlite3_mprintf(
13556          "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
13557      );
13558    }else{
13559      zQuery = sqlite3_mprintf(
13560          "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
13561      );
13562    }
13563  }
13564  sqlite3_free(zCols);
13565  sqlite3_free(zOrder);
13566
13567  /* Formulate the query text */
13568  if( rc==SQLITE_OK ){
13569    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13570    rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
13571  }
13572  sqlite3_free(zQuery);
13573
13574  if( rc==SQLITE_OK ){
13575    aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
13576  }
13577  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13578    IdxHashEntry *pEntry;
13579    char *zStat = 0;
13580    for(i=0; i<=nCol; i++) aStat[i] = 1;
13581    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
13582      aStat[0]++;
13583      for(i=0; i<nCol; i++){
13584        if( sqlite3_column_int(pQuery, i)==0 ) break;
13585      }
13586      for(/*no-op*/; i<nCol; i++){
13587        aStat[i+1]++;
13588      }
13589    }
13590
13591    if( rc==SQLITE_OK ){
13592      int s0 = aStat[0];
13593      zStat = sqlite3_mprintf("%d", s0);
13594      if( zStat==0 ) rc = SQLITE_NOMEM;
13595      for(i=1; rc==SQLITE_OK && i<=nCol; i++){
13596        zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
13597      }
13598    }
13599
13600    if( rc==SQLITE_OK ){
13601      sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
13602      sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
13603      sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
13604      sqlite3_step(pWriteStat);
13605      rc = sqlite3_reset(pWriteStat);
13606    }
13607
13608    pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
13609    if( pEntry ){
13610      assert( pEntry->zVal2==0 );
13611      pEntry->zVal2 = zStat;
13612    }else{
13613      sqlite3_free(zStat);
13614    }
13615  }
13616  sqlite3_free(aStat);
13617  idxFinalize(&rc, pQuery);
13618
13619  return rc;
13620}
13621
13622static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
13623  int rc;
13624  char *zSql;
13625
13626  rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13627  if( rc!=SQLITE_OK ) return rc;
13628
13629  zSql = sqlite3_mprintf(
13630      "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
13631  );
13632  if( zSql==0 ) return SQLITE_NOMEM;
13633  rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
13634  sqlite3_free(zSql);
13635
13636  return rc;
13637}
13638
13639/*
13640** This function is called as part of sqlite3_expert_analyze(). Candidate
13641** indexes have already been created in database sqlite3expert.dbm, this
13642** function populates sqlite_stat1 table in the same database.
13643**
13644** The stat1 data is generated by querying the
13645*/
13646static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
13647  int rc = SQLITE_OK;
13648  int nMax =0;
13649  struct IdxRemCtx *pCtx = 0;
13650  struct IdxSampleCtx samplectx;
13651  int i;
13652  i64 iPrev = -100000;
13653  sqlite3_stmt *pAllIndex = 0;
13654  sqlite3_stmt *pIndexXInfo = 0;
13655  sqlite3_stmt *pWrite = 0;
13656
13657  const char *zAllIndex =
13658    "SELECT s.rowid, s.name, l.name FROM "
13659    "  sqlite_schema AS s, "
13660    "  pragma_index_list(s.name) AS l "
13661    "WHERE s.type = 'table'";
13662  const char *zIndexXInfo =
13663    "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
13664  const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
13665
13666  /* If iSample==0, no sqlite_stat1 data is required. */
13667  if( p->iSample==0 ) return SQLITE_OK;
13668
13669  rc = idxLargestIndex(p->dbm, &nMax, pzErr);
13670  if( nMax<=0 || rc!=SQLITE_OK ) return rc;
13671
13672  rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
13673
13674  if( rc==SQLITE_OK ){
13675    int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
13676    pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
13677  }
13678
13679  if( rc==SQLITE_OK ){
13680    sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
13681    rc = sqlite3_create_function(
13682        dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
13683    );
13684  }
13685  if( rc==SQLITE_OK ){
13686    rc = sqlite3_create_function(
13687        p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
13688    );
13689  }
13690
13691  if( rc==SQLITE_OK ){
13692    pCtx->nSlot = nMax+1;
13693    rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
13694  }
13695  if( rc==SQLITE_OK ){
13696    rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
13697  }
13698  if( rc==SQLITE_OK ){
13699    rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
13700  }
13701
13702  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
13703    i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
13704    const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
13705    const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
13706    if( zTab==0 || zIdx==0 ) continue;
13707    if( p->iSample<100 && iPrev!=iRowid ){
13708      samplectx.target = (double)p->iSample / 100.0;
13709      samplectx.iTarget = p->iSample;
13710      samplectx.nRow = 0.0;
13711      samplectx.nRet = 0.0;
13712      rc = idxBuildSampleTable(p, zTab);
13713      if( rc!=SQLITE_OK ) break;
13714    }
13715    rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
13716    iPrev = iRowid;
13717  }
13718  if( rc==SQLITE_OK && p->iSample<100 ){
13719    rc = sqlite3_exec(p->dbv,
13720        "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
13721    );
13722  }
13723
13724  idxFinalize(&rc, pAllIndex);
13725  idxFinalize(&rc, pIndexXInfo);
13726  idxFinalize(&rc, pWrite);
13727
13728  if( pCtx ){
13729    for(i=0; i<pCtx->nSlot; i++){
13730      sqlite3_free(pCtx->aSlot[i].z);
13731    }
13732    sqlite3_free(pCtx);
13733  }
13734
13735  if( rc==SQLITE_OK ){
13736    rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
13737  }
13738
13739  sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
13740  return rc;
13741}
13742
13743/*
13744** Define and possibly pretend to use a useless collation sequence.
13745** This pretense allows expert to accept SQL using custom collations.
13746*/
13747int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
13748  (void)up1;
13749  (void)up2;
13750  (void)up3;
13751  (void)up4;
13752  (void)up5;
13753  assert(0); /* VDBE should never be run. */
13754  return 0;
13755}
13756/* And a callback to register above upon actual need */
13757void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
13758  (void)up1;
13759  sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
13760}
13761
13762#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13763  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13764/*
13765** dummy functions for no-op implementation of UDFs during expert's work
13766*/
13767void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
13768  (void)up1;
13769  (void)up2;
13770  (void)up3;
13771  assert(0); /* VDBE should never be run. */
13772}
13773void dummyUDFvalue(sqlite3_context *up1){
13774  (void)up1;
13775  assert(0); /* VDBE should never be run. */
13776}
13777
13778/*
13779** Register UDFs from user database with another.
13780*/
13781int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
13782  sqlite3_stmt *pStmt;
13783  int rc = sqlite3_prepare_v2(dbSrc,
13784            "SELECT name,type,enc,narg,flags "
13785            "FROM pragma_function_list() "
13786            "WHERE builtin==0", -1, &pStmt, 0);
13787  if( rc==SQLITE_OK ){
13788    while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
13789      int nargs = sqlite3_column_int(pStmt,3);
13790      int flags = sqlite3_column_int(pStmt,4);
13791      const char *name = (char*)sqlite3_column_text(pStmt,0);
13792      const char *type = (char*)sqlite3_column_text(pStmt,1);
13793      const char *enc = (char*)sqlite3_column_text(pStmt,2);
13794      if( name==0 || type==0 || enc==0 ){
13795        /* no-op.  Only happens on OOM */
13796      }else{
13797        int ienc = SQLITE_UTF8;
13798        int rcf = SQLITE_ERROR;
13799        if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
13800        else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
13801        ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
13802        if( strcmp(type,"w")==0 ){
13803          rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
13804                                               dummyUDF,dummyUDFvalue,0,0,0);
13805        }else if( strcmp(type,"a")==0 ){
13806          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13807                                        0,dummyUDF,dummyUDFvalue);
13808        }else if( strcmp(type,"s")==0 ){
13809          rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
13810                                        dummyUDF,0,0);
13811        }
13812        if( rcf!=SQLITE_OK ){
13813          rc = rcf;
13814          break;
13815        }
13816      }
13817    }
13818    sqlite3_finalize(pStmt);
13819    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
13820  }
13821  return rc;
13822}
13823#endif
13824
13825/*
13826** Allocate a new sqlite3expert object.
13827*/
13828sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
13829  int rc = SQLITE_OK;
13830  sqlite3expert *pNew;
13831
13832  pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
13833
13834  /* Open two in-memory databases to work with. The "vtab database" (dbv)
13835  ** will contain a virtual table corresponding to each real table in
13836  ** the user database schema, and a copy of each view. It is used to
13837  ** collect information regarding the WHERE, ORDER BY and other clauses
13838  ** of the user's query.
13839  */
13840  if( rc==SQLITE_OK ){
13841    pNew->db = db;
13842    pNew->iSample = 100;
13843    rc = sqlite3_open(":memory:", &pNew->dbv);
13844  }
13845  if( rc==SQLITE_OK ){
13846    rc = sqlite3_open(":memory:", &pNew->dbm);
13847    if( rc==SQLITE_OK ){
13848      sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
13849    }
13850  }
13851
13852  /* Allow custom collations to be dealt with through prepare. */
13853  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
13854  if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
13855
13856#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
13857  && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
13858  /* Register UDFs from database [db] with [dbm] and [dbv]. */
13859  if( rc==SQLITE_OK ){
13860    rc = registerUDFs(pNew->db, pNew->dbm);
13861  }
13862  if( rc==SQLITE_OK ){
13863    rc = registerUDFs(pNew->db, pNew->dbv);
13864  }
13865#endif
13866
13867  /* Copy the entire schema of database [db] into [dbm]. */
13868  if( rc==SQLITE_OK ){
13869    sqlite3_stmt *pSql = 0;
13870    rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
13871        "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
13872        " AND sql NOT LIKE 'CREATE VIRTUAL %%' ORDER BY rowid"
13873    );
13874    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
13875      const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
13876      if( zSql ) rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
13877    }
13878    idxFinalize(&rc, pSql);
13879  }
13880
13881  /* Create the vtab schema */
13882  if( rc==SQLITE_OK ){
13883    rc = idxCreateVtabSchema(pNew, pzErrmsg);
13884  }
13885
13886  /* Register the auth callback with dbv */
13887  if( rc==SQLITE_OK ){
13888    sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
13889  }
13890
13891  /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
13892  ** return the new sqlite3expert handle.  */
13893  if( rc!=SQLITE_OK ){
13894    sqlite3_expert_destroy(pNew);
13895    pNew = 0;
13896  }
13897  return pNew;
13898}
13899
13900/*
13901** Configure an sqlite3expert object.
13902*/
13903int sqlite3_expert_config(sqlite3expert *p, int op, ...){
13904  int rc = SQLITE_OK;
13905  va_list ap;
13906  va_start(ap, op);
13907  switch( op ){
13908    case EXPERT_CONFIG_SAMPLE: {
13909      int iVal = va_arg(ap, int);
13910      if( iVal<0 ) iVal = 0;
13911      if( iVal>100 ) iVal = 100;
13912      p->iSample = iVal;
13913      break;
13914    }
13915    default:
13916      rc = SQLITE_NOTFOUND;
13917      break;
13918  }
13919
13920  va_end(ap);
13921  return rc;
13922}
13923
13924/*
13925** Add an SQL statement to the analysis.
13926*/
13927int sqlite3_expert_sql(
13928  sqlite3expert *p,               /* From sqlite3_expert_new() */
13929  const char *zSql,               /* SQL statement to add */
13930  char **pzErr                    /* OUT: Error message (if any) */
13931){
13932  IdxScan *pScanOrig = p->pScan;
13933  IdxStatement *pStmtOrig = p->pStatement;
13934  int rc = SQLITE_OK;
13935  const char *zStmt = zSql;
13936
13937  if( p->bRun ) return SQLITE_MISUSE;
13938
13939  while( rc==SQLITE_OK && zStmt && zStmt[0] ){
13940    sqlite3_stmt *pStmt = 0;
13941    /* Ensure that the provided statement compiles against user's DB. */
13942    rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
13943    if( rc!=SQLITE_OK ) break;
13944    sqlite3_finalize(pStmt);
13945    rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
13946    if( rc==SQLITE_OK ){
13947      if( pStmt ){
13948        IdxStatement *pNew;
13949        const char *z = sqlite3_sql(pStmt);
13950        int n = STRLEN(z);
13951        pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
13952        if( rc==SQLITE_OK ){
13953          pNew->zSql = (char*)&pNew[1];
13954          memcpy(pNew->zSql, z, n+1);
13955          pNew->pNext = p->pStatement;
13956          if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
13957          p->pStatement = pNew;
13958        }
13959        sqlite3_finalize(pStmt);
13960      }
13961    }else{
13962      idxDatabaseError(p->dbv, pzErr);
13963    }
13964  }
13965
13966  if( rc!=SQLITE_OK ){
13967    idxScanFree(p->pScan, pScanOrig);
13968    idxStatementFree(p->pStatement, pStmtOrig);
13969    p->pScan = pScanOrig;
13970    p->pStatement = pStmtOrig;
13971  }
13972
13973  return rc;
13974}
13975
13976int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
13977  int rc;
13978  IdxHashEntry *pEntry;
13979
13980  /* Do trigger processing to collect any extra IdxScan structures */
13981  rc = idxProcessTriggers(p, pzErr);
13982
13983  /* Create candidate indexes within the in-memory database file */
13984  if( rc==SQLITE_OK ){
13985    rc = idxCreateCandidates(p);
13986  }else if ( rc==SQLITE_BUSY_TIMEOUT ){
13987    if( pzErr )
13988      *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
13989    return rc;
13990  }
13991
13992  /* Generate the stat1 data */
13993  if( rc==SQLITE_OK ){
13994    rc = idxPopulateStat1(p, pzErr);
13995  }
13996
13997  /* Formulate the EXPERT_REPORT_CANDIDATES text */
13998  for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
13999    p->zCandidates = idxAppendText(&rc, p->zCandidates,
14000        "%s;%s%s\n", pEntry->zVal,
14001        pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
14002    );
14003  }
14004
14005  /* Figure out which of the candidate indexes are preferred by the query
14006  ** planner and report the results to the user.  */
14007  if( rc==SQLITE_OK ){
14008    rc = idxFindIndexes(p, pzErr);
14009  }
14010
14011  if( rc==SQLITE_OK ){
14012    p->bRun = 1;
14013  }
14014  return rc;
14015}
14016
14017/*
14018** Return the total number of statements that have been added to this
14019** sqlite3expert using sqlite3_expert_sql().
14020*/
14021int sqlite3_expert_count(sqlite3expert *p){
14022  int nRet = 0;
14023  if( p->pStatement ) nRet = p->pStatement->iId+1;
14024  return nRet;
14025}
14026
14027/*
14028** Return a component of the report.
14029*/
14030const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
14031  const char *zRet = 0;
14032  IdxStatement *pStmt;
14033
14034  if( p->bRun==0 ) return 0;
14035  for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
14036  switch( eReport ){
14037    case EXPERT_REPORT_SQL:
14038      if( pStmt ) zRet = pStmt->zSql;
14039      break;
14040    case EXPERT_REPORT_INDEXES:
14041      if( pStmt ) zRet = pStmt->zIdx;
14042      break;
14043    case EXPERT_REPORT_PLAN:
14044      if( pStmt ) zRet = pStmt->zEQP;
14045      break;
14046    case EXPERT_REPORT_CANDIDATES:
14047      zRet = p->zCandidates;
14048      break;
14049  }
14050  return zRet;
14051}
14052
14053/*
14054** Free an sqlite3expert object.
14055*/
14056void sqlite3_expert_destroy(sqlite3expert *p){
14057  if( p ){
14058    sqlite3_close(p->dbm);
14059    sqlite3_close(p->dbv);
14060    idxScanFree(p->pScan, 0);
14061    idxStatementFree(p->pStatement, 0);
14062    idxTableFree(p->pTable);
14063    idxWriteFree(p->pWrite);
14064    idxHashClear(&p->hIdx);
14065    sqlite3_free(p->zCandidates);
14066    sqlite3_free(p);
14067  }
14068}
14069
14070#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
14071
14072/************************* End ../ext/expert/sqlite3expert.c ********************/
14073
14074/************************* Begin ../ext/intck/sqlite3intck.h ******************/
14075/*
14076** 2024-02-08
14077**
14078** The author disclaims copyright to this source code.  In place of
14079** a legal notice, here is a blessing:
14080**
14081**    May you do good and not evil.
14082**    May you find forgiveness for yourself and forgive others.
14083**    May you share freely, never taking more than you give.
14084**
14085*************************************************************************
14086*/
14087
14088/*
14089** Incremental Integrity-Check Extension
14090** -------------------------------------
14091**
14092** This module contains code to check whether or not an SQLite database
14093** is well-formed or corrupt. This is the same task as performed by SQLite's
14094** built-in "PRAGMA integrity_check" command. This module differs from
14095** "PRAGMA integrity_check" in that:
14096**
14097**   +  It is less thorough - this module does not detect certain types
14098**      of corruption that are detected by the PRAGMA command. However,
14099**      it does detect all kinds of corruption that are likely to cause
14100**      errors in SQLite applications.
14101**
14102**   +  It is slower. Sometimes up to three times slower.
14103**
14104**   +  It allows integrity-check operations to be split into multiple
14105**      transactions, so that the database does not need to be read-locked
14106**      for the duration of the integrity-check.
14107**
14108** One way to use the API to run integrity-check on the "main" database
14109** of handle db is:
14110**
14111**   int rc = SQLITE_OK;
14112**   sqlite3_intck *p = 0;
14113**
14114**   sqlite3_intck_open(db, "main", &p);
14115**   while( SQLITE_OK==sqlite3_intck_step(p) ){
14116**     const char *zMsg = sqlite3_intck_message(p);
14117**     if( zMsg ) printf("corruption: %s\n", zMsg);
14118**   }
14119**   rc = sqlite3_intck_error(p, &zErr);
14120**   if( rc!=SQLITE_OK ){
14121**     printf("error occured (rc=%d), (errmsg=%s)\n", rc, zErr);
14122**   }
14123**   sqlite3_intck_close(p);
14124**
14125** Usually, the sqlite3_intck object opens a read transaction within the
14126** first call to sqlite3_intck_step() and holds it open until the
14127** integrity-check is complete. However, if sqlite3_intck_unlock() is
14128** called, the read transaction is ended and a new read transaction opened
14129** by the subsequent call to sqlite3_intck_step().
14130*/
14131
14132#ifndef _SQLITE_INTCK_H
14133#define _SQLITE_INTCK_H
14134
14135/* #include "sqlite3.h" */
14136
14137#ifdef __cplusplus
14138extern "C" {
14139#endif
14140
14141/*
14142** An ongoing incremental integrity-check operation is represented by an
14143** opaque pointer of the following type.
14144*/
14145typedef struct sqlite3_intck sqlite3_intck;
14146
14147/*
14148** Open a new incremental integrity-check object. If successful, populate
14149** output variable (*ppOut) with the new object handle and return SQLITE_OK.
14150** Or, if an error occurs, set (*ppOut) to NULL and return an SQLite error
14151** code (e.g. SQLITE_NOMEM).
14152**
14153** The integrity-check will be conducted on database zDb (which must be "main",
14154** "temp", or the name of an attached database) of database handle db. Once
14155** this function has been called successfully, the caller should not use
14156** database handle db until the integrity-check object has been destroyed
14157** using sqlite3_intck_close().
14158*/
14159int sqlite3_intck_open(
14160  sqlite3 *db,                    /* Database handle */
14161  const char *zDb,                /* Database name ("main", "temp" etc.) */
14162  sqlite3_intck **ppOut           /* OUT: New sqlite3_intck handle */
14163);
14164
14165/*
14166** Close and release all resources associated with a handle opened by an
14167** earlier call to sqlite3_intck_open(). The results of using an
14168** integrity-check handle after it has been passed to this function are
14169** undefined.
14170*/
14171void sqlite3_intck_close(sqlite3_intck *pCk);
14172
14173/*
14174** Do the next step of the integrity-check operation specified by the handle
14175** passed as the only argument. This function returns SQLITE_DONE if the
14176** integrity-check operation is finished, or an SQLite error code if
14177** an error occurs, or SQLITE_OK if no error occurs but the integrity-check
14178** is not finished. It is not considered an error if database corruption
14179** is encountered.
14180**
14181** Following a successful call to sqlite3_intck_step() (one that returns
14182** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if
14183** corruption was detected in the db.
14184**
14185** If an error occurs and a value other than SQLITE_OK or SQLITE_DONE is
14186** returned, then the integrity-check handle is placed in an error state.
14187** In this state all subsequent calls to sqlite3_intck_step() or
14188** sqlite3_intck_unlock() will immediately return the same error. The
14189** sqlite3_intck_error() method may be used to obtain an English language
14190** error message in this case.
14191*/
14192int sqlite3_intck_step(sqlite3_intck *pCk);
14193
14194/*
14195** If the previous call to sqlite3_intck_step() encountered corruption
14196** within the database, then this function returns a pointer to a buffer
14197** containing a nul-terminated string describing the corruption in
14198** English. If the previous call to sqlite3_intck_step() did not encounter
14199** corruption, or if there was no previous call, this function returns
14200** NULL.
14201*/
14202const char *sqlite3_intck_message(sqlite3_intck *pCk);
14203
14204/*
14205** Close any read-transaction opened by an earlier call to
14206** sqlite3_intck_step(). Any subsequent call to sqlite3_intck_step() will
14207** open a new transaction. Return SQLITE_OK if successful, or an SQLite error
14208** code otherwise.
14209**
14210** If an error occurs, then the integrity-check handle is placed in an error
14211** state. In this state all subsequent calls to sqlite3_intck_step() or
14212** sqlite3_intck_unlock() will immediately return the same error. The
14213** sqlite3_intck_error() method may be used to obtain an English language
14214** error message in this case.
14215*/
14216int sqlite3_intck_unlock(sqlite3_intck *pCk);
14217
14218/*
14219** If an error has occurred in an earlier call to sqlite3_intck_step()
14220** or sqlite3_intck_unlock(), then this method returns the associated
14221** SQLite error code. Additionally, if pzErr is not NULL, then (*pzErr)
14222** may be set to point to a nul-terminated string containing an English
14223** language error message. Or, if no error message is available, to
14224** NULL.
14225**
14226** If no error has occurred within sqlite3_intck_step() or
14227** sqlite_intck_unlock() calls on the handle passed as the first argument,
14228** then SQLITE_OK is returned and (*pzErr) set to NULL.
14229*/
14230int sqlite3_intck_error(sqlite3_intck *pCk, const char **pzErr);
14231
14232/*
14233** This API is used for testing only. It returns the full-text of an SQL
14234** statement used to test object zObj, which may be a table or index.
14235** The returned buffer is valid until the next call to either this function
14236** or sqlite3_intck_close() on the same sqlite3_intck handle.
14237*/
14238const char *sqlite3_intck_test_sql(sqlite3_intck *pCk, const char *zObj);
14239
14240
14241#ifdef __cplusplus
14242}  /* end of the 'extern "C"' block */
14243#endif
14244
14245#endif /* ifndef _SQLITE_INTCK_H */
14246
14247/************************* End ../ext/intck/sqlite3intck.h ********************/
14248/************************* Begin ../ext/intck/sqlite3intck.c ******************/
14249/*
14250** 2024-02-08
14251**
14252** The author disclaims copyright to this source code.  In place of
14253** a legal notice, here is a blessing:
14254**
14255**    May you do good and not evil.
14256**    May you find forgiveness for yourself and forgive others.
14257**    May you share freely, never taking more than you give.
14258**
14259*************************************************************************
14260*/
14261
14262/* #include "sqlite3intck.h" */
14263#include <string.h>
14264#include <assert.h>
14265
14266#include <stdio.h>
14267#include <stdlib.h>
14268
14269/*
14270** nKeyVal:
14271**   The number of values that make up the 'key' for the current pCheck
14272**   statement.
14273**
14274** rc:
14275**   Error code returned by most recent sqlite3_intck_step() or
14276**   sqlite3_intck_unlock() call. This is set to SQLITE_DONE when
14277**   the integrity-check operation is finished.
14278**
14279** zErr:
14280**   If the object has entered the error state, this is the error message.
14281**   Is freed using sqlite3_free() when the object is deleted.
14282**
14283** zTestSql:
14284**   The value returned by the most recent call to sqlite3_intck_testsql().
14285**   Each call to testsql() frees the previous zTestSql value (using
14286**   sqlite3_free()) and replaces it with the new value it will return.
14287*/
14288struct sqlite3_intck {
14289  sqlite3 *db;
14290  const char *zDb;                /* Copy of zDb parameter to _open() */
14291  char *zObj;                     /* Current object. Or NULL. */
14292
14293  sqlite3_stmt *pCheck;           /* Current check statement */
14294  char *zKey;
14295  int nKeyVal;
14296
14297  char *zMessage;
14298  int bCorruptSchema;
14299
14300  int rc;                         /* Error code */
14301  char *zErr;                     /* Error message */
14302  char *zTestSql;                 /* Returned by sqlite3_intck_test_sql() */
14303};
14304
14305
14306/*
14307** Some error has occurred while using database p->db. Save the error message
14308** and error code currently held by the database handle in p->rc and p->zErr.
14309*/
14310static void intckSaveErrmsg(sqlite3_intck *p){
14311  p->rc = sqlite3_errcode(p->db);
14312  sqlite3_free(p->zErr);
14313  p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
14314}
14315
14316/*
14317** If the handle passed as the first argument is already in the error state,
14318** then this function is a no-op (returns NULL immediately). Otherwise, if an
14319** error occurs within this function, it leaves an error in said handle.
14320**
14321** Otherwise, this function attempts to prepare SQL statement zSql and
14322** return the resulting statement handle to the user.
14323*/
14324static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){
14325  sqlite3_stmt *pRet = 0;
14326  if( p->rc==SQLITE_OK ){
14327    p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0);
14328    if( p->rc!=SQLITE_OK ){
14329      intckSaveErrmsg(p);
14330      assert( pRet==0 );
14331    }
14332  }
14333  return pRet;
14334}
14335
14336/*
14337** If the handle passed as the first argument is already in the error state,
14338** then this function is a no-op (returns NULL immediately). Otherwise, if an
14339** error occurs within this function, it leaves an error in said handle.
14340**
14341** Otherwise, this function treats argument zFmt as a printf() style format
14342** string. It formats it according to the trailing arguments and then
14343** attempts to prepare the results and return the resulting prepared
14344** statement.
14345*/
14346static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){
14347  sqlite3_stmt *pRet = 0;
14348  va_list ap;
14349  char *zSql = 0;
14350  va_start(ap, zFmt);
14351  zSql = sqlite3_vmprintf(zFmt, ap);
14352  if( p->rc==SQLITE_OK && zSql==0 ){
14353    p->rc = SQLITE_NOMEM;
14354  }
14355  pRet = intckPrepare(p, zSql);
14356  sqlite3_free(zSql);
14357  va_end(ap);
14358  return pRet;
14359}
14360
14361/*
14362** Finalize SQL statement pStmt. If an error occurs and the handle passed
14363** as the first argument does not already contain an error, store the
14364** error in the handle.
14365*/
14366static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){
14367  int rc = sqlite3_finalize(pStmt);
14368  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
14369    intckSaveErrmsg(p);
14370  }
14371}
14372
14373/*
14374** If there is already an error in handle p, return it. Otherwise, call
14375** sqlite3_step() on the statement handle and return that value.
14376*/
14377static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){
14378  if( p->rc ) return p->rc;
14379  return sqlite3_step(pStmt);
14380}
14381
14382/*
14383** Execute SQL statement zSql. There is no way to obtain any results
14384** returned by the statement. This function uses the sqlite3_intck error
14385** code convention.
14386*/
14387static void intckExec(sqlite3_intck *p, const char *zSql){
14388  sqlite3_stmt *pStmt = 0;
14389  pStmt = intckPrepare(p, zSql);
14390  intckStep(p, pStmt);
14391  intckFinalize(p, pStmt);
14392}
14393
14394/*
14395** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error
14396** code convention.
14397*/
14398static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){
14399  va_list ap;
14400  char *zRet = 0;
14401  va_start(ap, zFmt);
14402  zRet = sqlite3_vmprintf(zFmt, ap);
14403  if( p->rc==SQLITE_OK ){
14404    if( zRet==0 ){
14405      p->rc = SQLITE_NOMEM;
14406    }
14407  }else{
14408    sqlite3_free(zRet);
14409    zRet = 0;
14410  }
14411  return zRet;
14412}
14413
14414/*
14415** This is used by sqlite3_intck_unlock() to save the vector key value
14416** required to restart the current pCheck query as a nul-terminated string
14417** in p->zKey.
14418*/
14419static void intckSaveKey(sqlite3_intck *p){
14420  int ii;
14421  char *zSql = 0;
14422  sqlite3_stmt *pStmt = 0;
14423  sqlite3_stmt *pXinfo = 0;
14424  const char *zDir = 0;
14425
14426  assert( p->pCheck );
14427  assert( p->zKey==0 );
14428
14429  pXinfo = intckPrepareFmt(p,
14430      "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, "
14431      "pragma_index_xinfo(%Q, %Q) "
14432      "WHERE s.type='index' AND s.name=%Q",
14433      p->zDb, p->zObj, p->zDb, p->zObj
14434  );
14435  if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){
14436    zDir = (const char*)sqlite3_column_text(pXinfo, 0);
14437  }
14438
14439  if( zDir==0 ){
14440    /* Object is a table, not an index. This is the easy case,as there are
14441    ** no DESC columns or NULL values in a primary key.  */
14442    const char *zSep = "SELECT '(' || ";
14443    for(ii=0; ii<p->nKeyVal; ii++){
14444      zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep);
14445      zSep = " || ', ' || ";
14446    }
14447    zSql = intckMprintf(p, "%z || ')'", zSql);
14448  }else{
14449
14450    /* Object is an index. */
14451    assert( p->nKeyVal>1 );
14452    for(ii=p->nKeyVal; ii>0; ii--){
14453      int bLastIsDesc = zDir[ii-1]=='1';
14454      int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL;
14455      const char *zLast = sqlite3_column_name(p->pCheck, ii);
14456      char *zLhs = 0;
14457      char *zRhs = 0;
14458      char *zWhere = 0;
14459
14460      if( bLastIsNull ){
14461        if( bLastIsDesc ) continue;
14462        zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast);
14463      }else{
14464        const char *zOp = bLastIsDesc ? "<" : ">";
14465        zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii);
14466      }
14467
14468      if( ii>1 ){
14469        const char *zLhsSep = "";
14470        const char *zRhsSep = "";
14471        int jj;
14472        for(jj=0; jj<ii-1; jj++){
14473          const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1);
14474          zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias);
14475          zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1);
14476          zLhsSep = ",";
14477          zRhsSep = " || ',' || ";
14478        }
14479
14480        zWhere = intckMprintf(p,
14481            "'(%z) IS (' || %z || ') AND ' || %z",
14482            zLhs, zRhs, zWhere);
14483      }
14484      zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere);
14485
14486      zSql = intckMprintf(p, "%z%s(quote( %z ) )",
14487          zSql,
14488          (zSql==0 ? "VALUES" : ",\n      "),
14489          zWhere
14490      );
14491    }
14492    zSql = intckMprintf(p,
14493        "WITH wc(q) AS (\n%z\n)"
14494        "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n      ') FROM wc"
14495        , zSql
14496    );
14497  }
14498
14499  pStmt = intckPrepare(p, zSql);
14500  if( p->rc==SQLITE_OK ){
14501    for(ii=0; ii<p->nKeyVal; ii++){
14502      sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1));
14503    }
14504    if( SQLITE_ROW==sqlite3_step(pStmt) ){
14505      p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
14506    }
14507    intckFinalize(p, pStmt);
14508  }
14509
14510  sqlite3_free(zSql);
14511  intckFinalize(p, pXinfo);
14512}
14513
14514/*
14515** Find the next database object (table or index) to check. If successful,
14516** set sqlite3_intck.zObj to point to a nul-terminated buffer containing
14517** the object's name before returning.
14518*/
14519static void intckFindObject(sqlite3_intck *p){
14520  sqlite3_stmt *pStmt = 0;
14521  char *zPrev = p->zObj;
14522  p->zObj = 0;
14523
14524  assert( p->rc==SQLITE_OK );
14525  assert( p->pCheck==0 );
14526
14527  pStmt = intckPrepareFmt(p,
14528    "WITH tables(table_name) AS ("
14529    "  SELECT name"
14530    "  FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage"
14531    "  UNION ALL "
14532    "  SELECT 'sqlite_schema'"
14533    ")"
14534    "SELECT table_name FROM tables "
14535    "WHERE ?1 IS NULL OR table_name%s?1 "
14536    "ORDER BY 1"
14537    , p->zDb, (p->zKey ? ">=" : ">")
14538  );
14539
14540  if( p->rc==SQLITE_OK ){
14541    sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT);
14542    if( sqlite3_step(pStmt)==SQLITE_ROW ){
14543      p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0));
14544    }
14545  }
14546  intckFinalize(p, pStmt);
14547
14548  /* If this is a new object, ensure the previous key value is cleared. */
14549  if( sqlite3_stricmp(p->zObj, zPrev) ){
14550    sqlite3_free(p->zKey);
14551    p->zKey = 0;
14552  }
14553
14554  sqlite3_free(zPrev);
14555}
14556
14557/*
14558** Return the size in bytes of the first token in nul-terminated buffer z.
14559** For the purposes of this call, a token is either:
14560**
14561**   *  a quoted SQL string,
14562*    *  a contiguous series of ascii alphabet characters, or
14563*    *  any other single byte.
14564*/
14565static int intckGetToken(const char *z){
14566  char c = z[0];
14567  int iRet = 1;
14568  if( c=='\'' || c=='"' || c=='`' ){
14569    while( 1 ){
14570      if( z[iRet]==c ){
14571        iRet++;
14572        if( z[iRet]!=c ) break;
14573      }
14574      iRet++;
14575    }
14576  }
14577  else if( c=='[' ){
14578    while( z[iRet++]!=']' && z[iRet] );
14579  }
14580  else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
14581    while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
14582      iRet++;
14583    }
14584  }
14585
14586  return iRet;
14587}
14588
14589/*
14590** Return true if argument c is an ascii whitespace character.
14591*/
14592static int intckIsSpace(char c){
14593  return (c==' ' || c=='\t' || c=='\n' || c=='\r');
14594}
14595
14596/*
14597** Argument z points to the text of a CREATE INDEX statement. This function
14598** identifies the part of the text that contains either the index WHERE
14599** clause (if iCol<0) or the iCol'th column of the index.
14600**
14601** If (iCol<0), the identified fragment does not include the "WHERE" keyword,
14602** only the expression that follows it. If (iCol>=0) then the identified
14603** fragment does not include any trailing sort-order keywords - "ASC" or
14604** "DESC".
14605**
14606** If the CREATE INDEX statement does not contain the requested field or
14607** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to
14608** the identified fragment is returned and output parameter (*pnByte) set
14609** to its size in bytes.
14610*/
14611static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){
14612  int iOff = 0;
14613  int iThisCol = 0;
14614  int iStart = 0;
14615  int nOpen = 0;
14616
14617  const char *zRet = 0;
14618  int nRet = 0;
14619
14620  int iEndOfCol = 0;
14621
14622  /* Skip forward until the first "(" token */
14623  while( z[iOff]!='(' ){
14624    iOff += intckGetToken(&z[iOff]);
14625    if( z[iOff]=='\0' ) return 0;
14626  }
14627  assert( z[iOff]=='(' );
14628
14629  nOpen = 1;
14630  iOff++;
14631  iStart = iOff;
14632  while( z[iOff] ){
14633    const char *zToken = &z[iOff];
14634    int nToken = 0;
14635
14636    /* Check if this is the end of the current column - either a "," or ")"
14637    ** when nOpen==1.  */
14638    if( nOpen==1 ){
14639      if( z[iOff]==',' || z[iOff]==')' ){
14640        if( iCol==iThisCol ){
14641          int iEnd = iEndOfCol ? iEndOfCol : iOff;
14642          nRet = (iEnd - iStart);
14643          zRet = &z[iStart];
14644          break;
14645        }
14646        iStart = iOff+1;
14647        while( intckIsSpace(z[iStart]) ) iStart++;
14648        iThisCol++;
14649      }
14650      if( z[iOff]==')' ) break;
14651    }
14652    if( z[iOff]=='(' ) nOpen++;
14653    if( z[iOff]==')' ) nOpen--;
14654    nToken = intckGetToken(zToken);
14655
14656    if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken))
14657     || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken))
14658    ){
14659      iEndOfCol = iOff;
14660    }else if( 0==intckIsSpace(zToken[0]) ){
14661      iEndOfCol = 0;
14662    }
14663
14664    iOff += nToken;
14665  }
14666
14667  /* iStart is now the byte offset of 1 byte passed the final ')' in the
14668  ** CREATE INDEX statement. Try to find a WHERE clause to return.  */
14669  while( zRet==0 && z[iOff] ){
14670    int n = intckGetToken(&z[iOff]);
14671    if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){
14672      zRet = &z[iOff+5];
14673      nRet = (int)strlen(zRet);
14674    }
14675    iOff += n;
14676  }
14677
14678  /* Trim any whitespace from the start and end of the returned string. */
14679  if( zRet ){
14680    while( intckIsSpace(zRet[0]) ){
14681      nRet--;
14682      zRet++;
14683    }
14684    while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--;
14685  }
14686
14687  *pnByte = nRet;
14688  return zRet;
14689}
14690
14691/*
14692** User-defined SQL function wrapper for intckParseCreateIndex():
14693**
14694**     SELECT parse_create_index(<sql>, <icol>);
14695*/
14696static void intckParseCreateIndexFunc(
14697  sqlite3_context *pCtx,
14698  int nVal,
14699  sqlite3_value **apVal
14700){
14701  const char *zSql = (const char*)sqlite3_value_text(apVal[0]);
14702  int idx = sqlite3_value_int(apVal[1]);
14703  const char *zRes = 0;
14704  int nRes = 0;
14705
14706  assert( nVal==2 );
14707  if( zSql ){
14708    zRes = intckParseCreateIndex(zSql, idx, &nRes);
14709  }
14710  sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT);
14711}
14712
14713/*
14714** Return true if sqlite3_intck.db has automatic indexes enabled, false
14715** otherwise.
14716*/
14717static int intckGetAutoIndex(sqlite3_intck *p){
14718  int bRet = 0;
14719  sqlite3_stmt *pStmt = 0;
14720  pStmt = intckPrepare(p, "PRAGMA automatic_index");
14721  if( SQLITE_ROW==intckStep(p, pStmt) ){
14722    bRet = sqlite3_column_int(pStmt, 0);
14723  }
14724  intckFinalize(p, pStmt);
14725  return bRet;
14726}
14727
14728/*
14729** Return true if zObj is an index, or false otherwise.
14730*/
14731static int intckIsIndex(sqlite3_intck *p, const char *zObj){
14732  int bRet = 0;
14733  sqlite3_stmt *pStmt = 0;
14734  pStmt = intckPrepareFmt(p,
14735      "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'",
14736      p->zDb, zObj
14737  );
14738  if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
14739    bRet = 1;
14740  }
14741  intckFinalize(p, pStmt);
14742  return bRet;
14743}
14744
14745/*
14746** Return a pointer to a nul-terminated buffer containing the SQL statement
14747** used to check database object zObj (a table or index) for corruption.
14748** If parameter zPrev is not NULL, then it must be a string containing the
14749** vector key required to restart the check where it left off last time.
14750** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of
14751** columns in the vector key value for the specified object.
14752**
14753** This function uses the sqlite3_intck error code convention.
14754*/
14755static char *intckCheckObjectSql(
14756  sqlite3_intck *p,               /* Integrity check object */
14757  const char *zObj,               /* Object (table or index) to scan */
14758  const char *zPrev,              /* Restart key vector, if any */
14759  int *pnKeyVal                   /* OUT: Number of key-values for this scan */
14760){
14761  char *zRet = 0;
14762  sqlite3_stmt *pStmt = 0;
14763  int bAutoIndex = 0;
14764  int bIsIndex = 0;
14765
14766  const char *zCommon =
14767      /* Relation without_rowid also contains just one row. Column "b" is
14768      ** set to true if the table being examined is a WITHOUT ROWID table,
14769      ** or false otherwise.  */
14770      ", without_rowid(b) AS ("
14771      "  SELECT EXISTS ("
14772      "    SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l"
14773      "      WHERE origin='pk' "
14774      "      AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)"
14775      "  )"
14776      ")"
14777      ""
14778      /* Table idx_cols contains 1 row for each column in each index on the
14779      ** table being checked. Columns are:
14780      **
14781      **   idx_name: Name of the index.
14782      **   idx_ispk: True if this index is the PK of a WITHOUT ROWID table.
14783      **   col_name: Name of indexed column, or NULL for index on expression.
14784      **   col_expr: Indexed expression, including COLLATE clause.
14785      **   col_alias: Alias used for column in 'intck_wrapper' table.
14786      */
14787      ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS ("
14788      "  SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE(("
14789      "    SELECT parse_create_index(sql, i.seqno) FROM "
14790      "    sqlite_schema WHERE name = l.name"
14791      "  ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll)),"
14792      "  'c' || row_number() OVER ()"
14793      "  FROM "
14794      "      tabname t,"
14795      "      without_rowid w,"
14796      "      pragma_index_list(t.tab, t.db) l,"
14797      "      pragma_index_xinfo(l.name) i"
14798      "      WHERE i.key"
14799      "  UNION ALL"
14800      "  SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0"
14801      ")"
14802      ""
14803      ""
14804      /*
14805      ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where
14806      ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2":
14807      **
14808      **   o_pk:   "o.c1, o.c2"
14809      **   i_pk:   "i.'a', i.'b'"
14810      **   ...
14811      **   n_pk:   2
14812      */
14813      ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS ("
14814      "    WITH pkfields(f, a) AS ("
14815      "      SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk"
14816      "    )"
14817      "    SELECT t.db, t.tab, t.idx, "
14818      "           group_concat(a, ', '), "
14819      "           group_concat('i.'||quote(f), ', '), "
14820      "           group_concat('quote(o.'||a||')', ' || '','' || '),  "
14821      "           format('(%s)==(%s)',"
14822      "               group_concat('o.'||a, ', '), "
14823      "               group_concat(format('\"%w\"', f), ', ')"
14824      "           ),"
14825      "           group_concat('%s', ','),"
14826      "           group_concat('quote('||a||')', ', '),  "
14827      "           count(*)"
14828      "    FROM tabname t, pkfields"
14829      ")"
14830      ""
14831      ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS ("
14832      "  SELECT idx_name,"
14833      "    format('(%s,%s) IS (%s,%s)', "
14834      "           group_concat(i.col_expr, ', '), i_pk,"
14835      "           group_concat('o.'||i.col_alias, ', '), o_pk"
14836      "    ), "
14837      "    parse_create_index("
14838      "        (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1"
14839      "    ),"
14840      "    'cond' || row_number() OVER ()"
14841      "    , group_concat('%s', ',')"
14842      "    , group_concat('quote('||i.col_alias||')', ', ')"
14843      "  FROM tabpk t, "
14844      "       without_rowid w,"
14845      "       idx_cols i"
14846      "  WHERE i.idx_ispk==0 "
14847      "  GROUP BY idx_name"
14848      ")"
14849      ""
14850      ", wrapper_with(s) AS ("
14851      "  SELECT 'intck_wrapper AS (\n  SELECT\n    ' || ("
14852      "      WITH f(a, b) AS ("
14853      "        SELECT col_expr, col_alias FROM idx_cols"
14854      "          UNION ALL "
14855      "        SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL"
14856      "      )"
14857      "      SELECT group_concat(format('%s AS %s', a, b), ',\n    ') FROM f"
14858      "    )"
14859      "    || format('\n  FROM %Q.%Q ', t.db, t.tab)"
14860           /* If the object being checked is a table, append "NOT INDEXED".
14861           ** Otherwise, append "INDEXED BY <index>", and then, if the index
14862           ** is a partial index " WHERE <condition>".  */
14863      "    || CASE WHEN t.idx IS NULL THEN "
14864      "        'NOT INDEXED'"
14865      "       ELSE"
14866      "        format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)"
14867      "       END"
14868      "    || '\n)'"
14869      "    FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)"
14870      ")"
14871      ""
14872  ;
14873
14874  bAutoIndex = intckGetAutoIndex(p);
14875  if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0");
14876
14877  bIsIndex = intckIsIndex(p, zObj);
14878  if( bIsIndex ){
14879    pStmt = intckPrepareFmt(p,
14880      /* Table idxname contains a single row. The first column, "db", contains
14881      ** the name of the db containing the table (e.g. "main") and the second,
14882      ** "tab", the name of the table itself.  */
14883      "WITH tabname(db, tab, idx) AS ("
14884      "  SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q "
14885      ")"
14886      ""
14887      ", whereclause(w_c) AS (%s)"
14888      ""
14889      "%s" /* zCommon */
14890      ""
14891      ", case_statement(c) AS ("
14892      "  SELECT "
14893      "    'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' "
14894      "    || '      SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '"
14895      "    || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)"
14896      "    || '    )\n  THEN NULL\n    '"
14897      "    || 'ELSE format(''surplus entry ('"
14898      "    ||   group_concat('%%s', ',') || ',' || p.ps_pk"
14899      "    || ') in index ' || t.idx || ''', ' "
14900      "    ||   group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk"
14901      "    || ')'"
14902      "    || '\n  END AS error_message'"
14903      "  FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx"
14904      ")"
14905      ""
14906      ", thiskey(k, n) AS ("
14907      "    SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, "
14908      "           count(*) + p.n_pk "
14909      "    FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx"
14910      ")"
14911      ""
14912      ", main_select(m, n) AS ("
14913      "  SELECT format("
14914      "      'WITH %%s\n' ||"
14915      "      ', idx_checker AS (\n' ||"
14916      "      '  SELECT %%s,\n' ||"
14917      "      '  %%s\n' || "
14918      "      '  FROM intck_wrapper AS o\n' ||"
14919      "      ')\n',"
14920      "      ww.s, c, t.k"
14921      "  ), t.n"
14922      "  FROM case_statement, wrapper_with ww, thiskey t"
14923      ")"
14924
14925      "SELECT m || "
14926      "    group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n"
14927      " FROM "
14928      "main_select, whereclause "
14929      , p->zDb, p->zDb, zObj, zObj
14930      , zPrev ? zPrev : "VALUES('')", zCommon
14931      );
14932  }else{
14933    pStmt = intckPrepareFmt(p,
14934      /* Table tabname contains a single row. The first column, "db", contains
14935      ** the name of the db containing the table (e.g. "main") and the second,
14936      ** "tab", the name of the table itself.  */
14937      "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)"
14938      ""
14939      "%s" /* zCommon */
14940
14941      /* expr(e) contains one row for each index on table zObj. Value e
14942      ** is set to an expression that evaluates to NULL if the required
14943      ** entry is present in the index, or an error message otherwise.  */
14944      ", expr(e, p) AS ("
14945      "  SELECT format('CASE WHEN EXISTS \n"
14946      "    (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n"
14947      "    THEN NULL\n"
14948      "    ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n"
14949      "  END\n'"
14950      "    , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')',"
14951      "      i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk),"
14952      "    CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END"
14953      "  FROM tabpk t, idx i"
14954      ")"
14955
14956      ", numbered(ii, cond, e) AS ("
14957      "  SELECT 0, 'n.ii=0', 'NULL'"
14958      "    UNION ALL "
14959      "  SELECT row_number() OVER (),"
14960      "      '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e"
14961      "  FROM expr"
14962      ")"
14963
14964      ", counter_with(w) AS ("
14965      "    SELECT 'WITH intck_counter(ii) AS (\n  ' || "
14966      "       group_concat('SELECT '||ii, ' UNION ALL\n  ') "
14967      "    || '\n)' FROM numbered"
14968      ")"
14969      ""
14970      ", case_statement(c) AS ("
14971      "    SELECT 'CASE ' || "
14972      "    group_concat(format('\n  WHEN %%s THEN (%%s)', cond, e), '') ||"
14973      "    '\nEND AS error_message'"
14974      "    FROM numbered"
14975      ")"
14976      ""
14977
14978      /* This table contains a single row consisting of a single value -
14979      ** the text of an SQL expression that may be used by the main SQL
14980      ** statement to output an SQL literal that can be used to resume
14981      ** the scan if it is suspended. e.g. for a rowid table, an expression
14982      ** like:
14983      **
14984      **     format('(%d,%d)', _rowid_, n.ii)
14985      */
14986      ", thiskey(k, n) AS ("
14987      "    SELECT o_pk || ', ii', n_pk+1 FROM tabpk"
14988      ")"
14989      ""
14990      ", whereclause(w_c) AS ("
14991      "    SELECT CASE WHEN prev!='' THEN "
14992      "    '\nWHERE (' || o_pk ||', n.ii) > ' || prev"
14993      "    ELSE ''"
14994      "    END"
14995      "    FROM tabpk, tabname"
14996      ")"
14997      ""
14998      ", main_select(m, n) AS ("
14999      "  SELECT format("
15000      "      '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o"
15001               ", intck_counter AS n%%s\nORDER BY %%s', "
15002      "      w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk"
15003      "  ), thiskey.n"
15004      "  FROM case_statement, tabpk t, counter_with, "
15005      "       wrapper_with ww, thiskey, whereclause"
15006      ")"
15007
15008      "SELECT m, n FROM main_select",
15009      p->zDb, zObj, zPrev, zCommon
15010    );
15011  }
15012
15013  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
15014    zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0));
15015    if( pnKeyVal ){
15016      *pnKeyVal = sqlite3_column_int(pStmt, 1);
15017    }
15018  }
15019  intckFinalize(p, pStmt);
15020
15021  if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
15022  return zRet;
15023}
15024
15025/*
15026** Open a new integrity-check object.
15027*/
15028int sqlite3_intck_open(
15029  sqlite3 *db,                    /* Database handle to operate on */
15030  const char *zDbArg,             /* "main", "temp" etc. */
15031  sqlite3_intck **ppOut           /* OUT: New integrity-check handle */
15032){
15033  sqlite3_intck *pNew = 0;
15034  int rc = SQLITE_OK;
15035  const char *zDb = zDbArg ? zDbArg : "main";
15036  int nDb = (int)strlen(zDb);
15037
15038  pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1);
15039  if( pNew==0 ){
15040    rc = SQLITE_NOMEM;
15041  }else{
15042    memset(pNew, 0, sizeof(*pNew));
15043    pNew->db = db;
15044    pNew->zDb = (const char*)&pNew[1];
15045    memcpy(&pNew[1], zDb, nDb+1);
15046    rc = sqlite3_create_function(db, "parse_create_index",
15047        2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
15048    );
15049    if( rc!=SQLITE_OK ){
15050      sqlite3_intck_close(pNew);
15051      pNew = 0;
15052    }
15053  }
15054
15055  *ppOut = pNew;
15056  return rc;
15057}
15058
15059/*
15060** Free the integrity-check object.
15061*/
15062void sqlite3_intck_close(sqlite3_intck *p){
15063  if( p ){
15064    sqlite3_finalize(p->pCheck);
15065    sqlite3_create_function(
15066        p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
15067    );
15068    sqlite3_free(p->zObj);
15069    sqlite3_free(p->zKey);
15070    sqlite3_free(p->zTestSql);
15071    sqlite3_free(p->zErr);
15072    sqlite3_free(p->zMessage);
15073    sqlite3_free(p);
15074  }
15075}
15076
15077/*
15078** Step the integrity-check object.
15079*/
15080int sqlite3_intck_step(sqlite3_intck *p){
15081  if( p->rc==SQLITE_OK ){
15082
15083    if( p->zMessage ){
15084      sqlite3_free(p->zMessage);
15085      p->zMessage = 0;
15086    }
15087
15088    if( p->bCorruptSchema ){
15089      p->rc = SQLITE_DONE;
15090    }else
15091    if( p->pCheck==0 ){
15092      intckFindObject(p);
15093      if( p->rc==SQLITE_OK ){
15094        if( p->zObj ){
15095          char *zSql = 0;
15096          zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal);
15097          p->pCheck = intckPrepare(p, zSql);
15098          sqlite3_free(zSql);
15099          sqlite3_free(p->zKey);
15100          p->zKey = 0;
15101        }else{
15102          p->rc = SQLITE_DONE;
15103        }
15104      }else if( p->rc==SQLITE_CORRUPT ){
15105        p->rc = SQLITE_OK;
15106        p->zMessage = intckMprintf(p, "%s",
15107            "corruption found while reading database schema"
15108        );
15109        p->bCorruptSchema = 1;
15110      }
15111    }
15112
15113    if( p->pCheck ){
15114      assert( p->rc==SQLITE_OK );
15115      if( sqlite3_step(p->pCheck)==SQLITE_ROW ){
15116        /* Normal case, do nothing. */
15117      }else{
15118        intckFinalize(p, p->pCheck);
15119        p->pCheck = 0;
15120        p->nKeyVal = 0;
15121        if( p->rc==SQLITE_CORRUPT ){
15122          p->rc = SQLITE_OK;
15123          p->zMessage = intckMprintf(p,
15124              "corruption found while scanning database object %s", p->zObj
15125          );
15126        }
15127      }
15128    }
15129  }
15130
15131  return p->rc;
15132}
15133
15134/*
15135** Return a message describing the corruption encountered by the most recent
15136** call to sqlite3_intck_step(), or NULL if no corruption was encountered.
15137*/
15138const char *sqlite3_intck_message(sqlite3_intck *p){
15139  assert( p->pCheck==0 || p->zMessage==0 );
15140  if( p->zMessage ){
15141    return p->zMessage;
15142  }
15143  if( p->pCheck ){
15144    return (const char*)sqlite3_column_text(p->pCheck, 0);
15145  }
15146  return 0;
15147}
15148
15149/*
15150** Return the error code and message.
15151*/
15152int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){
15153  if( pzErr ) *pzErr = p->zErr;
15154  return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc);
15155}
15156
15157/*
15158** Close any read transaction the integrity-check object is holding open
15159** on the database.
15160*/
15161int sqlite3_intck_unlock(sqlite3_intck *p){
15162  if( p->rc==SQLITE_OK && p->pCheck ){
15163    assert( p->zKey==0 && p->nKeyVal>0 );
15164    intckSaveKey(p);
15165    intckFinalize(p, p->pCheck);
15166    p->pCheck = 0;
15167  }
15168  return p->rc;
15169}
15170
15171/*
15172** Return the SQL statement used to check object zObj. Or, if zObj is
15173** NULL, the current SQL statement.
15174*/
15175const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){
15176  sqlite3_free(p->zTestSql);
15177  if( zObj ){
15178    p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0);
15179  }else{
15180    if( p->zObj ){
15181      p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0);
15182    }else{
15183      sqlite3_free(p->zTestSql);
15184      p->zTestSql = 0;
15185    }
15186  }
15187  return p->zTestSql;
15188}
15189
15190/************************* End ../ext/intck/sqlite3intck.c ********************/
15191
15192#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
15193#define SQLITE_SHELL_HAVE_RECOVER 1
15194#else
15195#define SQLITE_SHELL_HAVE_RECOVER 0
15196#endif
15197#if SQLITE_SHELL_HAVE_RECOVER
15198/************************* Begin ../ext/recover/sqlite3recover.h ******************/
15199/*
15200** 2022-08-27
15201**
15202** The author disclaims copyright to this source code.  In place of
15203** a legal notice, here is a blessing:
15204**
15205**    May you do good and not evil.
15206**    May you find forgiveness for yourself and forgive others.
15207**    May you share freely, never taking more than you give.
15208**
15209*************************************************************************
15210**
15211** This file contains the public interface to the "recover" extension -
15212** an SQLite extension designed to recover data from corrupted database
15213** files.
15214*/
15215
15216/*
15217** OVERVIEW:
15218**
15219** To use the API to recover data from a corrupted database, an
15220** application:
15221**
15222**   1) Creates an sqlite3_recover handle by calling either
15223**      sqlite3_recover_init() or sqlite3_recover_init_sql().
15224**
15225**   2) Configures the new handle using one or more calls to
15226**      sqlite3_recover_config().
15227**
15228**   3) Executes the recovery by repeatedly calling sqlite3_recover_step() on
15229**      the handle until it returns something other than SQLITE_OK. If it
15230**      returns SQLITE_DONE, then the recovery operation completed without
15231**      error. If it returns some other non-SQLITE_OK value, then an error
15232**      has occurred.
15233**
15234**   4) Retrieves any error code and English language error message using the
15235**      sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs,
15236**      respectively.
15237**
15238**   5) Destroys the sqlite3_recover handle and frees all resources
15239**      using sqlite3_recover_finish().
15240**
15241** The application may abandon the recovery operation at any point
15242** before it is finished by passing the sqlite3_recover handle to
15243** sqlite3_recover_finish(). This is not an error, but the final state
15244** of the output database, or the results of running the partial script
15245** delivered to the SQL callback, are undefined.
15246*/
15247
15248#ifndef _SQLITE_RECOVER_H
15249#define _SQLITE_RECOVER_H
15250
15251/* #include "sqlite3.h" */
15252
15253#ifdef __cplusplus
15254extern "C" {
15255#endif
15256
15257/*
15258** An instance of the sqlite3_recover object represents a recovery
15259** operation in progress.
15260**
15261** Constructors:
15262**
15263**    sqlite3_recover_init()
15264**    sqlite3_recover_init_sql()
15265**
15266** Destructor:
15267**
15268**    sqlite3_recover_finish()
15269**
15270** Methods:
15271**
15272**    sqlite3_recover_config()
15273**    sqlite3_recover_errcode()
15274**    sqlite3_recover_errmsg()
15275**    sqlite3_recover_run()
15276**    sqlite3_recover_step()
15277*/
15278typedef struct sqlite3_recover sqlite3_recover;
15279
15280/*
15281** These two APIs attempt to create and return a new sqlite3_recover object.
15282** In both cases the first two arguments identify the (possibly
15283** corrupt) database to recover data from. The first argument is an open
15284** database handle and the second the name of a database attached to that
15285** handle (i.e. "main", "temp" or the name of an attached database).
15286**
15287** If sqlite3_recover_init() is used to create the new sqlite3_recover
15288** handle, then data is recovered into a new database, identified by
15289** string parameter zUri. zUri may be an absolute or relative file path,
15290** or may be an SQLite URI. If the identified database file already exists,
15291** it is overwritten.
15292**
15293** If sqlite3_recover_init_sql() is invoked, then any recovered data will
15294** be returned to the user as a series of SQL statements. Executing these
15295** SQL statements results in the same database as would have been created
15296** had sqlite3_recover_init() been used. For each SQL statement in the
15297** output, the callback function passed as the third argument (xSql) is
15298** invoked once. The first parameter is a passed a copy of the fourth argument
15299** to this function (pCtx) as its first parameter, and a pointer to a
15300** nul-terminated buffer containing the SQL statement formated as UTF-8 as
15301** the second. If the xSql callback returns any value other than SQLITE_OK,
15302** then processing is immediately abandoned and the value returned used as
15303** the recover handle error code (see below).
15304**
15305** If an out-of-memory error occurs, NULL may be returned instead of
15306** a valid handle. In all other cases, it is the responsibility of the
15307** application to avoid resource leaks by ensuring that
15308** sqlite3_recover_finish() is called on all allocated handles.
15309*/
15310sqlite3_recover *sqlite3_recover_init(
15311  sqlite3* db,
15312  const char *zDb,
15313  const char *zUri
15314);
15315sqlite3_recover *sqlite3_recover_init_sql(
15316  sqlite3* db,
15317  const char *zDb,
15318  int (*xSql)(void*, const char*),
15319  void *pCtx
15320);
15321
15322/*
15323** Configure an sqlite3_recover object that has just been created using
15324** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function
15325** may only be called before the first call to sqlite3_recover_step()
15326** or sqlite3_recover_run() on the object.
15327**
15328** The second argument passed to this function must be one of the
15329** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument
15330** depend on the specific SQLITE_RECOVER_* symbol in use.
15331**
15332** SQLITE_OK is returned if the configuration operation was successful,
15333** or an SQLite error code otherwise.
15334*/
15335int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg);
15336
15337/*
15338** SQLITE_RECOVER_LOST_AND_FOUND:
15339**   The pArg argument points to a string buffer containing the name
15340**   of a "lost-and-found" table in the output database, or NULL. If
15341**   the argument is non-NULL and the database contains seemingly
15342**   valid pages that cannot be associated with any table in the
15343**   recovered part of the schema, data is extracted from these
15344**   pages to add to the lost-and-found table.
15345**
15346** SQLITE_RECOVER_FREELIST_CORRUPT:
15347**   The pArg value must actually be a pointer to a value of type
15348**   int containing value 0 or 1 cast as a (void*). If this option is set
15349**   (argument is 1) and a lost-and-found table has been configured using
15350**   SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is
15351**   corrupt and an attempt is made to recover records from pages that
15352**   appear to be linked into the freelist. Otherwise, pages on the freelist
15353**   are ignored. Setting this option can recover more data from the
15354**   database, but often ends up "recovering" deleted records. The default
15355**   value is 0 (clear).
15356**
15357** SQLITE_RECOVER_ROWIDS:
15358**   The pArg value must actually be a pointer to a value of type
15359**   int containing value 0 or 1 cast as a (void*). If this option is set
15360**   (argument is 1), then an attempt is made to recover rowid values
15361**   that are not also INTEGER PRIMARY KEY values. If this option is
15362**   clear, then new rowids are assigned to all recovered rows. The
15363**   default value is 1 (set).
15364**
15365** SQLITE_RECOVER_SLOWINDEXES:
15366**   The pArg value must actually be a pointer to a value of type
15367**   int containing value 0 or 1 cast as a (void*). If this option is clear
15368**   (argument is 0), then when creating an output database, the recover
15369**   module creates and populates non-UNIQUE indexes right at the end of the
15370**   recovery operation - after all recoverable data has been inserted
15371**   into the new database. This is faster overall, but means that the
15372**   final call to sqlite3_recover_step() for a recovery operation may
15373**   be need to create a large number of indexes, which may be very slow.
15374**
15375**   Or, if this option is set (argument is 1), then non-UNIQUE indexes
15376**   are created in the output database before it is populated with
15377**   recovered data. This is slower overall, but avoids the slow call
15378**   to sqlite3_recover_step() at the end of the recovery operation.
15379**
15380**   The default option value is 0.
15381*/
15382#define SQLITE_RECOVER_LOST_AND_FOUND   1
15383#define SQLITE_RECOVER_FREELIST_CORRUPT 2
15384#define SQLITE_RECOVER_ROWIDS           3
15385#define SQLITE_RECOVER_SLOWINDEXES      4
15386
15387/*
15388** Perform a unit of work towards the recovery operation. This function
15389** must normally be called multiple times to complete database recovery.
15390**
15391** If no error occurs but the recovery operation is not completed, this
15392** function returns SQLITE_OK. If recovery has been completed successfully
15393** then SQLITE_DONE is returned. If an error has occurred, then an SQLite
15394** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not
15395** considered an error if some or all of the data cannot be recovered
15396** due to database corruption.
15397**
15398** Once sqlite3_recover_step() has returned a value other than SQLITE_OK,
15399** all further such calls on the same recover handle are no-ops that return
15400** the same non-SQLITE_OK value.
15401*/
15402int sqlite3_recover_step(sqlite3_recover*);
15403
15404/*
15405** Run the recovery operation to completion. Return SQLITE_OK if successful,
15406** or an SQLite error code otherwise. Calling this function is the same
15407** as executing:
15408**
15409**     while( SQLITE_OK==sqlite3_recover_step(p) );
15410**     return sqlite3_recover_errcode(p);
15411*/
15412int sqlite3_recover_run(sqlite3_recover*);
15413
15414/*
15415** If an error has been encountered during a prior call to
15416** sqlite3_recover_step(), then this function attempts to return a
15417** pointer to a buffer containing an English language explanation of
15418** the error. If no error message is available, or if an out-of memory
15419** error occurs while attempting to allocate a buffer in which to format
15420** the error message, NULL is returned.
15421**
15422** The returned buffer remains valid until the sqlite3_recover handle is
15423** destroyed using sqlite3_recover_finish().
15424*/
15425const char *sqlite3_recover_errmsg(sqlite3_recover*);
15426
15427/*
15428** If this function is called on an sqlite3_recover handle after
15429** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK.
15430*/
15431int sqlite3_recover_errcode(sqlite3_recover*);
15432
15433/*
15434** Clean up a recovery object created by a call to sqlite3_recover_init().
15435** The results of using a recovery object with any API after it has been
15436** passed to this function are undefined.
15437**
15438** This function returns the same value as sqlite3_recover_errcode().
15439*/
15440int sqlite3_recover_finish(sqlite3_recover*);
15441
15442
15443#ifdef __cplusplus
15444}  /* end of the 'extern "C"' block */
15445#endif
15446
15447#endif /* ifndef _SQLITE_RECOVER_H */
15448
15449/************************* End ../ext/recover/sqlite3recover.h ********************/
15450# ifndef SQLITE_HAVE_SQLITE3R
15451/************************* Begin ../ext/recover/dbdata.c ******************/
15452/*
15453** 2019-04-17
15454**
15455** The author disclaims copyright to this source code.  In place of
15456** a legal notice, here is a blessing:
15457**
15458**    May you do good and not evil.
15459**    May you find forgiveness for yourself and forgive others.
15460**    May you share freely, never taking more than you give.
15461**
15462******************************************************************************
15463**
15464** This file contains an implementation of two eponymous virtual tables,
15465** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the
15466** "sqlite_dbpage" eponymous virtual table be available.
15467**
15468** SQLITE_DBDATA:
15469**   sqlite_dbdata is used to extract data directly from a database b-tree
15470**   page and its associated overflow pages, bypassing the b-tree layer.
15471**   The table schema is equivalent to:
15472**
15473**     CREATE TABLE sqlite_dbdata(
15474**       pgno INTEGER,
15475**       cell INTEGER,
15476**       field INTEGER,
15477**       value ANY,
15478**       schema TEXT HIDDEN
15479**     );
15480**
15481**   IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE
15482**   FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND
15483**   "schema".
15484**
15485**   Each page of the database is inspected. If it cannot be interpreted as
15486**   a b-tree page, or if it is a b-tree page containing 0 entries, the
15487**   sqlite_dbdata table contains no rows for that page.  Otherwise, the
15488**   table contains one row for each field in the record associated with
15489**   each cell on the page. For intkey b-trees, the key value is stored in
15490**   field -1.
15491**
15492**   For example, for the database:
15493**
15494**     CREATE TABLE t1(a, b);     -- root page is page 2
15495**     INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five');
15496**     INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten');
15497**
15498**   the sqlite_dbdata table contains, as well as from entries related to
15499**   page 1, content equivalent to:
15500**
15501**     INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES
15502**         (2, 0, -1, 5     ),
15503**         (2, 0,  0, 'v'   ),
15504**         (2, 0,  1, 'five'),
15505**         (2, 1, -1, 10    ),
15506**         (2, 1,  0, 'x'   ),
15507**         (2, 1,  1, 'ten' );
15508**
15509**   If database corruption is encountered, this module does not report an
15510**   error. Instead, it attempts to extract as much data as possible and
15511**   ignores the corruption.
15512**
15513** SQLITE_DBPTR:
15514**   The sqlite_dbptr table has the following schema:
15515**
15516**     CREATE TABLE sqlite_dbptr(
15517**       pgno INTEGER,
15518**       child INTEGER,
15519**       schema TEXT HIDDEN
15520**     );
15521**
15522**   It contains one entry for each b-tree pointer between a parent and
15523**   child page in the database.
15524*/
15525
15526#if !defined(SQLITEINT_H)
15527/* #include "sqlite3.h" */
15528
15529/* typedef unsigned char u8; */
15530/* typedef unsigned int u32; */
15531
15532#endif
15533#include <string.h>
15534#include <assert.h>
15535
15536#ifndef SQLITE_OMIT_VIRTUALTABLE
15537
15538#define DBDATA_PADDING_BYTES 100
15539
15540typedef struct DbdataTable DbdataTable;
15541typedef struct DbdataCursor DbdataCursor;
15542typedef struct DbdataBuffer DbdataBuffer;
15543
15544/*
15545** Buffer type.
15546*/
15547struct DbdataBuffer {
15548  u8 *aBuf;
15549  sqlite3_int64 nBuf;
15550};
15551
15552/* Cursor object */
15553struct DbdataCursor {
15554  sqlite3_vtab_cursor base;       /* Base class.  Must be first */
15555  sqlite3_stmt *pStmt;            /* For fetching database pages */
15556
15557  int iPgno;                      /* Current page number */
15558  u8 *aPage;                      /* Buffer containing page */
15559  int nPage;                      /* Size of aPage[] in bytes */
15560  int nCell;                      /* Number of cells on aPage[] */
15561  int iCell;                      /* Current cell number */
15562  int bOnePage;                   /* True to stop after one page */
15563  int szDb;
15564  sqlite3_int64 iRowid;
15565
15566  /* Only for the sqlite_dbdata table */
15567  DbdataBuffer rec;
15568  sqlite3_int64 nRec;             /* Size of pRec[] in bytes */
15569  sqlite3_int64 nHdr;             /* Size of header in bytes */
15570  int iField;                     /* Current field number */
15571  u8 *pHdrPtr;
15572  u8 *pPtr;
15573  u32 enc;                        /* Text encoding */
15574
15575  sqlite3_int64 iIntkey;          /* Integer key value */
15576};
15577
15578/* Table object */
15579struct DbdataTable {
15580  sqlite3_vtab base;              /* Base class.  Must be first */
15581  sqlite3 *db;                    /* The database connection */
15582  sqlite3_stmt *pStmt;            /* For fetching database pages */
15583  int bPtr;                       /* True for sqlite3_dbptr table */
15584};
15585
15586/* Column and schema definitions for sqlite_dbdata */
15587#define DBDATA_COLUMN_PGNO        0
15588#define DBDATA_COLUMN_CELL        1
15589#define DBDATA_COLUMN_FIELD       2
15590#define DBDATA_COLUMN_VALUE       3
15591#define DBDATA_COLUMN_SCHEMA      4
15592#define DBDATA_SCHEMA             \
15593      "CREATE TABLE x("           \
15594      "  pgno INTEGER,"           \
15595      "  cell INTEGER,"           \
15596      "  field INTEGER,"          \
15597      "  value ANY,"              \
15598      "  schema TEXT HIDDEN"      \
15599      ")"
15600
15601/* Column and schema definitions for sqlite_dbptr */
15602#define DBPTR_COLUMN_PGNO         0
15603#define DBPTR_COLUMN_CHILD        1
15604#define DBPTR_COLUMN_SCHEMA       2
15605#define DBPTR_SCHEMA              \
15606      "CREATE TABLE x("           \
15607      "  pgno INTEGER,"           \
15608      "  child INTEGER,"          \
15609      "  schema TEXT HIDDEN"      \
15610      ")"
15611
15612/*
15613** Ensure the buffer passed as the first argument is at least nMin bytes
15614** in size. If an error occurs while attempting to resize the buffer,
15615** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
15616*/
15617static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){
15618  if( nMin>pBuf->nBuf ){
15619    sqlite3_int64 nNew = nMin+16384;
15620    u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew);
15621
15622    if( aNew==0 ) return SQLITE_NOMEM;
15623    pBuf->aBuf = aNew;
15624    pBuf->nBuf = nNew;
15625  }
15626  return SQLITE_OK;
15627}
15628
15629/*
15630** Release the allocation managed by buffer pBuf.
15631*/
15632static void dbdataBufferFree(DbdataBuffer *pBuf){
15633  sqlite3_free(pBuf->aBuf);
15634  memset(pBuf, 0, sizeof(*pBuf));
15635}
15636
15637/*
15638** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual
15639** table.
15640*/
15641static int dbdataConnect(
15642  sqlite3 *db,
15643  void *pAux,
15644  int argc, const char *const*argv,
15645  sqlite3_vtab **ppVtab,
15646  char **pzErr
15647){
15648  DbdataTable *pTab = 0;
15649  int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA);
15650
15651  (void)argc;
15652  (void)argv;
15653  (void)pzErr;
15654  sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS);
15655  if( rc==SQLITE_OK ){
15656    pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable));
15657    if( pTab==0 ){
15658      rc = SQLITE_NOMEM;
15659    }else{
15660      memset(pTab, 0, sizeof(DbdataTable));
15661      pTab->db = db;
15662      pTab->bPtr = (pAux!=0);
15663    }
15664  }
15665
15666  *ppVtab = (sqlite3_vtab*)pTab;
15667  return rc;
15668}
15669
15670/*
15671** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table.
15672*/
15673static int dbdataDisconnect(sqlite3_vtab *pVtab){
15674  DbdataTable *pTab = (DbdataTable*)pVtab;
15675  if( pTab ){
15676    sqlite3_finalize(pTab->pStmt);
15677    sqlite3_free(pVtab);
15678  }
15679  return SQLITE_OK;
15680}
15681
15682/*
15683** This function interprets two types of constraints:
15684**
15685**       schema=?
15686**       pgno=?
15687**
15688** If neither are present, idxNum is set to 0. If schema=? is present,
15689** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit
15690** in idxNum is set.
15691**
15692** If both parameters are present, schema is in position 0 and pgno in
15693** position 1.
15694*/
15695static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){
15696  DbdataTable *pTab = (DbdataTable*)tab;
15697  int i;
15698  int iSchema = -1;
15699  int iPgno = -1;
15700  int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA);
15701
15702  for(i=0; i<pIdx->nConstraint; i++){
15703    struct sqlite3_index_constraint *p = &pIdx->aConstraint[i];
15704    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
15705      if( p->iColumn==colSchema ){
15706        if( p->usable==0 ) return SQLITE_CONSTRAINT;
15707        iSchema = i;
15708      }
15709      if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){
15710        iPgno = i;
15711      }
15712    }
15713  }
15714
15715  if( iSchema>=0 ){
15716    pIdx->aConstraintUsage[iSchema].argvIndex = 1;
15717    pIdx->aConstraintUsage[iSchema].omit = 1;
15718  }
15719  if( iPgno>=0 ){
15720    pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0);
15721    pIdx->aConstraintUsage[iPgno].omit = 1;
15722    pIdx->estimatedCost = 100;
15723    pIdx->estimatedRows =  50;
15724
15725    if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){
15726      int iCol = pIdx->aOrderBy[0].iColumn;
15727      if( pIdx->nOrderBy==1 ){
15728        pIdx->orderByConsumed = (iCol==0 || iCol==1);
15729      }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){
15730        pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1);
15731      }
15732    }
15733
15734  }else{
15735    pIdx->estimatedCost = 100000000;
15736    pIdx->estimatedRows = 1000000000;
15737  }
15738  pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00);
15739  return SQLITE_OK;
15740}
15741
15742/*
15743** Open a new sqlite_dbdata or sqlite_dbptr cursor.
15744*/
15745static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
15746  DbdataCursor *pCsr;
15747
15748  pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor));
15749  if( pCsr==0 ){
15750    return SQLITE_NOMEM;
15751  }else{
15752    memset(pCsr, 0, sizeof(DbdataCursor));
15753    pCsr->base.pVtab = pVTab;
15754  }
15755
15756  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
15757  return SQLITE_OK;
15758}
15759
15760/*
15761** Restore a cursor object to the state it was in when first allocated
15762** by dbdataOpen().
15763*/
15764static void dbdataResetCursor(DbdataCursor *pCsr){
15765  DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab);
15766  if( pTab->pStmt==0 ){
15767    pTab->pStmt = pCsr->pStmt;
15768  }else{
15769    sqlite3_finalize(pCsr->pStmt);
15770  }
15771  pCsr->pStmt = 0;
15772  pCsr->iPgno = 1;
15773  pCsr->iCell = 0;
15774  pCsr->iField = 0;
15775  pCsr->bOnePage = 0;
15776  sqlite3_free(pCsr->aPage);
15777  dbdataBufferFree(&pCsr->rec);
15778  pCsr->aPage = 0;
15779  pCsr->nRec = 0;
15780}
15781
15782/*
15783** Close an sqlite_dbdata or sqlite_dbptr cursor.
15784*/
15785static int dbdataClose(sqlite3_vtab_cursor *pCursor){
15786  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
15787  dbdataResetCursor(pCsr);
15788  sqlite3_free(pCsr);
15789  return SQLITE_OK;
15790}
15791
15792/*
15793** Utility methods to decode 16 and 32-bit big-endian unsigned integers.
15794*/
15795static u32 get_uint16(unsigned char *a){
15796  return (a[0]<<8)|a[1];
15797}
15798static u32 get_uint32(unsigned char *a){
15799  return ((u32)a[0]<<24)
15800       | ((u32)a[1]<<16)
15801       | ((u32)a[2]<<8)
15802       | ((u32)a[3]);
15803}
15804
15805/*
15806** Load page pgno from the database via the sqlite_dbpage virtual table.
15807** If successful, set (*ppPage) to point to a buffer containing the page
15808** data, (*pnPage) to the size of that buffer in bytes and return
15809** SQLITE_OK. In this case it is the responsibility of the caller to
15810** eventually free the buffer using sqlite3_free().
15811**
15812** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and
15813** return an SQLite error code.
15814*/
15815static int dbdataLoadPage(
15816  DbdataCursor *pCsr,             /* Cursor object */
15817  u32 pgno,                       /* Page number of page to load */
15818  u8 **ppPage,                    /* OUT: pointer to page buffer */
15819  int *pnPage                     /* OUT: Size of (*ppPage) in bytes */
15820){
15821  int rc2;
15822  int rc = SQLITE_OK;
15823  sqlite3_stmt *pStmt = pCsr->pStmt;
15824
15825  *ppPage = 0;
15826  *pnPage = 0;
15827  if( pgno>0 ){
15828    sqlite3_bind_int64(pStmt, 2, pgno);
15829    if( SQLITE_ROW==sqlite3_step(pStmt) ){
15830      int nCopy = sqlite3_column_bytes(pStmt, 0);
15831      if( nCopy>0 ){
15832        u8 *pPage;
15833        pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES);
15834        if( pPage==0 ){
15835          rc = SQLITE_NOMEM;
15836        }else{
15837          const u8 *pCopy = sqlite3_column_blob(pStmt, 0);
15838          memcpy(pPage, pCopy, nCopy);
15839          memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES);
15840        }
15841        *ppPage = pPage;
15842        *pnPage = nCopy;
15843      }
15844    }
15845    rc2 = sqlite3_reset(pStmt);
15846    if( rc==SQLITE_OK ) rc = rc2;
15847  }
15848
15849  return rc;
15850}
15851
15852/*
15853** Read a varint.  Put the value in *pVal and return the number of bytes.
15854*/
15855static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){
15856  sqlite3_uint64 u = 0;
15857  int i;
15858  for(i=0; i<8; i++){
15859    u = (u<<7) + (z[i]&0x7f);
15860    if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
15861  }
15862  u = (u<<8) + (z[i]&0xff);
15863  *pVal = (sqlite3_int64)u;
15864  return 9;
15865}
15866
15867/*
15868** Like dbdataGetVarint(), but set the output to 0 if it is less than 0
15869** or greater than 0xFFFFFFFF. This can be used for all varints in an
15870** SQLite database except for key values in intkey tables.
15871*/
15872static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){
15873  sqlite3_int64 val;
15874  int nRet = dbdataGetVarint(z, &val);
15875  if( val<0 || val>0xFFFFFFFF ) val = 0;
15876  *pVal = val;
15877  return nRet;
15878}
15879
15880/*
15881** Return the number of bytes of space used by an SQLite value of type
15882** eType.
15883*/
15884static int dbdataValueBytes(int eType){
15885  switch( eType ){
15886    case 0: case 8: case 9:
15887    case 10: case 11:
15888      return 0;
15889    case 1:
15890      return 1;
15891    case 2:
15892      return 2;
15893    case 3:
15894      return 3;
15895    case 4:
15896      return 4;
15897    case 5:
15898      return 6;
15899    case 6:
15900    case 7:
15901      return 8;
15902    default:
15903      if( eType>0 ){
15904        return ((eType-12) / 2);
15905      }
15906      return 0;
15907  }
15908}
15909
15910/*
15911** Load a value of type eType from buffer pData and use it to set the
15912** result of context object pCtx.
15913*/
15914static void dbdataValue(
15915  sqlite3_context *pCtx,
15916  u32 enc,
15917  int eType,
15918  u8 *pData,
15919  sqlite3_int64 nData
15920){
15921  if( eType>=0 ){
15922    if( dbdataValueBytes(eType)<=nData ){
15923      switch( eType ){
15924        case 0:
15925        case 10:
15926        case 11:
15927          sqlite3_result_null(pCtx);
15928          break;
15929
15930        case 8:
15931          sqlite3_result_int(pCtx, 0);
15932          break;
15933        case 9:
15934          sqlite3_result_int(pCtx, 1);
15935          break;
15936
15937        case 1: case 2: case 3: case 4: case 5: case 6: case 7: {
15938          sqlite3_uint64 v = (signed char)pData[0];
15939          pData++;
15940          switch( eType ){
15941            case 7:
15942            case 6:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
15943            case 5:  v = (v<<16) + (pData[0]<<8) + pData[1];  pData += 2;
15944            case 4:  v = (v<<8) + pData[0];  pData++;
15945            case 3:  v = (v<<8) + pData[0];  pData++;
15946            case 2:  v = (v<<8) + pData[0];  pData++;
15947          }
15948
15949          if( eType==7 ){
15950            double r;
15951            memcpy(&r, &v, sizeof(r));
15952            sqlite3_result_double(pCtx, r);
15953          }else{
15954            sqlite3_result_int64(pCtx, (sqlite3_int64)v);
15955          }
15956          break;
15957        }
15958
15959        default: {
15960          int n = ((eType-12) / 2);
15961          if( eType % 2 ){
15962            switch( enc ){
15963  #ifndef SQLITE_OMIT_UTF16
15964              case SQLITE_UTF16BE:
15965                sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
15966                break;
15967              case SQLITE_UTF16LE:
15968                sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT);
15969                break;
15970  #endif
15971              default:
15972                sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT);
15973                break;
15974            }
15975          }else{
15976            sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT);
15977          }
15978        }
15979      }
15980    }else{
15981      if( eType==7 ){
15982        sqlite3_result_double(pCtx, 0.0);
15983      }else if( eType<7 ){
15984        sqlite3_result_int(pCtx, 0);
15985      }else if( eType%2 ){
15986        sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
15987      }else{
15988        sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC);
15989      }
15990    }
15991  }
15992}
15993
15994/* This macro is a copy of the MX_CELL() macro in the SQLite core. Given
15995** a page-size, it returns the maximum number of cells that may be present
15996** on the page.  */
15997#define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6)
15998
15999/* Maximum number of fields that may appear in a single record. This is
16000** the "hard-limit", according to comments in sqliteLimit.h. */
16001#define DBDATA_MX_FIELD 32676
16002
16003/*
16004** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry.
16005*/
16006static int dbdataNext(sqlite3_vtab_cursor *pCursor){
16007  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16008  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16009
16010  pCsr->iRowid++;
16011  while( 1 ){
16012    int rc;
16013    int iOff = (pCsr->iPgno==1 ? 100 : 0);
16014    int bNextPage = 0;
16015
16016    if( pCsr->aPage==0 ){
16017      while( 1 ){
16018        if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK;
16019        rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage);
16020        if( rc!=SQLITE_OK ) return rc;
16021        if( pCsr->aPage && pCsr->nPage>=256 ) break;
16022        sqlite3_free(pCsr->aPage);
16023        pCsr->aPage = 0;
16024        if( pCsr->bOnePage ) return SQLITE_OK;
16025        pCsr->iPgno++;
16026      }
16027
16028      assert( iOff+3+2<=pCsr->nPage );
16029      pCsr->iCell = pTab->bPtr ? -2 : 0;
16030      pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]);
16031      if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){
16032        pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage);
16033      }
16034    }
16035
16036    if( pTab->bPtr ){
16037      if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){
16038        pCsr->iCell = pCsr->nCell;
16039      }
16040      pCsr->iCell++;
16041      if( pCsr->iCell>=pCsr->nCell ){
16042        sqlite3_free(pCsr->aPage);
16043        pCsr->aPage = 0;
16044        if( pCsr->bOnePage ) return SQLITE_OK;
16045        pCsr->iPgno++;
16046      }else{
16047        return SQLITE_OK;
16048      }
16049    }else{
16050      /* If there is no record loaded, load it now. */
16051      assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 );
16052      if( pCsr->nRec==0 ){
16053        int bHasRowid = 0;
16054        int nPointer = 0;
16055        sqlite3_int64 nPayload = 0;
16056        sqlite3_int64 nHdr = 0;
16057        int iHdr;
16058        int U, X;
16059        int nLocal;
16060
16061        switch( pCsr->aPage[iOff] ){
16062          case 0x02:
16063            nPointer = 4;
16064            break;
16065          case 0x0a:
16066            break;
16067          case 0x0d:
16068            bHasRowid = 1;
16069            break;
16070          default:
16071            /* This is not a b-tree page with records on it. Continue. */
16072            pCsr->iCell = pCsr->nCell;
16073            break;
16074        }
16075
16076        if( pCsr->iCell>=pCsr->nCell ){
16077          bNextPage = 1;
16078        }else{
16079          int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2;
16080
16081          if( iCellPtr>pCsr->nPage ){
16082            bNextPage = 1;
16083          }else{
16084            iOff = get_uint16(&pCsr->aPage[iCellPtr]);
16085          }
16086
16087          /* For an interior node cell, skip past the child-page number */
16088          iOff += nPointer;
16089
16090          /* Load the "byte of payload including overflow" field */
16091          if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){
16092            bNextPage = 1;
16093          }else{
16094            iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
16095            if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
16096            if( nPayload==0 ) nPayload = 1;
16097          }
16098
16099          /* If this is a leaf intkey cell, load the rowid */
16100          if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
16101            iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
16102          }
16103
16104          /* Figure out how much data to read from the local page */
16105          U = pCsr->nPage;
16106          if( bHasRowid ){
16107            X = U-35;
16108          }else{
16109            X = ((U-12)*64/255)-23;
16110          }
16111          if( nPayload<=X ){
16112            nLocal = nPayload;
16113          }else{
16114            int M, K;
16115            M = ((U-12)*32/255)-23;
16116            K = M+((nPayload-M)%(U-4));
16117            if( K<=X ){
16118              nLocal = K;
16119            }else{
16120              nLocal = M;
16121            }
16122          }
16123
16124          if( bNextPage || nLocal+iOff>pCsr->nPage ){
16125            bNextPage = 1;
16126          }else{
16127
16128            /* Allocate space for payload. And a bit more to catch small buffer
16129            ** overruns caused by attempting to read a varint or similar from
16130            ** near the end of a corrupt record.  */
16131            rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES);
16132            if( rc!=SQLITE_OK ) return rc;
16133            assert( nPayload!=0 );
16134
16135            /* Load the nLocal bytes of payload */
16136            memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal);
16137            iOff += nLocal;
16138
16139            /* Load content from overflow pages */
16140            if( nPayload>nLocal ){
16141              sqlite3_int64 nRem = nPayload - nLocal;
16142              u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]);
16143              while( nRem>0 ){
16144                u8 *aOvfl = 0;
16145                int nOvfl = 0;
16146                int nCopy;
16147                rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl);
16148                assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage );
16149                if( rc!=SQLITE_OK ) return rc;
16150                if( aOvfl==0 ) break;
16151
16152                nCopy = U-4;
16153                if( nCopy>nRem ) nCopy = nRem;
16154                memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy);
16155                nRem -= nCopy;
16156
16157                pgnoOvfl = get_uint32(aOvfl);
16158                sqlite3_free(aOvfl);
16159              }
16160              nPayload -= nRem;
16161            }
16162            memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES);
16163            pCsr->nRec = nPayload;
16164
16165            iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr);
16166            if( nHdr>nPayload ) nHdr = 0;
16167            pCsr->nHdr = nHdr;
16168            pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr];
16169            pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr];
16170            pCsr->iField = (bHasRowid ? -1 : 0);
16171          }
16172        }
16173      }else{
16174        pCsr->iField++;
16175        if( pCsr->iField>0 ){
16176          sqlite3_int64 iType;
16177          if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec]
16178           || pCsr->iField>=DBDATA_MX_FIELD
16179          ){
16180            bNextPage = 1;
16181          }else{
16182            int szField = 0;
16183            pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
16184            szField = dbdataValueBytes(iType);
16185            if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))<szField ){
16186              pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nRec];
16187            }else{
16188              pCsr->pPtr += szField;
16189            }
16190          }
16191        }
16192      }
16193
16194      if( bNextPage ){
16195        sqlite3_free(pCsr->aPage);
16196        pCsr->aPage = 0;
16197        pCsr->nRec = 0;
16198        if( pCsr->bOnePage ) return SQLITE_OK;
16199        pCsr->iPgno++;
16200      }else{
16201        if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){
16202          return SQLITE_OK;
16203        }
16204
16205        /* Advance to the next cell. The next iteration of the loop will load
16206        ** the record and so on. */
16207        pCsr->nRec = 0;
16208        pCsr->iCell++;
16209      }
16210    }
16211  }
16212
16213  assert( !"can't get here" );
16214  return SQLITE_OK;
16215}
16216
16217/*
16218** Return true if the cursor is at EOF.
16219*/
16220static int dbdataEof(sqlite3_vtab_cursor *pCursor){
16221  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16222  return pCsr->aPage==0;
16223}
16224
16225/*
16226** Return true if nul-terminated string zSchema ends in "()". Or false
16227** otherwise.
16228*/
16229static int dbdataIsFunction(const char *zSchema){
16230  size_t n = strlen(zSchema);
16231  if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){
16232    return (int)n-2;
16233  }
16234  return 0;
16235}
16236
16237/*
16238** Determine the size in pages of database zSchema (where zSchema is
16239** "main", "temp" or the name of an attached database) and set
16240** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise,
16241** an SQLite error code.
16242*/
16243static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){
16244  DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab;
16245  char *zSql = 0;
16246  int rc, rc2;
16247  int nFunc = 0;
16248  sqlite3_stmt *pStmt = 0;
16249
16250  if( (nFunc = dbdataIsFunction(zSchema))>0 ){
16251    zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema);
16252  }else{
16253    zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema);
16254  }
16255  if( zSql==0 ) return SQLITE_NOMEM;
16256
16257  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
16258  sqlite3_free(zSql);
16259  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
16260    pCsr->szDb = sqlite3_column_int(pStmt, 0);
16261  }
16262  rc2 = sqlite3_finalize(pStmt);
16263  if( rc==SQLITE_OK ) rc = rc2;
16264  return rc;
16265}
16266
16267/*
16268** Attempt to figure out the encoding of the database by retrieving page 1
16269** and inspecting the header field. If successful, set the pCsr->enc variable
16270** and return SQLITE_OK. Otherwise, return an SQLite error code.
16271*/
16272static int dbdataGetEncoding(DbdataCursor *pCsr){
16273  int rc = SQLITE_OK;
16274  int nPg1 = 0;
16275  u8 *aPg1 = 0;
16276  rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1);
16277  if( rc==SQLITE_OK && nPg1>=(56+4) ){
16278    pCsr->enc = get_uint32(&aPg1[56]);
16279  }
16280  sqlite3_free(aPg1);
16281  return rc;
16282}
16283
16284
16285/*
16286** xFilter method for sqlite_dbdata and sqlite_dbptr.
16287*/
16288static int dbdataFilter(
16289  sqlite3_vtab_cursor *pCursor,
16290  int idxNum, const char *idxStr,
16291  int argc, sqlite3_value **argv
16292){
16293  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16294  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16295  int rc = SQLITE_OK;
16296  const char *zSchema = "main";
16297  (void)idxStr;
16298  (void)argc;
16299
16300  dbdataResetCursor(pCsr);
16301  assert( pCsr->iPgno==1 );
16302  if( idxNum & 0x01 ){
16303    zSchema = (const char*)sqlite3_value_text(argv[0]);
16304    if( zSchema==0 ) zSchema = "";
16305  }
16306  if( idxNum & 0x02 ){
16307    pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]);
16308    pCsr->bOnePage = 1;
16309  }else{
16310    rc = dbdataDbsize(pCsr, zSchema);
16311  }
16312
16313  if( rc==SQLITE_OK ){
16314    int nFunc = 0;
16315    if( pTab->pStmt ){
16316      pCsr->pStmt = pTab->pStmt;
16317      pTab->pStmt = 0;
16318    }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){
16319      char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema);
16320      if( zSql==0 ){
16321        rc = SQLITE_NOMEM;
16322      }else{
16323        rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
16324        sqlite3_free(zSql);
16325      }
16326    }else{
16327      rc = sqlite3_prepare_v2(pTab->db,
16328          "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1,
16329          &pCsr->pStmt, 0
16330      );
16331    }
16332  }
16333  if( rc==SQLITE_OK ){
16334    rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT);
16335  }
16336
16337  /* Try to determine the encoding of the db by inspecting the header
16338  ** field on page 1. */
16339  if( rc==SQLITE_OK ){
16340    rc = dbdataGetEncoding(pCsr);
16341  }
16342
16343  if( rc!=SQLITE_OK ){
16344    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
16345  }
16346
16347  if( rc==SQLITE_OK ){
16348    rc = dbdataNext(pCursor);
16349  }
16350  return rc;
16351}
16352
16353/*
16354** Return a column for the sqlite_dbdata or sqlite_dbptr table.
16355*/
16356static int dbdataColumn(
16357  sqlite3_vtab_cursor *pCursor,
16358  sqlite3_context *ctx,
16359  int i
16360){
16361  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16362  DbdataTable *pTab = (DbdataTable*)pCursor->pVtab;
16363  if( pTab->bPtr ){
16364    switch( i ){
16365      case DBPTR_COLUMN_PGNO:
16366        sqlite3_result_int64(ctx, pCsr->iPgno);
16367        break;
16368      case DBPTR_COLUMN_CHILD: {
16369        int iOff = pCsr->iPgno==1 ? 100 : 0;
16370        if( pCsr->iCell<0 ){
16371          iOff += 8;
16372        }else{
16373          iOff += 12 + pCsr->iCell*2;
16374          if( iOff>pCsr->nPage ) return SQLITE_OK;
16375          iOff = get_uint16(&pCsr->aPage[iOff]);
16376        }
16377        if( iOff<=pCsr->nPage ){
16378          sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff]));
16379        }
16380        break;
16381      }
16382    }
16383  }else{
16384    switch( i ){
16385      case DBDATA_COLUMN_PGNO:
16386        sqlite3_result_int64(ctx, pCsr->iPgno);
16387        break;
16388      case DBDATA_COLUMN_CELL:
16389        sqlite3_result_int(ctx, pCsr->iCell);
16390        break;
16391      case DBDATA_COLUMN_FIELD:
16392        sqlite3_result_int(ctx, pCsr->iField);
16393        break;
16394      case DBDATA_COLUMN_VALUE: {
16395        if( pCsr->iField<0 ){
16396          sqlite3_result_int64(ctx, pCsr->iIntkey);
16397        }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){
16398          sqlite3_int64 iType;
16399          dbdataGetVarintU32(pCsr->pHdrPtr, &iType);
16400          dbdataValue(
16401              ctx, pCsr->enc, iType, pCsr->pPtr,
16402              &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr
16403          );
16404        }
16405        break;
16406      }
16407    }
16408  }
16409  return SQLITE_OK;
16410}
16411
16412/*
16413** Return the rowid for an sqlite_dbdata or sqlite_dptr table.
16414*/
16415static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
16416  DbdataCursor *pCsr = (DbdataCursor*)pCursor;
16417  *pRowid = pCsr->iRowid;
16418  return SQLITE_OK;
16419}
16420
16421
16422/*
16423** Invoke this routine to register the "sqlite_dbdata" virtual table module
16424*/
16425static int sqlite3DbdataRegister(sqlite3 *db){
16426  static sqlite3_module dbdata_module = {
16427    0,                            /* iVersion */
16428    0,                            /* xCreate */
16429    dbdataConnect,                /* xConnect */
16430    dbdataBestIndex,              /* xBestIndex */
16431    dbdataDisconnect,             /* xDisconnect */
16432    0,                            /* xDestroy */
16433    dbdataOpen,                   /* xOpen - open a cursor */
16434    dbdataClose,                  /* xClose - close a cursor */
16435    dbdataFilter,                 /* xFilter - configure scan constraints */
16436    dbdataNext,                   /* xNext - advance a cursor */
16437    dbdataEof,                    /* xEof - check for end of scan */
16438    dbdataColumn,                 /* xColumn - read data */
16439    dbdataRowid,                  /* xRowid - read data */
16440    0,                            /* xUpdate */
16441    0,                            /* xBegin */
16442    0,                            /* xSync */
16443    0,                            /* xCommit */
16444    0,                            /* xRollback */
16445    0,                            /* xFindMethod */
16446    0,                            /* xRename */
16447    0,                            /* xSavepoint */
16448    0,                            /* xRelease */
16449    0,                            /* xRollbackTo */
16450    0,                            /* xShadowName */
16451    0                             /* xIntegrity */
16452  };
16453
16454  int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0);
16455  if( rc==SQLITE_OK ){
16456    rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1);
16457  }
16458  return rc;
16459}
16460
16461int sqlite3_dbdata_init(
16462  sqlite3 *db,
16463  char **pzErrMsg,
16464  const sqlite3_api_routines *pApi
16465){
16466  (void)pzErrMsg;
16467  return sqlite3DbdataRegister(db);
16468}
16469
16470#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
16471
16472/************************* End ../ext/recover/dbdata.c ********************/
16473/************************* Begin ../ext/recover/sqlite3recover.c ******************/
16474/*
16475** 2022-08-27
16476**
16477** The author disclaims copyright to this source code.  In place of
16478** a legal notice, here is a blessing:
16479**
16480**    May you do good and not evil.
16481**    May you find forgiveness for yourself and forgive others.
16482**    May you share freely, never taking more than you give.
16483**
16484*************************************************************************
16485**
16486*/
16487
16488
16489/* #include "sqlite3recover.h" */
16490#include <assert.h>
16491#include <string.h>
16492
16493#ifndef SQLITE_OMIT_VIRTUALTABLE
16494
16495/*
16496** Declaration for public API function in file dbdata.c. This may be called
16497** with NULL as the final two arguments to register the sqlite_dbptr and
16498** sqlite_dbdata virtual tables with a database handle.
16499*/
16500#ifdef _WIN32
16501
16502#endif
16503int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*);
16504
16505/* typedef unsigned int u32; */
16506/* typedef unsigned char u8; */
16507/* typedef sqlite3_int64 i64; */
16508
16509typedef struct RecoverTable RecoverTable;
16510typedef struct RecoverColumn RecoverColumn;
16511
16512/*
16513** When recovering rows of data that can be associated with table
16514** definitions recovered from the sqlite_schema table, each table is
16515** represented by an instance of the following object.
16516**
16517** iRoot:
16518**   The root page in the original database. Not necessarily (and usually
16519**   not) the same in the recovered database.
16520**
16521** zTab:
16522**   Name of the table.
16523**
16524** nCol/aCol[]:
16525**   aCol[] is an array of nCol columns. In the order in which they appear
16526**   in the table.
16527**
16528** bIntkey:
16529**   Set to true for intkey tables, false for WITHOUT ROWID.
16530**
16531** iRowidBind:
16532**   Each column in the aCol[] array has associated with it the index of
16533**   the bind parameter its values will be bound to in the INSERT statement
16534**   used to construct the output database. If the table does has a rowid
16535**   but not an INTEGER PRIMARY KEY column, then iRowidBind contains the
16536**   index of the bind paramater to which the rowid value should be bound.
16537**   Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY
16538**   KEY column, then the rowid value should be bound to the index associated
16539**   with the column.
16540**
16541** pNext:
16542**   All RecoverTable objects used by the recovery operation are allocated
16543**   and populated as part of creating the recovered database schema in
16544**   the output database, before any non-schema data are recovered. They
16545**   are then stored in a singly-linked list linked by this variable beginning
16546**   at sqlite3_recover.pTblList.
16547*/
16548struct RecoverTable {
16549  u32 iRoot;                      /* Root page in original database */
16550  char *zTab;                     /* Name of table */
16551  int nCol;                       /* Number of columns in table */
16552  RecoverColumn *aCol;            /* Array of columns */
16553  int bIntkey;                    /* True for intkey, false for without rowid */
16554  int iRowidBind;                 /* If >0, bind rowid to INSERT here */
16555  RecoverTable *pNext;
16556};
16557
16558/*
16559** Each database column is represented by an instance of the following object
16560** stored in the RecoverTable.aCol[] array of the associated table.
16561**
16562** iField:
16563**   The index of the associated field within database records. Or -1 if
16564**   there is no associated field (e.g. for virtual generated columns).
16565**
16566** iBind:
16567**   The bind index of the INSERT statement to bind this columns values
16568**   to. Or 0 if there is no such index (iff (iField<0)).
16569**
16570** bIPK:
16571**   True if this is the INTEGER PRIMARY KEY column.
16572**
16573** zCol:
16574**   Name of column.
16575**
16576** eHidden:
16577**   A RECOVER_EHIDDEN_* constant value (see below for interpretation of each).
16578*/
16579struct RecoverColumn {
16580  int iField;                     /* Field in record on disk */
16581  int iBind;                      /* Binding to use in INSERT */
16582  int bIPK;                       /* True for IPK column */
16583  char *zCol;
16584  int eHidden;
16585};
16586
16587#define RECOVER_EHIDDEN_NONE    0      /* Normal database column */
16588#define RECOVER_EHIDDEN_HIDDEN  1      /* Column is __HIDDEN__ */
16589#define RECOVER_EHIDDEN_VIRTUAL 2      /* Virtual generated column */
16590#define RECOVER_EHIDDEN_STORED  3      /* Stored generated column */
16591
16592/*
16593** Bitmap object used to track pages in the input database. Allocated
16594** and manipulated only by the following functions:
16595**
16596**     recoverBitmapAlloc()
16597**     recoverBitmapFree()
16598**     recoverBitmapSet()
16599**     recoverBitmapQuery()
16600**
16601** nPg:
16602**   Largest page number that may be stored in the bitmap. The range
16603**   of valid keys is 1 to nPg, inclusive.
16604**
16605** aElem[]:
16606**   Array large enough to contain a bit for each key. For key value
16607**   iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32].
16608**   In other words, the following is true if bit iKey is set, or
16609**   false if it is clear:
16610**
16611**       (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0
16612*/
16613typedef struct RecoverBitmap RecoverBitmap;
16614struct RecoverBitmap {
16615  i64 nPg;                        /* Size of bitmap */
16616  u32 aElem[1];                   /* Array of 32-bit bitmasks */
16617};
16618
16619/*
16620** State variables (part of the sqlite3_recover structure) used while
16621** recovering data for tables identified in the recovered schema (state
16622** RECOVER_STATE_WRITING).
16623*/
16624typedef struct RecoverStateW1 RecoverStateW1;
16625struct RecoverStateW1 {
16626  sqlite3_stmt *pTbls;
16627  sqlite3_stmt *pSel;
16628  sqlite3_stmt *pInsert;
16629  int nInsert;
16630
16631  RecoverTable *pTab;             /* Table currently being written */
16632  int nMax;                       /* Max column count in any schema table */
16633  sqlite3_value **apVal;          /* Array of nMax values */
16634  int nVal;                       /* Number of valid entries in apVal[] */
16635  int bHaveRowid;
16636  i64 iRowid;
16637  i64 iPrevPage;
16638  int iPrevCell;
16639};
16640
16641/*
16642** State variables (part of the sqlite3_recover structure) used while
16643** recovering data destined for the lost and found table (states
16644** RECOVER_STATE_LOSTANDFOUND[123]).
16645*/
16646typedef struct RecoverStateLAF RecoverStateLAF;
16647struct RecoverStateLAF {
16648  RecoverBitmap *pUsed;
16649  i64 nPg;                        /* Size of db in pages */
16650  sqlite3_stmt *pAllAndParent;
16651  sqlite3_stmt *pMapInsert;
16652  sqlite3_stmt *pMaxField;
16653  sqlite3_stmt *pUsedPages;
16654  sqlite3_stmt *pFindRoot;
16655  sqlite3_stmt *pInsert;          /* INSERT INTO lost_and_found ... */
16656  sqlite3_stmt *pAllPage;
16657  sqlite3_stmt *pPageData;
16658  sqlite3_value **apVal;
16659  int nMaxField;
16660};
16661
16662/*
16663** Main recover handle structure.
16664*/
16665struct sqlite3_recover {
16666  /* Copies of sqlite3_recover_init[_sql]() parameters */
16667  sqlite3 *dbIn;                  /* Input database */
16668  char *zDb;                      /* Name of input db ("main" etc.) */
16669  char *zUri;                     /* URI for output database */
16670  void *pSqlCtx;                  /* SQL callback context */
16671  int (*xSql)(void*,const char*); /* Pointer to SQL callback function */
16672
16673  /* Values configured by sqlite3_recover_config() */
16674  char *zStateDb;                 /* State database to use (or NULL) */
16675  char *zLostAndFound;            /* Name of lost-and-found table (or NULL) */
16676  int bFreelistCorrupt;           /* SQLITE_RECOVER_FREELIST_CORRUPT setting */
16677  int bRecoverRowid;              /* SQLITE_RECOVER_ROWIDS setting */
16678  int bSlowIndexes;               /* SQLITE_RECOVER_SLOWINDEXES setting */
16679
16680  int pgsz;
16681  int detected_pgsz;
16682  int nReserve;
16683  u8 *pPage1Disk;
16684  u8 *pPage1Cache;
16685
16686  /* Error code and error message */
16687  int errCode;                    /* For sqlite3_recover_errcode() */
16688  char *zErrMsg;                  /* For sqlite3_recover_errmsg() */
16689
16690  int eState;
16691  int bCloseTransaction;
16692
16693  /* Variables used with eState==RECOVER_STATE_WRITING */
16694  RecoverStateW1 w1;
16695
16696  /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */
16697  RecoverStateLAF laf;
16698
16699  /* Fields used within sqlite3_recover_run() */
16700  sqlite3 *dbOut;                 /* Output database */
16701  sqlite3_stmt *pGetPage;         /* SELECT against input db sqlite_dbdata */
16702  RecoverTable *pTblList;         /* List of tables recovered from schema */
16703};
16704
16705/*
16706** The various states in which an sqlite3_recover object may exist:
16707**
16708**   RECOVER_STATE_INIT:
16709**    The object is initially created in this state. sqlite3_recover_step()
16710**    has yet to be called. This is the only state in which it is permitted
16711**    to call sqlite3_recover_config().
16712**
16713**   RECOVER_STATE_WRITING:
16714**
16715**   RECOVER_STATE_LOSTANDFOUND1:
16716**    State to populate the bitmap of pages used by other tables or the
16717**    database freelist.
16718**
16719**   RECOVER_STATE_LOSTANDFOUND2:
16720**    Populate the recovery.map table - used to figure out a "root" page
16721**    for each lost page from in the database from which records are
16722**    extracted.
16723**
16724**   RECOVER_STATE_LOSTANDFOUND3:
16725**    Populate the lost-and-found table itself.
16726*/
16727#define RECOVER_STATE_INIT           0
16728#define RECOVER_STATE_WRITING        1
16729#define RECOVER_STATE_LOSTANDFOUND1  2
16730#define RECOVER_STATE_LOSTANDFOUND2  3
16731#define RECOVER_STATE_LOSTANDFOUND3  4
16732#define RECOVER_STATE_SCHEMA2        5
16733#define RECOVER_STATE_DONE           6
16734
16735
16736/*
16737** Global variables used by this extension.
16738*/
16739typedef struct RecoverGlobal RecoverGlobal;
16740struct RecoverGlobal {
16741  const sqlite3_io_methods *pMethods;
16742  sqlite3_recover *p;
16743};
16744static RecoverGlobal recover_g;
16745
16746/*
16747** Use this static SQLite mutex to protect the globals during the
16748** first call to sqlite3_recover_step().
16749*/
16750#define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2
16751
16752
16753/*
16754** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid).
16755*/
16756#define RECOVER_ROWID_DEFAULT 1
16757
16758/*
16759** Mutex handling:
16760**
16761**    recoverEnterMutex()       -   Enter the recovery mutex
16762**    recoverLeaveMutex()       -   Leave the recovery mutex
16763**    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
16764*/
16765#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
16766# define recoverEnterMutex()
16767# define recoverLeaveMutex()
16768#else
16769static void recoverEnterMutex(void){
16770  sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
16771}
16772static void recoverLeaveMutex(void){
16773  sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
16774}
16775#endif
16776#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
16777static void recoverAssertMutexHeld(void){
16778  assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
16779}
16780#else
16781# define recoverAssertMutexHeld()
16782#endif
16783
16784
16785/*
16786** Like strlen(). But handles NULL pointer arguments.
16787*/
16788static int recoverStrlen(const char *zStr){
16789  if( zStr==0 ) return 0;
16790  return (int)(strlen(zStr)&0x7fffffff);
16791}
16792
16793/*
16794** This function is a no-op if the recover handle passed as the first
16795** argument already contains an error (if p->errCode!=SQLITE_OK).
16796**
16797** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
16798** bytes in size. If successful, a pointer to the new buffer is returned. Or,
16799** if an OOM error occurs, NULL is returned and the handle error code
16800** (p->errCode) set to SQLITE_NOMEM.
16801*/
16802static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
16803  void *pRet = 0;
16804  assert( nByte>0 );
16805  if( p->errCode==SQLITE_OK ){
16806    pRet = sqlite3_malloc64(nByte);
16807    if( pRet ){
16808      memset(pRet, 0, nByte);
16809    }else{
16810      p->errCode = SQLITE_NOMEM;
16811    }
16812  }
16813  return pRet;
16814}
16815
16816/*
16817** Set the error code and error message for the recover handle passed as
16818** the first argument. The error code is set to the value of parameter
16819** errCode.
16820**
16821** Parameter zFmt must be a printf() style formatting string. The handle
16822** error message is set to the result of using any trailing arguments for
16823** parameter substitutions in the formatting string.
16824**
16825** For example:
16826**
16827**   recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename);
16828*/
16829static int recoverError(
16830  sqlite3_recover *p,
16831  int errCode,
16832  const char *zFmt, ...
16833){
16834  char *z = 0;
16835  va_list ap;
16836  va_start(ap, zFmt);
16837  if( zFmt ){
16838    z = sqlite3_vmprintf(zFmt, ap);
16839    va_end(ap);
16840  }
16841  sqlite3_free(p->zErrMsg);
16842  p->zErrMsg = z;
16843  p->errCode = errCode;
16844  return errCode;
16845}
16846
16847
16848/*
16849** This function is a no-op if p->errCode is initially other than SQLITE_OK.
16850** In this case it returns NULL.
16851**
16852** Otherwise, an attempt is made to allocate and return a bitmap object
16853** large enough to store a bit for all page numbers between 1 and nPg,
16854** inclusive. The bitmap is initially zeroed.
16855*/
16856static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){
16857  int nElem = (nPg+1+31) / 32;
16858  int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32);
16859  RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte);
16860
16861  if( pRet ){
16862    pRet->nPg = nPg;
16863  }
16864  return pRet;
16865}
16866
16867/*
16868** Free a bitmap object allocated by recoverBitmapAlloc().
16869*/
16870static void recoverBitmapFree(RecoverBitmap *pMap){
16871  sqlite3_free(pMap);
16872}
16873
16874/*
16875** Set the bit associated with page iPg in bitvec pMap.
16876*/
16877static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){
16878  if( iPg<=pMap->nPg ){
16879    int iElem = (iPg / 32);
16880    int iBit = (iPg % 32);
16881    pMap->aElem[iElem] |= (((u32)1) << iBit);
16882  }
16883}
16884
16885/*
16886** Query bitmap object pMap for the state of the bit associated with page
16887** iPg. Return 1 if it is set, or 0 otherwise.
16888*/
16889static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){
16890  int ret = 1;
16891  if( iPg<=pMap->nPg && iPg>0 ){
16892    int iElem = (iPg / 32);
16893    int iBit = (iPg % 32);
16894    ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0;
16895  }
16896  return ret;
16897}
16898
16899/*
16900** Set the recover handle error to the error code and message returned by
16901** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database
16902** handle db.
16903*/
16904static int recoverDbError(sqlite3_recover *p, sqlite3 *db){
16905  return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db));
16906}
16907
16908/*
16909** This function is a no-op if recover handle p already contains an error
16910** (if p->errCode!=SQLITE_OK).
16911**
16912** Otherwise, it attempts to prepare the SQL statement in zSql against
16913** database handle db. If successful, the statement handle is returned.
16914** Or, if an error occurs, NULL is returned and an error left in the
16915** recover handle.
16916*/
16917static sqlite3_stmt *recoverPrepare(
16918  sqlite3_recover *p,
16919  sqlite3 *db,
16920  const char *zSql
16921){
16922  sqlite3_stmt *pStmt = 0;
16923  if( p->errCode==SQLITE_OK ){
16924    if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){
16925      recoverDbError(p, db);
16926    }
16927  }
16928  return pStmt;
16929}
16930
16931/*
16932** This function is a no-op if recover handle p already contains an error
16933** (if p->errCode!=SQLITE_OK).
16934**
16935** Otherwise, argument zFmt is used as a printf() style format string,
16936** along with any trailing arguments, to create an SQL statement. This
16937** SQL statement is prepared against database handle db and, if successful,
16938** the statment handle returned. Or, if an error occurs - either during
16939** the printf() formatting or when preparing the resulting SQL - an
16940** error code and message are left in the recover handle.
16941*/
16942static sqlite3_stmt *recoverPreparePrintf(
16943  sqlite3_recover *p,
16944  sqlite3 *db,
16945  const char *zFmt, ...
16946){
16947  sqlite3_stmt *pStmt = 0;
16948  if( p->errCode==SQLITE_OK ){
16949    va_list ap;
16950    char *z;
16951    va_start(ap, zFmt);
16952    z = sqlite3_vmprintf(zFmt, ap);
16953    va_end(ap);
16954    if( z==0 ){
16955      p->errCode = SQLITE_NOMEM;
16956    }else{
16957      pStmt = recoverPrepare(p, db, z);
16958      sqlite3_free(z);
16959    }
16960  }
16961  return pStmt;
16962}
16963
16964/*
16965** Reset SQLite statement handle pStmt. If the call to sqlite3_reset()
16966** indicates that an error occurred, and there is not already an error
16967** in the recover handle passed as the first argument, set the error
16968** code and error message appropriately.
16969**
16970** This function returns a copy of the statement handle pointer passed
16971** as the second argument.
16972*/
16973static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){
16974  int rc = sqlite3_reset(pStmt);
16975  if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){
16976    recoverDbError(p, sqlite3_db_handle(pStmt));
16977  }
16978  return pStmt;
16979}
16980
16981/*
16982** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset()
16983** indicates that an error occurred, and there is not already an error
16984** in the recover handle passed as the first argument, set the error
16985** code and error message appropriately.
16986*/
16987static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){
16988  sqlite3 *db = sqlite3_db_handle(pStmt);
16989  int rc = sqlite3_finalize(pStmt);
16990  if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){
16991    recoverDbError(p, db);
16992  }
16993}
16994
16995/*
16996** This function is a no-op if recover handle p already contains an error
16997** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this
16998** case.
16999**
17000** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK.
17001** Or, if an error occurs, leave an error code and message in the recover
17002** handle and return a copy of the error code.
17003*/
17004static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){
17005  if( p->errCode==SQLITE_OK ){
17006    int rc = sqlite3_exec(db, zSql, 0, 0, 0);
17007    if( rc ){
17008      recoverDbError(p, db);
17009    }
17010  }
17011  return p->errCode;
17012}
17013
17014/*
17015** Bind the value pVal to parameter iBind of statement pStmt. Leave an
17016** error in the recover handle passed as the first argument if an error
17017** (e.g. an OOM) occurs.
17018*/
17019static void recoverBindValue(
17020  sqlite3_recover *p,
17021  sqlite3_stmt *pStmt,
17022  int iBind,
17023  sqlite3_value *pVal
17024){
17025  if( p->errCode==SQLITE_OK ){
17026    int rc = sqlite3_bind_value(pStmt, iBind, pVal);
17027    if( rc ) recoverError(p, rc, 0);
17028  }
17029}
17030
17031/*
17032** This function is a no-op if recover handle p already contains an error
17033** (if p->errCode!=SQLITE_OK). NULL is returned in this case.
17034**
17035** Otherwise, an attempt is made to interpret zFmt as a printf() style
17036** formatting string and the result of using the trailing arguments for
17037** parameter substitution with it written into a buffer obtained from
17038** sqlite3_malloc(). If successful, a pointer to the buffer is returned.
17039** It is the responsibility of the caller to eventually free the buffer
17040** using sqlite3_free().
17041**
17042** Or, if an error occurs, an error code and message is left in the recover
17043** handle and NULL returned.
17044*/
17045static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){
17046  va_list ap;
17047  char *z;
17048  va_start(ap, zFmt);
17049  z = sqlite3_vmprintf(zFmt, ap);
17050  va_end(ap);
17051  if( p->errCode==SQLITE_OK ){
17052    if( z==0 ) p->errCode = SQLITE_NOMEM;
17053  }else{
17054    sqlite3_free(z);
17055    z = 0;
17056  }
17057  return z;
17058}
17059
17060/*
17061** This function is a no-op if recover handle p already contains an error
17062** (if p->errCode!=SQLITE_OK). Zero is returned in this case.
17063**
17064** Otherwise, execute "PRAGMA page_count" against the input database. If
17065** successful, return the integer result. Or, if an error occurs, leave an
17066** error code and error message in the sqlite3_recover handle and return
17067** zero.
17068*/
17069static i64 recoverPageCount(sqlite3_recover *p){
17070  i64 nPg = 0;
17071  if( p->errCode==SQLITE_OK ){
17072    sqlite3_stmt *pStmt = 0;
17073    pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb);
17074    if( pStmt ){
17075      sqlite3_step(pStmt);
17076      nPg = sqlite3_column_int64(pStmt, 0);
17077    }
17078    recoverFinalize(p, pStmt);
17079  }
17080  return nPg;
17081}
17082
17083/*
17084** Implementation of SQL scalar function "read_i32". The first argument to
17085** this function must be a blob. The second a non-negative integer. This
17086** function reads and returns a 32-bit big-endian integer from byte
17087** offset (4*<arg2>) of the blob.
17088**
17089**     SELECT read_i32(<blob>, <idx>)
17090*/
17091static void recoverReadI32(
17092  sqlite3_context *context,
17093  int argc,
17094  sqlite3_value **argv
17095){
17096  const unsigned char *pBlob;
17097  int nBlob;
17098  int iInt;
17099
17100  assert( argc==2 );
17101  nBlob = sqlite3_value_bytes(argv[0]);
17102  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
17103  iInt = sqlite3_value_int(argv[1]) & 0xFFFF;
17104
17105  if( (iInt+1)*4<=nBlob ){
17106    const unsigned char *a = &pBlob[iInt*4];
17107    i64 iVal = ((i64)a[0]<<24)
17108             + ((i64)a[1]<<16)
17109             + ((i64)a[2]<< 8)
17110             + ((i64)a[3]<< 0);
17111    sqlite3_result_int64(context, iVal);
17112  }
17113}
17114
17115/*
17116** Implementation of SQL scalar function "page_is_used". This function
17117** is used as part of the procedure for locating orphan rows for the
17118** lost-and-found table, and it depends on those routines having populated
17119** the sqlite3_recover.laf.pUsed variable.
17120**
17121** The only argument to this function is a page-number. It returns true
17122** if the page has already been used somehow during data recovery, or false
17123** otherwise.
17124**
17125**     SELECT page_is_used(<pgno>);
17126*/
17127static void recoverPageIsUsed(
17128  sqlite3_context *pCtx,
17129  int nArg,
17130  sqlite3_value **apArg
17131){
17132  sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
17133  i64 pgno = sqlite3_value_int64(apArg[0]);
17134  assert( nArg==1 );
17135  sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno));
17136}
17137
17138/*
17139** The implementation of a user-defined SQL function invoked by the
17140** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages
17141** of the database being recovered.
17142**
17143** This function always takes a single integer argument. If the argument
17144** is zero, then the value returned is the number of pages in the db being
17145** recovered. If the argument is greater than zero, it is a page number.
17146** The value returned in this case is an SQL blob containing the data for
17147** the identified page of the db being recovered. e.g.
17148**
17149**     SELECT getpage(0);       -- return number of pages in db
17150**     SELECT getpage(4);       -- return page 4 of db as a blob of data
17151*/
17152static void recoverGetPage(
17153  sqlite3_context *pCtx,
17154  int nArg,
17155  sqlite3_value **apArg
17156){
17157  sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx);
17158  i64 pgno = sqlite3_value_int64(apArg[0]);
17159  sqlite3_stmt *pStmt = 0;
17160
17161  assert( nArg==1 );
17162  if( pgno==0 ){
17163    i64 nPg = recoverPageCount(p);
17164    sqlite3_result_int64(pCtx, nPg);
17165    return;
17166  }else{
17167    if( p->pGetPage==0 ){
17168      pStmt = p->pGetPage = recoverPreparePrintf(
17169          p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb
17170      );
17171    }else if( p->errCode==SQLITE_OK ){
17172      pStmt = p->pGetPage;
17173    }
17174
17175    if( pStmt ){
17176      sqlite3_bind_int64(pStmt, 1, pgno);
17177      if( SQLITE_ROW==sqlite3_step(pStmt) ){
17178        const u8 *aPg;
17179        int nPg;
17180        assert( p->errCode==SQLITE_OK );
17181        aPg = sqlite3_column_blob(pStmt, 0);
17182        nPg = sqlite3_column_bytes(pStmt, 0);
17183        if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){
17184          aPg = p->pPage1Disk;
17185        }
17186        sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT);
17187      }
17188      recoverReset(p, pStmt);
17189    }
17190  }
17191
17192  if( p->errCode ){
17193    if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1);
17194    sqlite3_result_error_code(pCtx, p->errCode);
17195  }
17196}
17197
17198/*
17199** Find a string that is not found anywhere in z[].  Return a pointer
17200** to that string.
17201**
17202** Try to use zA and zB first.  If both of those are already found in z[]
17203** then make up some string and store it in the buffer zBuf.
17204*/
17205static const char *recoverUnusedString(
17206  const char *z,                    /* Result must not appear anywhere in z */
17207  const char *zA, const char *zB,   /* Try these first */
17208  char *zBuf                        /* Space to store a generated string */
17209){
17210  unsigned i = 0;
17211  if( strstr(z, zA)==0 ) return zA;
17212  if( strstr(z, zB)==0 ) return zB;
17213  do{
17214    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
17215  }while( strstr(z,zBuf)!=0 );
17216  return zBuf;
17217}
17218
17219/*
17220** Implementation of scalar SQL function "escape_crnl".  The argument passed to
17221** this function is the output of built-in function quote(). If the first
17222** character of the input is "'", indicating that the value passed to quote()
17223** was a text value, then this function searches the input for "\n" and "\r"
17224** characters and adds a wrapper similar to the following:
17225**
17226**   replace(replace(<input>, '\n', char(10), '\r', char(13));
17227**
17228** Or, if the first character of the input is not "'", then a copy of the input
17229** is returned.
17230*/
17231static void recoverEscapeCrnl(
17232  sqlite3_context *context,
17233  int argc,
17234  sqlite3_value **argv
17235){
17236  const char *zText = (const char*)sqlite3_value_text(argv[0]);
17237  (void)argc;
17238  if( zText && zText[0]=='\'' ){
17239    int nText = sqlite3_value_bytes(argv[0]);
17240    int i;
17241    char zBuf1[20];
17242    char zBuf2[20];
17243    const char *zNL = 0;
17244    const char *zCR = 0;
17245    int nCR = 0;
17246    int nNL = 0;
17247
17248    for(i=0; zText[i]; i++){
17249      if( zNL==0 && zText[i]=='\n' ){
17250        zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1);
17251        nNL = (int)strlen(zNL);
17252      }
17253      if( zCR==0 && zText[i]=='\r' ){
17254        zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2);
17255        nCR = (int)strlen(zCR);
17256      }
17257    }
17258
17259    if( zNL || zCR ){
17260      int iOut = 0;
17261      i64 nMax = (nNL > nCR) ? nNL : nCR;
17262      i64 nAlloc = nMax * nText + (nMax+64)*2;
17263      char *zOut = (char*)sqlite3_malloc64(nAlloc);
17264      if( zOut==0 ){
17265        sqlite3_result_error_nomem(context);
17266        return;
17267      }
17268
17269      if( zNL && zCR ){
17270        memcpy(&zOut[iOut], "replace(replace(", 16);
17271        iOut += 16;
17272      }else{
17273        memcpy(&zOut[iOut], "replace(", 8);
17274        iOut += 8;
17275      }
17276      for(i=0; zText[i]; i++){
17277        if( zText[i]=='\n' ){
17278          memcpy(&zOut[iOut], zNL, nNL);
17279          iOut += nNL;
17280        }else if( zText[i]=='\r' ){
17281          memcpy(&zOut[iOut], zCR, nCR);
17282          iOut += nCR;
17283        }else{
17284          zOut[iOut] = zText[i];
17285          iOut++;
17286        }
17287      }
17288
17289      if( zNL ){
17290        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
17291        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
17292        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
17293      }
17294      if( zCR ){
17295        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
17296        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
17297        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
17298      }
17299
17300      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
17301      sqlite3_free(zOut);
17302      return;
17303    }
17304  }
17305
17306  sqlite3_result_value(context, argv[0]);
17307}
17308
17309/*
17310** This function is a no-op if recover handle p already contains an error
17311** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17312** this case.
17313**
17314** Otherwise, attempt to populate temporary table "recovery.schema" with the
17315** parts of the database schema that can be extracted from the input database.
17316**
17317** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
17318** and error message are left in the recover handle and a copy of the
17319** error code returned. It is not considered an error if part of all of
17320** the database schema cannot be recovered due to corruption.
17321*/
17322static int recoverCacheSchema(sqlite3_recover *p){
17323  return recoverExec(p, p->dbOut,
17324    "WITH RECURSIVE pages(p) AS ("
17325    "  SELECT 1"
17326    "    UNION"
17327    "  SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p"
17328    ")"
17329    "INSERT INTO recovery.schema SELECT"
17330    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
17331    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
17332    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
17333    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
17334    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
17335    "FROM sqlite_dbdata('getpage()') WHERE pgno IN ("
17336    "  SELECT p FROM pages"
17337    ") GROUP BY pgno, cell"
17338  );
17339}
17340
17341/*
17342** If this recover handle is not in SQL callback mode (i.e. was not created
17343** using sqlite3_recover_init_sql()) of if an error has already occurred,
17344** this function is a no-op. Otherwise, issue a callback with SQL statement
17345** zSql as the parameter.
17346**
17347** If the callback returns non-zero, set the recover handle error code to
17348** the value returned (so that the caller will abandon processing).
17349*/
17350static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){
17351  if( p->errCode==SQLITE_OK && p->xSql ){
17352    int res = p->xSql(p->pSqlCtx, zSql);
17353    if( res ){
17354      recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res);
17355    }
17356  }
17357}
17358
17359/*
17360** Transfer the following settings from the input database to the output
17361** database:
17362**
17363**   + page-size,
17364**   + auto-vacuum settings,
17365**   + database encoding,
17366**   + user-version (PRAGMA user_version), and
17367**   + application-id (PRAGMA application_id), and
17368*/
17369static void recoverTransferSettings(sqlite3_recover *p){
17370  const char *aPragma[] = {
17371    "encoding",
17372    "page_size",
17373    "auto_vacuum",
17374    "user_version",
17375    "application_id"
17376  };
17377  int ii;
17378
17379  /* Truncate the output database to 0 pages in size. This is done by
17380  ** opening a new, empty, temp db, then using the backup API to clobber
17381  ** any existing output db with a copy of it. */
17382  if( p->errCode==SQLITE_OK ){
17383    sqlite3 *db2 = 0;
17384    int rc = sqlite3_open("", &db2);
17385    if( rc!=SQLITE_OK ){
17386      recoverDbError(p, db2);
17387      return;
17388    }
17389
17390    for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){
17391      const char *zPrag = aPragma[ii];
17392      sqlite3_stmt *p1 = 0;
17393      p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag);
17394      if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){
17395        const char *zArg = (const char*)sqlite3_column_text(p1, 0);
17396        char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg);
17397        recoverSqlCallback(p, z2);
17398        recoverExec(p, db2, z2);
17399        sqlite3_free(z2);
17400        if( zArg==0 ){
17401          recoverError(p, SQLITE_NOMEM, 0);
17402        }
17403      }
17404      recoverFinalize(p, p1);
17405    }
17406    recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;");
17407
17408    if( p->errCode==SQLITE_OK ){
17409      sqlite3 *db = p->dbOut;
17410      sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main");
17411      if( pBackup ){
17412        sqlite3_backup_step(pBackup, -1);
17413        p->errCode = sqlite3_backup_finish(pBackup);
17414      }else{
17415        recoverDbError(p, db);
17416      }
17417    }
17418
17419    sqlite3_close(db2);
17420  }
17421}
17422
17423/*
17424** This function is a no-op if recover handle p already contains an error
17425** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in
17426** this case.
17427**
17428** Otherwise, an attempt is made to open the output database, attach
17429** and create the schema of the temporary database used to store
17430** intermediate data, and to register all required user functions and
17431** virtual table modules with the output handle.
17432**
17433** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
17434** and error message are left in the recover handle and a copy of the
17435** error code returned.
17436*/
17437static int recoverOpenOutput(sqlite3_recover *p){
17438  struct Func {
17439    const char *zName;
17440    int nArg;
17441    void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
17442  } aFunc[] = {
17443    { "getpage", 1, recoverGetPage },
17444    { "page_is_used", 1, recoverPageIsUsed },
17445    { "read_i32", 2, recoverReadI32 },
17446    { "escape_crnl", 1, recoverEscapeCrnl },
17447  };
17448
17449  const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
17450  sqlite3 *db = 0;                /* New database handle */
17451  int ii;                         /* For iterating through aFunc[] */
17452
17453  assert( p->dbOut==0 );
17454
17455  if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){
17456    recoverDbError(p, db);
17457  }
17458
17459  /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules.
17460  ** These two are registered with the output database handle - this
17461  ** module depends on the input handle supporting the sqlite_dbpage
17462  ** virtual table only.  */
17463  if( p->errCode==SQLITE_OK ){
17464    p->errCode = sqlite3_dbdata_init(db, 0, 0);
17465  }
17466
17467  /* Register the custom user-functions with the output handle. */
17468  for(ii=0;
17469      p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0]));
17470      ii++){
17471    p->errCode = sqlite3_create_function(db, aFunc[ii].zName,
17472        aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0
17473    );
17474  }
17475
17476  p->dbOut = db;
17477  return p->errCode;
17478}
17479
17480/*
17481** Attach the auxiliary database 'recovery' to the output database handle.
17482** This temporary database is used during the recovery process and then
17483** discarded.
17484*/
17485static void recoverOpenRecovery(sqlite3_recover *p){
17486  char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb);
17487  recoverExec(p, p->dbOut, zSql);
17488  recoverExec(p, p->dbOut,
17489      "PRAGMA writable_schema = 1;"
17490      "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);"
17491      "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
17492  );
17493  sqlite3_free(zSql);
17494}
17495
17496
17497/*
17498** This function is a no-op if recover handle p already contains an error
17499** (if p->errCode!=SQLITE_OK).
17500**
17501** Otherwise, argument zName must be the name of a table that has just been
17502** created in the output database. This function queries the output db
17503** for the schema of said table, and creates a RecoverTable object to
17504** store the schema in memory. The new RecoverTable object is linked into
17505** the list at sqlite3_recover.pTblList.
17506**
17507** Parameter iRoot must be the root page of table zName in the INPUT
17508** database.
17509*/
17510static void recoverAddTable(
17511  sqlite3_recover *p,
17512  const char *zName,              /* Name of table created in output db */
17513  i64 iRoot                       /* Root page of same table in INPUT db */
17514){
17515  sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut,
17516      "PRAGMA table_xinfo(%Q)", zName
17517  );
17518
17519  if( pStmt ){
17520    int iPk = -1;
17521    int iBind = 1;
17522    RecoverTable *pNew = 0;
17523    int nCol = 0;
17524    int nName = recoverStrlen(zName);
17525    int nByte = 0;
17526    while( sqlite3_step(pStmt)==SQLITE_ROW ){
17527      nCol++;
17528      nByte += (sqlite3_column_bytes(pStmt, 1)+1);
17529    }
17530    nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1;
17531    recoverReset(p, pStmt);
17532
17533    pNew = recoverMalloc(p, nByte);
17534    if( pNew ){
17535      int i = 0;
17536      int iField = 0;
17537      char *csr = 0;
17538      pNew->aCol = (RecoverColumn*)&pNew[1];
17539      pNew->zTab = csr = (char*)&pNew->aCol[nCol];
17540      pNew->nCol = nCol;
17541      pNew->iRoot = iRoot;
17542      memcpy(csr, zName, nName);
17543      csr += nName+1;
17544
17545      for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){
17546        int iPKF = sqlite3_column_int(pStmt, 5);
17547        int n = sqlite3_column_bytes(pStmt, 1);
17548        const char *z = (const char*)sqlite3_column_text(pStmt, 1);
17549        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
17550        int eHidden = sqlite3_column_int(pStmt, 6);
17551
17552        if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i;
17553        if( iPKF>1 ) iPk = -2;
17554        pNew->aCol[i].zCol = csr;
17555        pNew->aCol[i].eHidden = eHidden;
17556        if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){
17557          pNew->aCol[i].iField = -1;
17558        }else{
17559          pNew->aCol[i].iField = iField++;
17560        }
17561        if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
17562         && eHidden!=RECOVER_EHIDDEN_STORED
17563        ){
17564          pNew->aCol[i].iBind = iBind++;
17565        }
17566        memcpy(csr, z, n);
17567        csr += (n+1);
17568      }
17569
17570      pNew->pNext = p->pTblList;
17571      p->pTblList = pNew;
17572      pNew->bIntkey = 1;
17573    }
17574
17575    recoverFinalize(p, pStmt);
17576
17577    pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName);
17578    while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
17579      int iField = sqlite3_column_int(pStmt, 0);
17580      int iCol = sqlite3_column_int(pStmt, 1);
17581
17582      assert( iCol<pNew->nCol );
17583      pNew->aCol[iCol].iField = iField;
17584
17585      pNew->bIntkey = 0;
17586      iPk = -2;
17587    }
17588    recoverFinalize(p, pStmt);
17589
17590    if( p->errCode==SQLITE_OK ){
17591      if( iPk>=0 ){
17592        pNew->aCol[iPk].bIPK = 1;
17593      }else if( pNew->bIntkey ){
17594        pNew->iRowidBind = iBind++;
17595      }
17596    }
17597  }
17598}
17599
17600/*
17601** This function is called after recoverCacheSchema() has cached those parts
17602** of the input database schema that could be recovered in temporary table
17603** "recovery.schema". This function creates in the output database copies
17604** of all parts of that schema that must be created before the tables can
17605** be populated. Specifically, this means:
17606**
17607**     * all tables that are not VIRTUAL, and
17608**     * UNIQUE indexes.
17609**
17610** If the recovery handle uses SQL callbacks, then callbacks containing
17611** the associated "CREATE TABLE" and "CREATE INDEX" statements are made.
17612**
17613** Additionally, records are added to the sqlite_schema table of the
17614** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE
17615** records are written directly to sqlite_schema, not actually executed.
17616** If the handle is in SQL callback mode, then callbacks are invoked
17617** with equivalent SQL statements.
17618*/
17619static int recoverWriteSchema1(sqlite3_recover *p){
17620  sqlite3_stmt *pSelect = 0;
17621  sqlite3_stmt *pTblname = 0;
17622
17623  pSelect = recoverPrepare(p, p->dbOut,
17624      "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS ("
17625      "  SELECT rootpage, name, sql, "
17626      "    type='table', "
17627      "    sql LIKE 'create virtual%',"
17628      "    (type='index' AND (sql LIKE '%unique%' OR ?1))"
17629      "  FROM recovery.schema"
17630      ")"
17631      "SELECT rootpage, tbl, isVirtual, name, sql"
17632      " FROM dbschema "
17633      "  WHERE tbl OR isIndex"
17634      "  ORDER BY tbl DESC, name=='sqlite_sequence' DESC"
17635  );
17636
17637  pTblname = recoverPrepare(p, p->dbOut,
17638      "SELECT name FROM sqlite_schema "
17639      "WHERE type='table' ORDER BY rowid DESC LIMIT 1"
17640  );
17641
17642  if( pSelect ){
17643    sqlite3_bind_int(pSelect, 1, p->bSlowIndexes);
17644    while( sqlite3_step(pSelect)==SQLITE_ROW ){
17645      i64 iRoot = sqlite3_column_int64(pSelect, 0);
17646      int bTable = sqlite3_column_int(pSelect, 1);
17647      int bVirtual = sqlite3_column_int(pSelect, 2);
17648      const char *zName = (const char*)sqlite3_column_text(pSelect, 3);
17649      const char *zSql = (const char*)sqlite3_column_text(pSelect, 4);
17650      char *zFree = 0;
17651      int rc = SQLITE_OK;
17652
17653      if( bVirtual ){
17654        zSql = (const char*)(zFree = recoverMPrintf(p,
17655            "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
17656            zName, zName, zSql
17657        ));
17658      }
17659      rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
17660      if( rc==SQLITE_OK ){
17661        recoverSqlCallback(p, zSql);
17662        if( bTable && !bVirtual ){
17663          if( SQLITE_ROW==sqlite3_step(pTblname) ){
17664            const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0);
17665            if( zTbl ) recoverAddTable(p, zTbl, iRoot);
17666          }
17667          recoverReset(p, pTblname);
17668        }
17669      }else if( rc!=SQLITE_ERROR ){
17670        recoverDbError(p, p->dbOut);
17671      }
17672      sqlite3_free(zFree);
17673    }
17674  }
17675  recoverFinalize(p, pSelect);
17676  recoverFinalize(p, pTblname);
17677
17678  return p->errCode;
17679}
17680
17681/*
17682** This function is called after the output database has been populated. It
17683** adds all recovered schema elements that were not created in the output
17684** database by recoverWriteSchema1() - everything except for tables and
17685** UNIQUE indexes. Specifically:
17686**
17687**     * views,
17688**     * triggers,
17689**     * non-UNIQUE indexes.
17690**
17691** If the recover handle is in SQL callback mode, then equivalent callbacks
17692** are issued to create the schema elements.
17693*/
17694static int recoverWriteSchema2(sqlite3_recover *p){
17695  sqlite3_stmt *pSelect = 0;
17696
17697  pSelect = recoverPrepare(p, p->dbOut,
17698      p->bSlowIndexes ?
17699      "SELECT rootpage, sql FROM recovery.schema "
17700      "  WHERE type!='table' AND type!='index'"
17701      :
17702      "SELECT rootpage, sql FROM recovery.schema "
17703      "  WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')"
17704  );
17705
17706  if( pSelect ){
17707    while( sqlite3_step(pSelect)==SQLITE_ROW ){
17708      const char *zSql = (const char*)sqlite3_column_text(pSelect, 1);
17709      int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0);
17710      if( rc==SQLITE_OK ){
17711        recoverSqlCallback(p, zSql);
17712      }else if( rc!=SQLITE_ERROR ){
17713        recoverDbError(p, p->dbOut);
17714      }
17715    }
17716  }
17717  recoverFinalize(p, pSelect);
17718
17719  return p->errCode;
17720}
17721
17722/*
17723** This function is a no-op if recover handle p already contains an error
17724** (if p->errCode!=SQLITE_OK). In this case it returns NULL.
17725**
17726** Otherwise, if the recover handle is configured to create an output
17727** database (was created by sqlite3_recover_init()), then this function
17728** prepares and returns an SQL statement to INSERT a new record into table
17729** pTab, assuming the first nField fields of a record extracted from disk
17730** are valid.
17731**
17732** For example, if table pTab is:
17733**
17734**     CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e);
17735**
17736** And nField is 4, then the SQL statement prepared and returned is:
17737**
17738**     INSERT INTO (a, c, d) VALUES (?1, ?2, ?3);
17739**
17740** In this case even though 4 values were extracted from the input db,
17741** only 3 are written to the output, as the generated STORED column
17742** cannot be written.
17743**
17744** If the recover handle is in SQL callback mode, then the SQL statement
17745** prepared is such that evaluating it returns a single row containing
17746** a single text value - itself an SQL statement similar to the above,
17747** except with SQL literals in place of the variables. For example:
17748**
17749**     SELECT 'INSERT INTO (a, c, d) VALUES ('
17750**          || quote(?1) || ', '
17751**          || quote(?2) || ', '
17752**          || quote(?3) || ')';
17753**
17754** In either case, it is the responsibility of the caller to eventually
17755** free the statement handle using sqlite3_finalize().
17756*/
17757static sqlite3_stmt *recoverInsertStmt(
17758  sqlite3_recover *p,
17759  RecoverTable *pTab,
17760  int nField
17761){
17762  sqlite3_stmt *pRet = 0;
17763  const char *zSep = "";
17764  const char *zSqlSep = "";
17765  char *zSql = 0;
17766  char *zFinal = 0;
17767  char *zBind = 0;
17768  int ii;
17769  int bSql = p->xSql ? 1 : 0;
17770
17771  if( nField<=0 ) return 0;
17772
17773  assert( nField<=pTab->nCol );
17774
17775  zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab);
17776
17777  if( pTab->iRowidBind ){
17778    assert( pTab->bIntkey );
17779    zSql = recoverMPrintf(p, "%z_rowid_", zSql);
17780    if( bSql ){
17781      zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind);
17782    }else{
17783      zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind);
17784    }
17785    zSqlSep = "||', '||";
17786    zSep = ", ";
17787  }
17788
17789  for(ii=0; ii<nField; ii++){
17790    int eHidden = pTab->aCol[ii].eHidden;
17791    if( eHidden!=RECOVER_EHIDDEN_VIRTUAL
17792     && eHidden!=RECOVER_EHIDDEN_STORED
17793    ){
17794      assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 );
17795      zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol);
17796
17797      if( bSql ){
17798        zBind = recoverMPrintf(p,
17799            "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind
17800        );
17801        zSqlSep = "||', '||";
17802      }else{
17803        zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind);
17804      }
17805      zSep = ", ";
17806    }
17807  }
17808
17809  if( bSql ){
17810    zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'",
17811        zSql, zBind
17812    );
17813  }else{
17814    zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind);
17815  }
17816
17817  pRet = recoverPrepare(p, p->dbOut, zFinal);
17818  sqlite3_free(zSql);
17819  sqlite3_free(zBind);
17820  sqlite3_free(zFinal);
17821
17822  return pRet;
17823}
17824
17825
17826/*
17827** Search the list of RecoverTable objects at p->pTblList for one that
17828** has root page iRoot in the input database. If such an object is found,
17829** return a pointer to it. Otherwise, return NULL.
17830*/
17831static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){
17832  RecoverTable *pRet = 0;
17833  for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext);
17834  return pRet;
17835}
17836
17837/*
17838** This function attempts to create a lost and found table within the
17839** output db. If successful, it returns a pointer to a buffer containing
17840** the name of the new table. It is the responsibility of the caller to
17841** eventually free this buffer using sqlite3_free().
17842**
17843** If an error occurs, NULL is returned and an error code and error
17844** message left in the recover handle.
17845*/
17846static char *recoverLostAndFoundCreate(
17847  sqlite3_recover *p,             /* Recover object */
17848  int nField                      /* Number of column fields in new table */
17849){
17850  char *zTbl = 0;
17851  sqlite3_stmt *pProbe = 0;
17852  int ii = 0;
17853
17854  pProbe = recoverPrepare(p, p->dbOut,
17855    "SELECT 1 FROM sqlite_schema WHERE name=?"
17856  );
17857  for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){
17858    int bFail = 0;
17859    if( ii<0 ){
17860      zTbl = recoverMPrintf(p, "%s", p->zLostAndFound);
17861    }else{
17862      zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii);
17863    }
17864
17865    if( p->errCode==SQLITE_OK ){
17866      sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC);
17867      if( SQLITE_ROW==sqlite3_step(pProbe) ){
17868        bFail = 1;
17869      }
17870      recoverReset(p, pProbe);
17871    }
17872
17873    if( bFail ){
17874      sqlite3_clear_bindings(pProbe);
17875      sqlite3_free(zTbl);
17876      zTbl = 0;
17877    }
17878  }
17879  recoverFinalize(p, pProbe);
17880
17881  if( zTbl ){
17882    const char *zSep = 0;
17883    char *zField = 0;
17884    char *zSql = 0;
17885
17886    zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, ";
17887    for(ii=0; p->errCode==SQLITE_OK && ii<nField; ii++){
17888      zField = recoverMPrintf(p, "%z%sc%d", zField, zSep, ii);
17889      zSep = ", ";
17890    }
17891
17892    zSql = recoverMPrintf(p, "CREATE TABLE %s(%s)", zTbl, zField);
17893    sqlite3_free(zField);
17894
17895    recoverExec(p, p->dbOut, zSql);
17896    recoverSqlCallback(p, zSql);
17897    sqlite3_free(zSql);
17898  }else if( p->errCode==SQLITE_OK ){
17899    recoverError(
17900        p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound
17901    );
17902  }
17903
17904  return zTbl;
17905}
17906
17907/*
17908** Synthesize and prepare an INSERT statement to write to the lost_and_found
17909** table in the output database. The name of the table is zTab, and it has
17910** nField c* fields.
17911*/
17912static sqlite3_stmt *recoverLostAndFoundInsert(
17913  sqlite3_recover *p,
17914  const char *zTab,
17915  int nField
17916){
17917  int nTotal = nField + 4;
17918  int ii;
17919  char *zBind = 0;
17920  sqlite3_stmt *pRet = 0;
17921
17922  if( p->xSql==0 ){
17923    for(ii=0; ii<nTotal; ii++){
17924      zBind = recoverMPrintf(p, "%z%s?", zBind, zBind?", ":"", ii);
17925    }
17926    pRet = recoverPreparePrintf(
17927        p, p->dbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind
17928    );
17929  }else{
17930    const char *zSep = "";
17931    for(ii=0; ii<nTotal; ii++){
17932      zBind = recoverMPrintf(p, "%z%squote(?)", zBind, zSep);
17933      zSep = "|| ', ' ||";
17934    }
17935    pRet = recoverPreparePrintf(
17936        p, p->dbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind
17937    );
17938  }
17939
17940  sqlite3_free(zBind);
17941  return pRet;
17942}
17943
17944/*
17945** Input database page iPg contains data that will be written to the
17946** lost-and-found table of the output database. This function attempts
17947** to identify the root page of the tree that page iPg belonged to.
17948** If successful, it sets output variable (*piRoot) to the page number
17949** of the root page and returns SQLITE_OK. Otherwise, if an error occurs,
17950** an SQLite error code is returned and the final value of *piRoot
17951** undefined.
17952*/
17953static int recoverLostAndFoundFindRoot(
17954  sqlite3_recover *p,
17955  i64 iPg,
17956  i64 *piRoot
17957){
17958  RecoverStateLAF *pLaf = &p->laf;
17959
17960  if( pLaf->pFindRoot==0 ){
17961    pLaf->pFindRoot = recoverPrepare(p, p->dbOut,
17962        "WITH RECURSIVE p(pgno) AS ("
17963        "  SELECT ?"
17964        "    UNION"
17965        "  SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno"
17966        ") "
17967        "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno "
17968        "    AND m.parent IS NULL"
17969    );
17970  }
17971  if( p->errCode==SQLITE_OK ){
17972    sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg);
17973    if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){
17974      *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0);
17975    }else{
17976      *piRoot = iPg;
17977    }
17978    recoverReset(p, pLaf->pFindRoot);
17979  }
17980  return p->errCode;
17981}
17982
17983/*
17984** Recover data from page iPage of the input database and write it to
17985** the lost-and-found table in the output database.
17986*/
17987static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){
17988  RecoverStateLAF *pLaf = &p->laf;
17989  sqlite3_value **apVal = pLaf->apVal;
17990  sqlite3_stmt *pPageData = pLaf->pPageData;
17991  sqlite3_stmt *pInsert = pLaf->pInsert;
17992
17993  int nVal = -1;
17994  int iPrevCell = 0;
17995  i64 iRoot = 0;
17996  int bHaveRowid = 0;
17997  i64 iRowid = 0;
17998  int ii = 0;
17999
18000  if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return;
18001  sqlite3_bind_int64(pPageData, 1, iPage);
18002  while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){
18003    int iCell = sqlite3_column_int64(pPageData, 0);
18004    int iField = sqlite3_column_int64(pPageData, 1);
18005
18006    if( iPrevCell!=iCell && nVal>=0 ){
18007      /* Insert the new row */
18008      sqlite3_bind_int64(pInsert, 1, iRoot);      /* rootpgno */
18009      sqlite3_bind_int64(pInsert, 2, iPage);      /* pgno */
18010      sqlite3_bind_int(pInsert, 3, nVal);         /* nfield */
18011      if( bHaveRowid ){
18012        sqlite3_bind_int64(pInsert, 4, iRowid);   /* id */
18013      }
18014      for(ii=0; ii<nVal; ii++){
18015        recoverBindValue(p, pInsert, 5+ii, apVal[ii]);
18016      }
18017      if( sqlite3_step(pInsert)==SQLITE_ROW ){
18018        recoverSqlCallback(p, (const char*)sqlite3_column_text(pInsert, 0));
18019      }
18020      recoverReset(p, pInsert);
18021
18022      /* Discard the accumulated row data */
18023      for(ii=0; ii<nVal; ii++){
18024        sqlite3_value_free(apVal[ii]);
18025        apVal[ii] = 0;
18026      }
18027      sqlite3_clear_bindings(pInsert);
18028      bHaveRowid = 0;
18029      nVal = -1;
18030    }
18031
18032    if( iCell<0 ) break;
18033
18034    if( iField<0 ){
18035      assert( nVal==-1 );
18036      iRowid = sqlite3_column_int64(pPageData, 2);
18037      bHaveRowid = 1;
18038      nVal = 0;
18039    }else if( iField<pLaf->nMaxField ){
18040      sqlite3_value *pVal = sqlite3_column_value(pPageData, 2);
18041      apVal[iField] = sqlite3_value_dup(pVal);
18042      assert( iField==nVal || (nVal==-1 && iField==0) );
18043      nVal = iField+1;
18044      if( apVal[iField]==0 ){
18045        recoverError(p, SQLITE_NOMEM, 0);
18046      }
18047    }
18048
18049    iPrevCell = iCell;
18050  }
18051  recoverReset(p, pPageData);
18052
18053  for(ii=0; ii<nVal; ii++){
18054    sqlite3_value_free(apVal[ii]);
18055    apVal[ii] = 0;
18056  }
18057}
18058
18059/*
18060** Perform one step (sqlite3_recover_step()) of work for the connection
18061** passed as the only argument, which is guaranteed to be in
18062** RECOVER_STATE_LOSTANDFOUND3 state - during which the lost-and-found
18063** table of the output database is populated with recovered data that can
18064** not be assigned to any recovered schema object.
18065*/
18066static int recoverLostAndFound3Step(sqlite3_recover *p){
18067  RecoverStateLAF *pLaf = &p->laf;
18068  if( p->errCode==SQLITE_OK ){
18069    if( pLaf->pInsert==0 ){
18070      return SQLITE_DONE;
18071    }else{
18072      if( p->errCode==SQLITE_OK ){
18073        int res = sqlite3_step(pLaf->pAllPage);
18074        if( res==SQLITE_ROW ){
18075          i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0);
18076          if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){
18077            recoverLostAndFoundOnePage(p, iPage);
18078          }
18079        }else{
18080          recoverReset(p, pLaf->pAllPage);
18081          return SQLITE_DONE;
18082        }
18083      }
18084    }
18085  }
18086  return SQLITE_OK;
18087}
18088
18089/*
18090** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3
18091** state - during which the lost-and-found table of the output database
18092** is populated with recovered data that can not be assigned to any
18093** recovered schema object.
18094*/
18095static void recoverLostAndFound3Init(sqlite3_recover *p){
18096  RecoverStateLAF *pLaf = &p->laf;
18097
18098  if( pLaf->nMaxField>0 ){
18099    char *zTab = 0;               /* Name of lost_and_found table */
18100
18101    zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField);
18102    pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField);
18103    sqlite3_free(zTab);
18104
18105    pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut,
18106        "WITH RECURSIVE seq(ii) AS ("
18107        "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
18108        ")"
18109        "SELECT ii FROM seq" , p->laf.nPg
18110    );
18111    pLaf->pPageData = recoverPrepare(p, p->dbOut,
18112        "SELECT cell, field, value "
18113        "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? "
18114        "UNION ALL "
18115        "SELECT -1, -1, -1"
18116    );
18117
18118    pLaf->apVal = (sqlite3_value**)recoverMalloc(p,
18119        pLaf->nMaxField*sizeof(sqlite3_value*)
18120    );
18121  }
18122}
18123
18124/*
18125** Initialize resources required in RECOVER_STATE_WRITING state - during which
18126** tables recovered from the schema of the input database are populated with
18127** recovered data.
18128*/
18129static int recoverWriteDataInit(sqlite3_recover *p){
18130  RecoverStateW1 *p1 = &p->w1;
18131  RecoverTable *pTbl = 0;
18132  int nByte = 0;
18133
18134  /* Figure out the maximum number of columns for any table in the schema */
18135  assert( p1->nMax==0 );
18136  for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){
18137    if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol;
18138  }
18139
18140  /* Allocate an array of (sqlite3_value*) in which to accumulate the values
18141  ** that will be written to the output database in a single row. */
18142  nByte = sizeof(sqlite3_value*) * (p1->nMax+1);
18143  p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte);
18144  if( p1->apVal==0 ) return p->errCode;
18145
18146  /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT
18147  ** to loop through cells that appear to belong to a single table (pSel). */
18148  p1->pTbls = recoverPrepare(p, p->dbOut,
18149      "SELECT rootpage FROM recovery.schema "
18150      "  WHERE type='table' AND (sql NOT LIKE 'create virtual%')"
18151      "  ORDER BY (tbl_name='sqlite_sequence') ASC"
18152  );
18153  p1->pSel = recoverPrepare(p, p->dbOut,
18154      "WITH RECURSIVE pages(page) AS ("
18155      "  SELECT ?1"
18156      "    UNION"
18157      "  SELECT child FROM sqlite_dbptr('getpage()'), pages "
18158      "    WHERE pgno=page"
18159      ") "
18160      "SELECT page, cell, field, value "
18161      "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno "
18162      "UNION ALL "
18163      "SELECT 0, 0, 0, 0"
18164  );
18165
18166  return p->errCode;
18167}
18168
18169/*
18170** Clean up resources allocated by recoverWriteDataInit() (stuff in
18171** sqlite3_recover.w1).
18172*/
18173static void recoverWriteDataCleanup(sqlite3_recover *p){
18174  RecoverStateW1 *p1 = &p->w1;
18175  int ii;
18176  for(ii=0; ii<p1->nVal; ii++){
18177    sqlite3_value_free(p1->apVal[ii]);
18178  }
18179  sqlite3_free(p1->apVal);
18180  recoverFinalize(p, p1->pInsert);
18181  recoverFinalize(p, p1->pTbls);
18182  recoverFinalize(p, p1->pSel);
18183  memset(p1, 0, sizeof(*p1));
18184}
18185
18186/*
18187** Perform one step (sqlite3_recover_step()) of work for the connection
18188** passed as the only argument, which is guaranteed to be in
18189** RECOVER_STATE_WRITING state - during which tables recovered from the
18190** schema of the input database are populated with recovered data.
18191*/
18192static int recoverWriteDataStep(sqlite3_recover *p){
18193  RecoverStateW1 *p1 = &p->w1;
18194  sqlite3_stmt *pSel = p1->pSel;
18195  sqlite3_value **apVal = p1->apVal;
18196
18197  if( p->errCode==SQLITE_OK && p1->pTab==0 ){
18198    if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){
18199      i64 iRoot = sqlite3_column_int64(p1->pTbls, 0);
18200      p1->pTab = recoverFindTable(p, iRoot);
18201
18202      recoverFinalize(p, p1->pInsert);
18203      p1->pInsert = 0;
18204
18205      /* If this table is unknown, return early. The caller will invoke this
18206      ** function again and it will move on to the next table.  */
18207      if( p1->pTab==0 ) return p->errCode;
18208
18209      /* If this is the sqlite_sequence table, delete any rows added by
18210      ** earlier INSERT statements on tables with AUTOINCREMENT primary
18211      ** keys before recovering its contents. The p1->pTbls SELECT statement
18212      ** is rigged to deliver "sqlite_sequence" last of all, so we don't
18213      ** worry about it being modified after it is recovered. */
18214      if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){
18215        recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence");
18216        recoverSqlCallback(p, "DELETE FROM sqlite_sequence");
18217      }
18218
18219      /* Bind the root page of this table within the original database to
18220      ** SELECT statement p1->pSel. The SELECT statement will then iterate
18221      ** through cells that look like they belong to table pTab.  */
18222      sqlite3_bind_int64(pSel, 1, iRoot);
18223
18224      p1->nVal = 0;
18225      p1->bHaveRowid = 0;
18226      p1->iPrevPage = -1;
18227      p1->iPrevCell = -1;
18228    }else{
18229      return SQLITE_DONE;
18230    }
18231  }
18232  assert( p->errCode!=SQLITE_OK || p1->pTab );
18233
18234  if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){
18235    RecoverTable *pTab = p1->pTab;
18236
18237    i64 iPage = sqlite3_column_int64(pSel, 0);
18238    int iCell = sqlite3_column_int(pSel, 1);
18239    int iField = sqlite3_column_int(pSel, 2);
18240    sqlite3_value *pVal = sqlite3_column_value(pSel, 3);
18241    int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell);
18242
18243    assert( bNewCell==0 || (iField==-1 || iField==0) );
18244    assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol );
18245
18246    if( bNewCell ){
18247      int ii = 0;
18248      if( p1->nVal>=0 ){
18249        if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){
18250          recoverFinalize(p, p1->pInsert);
18251          p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal);
18252          p1->nInsert = p1->nVal;
18253        }
18254        if( p1->nVal>0 ){
18255          sqlite3_stmt *pInsert = p1->pInsert;
18256          for(ii=0; ii<pTab->nCol; ii++){
18257            RecoverColumn *pCol = &pTab->aCol[ii];
18258            int iBind = pCol->iBind;
18259            if( iBind>0 ){
18260              if( pCol->bIPK ){
18261                sqlite3_bind_int64(pInsert, iBind, p1->iRowid);
18262              }else if( pCol->iField<p1->nVal ){
18263                recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]);
18264              }
18265            }
18266          }
18267          if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){
18268            sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid);
18269          }
18270          if( SQLITE_ROW==sqlite3_step(pInsert) ){
18271            const char *z = (const char*)sqlite3_column_text(pInsert, 0);
18272            recoverSqlCallback(p, z);
18273          }
18274          recoverReset(p, pInsert);
18275          assert( p->errCode || pInsert );
18276          if( pInsert ) sqlite3_clear_bindings(pInsert);
18277        }
18278      }
18279
18280      for(ii=0; ii<p1->nVal; ii++){
18281        sqlite3_value_free(apVal[ii]);
18282        apVal[ii] = 0;
18283      }
18284      p1->nVal = -1;
18285      p1->bHaveRowid = 0;
18286    }
18287
18288    if( iPage!=0 ){
18289      if( iField<0 ){
18290        p1->iRowid = sqlite3_column_int64(pSel, 3);
18291        assert( p1->nVal==-1 );
18292        p1->nVal = 0;
18293        p1->bHaveRowid = 1;
18294      }else if( iField<pTab->nCol ){
18295        assert( apVal[iField]==0 );
18296        apVal[iField] = sqlite3_value_dup( pVal );
18297        if( apVal[iField]==0 ){
18298          recoverError(p, SQLITE_NOMEM, 0);
18299        }
18300        p1->nVal = iField+1;
18301      }
18302      p1->iPrevCell = iCell;
18303      p1->iPrevPage = iPage;
18304    }
18305  }else{
18306    recoverReset(p, pSel);
18307    p1->pTab = 0;
18308  }
18309
18310  return p->errCode;
18311}
18312
18313/*
18314** Initialize resources required by sqlite3_recover_step() in
18315** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18316** already allocated to a recovered schema element is determined.
18317*/
18318static void recoverLostAndFound1Init(sqlite3_recover *p){
18319  RecoverStateLAF *pLaf = &p->laf;
18320  sqlite3_stmt *pStmt = 0;
18321
18322  assert( p->laf.pUsed==0 );
18323  pLaf->nPg = recoverPageCount(p);
18324  pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg);
18325
18326  /* Prepare a statement to iterate through all pages that are part of any tree
18327  ** in the recoverable part of the input database schema to the bitmap. And,
18328  ** if !p->bFreelistCorrupt, add all pages that appear to be part of the
18329  ** freelist.  */
18330  pStmt = recoverPrepare(
18331      p, p->dbOut,
18332      "WITH trunk(pgno) AS ("
18333      "  SELECT read_i32(getpage(1), 8) AS x WHERE x>0"
18334      "    UNION"
18335      "  SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0"
18336      "),"
18337      "trunkdata(pgno, data) AS ("
18338      "  SELECT pgno, getpage(pgno) FROM trunk"
18339      "),"
18340      "freelist(data, n, freepgno) AS ("
18341      "  SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata"
18342      "    UNION ALL"
18343      "  SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0"
18344      "),"
18345      ""
18346      "roots(r) AS ("
18347      "  SELECT 1 UNION ALL"
18348      "  SELECT rootpage FROM recovery.schema WHERE rootpage>0"
18349      "),"
18350      "used(page) AS ("
18351      "  SELECT r FROM roots"
18352      "    UNION"
18353      "  SELECT child FROM sqlite_dbptr('getpage()'), used "
18354      "    WHERE pgno=page"
18355      ") "
18356      "SELECT page FROM used"
18357      " UNION ALL "
18358      "SELECT freepgno FROM freelist WHERE NOT ?"
18359  );
18360  if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt);
18361  pLaf->pUsedPages = pStmt;
18362}
18363
18364/*
18365** Perform one step (sqlite3_recover_step()) of work for the connection
18366** passed as the only argument, which is guaranteed to be in
18367** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not
18368** already allocated to a recovered schema element is determined.
18369*/
18370static int recoverLostAndFound1Step(sqlite3_recover *p){
18371  RecoverStateLAF *pLaf = &p->laf;
18372  int rc = p->errCode;
18373  if( rc==SQLITE_OK ){
18374    rc = sqlite3_step(pLaf->pUsedPages);
18375    if( rc==SQLITE_ROW ){
18376      i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0);
18377      recoverBitmapSet(pLaf->pUsed, iPg);
18378      rc = SQLITE_OK;
18379    }else{
18380      recoverFinalize(p, pLaf->pUsedPages);
18381      pLaf->pUsedPages = 0;
18382    }
18383  }
18384  return rc;
18385}
18386
18387/*
18388** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2
18389** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1
18390** are sorted into sets that likely belonged to the same database tree.
18391*/
18392static void recoverLostAndFound2Init(sqlite3_recover *p){
18393  RecoverStateLAF *pLaf = &p->laf;
18394
18395  assert( p->laf.pAllAndParent==0 );
18396  assert( p->laf.pMapInsert==0 );
18397  assert( p->laf.pMaxField==0 );
18398  assert( p->laf.nMaxField==0 );
18399
18400  pLaf->pMapInsert = recoverPrepare(p, p->dbOut,
18401      "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)"
18402  );
18403  pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut,
18404      "WITH RECURSIVE seq(ii) AS ("
18405      "  SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld"
18406      ")"
18407      "SELECT pgno, child FROM sqlite_dbptr('getpage()') "
18408      " UNION ALL "
18409      "SELECT NULL, ii FROM seq", p->laf.nPg
18410  );
18411  pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut,
18412      "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?"
18413  );
18414}
18415
18416/*
18417** Perform one step (sqlite3_recover_step()) of work for the connection
18418** passed as the only argument, which is guaranteed to be in
18419** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified
18420** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged
18421** to the same database tree.
18422*/
18423static int recoverLostAndFound2Step(sqlite3_recover *p){
18424  RecoverStateLAF *pLaf = &p->laf;
18425  if( p->errCode==SQLITE_OK ){
18426    int res = sqlite3_step(pLaf->pAllAndParent);
18427    if( res==SQLITE_ROW ){
18428      i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1);
18429      if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){
18430        sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild);
18431        sqlite3_bind_value(pLaf->pMapInsert, 2,
18432            sqlite3_column_value(pLaf->pAllAndParent, 0)
18433        );
18434        sqlite3_step(pLaf->pMapInsert);
18435        recoverReset(p, pLaf->pMapInsert);
18436        sqlite3_bind_int64(pLaf->pMaxField, 1, iChild);
18437        if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){
18438          int nMax = sqlite3_column_int(pLaf->pMaxField, 0);
18439          if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax;
18440        }
18441        recoverReset(p, pLaf->pMaxField);
18442      }
18443    }else{
18444      recoverFinalize(p, pLaf->pAllAndParent);
18445      pLaf->pAllAndParent =0;
18446      return SQLITE_DONE;
18447    }
18448  }
18449  return p->errCode;
18450}
18451
18452/*
18453** Free all resources allocated as part of sqlite3_recover_step() calls
18454** in one of the RECOVER_STATE_LOSTANDFOUND[123] states.
18455*/
18456static void recoverLostAndFoundCleanup(sqlite3_recover *p){
18457  recoverBitmapFree(p->laf.pUsed);
18458  p->laf.pUsed = 0;
18459  sqlite3_finalize(p->laf.pUsedPages);
18460  sqlite3_finalize(p->laf.pAllAndParent);
18461  sqlite3_finalize(p->laf.pMapInsert);
18462  sqlite3_finalize(p->laf.pMaxField);
18463  sqlite3_finalize(p->laf.pFindRoot);
18464  sqlite3_finalize(p->laf.pInsert);
18465  sqlite3_finalize(p->laf.pAllPage);
18466  sqlite3_finalize(p->laf.pPageData);
18467  p->laf.pUsedPages = 0;
18468  p->laf.pAllAndParent = 0;
18469  p->laf.pMapInsert = 0;
18470  p->laf.pMaxField = 0;
18471  p->laf.pFindRoot = 0;
18472  p->laf.pInsert = 0;
18473  p->laf.pAllPage = 0;
18474  p->laf.pPageData = 0;
18475  sqlite3_free(p->laf.apVal);
18476  p->laf.apVal = 0;
18477}
18478
18479/*
18480** Free all resources allocated as part of sqlite3_recover_step() calls.
18481*/
18482static void recoverFinalCleanup(sqlite3_recover *p){
18483  RecoverTable *pTab = 0;
18484  RecoverTable *pNext = 0;
18485
18486  recoverWriteDataCleanup(p);
18487  recoverLostAndFoundCleanup(p);
18488
18489  for(pTab=p->pTblList; pTab; pTab=pNext){
18490    pNext = pTab->pNext;
18491    sqlite3_free(pTab);
18492  }
18493  p->pTblList = 0;
18494  sqlite3_finalize(p->pGetPage);
18495  p->pGetPage = 0;
18496  sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
18497
18498  {
18499#ifndef NDEBUG
18500    int res =
18501#endif
18502       sqlite3_close(p->dbOut);
18503    assert( res==SQLITE_OK );
18504  }
18505  p->dbOut = 0;
18506}
18507
18508/*
18509** Decode and return an unsigned 16-bit big-endian integer value from
18510** buffer a[].
18511*/
18512static u32 recoverGetU16(const u8 *a){
18513  return (((u32)a[0])<<8) + ((u32)a[1]);
18514}
18515
18516/*
18517** Decode and return an unsigned 32-bit big-endian integer value from
18518** buffer a[].
18519*/
18520static u32 recoverGetU32(const u8 *a){
18521  return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]);
18522}
18523
18524/*
18525** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal)
18526** and return the number of bytes consumed.
18527*/
18528static int recoverGetVarint(const u8 *a, i64 *pVal){
18529  sqlite3_uint64 u = 0;
18530  int i;
18531  for(i=0; i<8; i++){
18532    u = (u<<7) + (a[i]&0x7f);
18533    if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; }
18534  }
18535  u = (u<<8) + (a[i]&0xff);
18536  *pVal = (sqlite3_int64)u;
18537  return 9;
18538}
18539
18540/*
18541** The second argument points to a buffer n bytes in size. If this buffer
18542** or a prefix thereof appears to contain a well-formed SQLite b-tree page,
18543** return the page-size in bytes. Otherwise, if the buffer does not
18544** appear to contain a well-formed b-tree page, return 0.
18545*/
18546static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){
18547  u8 *aUsed = aTmp;
18548  int nFrag = 0;
18549  int nActual = 0;
18550  int iFree = 0;
18551  int nCell = 0;                  /* Number of cells on page */
18552  int iCellOff = 0;               /* Offset of cell array in page */
18553  int iContent = 0;
18554  int eType = 0;
18555  int ii = 0;
18556
18557  eType = (int)a[0];
18558  if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0;
18559
18560  iFree = (int)recoverGetU16(&a[1]);
18561  nCell = (int)recoverGetU16(&a[3]);
18562  iContent = (int)recoverGetU16(&a[5]);
18563  if( iContent==0 ) iContent = 65536;
18564  nFrag = (int)a[7];
18565
18566  if( iContent>n ) return 0;
18567
18568  memset(aUsed, 0, n);
18569  memset(aUsed, 0xFF, iContent);
18570
18571  /* Follow the free-list. This is the same format for all b-tree pages. */
18572  if( iFree && iFree<=iContent ) return 0;
18573  while( iFree ){
18574    int iNext = 0;
18575    int nByte = 0;
18576    if( iFree>(n-4) ) return 0;
18577    iNext = recoverGetU16(&a[iFree]);
18578    nByte = recoverGetU16(&a[iFree+2]);
18579    if( iFree+nByte>n || nByte<4 ) return 0;
18580    if( iNext && iNext<iFree+nByte ) return 0;
18581    memset(&aUsed[iFree], 0xFF, nByte);
18582    iFree = iNext;
18583  }
18584
18585  /* Run through the cells */
18586  if( eType==0x02 || eType==0x05 ){
18587    iCellOff = 12;
18588  }else{
18589    iCellOff = 8;
18590  }
18591  if( (iCellOff + 2*nCell)>iContent ) return 0;
18592  for(ii=0; ii<nCell; ii++){
18593    int iByte;
18594    i64 nPayload = 0;
18595    int nByte = 0;
18596    int iOff = recoverGetU16(&a[iCellOff + 2*ii]);
18597    if( iOff<iContent || iOff>n ){
18598      return 0;
18599    }
18600    if( eType==0x05 || eType==0x02 ) nByte += 4;
18601    nByte += recoverGetVarint(&a[iOff+nByte], &nPayload);
18602    if( eType==0x0D ){
18603      i64 dummy = 0;
18604      nByte += recoverGetVarint(&a[iOff+nByte], &dummy);
18605    }
18606    if( eType!=0x05 ){
18607      int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23);
18608      int M = ((n-12)*32/255)-23;
18609      int K = M+((nPayload-M)%(n-4));
18610
18611      if( nPayload<X ){
18612        nByte += nPayload;
18613      }else if( K<=X ){
18614        nByte += K+4;
18615      }else{
18616        nByte += M+4;
18617      }
18618    }
18619
18620    if( iOff+nByte>n ){
18621      return 0;
18622    }
18623    for(iByte=iOff; iByte<(iOff+nByte); iByte++){
18624      if( aUsed[iByte]!=0 ){
18625        return 0;
18626      }
18627      aUsed[iByte] = 0xFF;
18628    }
18629  }
18630
18631  nActual = 0;
18632  for(ii=0; ii<n; ii++){
18633    if( aUsed[ii]==0 ) nActual++;
18634  }
18635  return (nActual==nFrag);
18636}
18637
18638
18639static int recoverVfsClose(sqlite3_file*);
18640static int recoverVfsRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
18641static int recoverVfsWrite(sqlite3_file*, const void*, int, sqlite3_int64);
18642static int recoverVfsTruncate(sqlite3_file*, sqlite3_int64 size);
18643static int recoverVfsSync(sqlite3_file*, int flags);
18644static int recoverVfsFileSize(sqlite3_file*, sqlite3_int64 *pSize);
18645static int recoverVfsLock(sqlite3_file*, int);
18646static int recoverVfsUnlock(sqlite3_file*, int);
18647static int recoverVfsCheckReservedLock(sqlite3_file*, int *pResOut);
18648static int recoverVfsFileControl(sqlite3_file*, int op, void *pArg);
18649static int recoverVfsSectorSize(sqlite3_file*);
18650static int recoverVfsDeviceCharacteristics(sqlite3_file*);
18651static int recoverVfsShmMap(sqlite3_file*, int, int, int, void volatile**);
18652static int recoverVfsShmLock(sqlite3_file*, int offset, int n, int flags);
18653static void recoverVfsShmBarrier(sqlite3_file*);
18654static int recoverVfsShmUnmap(sqlite3_file*, int deleteFlag);
18655static int recoverVfsFetch(sqlite3_file*, sqlite3_int64, int, void**);
18656static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p);
18657
18658static sqlite3_io_methods recover_methods = {
18659  2, /* iVersion */
18660  recoverVfsClose,
18661  recoverVfsRead,
18662  recoverVfsWrite,
18663  recoverVfsTruncate,
18664  recoverVfsSync,
18665  recoverVfsFileSize,
18666  recoverVfsLock,
18667  recoverVfsUnlock,
18668  recoverVfsCheckReservedLock,
18669  recoverVfsFileControl,
18670  recoverVfsSectorSize,
18671  recoverVfsDeviceCharacteristics,
18672  recoverVfsShmMap,
18673  recoverVfsShmLock,
18674  recoverVfsShmBarrier,
18675  recoverVfsShmUnmap,
18676  recoverVfsFetch,
18677  recoverVfsUnfetch
18678};
18679
18680static int recoverVfsClose(sqlite3_file *pFd){
18681  assert( pFd->pMethods!=&recover_methods );
18682  return pFd->pMethods->xClose(pFd);
18683}
18684
18685/*
18686** Write value v to buffer a[] as a 16-bit big-endian unsigned integer.
18687*/
18688static void recoverPutU16(u8 *a, u32 v){
18689  a[0] = (v>>8) & 0x00FF;
18690  a[1] = (v>>0) & 0x00FF;
18691}
18692
18693/*
18694** Write value v to buffer a[] as a 32-bit big-endian unsigned integer.
18695*/
18696static void recoverPutU32(u8 *a, u32 v){
18697  a[0] = (v>>24) & 0x00FF;
18698  a[1] = (v>>16) & 0x00FF;
18699  a[2] = (v>>8) & 0x00FF;
18700  a[3] = (v>>0) & 0x00FF;
18701}
18702
18703/*
18704** Detect the page-size of the database opened by file-handle pFd by
18705** searching the first part of the file for a well-formed SQLite b-tree
18706** page. If parameter nReserve is non-zero, then as well as searching for
18707** a b-tree page with zero reserved bytes, this function searches for one
18708** with nReserve reserved bytes at the end of it.
18709**
18710** If successful, set variable p->detected_pgsz to the detected page-size
18711** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page
18712** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or,
18713** if an error occurs (e.g. an IO or OOM error), then an SQLite error code
18714** is returned. The final value of p->detected_pgsz is undefined in this
18715** case.
18716*/
18717static int recoverVfsDetectPagesize(
18718  sqlite3_recover *p,             /* Recover handle */
18719  sqlite3_file *pFd,              /* File-handle open on input database */
18720  u32 nReserve,                   /* Possible nReserve value */
18721  i64 nSz                         /* Size of database file in bytes */
18722){
18723  int rc = SQLITE_OK;
18724  const int nMin = 512;
18725  const int nMax = 65536;
18726  const int nMaxBlk = 4;
18727  u32 pgsz = 0;
18728  int iBlk = 0;
18729  u8 *aPg = 0;
18730  u8 *aTmp = 0;
18731  int nBlk = 0;
18732
18733  aPg = (u8*)sqlite3_malloc(2*nMax);
18734  if( aPg==0 ) return SQLITE_NOMEM;
18735  aTmp = &aPg[nMax];
18736
18737  nBlk = (nSz+nMax-1)/nMax;
18738  if( nBlk>nMaxBlk ) nBlk = nMaxBlk;
18739
18740  do {
18741    for(iBlk=0; rc==SQLITE_OK && iBlk<nBlk; iBlk++){
18742      int nByte = (nSz>=((iBlk+1)*nMax)) ? nMax : (nSz % nMax);
18743      memset(aPg, 0, nMax);
18744      rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax);
18745      if( rc==SQLITE_OK ){
18746        int pgsz2;
18747        for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){
18748          int iOff;
18749          for(iOff=0; iOff<nMax; iOff+=pgsz2){
18750            if( recoverIsValidPage(aTmp, &aPg[iOff], pgsz2-nReserve) ){
18751              pgsz = pgsz2;
18752              break;
18753            }
18754          }
18755        }
18756      }
18757    }
18758    if( pgsz>(u32)p->detected_pgsz ){
18759      p->detected_pgsz = pgsz;
18760      p->nReserve = nReserve;
18761    }
18762    if( nReserve==0 ) break;
18763    nReserve = 0;
18764  }while( 1 );
18765
18766  p->detected_pgsz = pgsz;
18767  sqlite3_free(aPg);
18768  return rc;
18769}
18770
18771/*
18772** The xRead() method of the wrapper VFS. This is used to intercept calls
18773** to read page 1 of the input database.
18774*/
18775static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){
18776  int rc = SQLITE_OK;
18777  if( pFd->pMethods==&recover_methods ){
18778    pFd->pMethods = recover_g.pMethods;
18779    rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
18780    if( nByte==16 ){
18781      sqlite3_randomness(16, aBuf);
18782    }else
18783    if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){
18784      /* Ensure that the database has a valid header file. The only fields
18785      ** that really matter to recovery are:
18786      **
18787      **   + Database page size (16-bits at offset 16)
18788      **   + Size of db in pages (32-bits at offset 28)
18789      **   + Database encoding (32-bits at offset 56)
18790      **
18791      ** Also preserved are:
18792      **
18793      **   + first freelist page (32-bits at offset 32)
18794      **   + size of freelist (32-bits at offset 36)
18795      **   + the wal-mode flags (16-bits at offset 18)
18796      **
18797      ** We also try to preserve the auto-vacuum, incr-value, user-version
18798      ** and application-id fields - all 32 bit quantities at offsets
18799      ** 52, 60, 64 and 68. All other fields are set to known good values.
18800      **
18801      ** Byte offset 105 should also contain the page-size as a 16-bit
18802      ** integer.
18803      */
18804      const int aPreserve[] = {32, 36, 52, 60, 64, 68};
18805      u8 aHdr[108] = {
18806        0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
18807        0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
18808        0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20,
18809        0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
18810        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18811        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04,
18812        0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
18813        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18814        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
18815        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18816        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18817        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
18818        0x00, 0x2e, 0x5b, 0x30,
18819
18820        0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00
18821      };
18822      u8 *a = (u8*)aBuf;
18823
18824      u32 pgsz = recoverGetU16(&a[16]);
18825      u32 nReserve = a[20];
18826      u32 enc = recoverGetU32(&a[56]);
18827      u32 dbsz = 0;
18828      i64 dbFileSize = 0;
18829      int ii;
18830      sqlite3_recover *p = recover_g.p;
18831
18832      if( pgsz==0x01 ) pgsz = 65536;
18833      rc = pFd->pMethods->xFileSize(pFd, &dbFileSize);
18834
18835      if( rc==SQLITE_OK && p->detected_pgsz==0 ){
18836        rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize);
18837      }
18838      if( p->detected_pgsz ){
18839        pgsz = p->detected_pgsz;
18840        nReserve = p->nReserve;
18841      }
18842
18843      if( pgsz ){
18844        dbsz = dbFileSize / pgsz;
18845      }
18846      if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){
18847        enc = SQLITE_UTF8;
18848      }
18849
18850      sqlite3_free(p->pPage1Cache);
18851      p->pPage1Cache = 0;
18852      p->pPage1Disk = 0;
18853
18854      p->pgsz = nByte;
18855      p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2);
18856      if( p->pPage1Cache ){
18857        p->pPage1Disk = &p->pPage1Cache[nByte];
18858        memcpy(p->pPage1Disk, aBuf, nByte);
18859        aHdr[18] = a[18];
18860        aHdr[19] = a[19];
18861        recoverPutU32(&aHdr[28], dbsz);
18862        recoverPutU32(&aHdr[56], enc);
18863        recoverPutU16(&aHdr[105], pgsz-nReserve);
18864        if( pgsz==65536 ) pgsz = 1;
18865        recoverPutU16(&aHdr[16], pgsz);
18866        aHdr[20] = nReserve;
18867        for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){
18868          memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4);
18869        }
18870        memcpy(aBuf, aHdr, sizeof(aHdr));
18871        memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr));
18872
18873        memcpy(p->pPage1Cache, aBuf, nByte);
18874      }else{
18875        rc = p->errCode;
18876      }
18877
18878    }
18879    pFd->pMethods = &recover_methods;
18880  }else{
18881    rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff);
18882  }
18883  return rc;
18884}
18885
18886/*
18887** Used to make sqlite3_io_methods wrapper methods less verbose.
18888*/
18889#define RECOVER_VFS_WRAPPER(code)                         \
18890  int rc = SQLITE_OK;                                     \
18891  if( pFd->pMethods==&recover_methods ){                  \
18892    pFd->pMethods = recover_g.pMethods;                   \
18893    rc = code;                                            \
18894    pFd->pMethods = &recover_methods;                     \
18895  }else{                                                  \
18896    rc = code;                                            \
18897  }                                                       \
18898  return rc;
18899
18900/*
18901** Methods of the wrapper VFS. All methods except for xRead() and xClose()
18902** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent
18903** method on the lower level VFS, then reinstall the wrapper before returning.
18904** Those that return an integer value use the RECOVER_VFS_WRAPPER macro.
18905*/
18906static int recoverVfsWrite(
18907  sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff
18908){
18909  RECOVER_VFS_WRAPPER (
18910      pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff)
18911  );
18912}
18913static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){
18914  RECOVER_VFS_WRAPPER (
18915      pFd->pMethods->xTruncate(pFd, size)
18916  );
18917}
18918static int recoverVfsSync(sqlite3_file *pFd, int flags){
18919  RECOVER_VFS_WRAPPER (
18920      pFd->pMethods->xSync(pFd, flags)
18921  );
18922}
18923static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){
18924  RECOVER_VFS_WRAPPER (
18925      pFd->pMethods->xFileSize(pFd, pSize)
18926  );
18927}
18928static int recoverVfsLock(sqlite3_file *pFd, int eLock){
18929  RECOVER_VFS_WRAPPER (
18930      pFd->pMethods->xLock(pFd, eLock)
18931  );
18932}
18933static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){
18934  RECOVER_VFS_WRAPPER (
18935      pFd->pMethods->xUnlock(pFd, eLock)
18936  );
18937}
18938static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){
18939  RECOVER_VFS_WRAPPER (
18940      pFd->pMethods->xCheckReservedLock(pFd, pResOut)
18941  );
18942}
18943static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){
18944  RECOVER_VFS_WRAPPER (
18945    (pFd->pMethods ?  pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND)
18946  );
18947}
18948static int recoverVfsSectorSize(sqlite3_file *pFd){
18949  RECOVER_VFS_WRAPPER (
18950      pFd->pMethods->xSectorSize(pFd)
18951  );
18952}
18953static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){
18954  RECOVER_VFS_WRAPPER (
18955      pFd->pMethods->xDeviceCharacteristics(pFd)
18956  );
18957}
18958static int recoverVfsShmMap(
18959  sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp
18960){
18961  RECOVER_VFS_WRAPPER (
18962      pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp)
18963  );
18964}
18965static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){
18966  RECOVER_VFS_WRAPPER (
18967      pFd->pMethods->xShmLock(pFd, offset, n, flags)
18968  );
18969}
18970static void recoverVfsShmBarrier(sqlite3_file *pFd){
18971  if( pFd->pMethods==&recover_methods ){
18972    pFd->pMethods = recover_g.pMethods;
18973    pFd->pMethods->xShmBarrier(pFd);
18974    pFd->pMethods = &recover_methods;
18975  }else{
18976    pFd->pMethods->xShmBarrier(pFd);
18977  }
18978}
18979static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){
18980  RECOVER_VFS_WRAPPER (
18981      pFd->pMethods->xShmUnmap(pFd, deleteFlag)
18982  );
18983}
18984
18985static int recoverVfsFetch(
18986  sqlite3_file *pFd,
18987  sqlite3_int64 iOff,
18988  int iAmt,
18989  void **pp
18990){
18991  (void)pFd;
18992  (void)iOff;
18993  (void)iAmt;
18994  *pp = 0;
18995  return SQLITE_OK;
18996}
18997static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){
18998  (void)pFd;
18999  (void)iOff;
19000  (void)p;
19001  return SQLITE_OK;
19002}
19003
19004/*
19005** Install the VFS wrapper around the file-descriptor open on the input
19006** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held
19007** when this function is called.
19008*/
19009static void recoverInstallWrapper(sqlite3_recover *p){
19010  sqlite3_file *pFd = 0;
19011  assert( recover_g.pMethods==0 );
19012  recoverAssertMutexHeld();
19013  sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd);
19014  assert( pFd==0 || pFd->pMethods!=&recover_methods );
19015  if( pFd && pFd->pMethods ){
19016    int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0);
19017    recover_g.pMethods = pFd->pMethods;
19018    recover_g.p = p;
19019    recover_methods.iVersion = iVersion;
19020    pFd->pMethods = &recover_methods;
19021  }
19022}
19023
19024/*
19025** Uninstall the VFS wrapper that was installed around the file-descriptor open
19026** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be
19027** held when this function is called.
19028*/
19029static void recoverUninstallWrapper(sqlite3_recover *p){
19030  sqlite3_file *pFd = 0;
19031  recoverAssertMutexHeld();
19032  sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd);
19033  if( pFd && pFd->pMethods ){
19034    pFd->pMethods = recover_g.pMethods;
19035    recover_g.pMethods = 0;
19036    recover_g.p = 0;
19037  }
19038}
19039
19040/*
19041** This function does the work of a single sqlite3_recover_step() call. It
19042** is guaranteed that the handle is not in an error state when this
19043** function is called.
19044*/
19045static void recoverStep(sqlite3_recover *p){
19046  assert( p && p->errCode==SQLITE_OK );
19047  switch( p->eState ){
19048    case RECOVER_STATE_INIT:
19049      /* This is the very first call to sqlite3_recover_step() on this object.
19050      */
19051      recoverSqlCallback(p, "BEGIN");
19052      recoverSqlCallback(p, "PRAGMA writable_schema = on");
19053
19054      recoverEnterMutex();
19055      recoverInstallWrapper(p);
19056
19057      /* Open the output database. And register required virtual tables and
19058      ** user functions with the new handle. */
19059      recoverOpenOutput(p);
19060
19061      /* Open transactions on both the input and output databases. */
19062      sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0);
19063      recoverExec(p, p->dbIn, "PRAGMA writable_schema = on");
19064      recoverExec(p, p->dbIn, "BEGIN");
19065      if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1;
19066      recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema");
19067      recoverTransferSettings(p);
19068      recoverOpenRecovery(p);
19069      recoverCacheSchema(p);
19070
19071      recoverUninstallWrapper(p);
19072      recoverLeaveMutex();
19073
19074      recoverExec(p, p->dbOut, "BEGIN");
19075
19076      recoverWriteSchema1(p);
19077      p->eState = RECOVER_STATE_WRITING;
19078      break;
19079
19080    case RECOVER_STATE_WRITING: {
19081      if( p->w1.pTbls==0 ){
19082        recoverWriteDataInit(p);
19083      }
19084      if( SQLITE_DONE==recoverWriteDataStep(p) ){
19085        recoverWriteDataCleanup(p);
19086        if( p->zLostAndFound ){
19087          p->eState = RECOVER_STATE_LOSTANDFOUND1;
19088        }else{
19089          p->eState = RECOVER_STATE_SCHEMA2;
19090        }
19091      }
19092      break;
19093    }
19094
19095    case RECOVER_STATE_LOSTANDFOUND1: {
19096      if( p->laf.pUsed==0 ){
19097        recoverLostAndFound1Init(p);
19098      }
19099      if( SQLITE_DONE==recoverLostAndFound1Step(p) ){
19100        p->eState = RECOVER_STATE_LOSTANDFOUND2;
19101      }
19102      break;
19103    }
19104    case RECOVER_STATE_LOSTANDFOUND2: {
19105      if( p->laf.pAllAndParent==0 ){
19106        recoverLostAndFound2Init(p);
19107      }
19108      if( SQLITE_DONE==recoverLostAndFound2Step(p) ){
19109        p->eState = RECOVER_STATE_LOSTANDFOUND3;
19110      }
19111      break;
19112    }
19113
19114    case RECOVER_STATE_LOSTANDFOUND3: {
19115      if( p->laf.pInsert==0 ){
19116        recoverLostAndFound3Init(p);
19117      }
19118      if( SQLITE_DONE==recoverLostAndFound3Step(p) ){
19119        p->eState = RECOVER_STATE_SCHEMA2;
19120      }
19121      break;
19122    }
19123
19124    case RECOVER_STATE_SCHEMA2: {
19125      int rc = SQLITE_OK;
19126
19127      recoverWriteSchema2(p);
19128      p->eState = RECOVER_STATE_DONE;
19129
19130      /* If no error has occurred, commit the write transaction on the output
19131      ** database. Regardless of whether or not an error has occurred, make
19132      ** an attempt to end the read transaction on the input database.  */
19133      recoverExec(p, p->dbOut, "COMMIT");
19134      rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
19135      if( p->errCode==SQLITE_OK ) p->errCode = rc;
19136
19137      recoverSqlCallback(p, "PRAGMA writable_schema = off");
19138      recoverSqlCallback(p, "COMMIT");
19139      p->eState = RECOVER_STATE_DONE;
19140      recoverFinalCleanup(p);
19141      break;
19142    };
19143
19144    case RECOVER_STATE_DONE: {
19145      /* no-op */
19146      break;
19147    };
19148  }
19149}
19150
19151
19152/*
19153** This is a worker function that does the heavy lifting for both init
19154** functions:
19155**
19156**     sqlite3_recover_init()
19157**     sqlite3_recover_init_sql()
19158**
19159** All this function does is allocate space for the recover handle and
19160** take copies of the input parameters. All the real work is done within
19161** sqlite3_recover_run().
19162*/
19163sqlite3_recover *recoverInit(
19164  sqlite3* db,
19165  const char *zDb,
19166  const char *zUri,               /* Output URI for _recover_init() */
19167  int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */
19168  void *pSqlCtx                   /* Context arg for _recover_init_sql() */
19169){
19170  sqlite3_recover *pRet = 0;
19171  int nDb = 0;
19172  int nUri = 0;
19173  int nByte = 0;
19174
19175  if( zDb==0 ){ zDb = "main"; }
19176
19177  nDb = recoverStrlen(zDb);
19178  nUri = recoverStrlen(zUri);
19179
19180  nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1;
19181  pRet = (sqlite3_recover*)sqlite3_malloc(nByte);
19182  if( pRet ){
19183    memset(pRet, 0, nByte);
19184    pRet->dbIn = db;
19185    pRet->zDb = (char*)&pRet[1];
19186    pRet->zUri = &pRet->zDb[nDb+1];
19187    memcpy(pRet->zDb, zDb, nDb);
19188    if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri);
19189    pRet->xSql = xSql;
19190    pRet->pSqlCtx = pSqlCtx;
19191    pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT;
19192  }
19193
19194  return pRet;
19195}
19196
19197/*
19198** Initialize a recovery handle that creates a new database containing
19199** the recovered data.
19200*/
19201sqlite3_recover *sqlite3_recover_init(
19202  sqlite3* db,
19203  const char *zDb,
19204  const char *zUri
19205){
19206  return recoverInit(db, zDb, zUri, 0, 0);
19207}
19208
19209/*
19210** Initialize a recovery handle that returns recovered data in the
19211** form of SQL statements via a callback.
19212*/
19213sqlite3_recover *sqlite3_recover_init_sql(
19214  sqlite3* db,
19215  const char *zDb,
19216  int (*xSql)(void*, const char*),
19217  void *pSqlCtx
19218){
19219  return recoverInit(db, zDb, 0, xSql, pSqlCtx);
19220}
19221
19222/*
19223** Return the handle error message, if any.
19224*/
19225const char *sqlite3_recover_errmsg(sqlite3_recover *p){
19226  return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory";
19227}
19228
19229/*
19230** Return the handle error code.
19231*/
19232int sqlite3_recover_errcode(sqlite3_recover *p){
19233  return p ? p->errCode : SQLITE_NOMEM;
19234}
19235
19236/*
19237** Configure the handle.
19238*/
19239int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){
19240  int rc = SQLITE_OK;
19241  if( p==0 ){
19242    rc = SQLITE_NOMEM;
19243  }else if( p->eState!=RECOVER_STATE_INIT ){
19244    rc = SQLITE_MISUSE;
19245  }else{
19246    switch( op ){
19247      case 789:
19248        /* This undocumented magic configuration option is used to set the
19249        ** name of the auxiliary database that is ATTACH-ed to the database
19250        ** connection and used to hold state information during the
19251        ** recovery process.  This option is for debugging use only and
19252        ** is subject to change or removal at any time. */
19253        sqlite3_free(p->zStateDb);
19254        p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg);
19255        break;
19256
19257      case SQLITE_RECOVER_LOST_AND_FOUND: {
19258        const char *zArg = (const char*)pArg;
19259        sqlite3_free(p->zLostAndFound);
19260        if( zArg ){
19261          p->zLostAndFound = recoverMPrintf(p, "%s", zArg);
19262        }else{
19263          p->zLostAndFound = 0;
19264        }
19265        break;
19266      }
19267
19268      case SQLITE_RECOVER_FREELIST_CORRUPT:
19269        p->bFreelistCorrupt = *(int*)pArg;
19270        break;
19271
19272      case SQLITE_RECOVER_ROWIDS:
19273        p->bRecoverRowid = *(int*)pArg;
19274        break;
19275
19276      case SQLITE_RECOVER_SLOWINDEXES:
19277        p->bSlowIndexes = *(int*)pArg;
19278        break;
19279
19280      default:
19281        rc = SQLITE_NOTFOUND;
19282        break;
19283    }
19284  }
19285
19286  return rc;
19287}
19288
19289/*
19290** Do a unit of work towards the recovery job. Return SQLITE_OK if
19291** no error has occurred but database recovery is not finished, SQLITE_DONE
19292** if database recovery has been successfully completed, or an SQLite
19293** error code if an error has occurred.
19294*/
19295int sqlite3_recover_step(sqlite3_recover *p){
19296  if( p==0 ) return SQLITE_NOMEM;
19297  if( p->errCode==SQLITE_OK ) recoverStep(p);
19298  if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){
19299    return SQLITE_DONE;
19300  }
19301  return p->errCode;
19302}
19303
19304/*
19305** Do the configured recovery operation. Return SQLITE_OK if successful, or
19306** else an SQLite error code.
19307*/
19308int sqlite3_recover_run(sqlite3_recover *p){
19309  while( SQLITE_OK==sqlite3_recover_step(p) );
19310  return sqlite3_recover_errcode(p);
19311}
19312
19313
19314/*
19315** Free all resources associated with the recover handle passed as the only
19316** argument. The results of using a handle with any sqlite3_recover_**
19317** API function after it has been passed to this function are undefined.
19318**
19319** A copy of the value returned by the first call made to sqlite3_recover_run()
19320** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has
19321** not been called on this handle.
19322*/
19323int sqlite3_recover_finish(sqlite3_recover *p){
19324  int rc;
19325  if( p==0 ){
19326    rc = SQLITE_NOMEM;
19327  }else{
19328    recoverFinalCleanup(p);
19329    if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){
19330      rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0);
19331      if( p->errCode==SQLITE_OK ) p->errCode = rc;
19332    }
19333    rc = p->errCode;
19334    sqlite3_free(p->zErrMsg);
19335    sqlite3_free(p->zStateDb);
19336    sqlite3_free(p->zLostAndFound);
19337    sqlite3_free(p->pPage1Cache);
19338    sqlite3_free(p);
19339  }
19340  return rc;
19341}
19342
19343#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
19344
19345/************************* End ../ext/recover/sqlite3recover.c ********************/
19346# endif /* SQLITE_HAVE_SQLITE3R */
19347#endif
19348#ifdef SQLITE_SHELL_EXTSRC
19349# include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
19350#endif
19351
19352#if defined(SQLITE_ENABLE_SESSION)
19353/*
19354** State information for a single open session
19355*/
19356typedef struct OpenSession OpenSession;
19357struct OpenSession {
19358  char *zName;             /* Symbolic name for this session */
19359  int nFilter;             /* Number of xFilter rejection GLOB patterns */
19360  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
19361  sqlite3_session *p;      /* The open session */
19362};
19363#endif
19364
19365typedef struct ExpertInfo ExpertInfo;
19366struct ExpertInfo {
19367  sqlite3expert *pExpert;
19368  int bVerbose;
19369};
19370
19371/* A single line in the EQP output */
19372typedef struct EQPGraphRow EQPGraphRow;
19373struct EQPGraphRow {
19374  int iEqpId;           /* ID for this row */
19375  int iParentId;        /* ID of the parent row */
19376  EQPGraphRow *pNext;   /* Next row in sequence */
19377  char zText[1];        /* Text to display for this row */
19378};
19379
19380/* All EQP output is collected into an instance of the following */
19381typedef struct EQPGraph EQPGraph;
19382struct EQPGraph {
19383  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
19384  EQPGraphRow *pLast;   /* Last element of the pRow list */
19385  char zPrefix[100];    /* Graph prefix */
19386};
19387
19388/* Parameters affecting columnar mode result display (defaulting together) */
19389typedef struct ColModeOpts {
19390  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
19391  u8 bQuote;            /* Quote results for .mode box and table */
19392  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
19393} ColModeOpts;
19394#define ColModeOpts_default { 60, 0, 0 }
19395#define ColModeOpts_default_qbox { 60, 1, 0 }
19396
19397/*
19398** State information about the database connection is contained in an
19399** instance of the following structure.
19400*/
19401typedef struct ShellState ShellState;
19402struct ShellState {
19403  sqlite3 *db;           /* The database */
19404  u8 autoExplain;        /* Automatically turn on .explain mode */
19405  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */
19406  u8 autoEQPtest;        /* autoEQP is in test mode */
19407  u8 autoEQPtrace;       /* autoEQP is in trace mode */
19408  u8 scanstatsOn;        /* True to display scan stats before each finalize */
19409  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
19410  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
19411  u8 nEqpLevel;          /* Depth of the EQP output graph */
19412  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
19413  u8 bSafeMode;          /* True to prohibit unsafe operations */
19414  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
19415  u8 eRestoreState;      /* See comments above doAutoDetectRestore() */
19416  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
19417  unsigned statsOn;      /* True to display memory stats before each finalize */
19418  unsigned mEqpLines;    /* Mask of vertical lines in the EQP output graph */
19419  int inputNesting;      /* Track nesting level of .read and other redirects */
19420  int outCount;          /* Revert to stdout when reaching zero */
19421  int cnt;               /* Number of records displayed so far */
19422  int lineno;            /* Line number of last line read from in */
19423  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
19424  FILE *in;              /* Read commands from this stream */
19425  FILE *out;             /* Write results here */
19426  FILE *traceOut;        /* Output for sqlite3_trace() */
19427  int nErr;              /* Number of errors seen */
19428  int mode;              /* An output mode setting */
19429  int modePrior;         /* Saved mode */
19430  int cMode;             /* temporary output mode for the current query */
19431  int normalMode;        /* Output mode before ".explain on" */
19432  int writableSchema;    /* True if PRAGMA writable_schema=ON */
19433  int showHeader;        /* True to show column names in List or Column mode */
19434  int nCheck;            /* Number of ".check" commands run */
19435  unsigned nProgress;    /* Number of progress callbacks encountered */
19436  unsigned mxProgress;   /* Maximum progress callbacks before failing */
19437  unsigned flgProgress;  /* Flags for the progress callback */
19438  unsigned shellFlgs;    /* Various flags */
19439  unsigned priorShFlgs;  /* Saved copy of flags */
19440  sqlite3_int64 szMax;   /* --maxsize argument to .open */
19441  char *zDestTable;      /* Name of destination table when MODE_Insert */
19442  char *zTempFile;       /* Temporary file that might need deleting */
19443  char zTestcase[30];    /* Name of current test case */
19444  char colSeparator[20]; /* Column separator character for several modes */
19445  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
19446  char colSepPrior[20];  /* Saved column separator */
19447  char rowSepPrior[20];  /* Saved row separator */
19448  int *colWidth;         /* Requested width of each column in columnar modes */
19449  int *actualWidth;      /* Actual width of each column */
19450  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
19451  char nullValue[20];    /* The text to print when a NULL comes back from
19452                         ** the database */
19453  char outfile[FILENAME_MAX]; /* Filename for *out */
19454  sqlite3_stmt *pStmt;   /* Current statement if any. */
19455  FILE *pLog;            /* Write log output here */
19456  struct AuxDb {         /* Storage space for auxiliary database connections */
19457    sqlite3 *db;               /* Connection pointer */
19458    const char *zDbFilename;   /* Filename used to open the connection */
19459    char *zFreeOnClose;        /* Free this memory allocation on close */
19460#if defined(SQLITE_ENABLE_SESSION)
19461    int nSession;              /* Number of active sessions */
19462    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
19463#endif
19464  } aAuxDb[5],           /* Array of all database connections */
19465    *pAuxDb;             /* Currently active database connection */
19466  int *aiIndent;         /* Array of indents used in MODE_Explain */
19467  int nIndent;           /* Size of array aiIndent[] */
19468  int iIndent;           /* Index of current op in aiIndent[] */
19469  char *zNonce;          /* Nonce for temporary safe-mode escapes */
19470  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
19471  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
19472#ifdef SQLITE_SHELL_FIDDLE
19473  struct {
19474    const char * zInput; /* Input string from wasm/JS proxy */
19475    const char * zPos;   /* Cursor pos into zInput */
19476    const char * zDefaultDbName; /* Default name for db file */
19477  } wasm;
19478#endif
19479};
19480
19481#ifdef SQLITE_SHELL_FIDDLE
19482static ShellState shellState;
19483#endif
19484
19485
19486/* Allowed values for ShellState.autoEQP
19487*/
19488#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
19489#define AUTOEQP_on       1           /* Automatic EQP is on */
19490#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
19491#define AUTOEQP_full     3           /* Show full EXPLAIN */
19492
19493/* Allowed values for ShellState.openMode
19494*/
19495#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
19496#define SHELL_OPEN_NORMAL      1      /* Normal database file */
19497#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
19498#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
19499#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
19500#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
19501#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
19502
19503/* Allowed values for ShellState.eTraceType
19504*/
19505#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
19506#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
19507#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
19508
19509/* Bits in the ShellState.flgProgress variable */
19510#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
19511#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progress
19512                                   ** callback limit is reached, and for each
19513                                   ** top-level SQL statement */
19514#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
19515
19516/*
19517** These are the allowed shellFlgs values
19518*/
19519#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
19520#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
19521#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
19522#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
19523#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
19524#define SHFLG_CountChanges   0x00000020 /* .changes setting */
19525#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
19526#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
19527#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
19528#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
19529#define SHFLG_TestingMode    0x00000400 /* allow unsafe testing features */
19530
19531/*
19532** Macros for testing and setting shellFlgs
19533*/
19534#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
19535#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
19536#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
19537
19538/*
19539** These are the allowed modes.
19540*/
19541#define MODE_Line     0  /* One column per line.  Blank line between records */
19542#define MODE_Column   1  /* One record per line in neat columns */
19543#define MODE_List     2  /* One record per line with a separator */
19544#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
19545#define MODE_Html     4  /* Generate an XHTML table */
19546#define MODE_Insert   5  /* Generate SQL "insert" statements */
19547#define MODE_Quote    6  /* Quote values as for SQL */
19548#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
19549#define MODE_Csv      8  /* Quote strings, numbers are plain */
19550#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
19551#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
19552#define MODE_Pretty  11  /* Pretty-print schemas */
19553#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
19554#define MODE_Json    13  /* Output JSON */
19555#define MODE_Markdown 14 /* Markdown formatting */
19556#define MODE_Table   15  /* MySQL-style table formatting */
19557#define MODE_Box     16  /* Unicode box-drawing characters */
19558#define MODE_Count   17  /* Output only a count of the rows of output */
19559#define MODE_Off     18  /* No query output shown */
19560#define MODE_ScanExp 19  /* Like MODE_Explain, but for ".scanstats vm" */
19561
19562static const char *modeDescr[] = {
19563  "line",
19564  "column",
19565  "list",
19566  "semi",
19567  "html",
19568  "insert",
19569  "quote",
19570  "tcl",
19571  "csv",
19572  "explain",
19573  "ascii",
19574  "prettyprint",
19575  "eqp",
19576  "json",
19577  "markdown",
19578  "table",
19579  "box",
19580  "count",
19581  "off"
19582};
19583
19584/*
19585** These are the column/row/line separators used by the various
19586** import/export modes.
19587*/
19588#define SEP_Column    "|"
19589#define SEP_Row       "\n"
19590#define SEP_Tab       "\t"
19591#define SEP_Space     " "
19592#define SEP_Comma     ","
19593#define SEP_CrLf      "\r\n"
19594#define SEP_Unit      "\x1F"
19595#define SEP_Record    "\x1E"
19596
19597/*
19598** Limit input nesting via .read or any other input redirect.
19599** It's not too expensive, so a generous allowance can be made.
19600*/
19601#define MAX_INPUT_NESTING 25
19602
19603/*
19604** A callback for the sqlite3_log() interface.
19605*/
19606static void shellLog(void *pArg, int iErrCode, const char *zMsg){
19607  ShellState *p = (ShellState*)pArg;
19608  if( p->pLog==0 ) return;
19609  sputf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
19610  fflush(p->pLog);
19611}
19612
19613/*
19614** SQL function:  shell_putsnl(X)
19615**
19616** Write the text X to the screen (or whatever output is being directed)
19617** adding a newline at the end, and then return X.
19618*/
19619static void shellPutsFunc(
19620  sqlite3_context *pCtx,
19621  int nVal,
19622  sqlite3_value **apVal
19623){
19624  /* Unused: (ShellState*)sqlite3_user_data(pCtx); */
19625  (void)nVal;
19626  oputf("%s\n", sqlite3_value_text(apVal[0]));
19627  sqlite3_result_value(pCtx, apVal[0]);
19628}
19629
19630/*
19631** If in safe mode, print an error message described by the arguments
19632** and exit immediately.
19633*/
19634static void failIfSafeMode(
19635  ShellState *p,
19636  const char *zErrMsg,
19637  ...
19638){
19639  if( p->bSafeMode ){
19640    va_list ap;
19641    char *zMsg;
19642    va_start(ap, zErrMsg);
19643    zMsg = sqlite3_vmprintf(zErrMsg, ap);
19644    va_end(ap);
19645    eputf("line %d: %s\n", p->lineno, zMsg);
19646    exit(1);
19647  }
19648}
19649
19650/*
19651** SQL function:   edit(VALUE)
19652**                 edit(VALUE,EDITOR)
19653**
19654** These steps:
19655**
19656**     (1) Write VALUE into a temporary file.
19657**     (2) Run program EDITOR on that temporary file.
19658**     (3) Read the temporary file back and return its content as the result.
19659**     (4) Delete the temporary file
19660**
19661** If the EDITOR argument is omitted, use the value in the VISUAL
19662** environment variable.  If still there is no EDITOR, through an error.
19663**
19664** Also throw an error if the EDITOR program returns a non-zero exit code.
19665*/
19666#ifndef SQLITE_NOHAVE_SYSTEM
19667static void editFunc(
19668  sqlite3_context *context,
19669  int argc,
19670  sqlite3_value **argv
19671){
19672  const char *zEditor;
19673  char *zTempFile = 0;
19674  sqlite3 *db;
19675  char *zCmd = 0;
19676  int bBin;
19677  int rc;
19678  int hasCRNL = 0;
19679  FILE *f = 0;
19680  sqlite3_int64 sz;
19681  sqlite3_int64 x;
19682  unsigned char *p = 0;
19683
19684  if( argc==2 ){
19685    zEditor = (const char*)sqlite3_value_text(argv[1]);
19686  }else{
19687    zEditor = getenv("VISUAL");
19688  }
19689  if( zEditor==0 ){
19690    sqlite3_result_error(context, "no editor for edit()", -1);
19691    return;
19692  }
19693  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
19694    sqlite3_result_error(context, "NULL input to edit()", -1);
19695    return;
19696  }
19697  db = sqlite3_context_db_handle(context);
19698  zTempFile = 0;
19699  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
19700  if( zTempFile==0 ){
19701    sqlite3_uint64 r = 0;
19702    sqlite3_randomness(sizeof(r), &r);
19703    zTempFile = sqlite3_mprintf("temp%llx", r);
19704    if( zTempFile==0 ){
19705      sqlite3_result_error_nomem(context);
19706      return;
19707    }
19708  }
19709  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
19710  /* When writing the file to be edited, do \n to \r\n conversions on systems
19711  ** that want \r\n line endings */
19712  f = fopen(zTempFile, bBin ? "wb" : "w");
19713  if( f==0 ){
19714    sqlite3_result_error(context, "edit() cannot open temp file", -1);
19715    goto edit_func_end;
19716  }
19717  sz = sqlite3_value_bytes(argv[0]);
19718  if( bBin ){
19719    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
19720  }else{
19721    const char *z = (const char*)sqlite3_value_text(argv[0]);
19722    /* Remember whether or not the value originally contained \r\n */
19723    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
19724    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
19725  }
19726  fclose(f);
19727  f = 0;
19728  if( x!=sz ){
19729    sqlite3_result_error(context, "edit() could not write the whole file", -1);
19730    goto edit_func_end;
19731  }
19732  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
19733  if( zCmd==0 ){
19734    sqlite3_result_error_nomem(context);
19735    goto edit_func_end;
19736  }
19737  rc = system(zCmd);
19738  sqlite3_free(zCmd);
19739  if( rc ){
19740    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
19741    goto edit_func_end;
19742  }
19743  f = fopen(zTempFile, "rb");
19744  if( f==0 ){
19745    sqlite3_result_error(context,
19746      "edit() cannot reopen temp file after edit", -1);
19747    goto edit_func_end;
19748  }
19749  fseek(f, 0, SEEK_END);
19750  sz = ftell(f);
19751  rewind(f);
19752  p = sqlite3_malloc64( sz+1 );
19753  if( p==0 ){
19754    sqlite3_result_error_nomem(context);
19755    goto edit_func_end;
19756  }
19757  x = fread(p, 1, (size_t)sz, f);
19758  fclose(f);
19759  f = 0;
19760  if( x!=sz ){
19761    sqlite3_result_error(context, "could not read back the whole file", -1);
19762    goto edit_func_end;
19763  }
19764  if( bBin ){
19765    sqlite3_result_blob64(context, p, sz, sqlite3_free);
19766  }else{
19767    sqlite3_int64 i, j;
19768    if( hasCRNL ){
19769      /* If the original contains \r\n then do no conversions back to \n */
19770    }else{
19771      /* If the file did not originally contain \r\n then convert any new
19772      ** \r\n back into \n */
19773      p[sz] = 0;
19774      for(i=j=0; i<sz; i++){
19775        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
19776        p[j++] = p[i];
19777      }
19778      sz = j;
19779      p[sz] = 0;
19780    }
19781    sqlite3_result_text64(context, (const char*)p, sz,
19782                          sqlite3_free, SQLITE_UTF8);
19783  }
19784  p = 0;
19785
19786edit_func_end:
19787  if( f ) fclose(f);
19788  unlink(zTempFile);
19789  sqlite3_free(zTempFile);
19790  sqlite3_free(p);
19791}
19792#endif /* SQLITE_NOHAVE_SYSTEM */
19793
19794/*
19795** Save or restore the current output mode
19796*/
19797static void outputModePush(ShellState *p){
19798  p->modePrior = p->mode;
19799  p->priorShFlgs = p->shellFlgs;
19800  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
19801  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
19802}
19803static void outputModePop(ShellState *p){
19804  p->mode = p->modePrior;
19805  p->shellFlgs = p->priorShFlgs;
19806  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
19807  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
19808}
19809
19810/*
19811** Output the given string as a hex-encoded blob (eg. X'1234' )
19812*/
19813static void output_hex_blob(const void *pBlob, int nBlob){
19814  int i;
19815  unsigned char *aBlob = (unsigned char*)pBlob;
19816
19817  char *zStr = sqlite3_malloc(nBlob*2 + 1);
19818  shell_check_oom(zStr);
19819
19820  for(i=0; i<nBlob; i++){
19821    static const char aHex[] = {
19822        '0', '1', '2', '3', '4', '5', '6', '7',
19823        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
19824    };
19825    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
19826    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
19827  }
19828  zStr[i*2] = '\0';
19829
19830  oputf("X'%s'", zStr);
19831  sqlite3_free(zStr);
19832}
19833
19834/*
19835** Find a string that is not found anywhere in z[].  Return a pointer
19836** to that string.
19837**
19838** Try to use zA and zB first.  If both of those are already found in z[]
19839** then make up some string and store it in the buffer zBuf.
19840*/
19841static const char *unused_string(
19842  const char *z,                    /* Result must not appear anywhere in z */
19843  const char *zA, const char *zB,   /* Try these first */
19844  char *zBuf                        /* Space to store a generated string */
19845){
19846  unsigned i = 0;
19847  if( strstr(z, zA)==0 ) return zA;
19848  if( strstr(z, zB)==0 ) return zB;
19849  do{
19850    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
19851  }while( strstr(z,zBuf)!=0 );
19852  return zBuf;
19853}
19854
19855/*
19856** Output the given string as a quoted string using SQL quoting conventions.
19857**
19858** See also: output_quoted_escaped_string()
19859*/
19860static void output_quoted_string(const char *z){
19861  int i;
19862  char c;
19863#ifndef SQLITE_SHELL_FIDDLE
19864  FILE *pfO = setOutputStream(invalidFileStream);
19865  setBinaryMode(pfO, 1);
19866#endif
19867  if( z==0 ) return;
19868  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
19869  if( c==0 ){
19870    oputf("'%s'",z);
19871  }else{
19872    oputz("'");
19873    while( *z ){
19874      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
19875      if( c=='\'' ) i++;
19876      if( i ){
19877        oputf("%.*s", i, z);
19878        z += i;
19879      }
19880      if( c=='\'' ){
19881        oputz("'");
19882        continue;
19883      }
19884      if( c==0 ){
19885        break;
19886      }
19887      z++;
19888    }
19889    oputz("'");
19890  }
19891#ifndef SQLITE_SHELL_FIDDLE
19892  setTextMode(pfO, 1);
19893#else
19894  setTextMode(stdout, 1);
19895#endif
19896}
19897
19898/*
19899** Output the given string as a quoted string using SQL quoting conventions.
19900** Additionallly , escape the "\n" and "\r" characters so that they do not
19901** get corrupted by end-of-line translation facilities in some operating
19902** systems.
19903**
19904** This is like output_quoted_string() but with the addition of the \r\n
19905** escape mechanism.
19906*/
19907static void output_quoted_escaped_string(const char *z){
19908  int i;
19909  char c;
19910#ifndef SQLITE_SHELL_FIDDLE
19911  FILE *pfO = setOutputStream(invalidFileStream);
19912  setBinaryMode(pfO, 1);
19913#endif
19914  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
19915  if( c==0 ){
19916    oputf("'%s'",z);
19917  }else{
19918    const char *zNL = 0;
19919    const char *zCR = 0;
19920    int nNL = 0;
19921    int nCR = 0;
19922    char zBuf1[20], zBuf2[20];
19923    for(i=0; z[i]; i++){
19924      if( z[i]=='\n' ) nNL++;
19925      if( z[i]=='\r' ) nCR++;
19926    }
19927    if( nNL ){
19928      oputz("replace(");
19929      zNL = unused_string(z, "\\n", "\\012", zBuf1);
19930    }
19931    if( nCR ){
19932      oputz("replace(");
19933      zCR = unused_string(z, "\\r", "\\015", zBuf2);
19934    }
19935    oputz("'");
19936    while( *z ){
19937      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
19938      if( c=='\'' ) i++;
19939      if( i ){
19940        oputf("%.*s", i, z);
19941        z += i;
19942      }
19943      if( c=='\'' ){
19944        oputz("'");
19945        continue;
19946      }
19947      if( c==0 ){
19948        break;
19949      }
19950      z++;
19951      if( c=='\n' ){
19952        oputz(zNL);
19953        continue;
19954      }
19955      oputz(zCR);
19956    }
19957    oputz("'");
19958    if( nCR ){
19959      oputf(",'%s',char(13))", zCR);
19960    }
19961    if( nNL ){
19962      oputf(",'%s',char(10))", zNL);
19963    }
19964  }
19965#ifndef SQLITE_SHELL_FIDDLE
19966  setTextMode(pfO, 1);
19967#else
19968  setTextMode(stdout, 1);
19969#endif
19970}
19971
19972/*
19973** Find earliest of chars within s specified in zAny.
19974** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated.
19975*/
19976static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){
19977  const char *pcFirst = 0;
19978  if( ns == ~(size_t)0 ) ns = strlen(s);
19979  while(*zAny){
19980    const char *pc = (const char*)memchr(s, *zAny&0xff, ns);
19981    if( pc ){
19982      pcFirst = pc;
19983      ns = pcFirst - s;
19984    }
19985    ++zAny;
19986  }
19987  return pcFirst;
19988}
19989/*
19990** Output the given string as a quoted according to C or TCL quoting rules.
19991*/
19992static void output_c_string(const char *z){
19993  char c;
19994  static const char *zq = "\"";
19995  static long ctrlMask = ~0L;
19996  static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */
19997  char ace[3] = "\\?";
19998  char cbsSay;
19999  oputz(zq);
20000  while( *z!=0 ){
20001    const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0);
20002    const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask);
20003    const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast;
20004    if( pcEnd > z ) oputb(z, (int)(pcEnd-z));
20005    if( (c = *pcEnd)==0 ) break;
20006    ++pcEnd;
20007    switch( c ){
20008    case '\\': case '"':
20009      cbsSay = (char)c;
20010      break;
20011    case '\t': cbsSay = 't'; break;
20012    case '\n': cbsSay = 'n'; break;
20013    case '\r': cbsSay = 'r'; break;
20014    case '\f': cbsSay = 'f'; break;
20015    default: cbsSay = 0; break;
20016    }
20017    if( cbsSay ){
20018      ace[1] = cbsSay;
20019      oputz(ace);
20020    }else if( !isprint(c&0xff) ){
20021      oputf("\\%03o", c&0xff);
20022    }else{
20023      ace[1] = (char)c;
20024      oputz(ace+1);
20025    }
20026    z = pcEnd;
20027  }
20028  oputz(zq);
20029}
20030
20031/*
20032** Output the given string as a quoted according to JSON quoting rules.
20033*/
20034static void output_json_string(const char *z, i64 n){
20035  char c;
20036  static const char *zq = "\"";
20037  static long ctrlMask = ~0L;
20038  static const char *zDQBS = "\"\\";
20039  const char *pcLimit;
20040  char ace[3] = "\\?";
20041  char cbsSay;
20042
20043  if( z==0 ) z = "";
20044  pcLimit = z + ((n<0)? strlen(z) : (size_t)n);
20045  oputz(zq);
20046  while( z < pcLimit ){
20047    const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z);
20048    const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask);
20049    const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast;
20050    if( pcEnd > z ){
20051      oputb(z, (int)(pcEnd-z));
20052      z = pcEnd;
20053    }
20054    if( z >= pcLimit ) break;
20055    c = *(z++);
20056    switch( c ){
20057    case '"': case '\\':
20058      cbsSay = (char)c;
20059      break;
20060    case '\b': cbsSay = 'b'; break;
20061    case '\f': cbsSay = 'f'; break;
20062    case '\n': cbsSay = 'n'; break;
20063    case '\r': cbsSay = 'r'; break;
20064    case '\t': cbsSay = 't'; break;
20065    default: cbsSay = 0; break;
20066    }
20067    if( cbsSay ){
20068      ace[1] = cbsSay;
20069      oputz(ace);
20070    }else if( c<=0x1f ){
20071      oputf("u%04x", c);
20072    }else{
20073      ace[1] = (char)c;
20074      oputz(ace+1);
20075    }
20076  }
20077  oputz(zq);
20078}
20079
20080/*
20081** Output the given string with characters that are special to
20082** HTML escaped.
20083*/
20084static void output_html_string(const char *z){
20085  int i;
20086  if( z==0 ) z = "";
20087  while( *z ){
20088    for(i=0;   z[i]
20089            && z[i]!='<'
20090            && z[i]!='&'
20091            && z[i]!='>'
20092            && z[i]!='\"'
20093            && z[i]!='\'';
20094        i++){}
20095    if( i>0 ){
20096      oputf("%.*s",i,z);
20097    }
20098    if( z[i]=='<' ){
20099      oputz("&lt;");
20100    }else if( z[i]=='&' ){
20101      oputz("&amp;");
20102    }else if( z[i]=='>' ){
20103      oputz("&gt;");
20104    }else if( z[i]=='\"' ){
20105      oputz("&quot;");
20106    }else if( z[i]=='\'' ){
20107      oputz("&#39;");
20108    }else{
20109      break;
20110    }
20111    z += i + 1;
20112  }
20113}
20114
20115/*
20116** If a field contains any character identified by a 1 in the following
20117** array, then the string must be quoted for CSV.
20118*/
20119static const char needCsvQuote[] = {
20120  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20121  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20122  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
20123  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20124  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20125  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20126  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
20127  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
20128  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20129  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20130  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20131  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20132  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20133  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20134  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20135  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
20136};
20137
20138/*
20139** Output a single term of CSV.  Actually, p->colSeparator is used for
20140** the separator, which may or may not be a comma.  p->nullValue is
20141** the null value.  Strings are quoted if necessary.  The separator
20142** is only issued if bSep is true.
20143*/
20144static void output_csv(ShellState *p, const char *z, int bSep){
20145  if( z==0 ){
20146    oputf("%s",p->nullValue);
20147  }else{
20148    unsigned i;
20149    for(i=0; z[i]; i++){
20150      if( needCsvQuote[((unsigned char*)z)[i]] ){
20151        i = 0;
20152        break;
20153      }
20154    }
20155    if( i==0 || strstr(z, p->colSeparator)!=0 ){
20156      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
20157      shell_check_oom(zQuoted);
20158      oputz(zQuoted);
20159      sqlite3_free(zQuoted);
20160    }else{
20161      oputz(z);
20162    }
20163  }
20164  if( bSep ){
20165    oputz(p->colSeparator);
20166  }
20167}
20168
20169/*
20170** This routine runs when the user presses Ctrl-C
20171*/
20172static void interrupt_handler(int NotUsed){
20173  UNUSED_PARAMETER(NotUsed);
20174  if( ++seenInterrupt>1 ) exit(1);
20175  if( globalDb ) sqlite3_interrupt(globalDb);
20176}
20177
20178#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
20179/*
20180** This routine runs for console events (e.g. Ctrl-C) on Win32
20181*/
20182static BOOL WINAPI ConsoleCtrlHandler(
20183  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
20184){
20185  if( dwCtrlType==CTRL_C_EVENT ){
20186    interrupt_handler(0);
20187    return TRUE;
20188  }
20189  return FALSE;
20190}
20191#endif
20192
20193#ifndef SQLITE_OMIT_AUTHORIZATION
20194/*
20195** This authorizer runs in safe mode.
20196*/
20197static int safeModeAuth(
20198  void *pClientData,
20199  int op,
20200  const char *zA1,
20201  const char *zA2,
20202  const char *zA3,
20203  const char *zA4
20204){
20205  ShellState *p = (ShellState*)pClientData;
20206  static const char *azProhibitedFunctions[] = {
20207    "edit",
20208    "fts3_tokenizer",
20209    "load_extension",
20210    "readfile",
20211    "writefile",
20212    "zipfile",
20213    "zipfile_cds",
20214  };
20215  UNUSED_PARAMETER(zA1);
20216  UNUSED_PARAMETER(zA3);
20217  UNUSED_PARAMETER(zA4);
20218  switch( op ){
20219    case SQLITE_ATTACH: {
20220#ifndef SQLITE_SHELL_FIDDLE
20221      /* In WASM builds the filesystem is a virtual sandbox, so
20222      ** there's no harm in using ATTACH. */
20223      failIfSafeMode(p, "cannot run ATTACH in safe mode");
20224#endif
20225      break;
20226    }
20227    case SQLITE_FUNCTION: {
20228      int i;
20229      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
20230        if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
20231          failIfSafeMode(p, "cannot use the %s() function in safe mode",
20232                         azProhibitedFunctions[i]);
20233        }
20234      }
20235      break;
20236    }
20237  }
20238  return SQLITE_OK;
20239}
20240
20241/*
20242** When the ".auth ON" is set, the following authorizer callback is
20243** invoked.  It always returns SQLITE_OK.
20244*/
20245static int shellAuth(
20246  void *pClientData,
20247  int op,
20248  const char *zA1,
20249  const char *zA2,
20250  const char *zA3,
20251  const char *zA4
20252){
20253  ShellState *p = (ShellState*)pClientData;
20254  static const char *azAction[] = { 0,
20255     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
20256     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
20257     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
20258     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
20259     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
20260     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
20261     "PRAGMA",               "READ",                 "SELECT",
20262     "TRANSACTION",          "UPDATE",               "ATTACH",
20263     "DETACH",               "ALTER_TABLE",          "REINDEX",
20264     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
20265     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
20266  };
20267  int i;
20268  const char *az[4];
20269  az[0] = zA1;
20270  az[1] = zA2;
20271  az[2] = zA3;
20272  az[3] = zA4;
20273  oputf("authorizer: %s", azAction[op]);
20274  for(i=0; i<4; i++){
20275    oputz(" ");
20276    if( az[i] ){
20277      output_c_string(az[i]);
20278    }else{
20279      oputz("NULL");
20280    }
20281  }
20282  oputz("\n");
20283  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
20284  return SQLITE_OK;
20285}
20286#endif
20287
20288/*
20289** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
20290**
20291** This routine converts some CREATE TABLE statements for shadow tables
20292** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
20293**
20294** If the schema statement in z[] contains a start-of-comment and if
20295** sqlite3_complete() returns false, try to terminate the comment before
20296** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
20297*/
20298static void printSchemaLine(const char *z, const char *zTail){
20299  char *zToFree = 0;
20300  if( z==0 ) return;
20301  if( zTail==0 ) return;
20302  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
20303    const char *zOrig = z;
20304    static const char *azTerm[] = { "", "*/", "\n" };
20305    int i;
20306    for(i=0; i<ArraySize(azTerm); i++){
20307      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
20308      shell_check_oom(zNew);
20309      if( sqlite3_complete(zNew) ){
20310        size_t n = strlen(zNew);
20311        zNew[n-1] = 0;
20312        zToFree = zNew;
20313        z = zNew;
20314        break;
20315      }
20316      sqlite3_free(zNew);
20317    }
20318  }
20319  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
20320    oputf("CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
20321  }else{
20322    oputf("%s%s", z, zTail);
20323  }
20324  sqlite3_free(zToFree);
20325}
20326static void printSchemaLineN(char *z, int n, const char *zTail){
20327  char c = z[n];
20328  z[n] = 0;
20329  printSchemaLine(z, zTail);
20330  z[n] = c;
20331}
20332
20333/*
20334** Return true if string z[] has nothing but whitespace and comments to the
20335** end of the first line.
20336*/
20337static int wsToEol(const char *z){
20338  int i;
20339  for(i=0; z[i]; i++){
20340    if( z[i]=='\n' ) return 1;
20341    if( IsSpace(z[i]) ) continue;
20342    if( z[i]=='-' && z[i+1]=='-' ) return 1;
20343    return 0;
20344  }
20345  return 1;
20346}
20347
20348/*
20349** Add a new entry to the EXPLAIN QUERY PLAN data
20350*/
20351static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
20352  EQPGraphRow *pNew;
20353  i64 nText;
20354  if( zText==0 ) return;
20355  nText = strlen(zText);
20356  if( p->autoEQPtest ){
20357    oputf("%d,%d,%s\n", iEqpId, p2, zText);
20358  }
20359  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
20360  shell_check_oom(pNew);
20361  pNew->iEqpId = iEqpId;
20362  pNew->iParentId = p2;
20363  memcpy(pNew->zText, zText, nText+1);
20364  pNew->pNext = 0;
20365  if( p->sGraph.pLast ){
20366    p->sGraph.pLast->pNext = pNew;
20367  }else{
20368    p->sGraph.pRow = pNew;
20369  }
20370  p->sGraph.pLast = pNew;
20371}
20372
20373/*
20374** Free and reset the EXPLAIN QUERY PLAN data that has been collected
20375** in p->sGraph.
20376*/
20377static void eqp_reset(ShellState *p){
20378  EQPGraphRow *pRow, *pNext;
20379  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
20380    pNext = pRow->pNext;
20381    sqlite3_free(pRow);
20382  }
20383  memset(&p->sGraph, 0, sizeof(p->sGraph));
20384}
20385
20386/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
20387** pOld, or return the first such line if pOld is NULL
20388*/
20389static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
20390  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
20391  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
20392  return pRow;
20393}
20394
20395/* Render a single level of the graph that has iEqpId as its parent.  Called
20396** recursively to render sublevels.
20397*/
20398static void eqp_render_level(ShellState *p, int iEqpId){
20399  EQPGraphRow *pRow, *pNext;
20400  i64 n = strlen(p->sGraph.zPrefix);
20401  char *z;
20402  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
20403    pNext = eqp_next_row(p, iEqpId, pRow);
20404    z = pRow->zText;
20405    oputf("%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
20406    if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
20407      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
20408      eqp_render_level(p, pRow->iEqpId);
20409      p->sGraph.zPrefix[n] = 0;
20410    }
20411  }
20412}
20413
20414/*
20415** Display and reset the EXPLAIN QUERY PLAN data
20416*/
20417static void eqp_render(ShellState *p, i64 nCycle){
20418  EQPGraphRow *pRow = p->sGraph.pRow;
20419  if( pRow ){
20420    if( pRow->zText[0]=='-' ){
20421      if( pRow->pNext==0 ){
20422        eqp_reset(p);
20423        return;
20424      }
20425      oputf("%s\n", pRow->zText+3);
20426      p->sGraph.pRow = pRow->pNext;
20427      sqlite3_free(pRow);
20428    }else if( nCycle>0 ){
20429      oputf("QUERY PLAN (cycles=%lld [100%%])\n", nCycle);
20430    }else{
20431      oputz("QUERY PLAN\n");
20432    }
20433    p->sGraph.zPrefix[0] = 0;
20434    eqp_render_level(p, 0);
20435    eqp_reset(p);
20436  }
20437}
20438
20439#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20440/*
20441** Progress handler callback.
20442*/
20443static int progress_handler(void *pClientData) {
20444  ShellState *p = (ShellState*)pClientData;
20445  p->nProgress++;
20446  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
20447    oputf("Progress limit reached (%u)\n", p->nProgress);
20448    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
20449    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
20450    return 1;
20451  }
20452  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
20453    oputf("Progress %u\n", p->nProgress);
20454  }
20455  return 0;
20456}
20457#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
20458
20459/*
20460** Print N dashes
20461*/
20462static void print_dashes(int N){
20463  const char zDash[] = "--------------------------------------------------";
20464  const int nDash = sizeof(zDash) - 1;
20465  while( N>nDash ){
20466    oputz(zDash);
20467    N -= nDash;
20468  }
20469  oputf("%.*s", N, zDash);
20470}
20471
20472/*
20473** Print a markdown or table-style row separator using ascii-art
20474*/
20475static void print_row_separator(
20476  ShellState *p,
20477  int nArg,
20478  const char *zSep
20479){
20480  int i;
20481  if( nArg>0 ){
20482    oputz(zSep);
20483    print_dashes(p->actualWidth[0]+2);
20484    for(i=1; i<nArg; i++){
20485      oputz(zSep);
20486      print_dashes(p->actualWidth[i]+2);
20487    }
20488    oputz(zSep);
20489  }
20490  oputz("\n");
20491}
20492
20493/*
20494** This is the callback routine that the shell
20495** invokes for each row of a query result.
20496*/
20497static int shell_callback(
20498  void *pArg,
20499  int nArg,        /* Number of result columns */
20500  char **azArg,    /* Text of each result column */
20501  char **azCol,    /* Column names */
20502  int *aiType      /* Column types.  Might be NULL */
20503){
20504  int i;
20505  ShellState *p = (ShellState*)pArg;
20506
20507  if( azArg==0 ) return 0;
20508  switch( p->cMode ){
20509    case MODE_Count:
20510    case MODE_Off: {
20511      break;
20512    }
20513    case MODE_Line: {
20514      int w = 5;
20515      if( azArg==0 ) break;
20516      for(i=0; i<nArg; i++){
20517        int len = strlen30(azCol[i] ? azCol[i] : "");
20518        if( len>w ) w = len;
20519      }
20520      if( p->cnt++>0 ) oputz(p->rowSeparator);
20521      for(i=0; i<nArg; i++){
20522        oputf("%*s = %s%s", w, azCol[i],
20523              azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
20524      }
20525      break;
20526    }
20527    case MODE_ScanExp:
20528    case MODE_Explain: {
20529      static const int aExplainWidth[] = {4,       13, 4, 4, 4, 13, 2, 13};
20530      static const int aExplainMap[] =   {0,       1,  2, 3, 4, 5,  6, 7 };
20531      static const int aScanExpWidth[] = {4, 6, 6, 13, 4, 4, 4, 13, 2, 13};
20532      static const int aScanExpMap[] =   {0, 9, 8, 1,  2, 3, 4, 5,  6, 7 };
20533
20534      const int *aWidth = aExplainWidth;
20535      const int *aMap = aExplainMap;
20536      int nWidth = ArraySize(aExplainWidth);
20537      int iIndent = 1;
20538
20539      if( p->cMode==MODE_ScanExp ){
20540        aWidth = aScanExpWidth;
20541        aMap = aScanExpMap;
20542        nWidth = ArraySize(aScanExpWidth);
20543        iIndent = 3;
20544      }
20545      if( nArg>nWidth ) nArg = nWidth;
20546
20547      /* If this is the first row seen, print out the headers */
20548      if( p->cnt++==0 ){
20549        for(i=0; i<nArg; i++){
20550          utf8_width_print(aWidth[i], azCol[ aMap[i] ]);
20551          oputz(i==nArg-1 ? "\n" : "  ");
20552        }
20553        for(i=0; i<nArg; i++){
20554          print_dashes(aWidth[i]);
20555          oputz(i==nArg-1 ? "\n" : "  ");
20556        }
20557      }
20558
20559      /* If there is no data, exit early. */
20560      if( azArg==0 ) break;
20561
20562      for(i=0; i<nArg; i++){
20563        const char *zSep = "  ";
20564        int w = aWidth[i];
20565        const char *zVal = azArg[ aMap[i] ];
20566        if( i==nArg-1 ) w = 0;
20567        if( zVal && strlenChar(zVal)>w ){
20568          w = strlenChar(zVal);
20569          zSep = " ";
20570        }
20571        if( i==iIndent && p->aiIndent && p->pStmt ){
20572          if( p->iIndent<p->nIndent ){
20573            oputf("%*.s", p->aiIndent[p->iIndent], "");
20574          }
20575          p->iIndent++;
20576        }
20577        utf8_width_print(w, zVal ? zVal : p->nullValue);
20578        oputz(i==nArg-1 ? "\n" : zSep);
20579      }
20580      break;
20581    }
20582    case MODE_Semi: {   /* .schema and .fullschema output */
20583      printSchemaLine(azArg[0], ";\n");
20584      break;
20585    }
20586    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
20587      char *z;
20588      int j;
20589      int nParen = 0;
20590      char cEnd = 0;
20591      char c;
20592      int nLine = 0;
20593      assert( nArg==1 );
20594      if( azArg[0]==0 ) break;
20595      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
20596       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
20597      ){
20598        oputf("%s;\n", azArg[0]);
20599        break;
20600      }
20601      z = sqlite3_mprintf("%s", azArg[0]);
20602      shell_check_oom(z);
20603      j = 0;
20604      for(i=0; IsSpace(z[i]); i++){}
20605      for(; (c = z[i])!=0; i++){
20606        if( IsSpace(c) ){
20607          if( z[j-1]=='\r' ) z[j-1] = '\n';
20608          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
20609        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
20610          j--;
20611        }
20612        z[j++] = c;
20613      }
20614      while( j>0 && IsSpace(z[j-1]) ){ j--; }
20615      z[j] = 0;
20616      if( strlen30(z)>=79 ){
20617        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
20618          if( c==cEnd ){
20619            cEnd = 0;
20620          }else if( c=='"' || c=='\'' || c=='`' ){
20621            cEnd = c;
20622          }else if( c=='[' ){
20623            cEnd = ']';
20624          }else if( c=='-' && z[i+1]=='-' ){
20625            cEnd = '\n';
20626          }else if( c=='(' ){
20627            nParen++;
20628          }else if( c==')' ){
20629            nParen--;
20630            if( nLine>0 && nParen==0 && j>0 ){
20631              printSchemaLineN(z, j, "\n");
20632              j = 0;
20633            }
20634          }
20635          z[j++] = c;
20636          if( nParen==1 && cEnd==0
20637           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
20638          ){
20639            if( c=='\n' ) j--;
20640            printSchemaLineN(z, j, "\n  ");
20641            j = 0;
20642            nLine++;
20643            while( IsSpace(z[i+1]) ){ i++; }
20644          }
20645        }
20646        z[j] = 0;
20647      }
20648      printSchemaLine(z, ";\n");
20649      sqlite3_free(z);
20650      break;
20651    }
20652    case MODE_List: {
20653      if( p->cnt++==0 && p->showHeader ){
20654        for(i=0; i<nArg; i++){
20655          oputf("%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator);
20656        }
20657      }
20658      if( azArg==0 ) break;
20659      for(i=0; i<nArg; i++){
20660        char *z = azArg[i];
20661        if( z==0 ) z = p->nullValue;
20662        oputz(z);
20663        oputz((i<nArg-1)? p->colSeparator : p->rowSeparator);
20664      }
20665      break;
20666    }
20667    case MODE_Html: {
20668      if( p->cnt++==0 && p->showHeader ){
20669        oputz("<TR>");
20670        for(i=0; i<nArg; i++){
20671          oputz("<TH>");
20672          output_html_string(azCol[i]);
20673          oputz("</TH>\n");
20674        }
20675        oputz("</TR>\n");
20676      }
20677      if( azArg==0 ) break;
20678      oputz("<TR>");
20679      for(i=0; i<nArg; i++){
20680        oputz("<TD>");
20681        output_html_string(azArg[i] ? azArg[i] : p->nullValue);
20682        oputz("</TD>\n");
20683      }
20684      oputz("</TR>\n");
20685      break;
20686    }
20687    case MODE_Tcl: {
20688      if( p->cnt++==0 && p->showHeader ){
20689        for(i=0; i<nArg; i++){
20690          output_c_string(azCol[i] ? azCol[i] : "");
20691          if(i<nArg-1) oputz(p->colSeparator);
20692        }
20693        oputz(p->rowSeparator);
20694      }
20695      if( azArg==0 ) break;
20696      for(i=0; i<nArg; i++){
20697        output_c_string(azArg[i] ? azArg[i] : p->nullValue);
20698        if(i<nArg-1) oputz(p->colSeparator);
20699      }
20700      oputz(p->rowSeparator);
20701      break;
20702    }
20703    case MODE_Csv: {
20704      setBinaryMode(p->out, 1);
20705      if( p->cnt++==0 && p->showHeader ){
20706        for(i=0; i<nArg; i++){
20707          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
20708        }
20709        oputz(p->rowSeparator);
20710      }
20711      if( nArg>0 ){
20712        for(i=0; i<nArg; i++){
20713          output_csv(p, azArg[i], i<nArg-1);
20714        }
20715        oputz(p->rowSeparator);
20716      }
20717      setTextMode(p->out, 1);
20718      break;
20719    }
20720    case MODE_Insert: {
20721      if( azArg==0 ) break;
20722      oputf("INSERT INTO %s",p->zDestTable);
20723      if( p->showHeader ){
20724        oputz("(");
20725        for(i=0; i<nArg; i++){
20726          if( i>0 ) oputz(",");
20727          if( quoteChar(azCol[i]) ){
20728            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
20729            shell_check_oom(z);
20730            oputz(z);
20731            sqlite3_free(z);
20732          }else{
20733            oputf("%s", azCol[i]);
20734          }
20735        }
20736        oputz(")");
20737      }
20738      p->cnt++;
20739      for(i=0; i<nArg; i++){
20740        oputz(i>0 ? "," : " VALUES(");
20741        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20742          oputz("NULL");
20743        }else if( aiType && aiType[i]==SQLITE_TEXT ){
20744          if( ShellHasFlag(p, SHFLG_Newlines) ){
20745            output_quoted_string(azArg[i]);
20746          }else{
20747            output_quoted_escaped_string(azArg[i]);
20748          }
20749        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
20750          oputz(azArg[i]);
20751        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20752          char z[50];
20753          double r = sqlite3_column_double(p->pStmt, i);
20754          sqlite3_uint64 ur;
20755          memcpy(&ur,&r,sizeof(r));
20756          if( ur==0x7ff0000000000000LL ){
20757            oputz("9.0e+999");
20758          }else if( ur==0xfff0000000000000LL ){
20759            oputz("-9.0e+999");
20760          }else{
20761            sqlite3_int64 ir = (sqlite3_int64)r;
20762            if( r==(double)ir ){
20763              sqlite3_snprintf(50,z,"%lld.0", ir);
20764            }else{
20765              sqlite3_snprintf(50,z,"%!.20g", r);
20766            }
20767            oputz(z);
20768          }
20769        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20770          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20771          int nBlob = sqlite3_column_bytes(p->pStmt, i);
20772          output_hex_blob(pBlob, nBlob);
20773        }else if( isNumber(azArg[i], 0) ){
20774          oputz(azArg[i]);
20775        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
20776          output_quoted_string(azArg[i]);
20777        }else{
20778          output_quoted_escaped_string(azArg[i]);
20779        }
20780      }
20781      oputz(");\n");
20782      break;
20783    }
20784    case MODE_Json: {
20785      if( azArg==0 ) break;
20786      if( p->cnt==0 ){
20787        fputs("[{", p->out);
20788      }else{
20789        fputs(",\n{", p->out);
20790      }
20791      p->cnt++;
20792      for(i=0; i<nArg; i++){
20793        output_json_string(azCol[i], -1);
20794        oputz(":");
20795        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20796          oputz("null");
20797        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20798          char z[50];
20799          double r = sqlite3_column_double(p->pStmt, i);
20800          sqlite3_uint64 ur;
20801          memcpy(&ur,&r,sizeof(r));
20802          if( ur==0x7ff0000000000000LL ){
20803            oputz("9.0e+999");
20804          }else if( ur==0xfff0000000000000LL ){
20805            oputz("-9.0e+999");
20806          }else{
20807            sqlite3_snprintf(50,z,"%!.20g", r);
20808            oputz(z);
20809          }
20810        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20811          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20812          int nBlob = sqlite3_column_bytes(p->pStmt, i);
20813          output_json_string(pBlob, nBlob);
20814        }else if( aiType && aiType[i]==SQLITE_TEXT ){
20815          output_json_string(azArg[i], -1);
20816        }else{
20817          oputz(azArg[i]);
20818        }
20819        if( i<nArg-1 ){
20820          oputz(",");
20821        }
20822      }
20823      oputz("}");
20824      break;
20825    }
20826    case MODE_Quote: {
20827      if( azArg==0 ) break;
20828      if( p->cnt==0 && p->showHeader ){
20829        for(i=0; i<nArg; i++){
20830          if( i>0 ) fputs(p->colSeparator, p->out);
20831          output_quoted_string(azCol[i]);
20832        }
20833        fputs(p->rowSeparator, p->out);
20834      }
20835      p->cnt++;
20836      for(i=0; i<nArg; i++){
20837        if( i>0 ) fputs(p->colSeparator, p->out);
20838        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
20839          oputz("NULL");
20840        }else if( aiType && aiType[i]==SQLITE_TEXT ){
20841          output_quoted_string(azArg[i]);
20842        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
20843          oputz(azArg[i]);
20844        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
20845          char z[50];
20846          double r = sqlite3_column_double(p->pStmt, i);
20847          sqlite3_snprintf(50,z,"%!.20g", r);
20848          oputz(z);
20849        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
20850          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
20851          int nBlob = sqlite3_column_bytes(p->pStmt, i);
20852          output_hex_blob(pBlob, nBlob);
20853        }else if( isNumber(azArg[i], 0) ){
20854          oputz(azArg[i]);
20855        }else{
20856          output_quoted_string(azArg[i]);
20857        }
20858      }
20859      fputs(p->rowSeparator, p->out);
20860      break;
20861    }
20862    case MODE_Ascii: {
20863      if( p->cnt++==0 && p->showHeader ){
20864        for(i=0; i<nArg; i++){
20865          if( i>0 ) oputz(p->colSeparator);
20866          oputz(azCol[i] ? azCol[i] : "");
20867        }
20868        oputz(p->rowSeparator);
20869      }
20870      if( azArg==0 ) break;
20871      for(i=0; i<nArg; i++){
20872        if( i>0 ) oputz(p->colSeparator);
20873        oputz(azArg[i] ? azArg[i] : p->nullValue);
20874      }
20875      oputz(p->rowSeparator);
20876      break;
20877    }
20878    case MODE_EQP: {
20879      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
20880      break;
20881    }
20882  }
20883  return 0;
20884}
20885
20886/*
20887** This is the callback routine that the SQLite library
20888** invokes for each row of a query result.
20889*/
20890static int callback(void *pArg, int nArg, char **azArg, char **azCol){
20891  /* since we don't have type info, call the shell_callback with a NULL value */
20892  return shell_callback(pArg, nArg, azArg, azCol, NULL);
20893}
20894
20895/*
20896** This is the callback routine from sqlite3_exec() that appends all
20897** output onto the end of a ShellText object.
20898*/
20899static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
20900  ShellText *p = (ShellText*)pArg;
20901  int i;
20902  UNUSED_PARAMETER(az);
20903  if( azArg==0 ) return 0;
20904  if( p->n ) appendText(p, "|", 0);
20905  for(i=0; i<nArg; i++){
20906    if( i ) appendText(p, ",", 0);
20907    if( azArg[i] ) appendText(p, azArg[i], 0);
20908  }
20909  return 0;
20910}
20911
20912/*
20913** Generate an appropriate SELFTEST table in the main database.
20914*/
20915static void createSelftestTable(ShellState *p){
20916  char *zErrMsg = 0;
20917  sqlite3_exec(p->db,
20918    "SAVEPOINT selftest_init;\n"
20919    "CREATE TABLE IF NOT EXISTS selftest(\n"
20920    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
20921    "  op TEXT,\n"                   /* Operator:  memo run */
20922    "  cmd TEXT,\n"                  /* Command text */
20923    "  ans TEXT\n"                   /* Desired answer */
20924    ");"
20925    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
20926    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
20927    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
20928    "         'memo','Tests generated by --init');\n"
20929    "INSERT INTO [_shell$self]\n"
20930    "  SELECT 'run',\n"
20931    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
20932                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
20933    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
20934                          "FROM sqlite_schema ORDER BY 2',224));\n"
20935    "INSERT INTO [_shell$self]\n"
20936    "  SELECT 'run',"
20937    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
20938    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
20939    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
20940    "  FROM (\n"
20941    "    SELECT name FROM sqlite_schema\n"
20942    "     WHERE type='table'\n"
20943    "       AND name<>'selftest'\n"
20944    "       AND coalesce(rootpage,0)>0\n"
20945    "  )\n"
20946    " ORDER BY name;\n"
20947    "INSERT INTO [_shell$self]\n"
20948    "  VALUES('run','PRAGMA integrity_check','ok');\n"
20949    "INSERT INTO selftest(tno,op,cmd,ans)"
20950    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
20951    "DROP TABLE [_shell$self];"
20952    ,0,0,&zErrMsg);
20953  if( zErrMsg ){
20954    eputf("SELFTEST initialization failure: %s\n", zErrMsg);
20955    sqlite3_free(zErrMsg);
20956  }
20957  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
20958}
20959
20960
20961/*
20962** Set the destination table field of the ShellState structure to
20963** the name of the table given.  Escape any quote characters in the
20964** table name.
20965*/
20966static void set_table_name(ShellState *p, const char *zName){
20967  int i, n;
20968  char cQuote;
20969  char *z;
20970
20971  if( p->zDestTable ){
20972    free(p->zDestTable);
20973    p->zDestTable = 0;
20974  }
20975  if( zName==0 ) return;
20976  cQuote = quoteChar(zName);
20977  n = strlen30(zName);
20978  if( cQuote ) n += n+2;
20979  z = p->zDestTable = malloc( n+1 );
20980  shell_check_oom(z);
20981  n = 0;
20982  if( cQuote ) z[n++] = cQuote;
20983  for(i=0; zName[i]; i++){
20984    z[n++] = zName[i];
20985    if( zName[i]==cQuote ) z[n++] = cQuote;
20986  }
20987  if( cQuote ) z[n++] = cQuote;
20988  z[n] = 0;
20989}
20990
20991/*
20992** Maybe construct two lines of text that point out the position of a
20993** syntax error.  Return a pointer to the text, in memory obtained from
20994** sqlite3_malloc().  Or, if the most recent error does not involve a
20995** specific token that we can point to, return an empty string.
20996**
20997** In all cases, the memory returned is obtained from sqlite3_malloc64()
20998** and should be released by the caller invoking sqlite3_free().
20999*/
21000static char *shell_error_context(const char *zSql, sqlite3 *db){
21001  int iOffset;
21002  size_t len;
21003  char *zCode;
21004  char *zMsg;
21005  int i;
21006  if( db==0
21007   || zSql==0
21008   || (iOffset = sqlite3_error_offset(db))<0
21009   || iOffset>=(int)strlen(zSql)
21010  ){
21011    return sqlite3_mprintf("");
21012  }
21013  while( iOffset>50 ){
21014    iOffset--;
21015    zSql++;
21016    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
21017  }
21018  len = strlen(zSql);
21019  if( len>78 ){
21020    len = 78;
21021    while( len>0 && (zSql[len]&0xc0)==0x80 ) len--;
21022  }
21023  zCode = sqlite3_mprintf("%.*s", len, zSql);
21024  shell_check_oom(zCode);
21025  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
21026  if( iOffset<25 ){
21027    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode,iOffset,"");
21028  }else{
21029    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode,iOffset-14,"");
21030  }
21031  return zMsg;
21032}
21033
21034
21035/*
21036** Execute a query statement that will generate SQL output.  Print
21037** the result columns, comma-separated, on a line and then add a
21038** semicolon terminator to the end of that line.
21039**
21040** If the number of columns is 1 and that column contains text "--"
21041** then write the semicolon on a separate line.  That way, if a
21042** "--" comment occurs at the end of the statement, the comment
21043** won't consume the semicolon terminator.
21044*/
21045static int run_table_dump_query(
21046  ShellState *p,           /* Query context */
21047  const char *zSelect      /* SELECT statement to extract content */
21048){
21049  sqlite3_stmt *pSelect;
21050  int rc;
21051  int nResult;
21052  int i;
21053  const char *z;
21054  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
21055  if( rc!=SQLITE_OK || !pSelect ){
21056    char *zContext = shell_error_context(zSelect, p->db);
21057    oputf("/**** ERROR: (%d) %s *****/\n%s",
21058          rc, sqlite3_errmsg(p->db), zContext);
21059    sqlite3_free(zContext);
21060    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
21061    return rc;
21062  }
21063  rc = sqlite3_step(pSelect);
21064  nResult = sqlite3_column_count(pSelect);
21065  while( rc==SQLITE_ROW ){
21066    z = (const char*)sqlite3_column_text(pSelect, 0);
21067    oputf("%s", z);
21068    for(i=1; i<nResult; i++){
21069      oputf(",%s", sqlite3_column_text(pSelect, i));
21070    }
21071    if( z==0 ) z = "";
21072    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
21073    if( z[0] ){
21074      oputz("\n;\n");
21075    }else{
21076      oputz(";\n");
21077    }
21078    rc = sqlite3_step(pSelect);
21079  }
21080  rc = sqlite3_finalize(pSelect);
21081  if( rc!=SQLITE_OK ){
21082    oputf("/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
21083    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
21084  }
21085  return rc;
21086}
21087
21088/*
21089** Allocate space and save off string indicating current error.
21090*/
21091static char *save_err_msg(
21092  sqlite3 *db,           /* Database to query */
21093  const char *zPhase,    /* When the error occurs */
21094  int rc,                /* Error code returned from API */
21095  const char *zSql       /* SQL string, or NULL */
21096){
21097  char *zErr;
21098  char *zContext;
21099  sqlite3_str *pStr = sqlite3_str_new(0);
21100  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
21101  if( rc>1 ){
21102    sqlite3_str_appendf(pStr, " (%d)", rc);
21103  }
21104  zContext = shell_error_context(zSql, db);
21105  if( zContext ){
21106    sqlite3_str_appendall(pStr, zContext);
21107    sqlite3_free(zContext);
21108  }
21109  zErr = sqlite3_str_finish(pStr);
21110  shell_check_oom(zErr);
21111  return zErr;
21112}
21113
21114#ifdef __linux__
21115/*
21116** Attempt to display I/O stats on Linux using /proc/PID/io
21117*/
21118static void displayLinuxIoStats(void){
21119  FILE *in;
21120  char z[200];
21121  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
21122  in = fopen(z, "rb");
21123  if( in==0 ) return;
21124  while( fgets(z, sizeof(z), in)!=0 ){
21125    static const struct {
21126      const char *zPattern;
21127      const char *zDesc;
21128    } aTrans[] = {
21129      { "rchar: ",                  "Bytes received by read():" },
21130      { "wchar: ",                  "Bytes sent to write():"    },
21131      { "syscr: ",                  "Read() system calls:"      },
21132      { "syscw: ",                  "Write() system calls:"     },
21133      { "read_bytes: ",             "Bytes read from storage:"  },
21134      { "write_bytes: ",            "Bytes written to storage:" },
21135      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
21136    };
21137    int i;
21138    for(i=0; i<ArraySize(aTrans); i++){
21139      int n = strlen30(aTrans[i].zPattern);
21140      if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
21141        oputf("%-36s %s", aTrans[i].zDesc, &z[n]);
21142        break;
21143      }
21144    }
21145  }
21146  fclose(in);
21147}
21148#endif
21149
21150/*
21151** Display a single line of status using 64-bit values.
21152*/
21153static void displayStatLine(
21154  char *zLabel,             /* Label for this one line */
21155  char *zFormat,            /* Format for the result */
21156  int iStatusCtrl,          /* Which status to display */
21157  int bReset                /* True to reset the stats */
21158){
21159  sqlite3_int64 iCur = -1;
21160  sqlite3_int64 iHiwtr = -1;
21161  int i, nPercent;
21162  char zLine[200];
21163  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
21164  for(i=0, nPercent=0; zFormat[i]; i++){
21165    if( zFormat[i]=='%' ) nPercent++;
21166  }
21167  if( nPercent>1 ){
21168    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
21169  }else{
21170    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
21171  }
21172  oputf("%-36s %s\n", zLabel, zLine);
21173}
21174
21175/*
21176** Display memory stats.
21177*/
21178static int display_stats(
21179  sqlite3 *db,                /* Database to query */
21180  ShellState *pArg,           /* Pointer to ShellState */
21181  int bReset                  /* True to reset the stats */
21182){
21183  int iCur;
21184  int iHiwtr;
21185  if( pArg==0 || pArg->out==0 ) return 0;
21186
21187  if( pArg->pStmt && pArg->statsOn==2 ){
21188    int nCol, i, x;
21189    sqlite3_stmt *pStmt = pArg->pStmt;
21190    char z[100];
21191    nCol = sqlite3_column_count(pStmt);
21192    oputf("%-36s %d\n", "Number of output columns:", nCol);
21193    for(i=0; i<nCol; i++){
21194      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
21195      oputf("%-36s %s\n", z, sqlite3_column_name(pStmt,i));
21196#ifndef SQLITE_OMIT_DECLTYPE
21197      sqlite3_snprintf(30, z+x, "declared type:");
21198      oputf("%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
21199#endif
21200#ifdef SQLITE_ENABLE_COLUMN_METADATA
21201      sqlite3_snprintf(30, z+x, "database name:");
21202      oputf("%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
21203      sqlite3_snprintf(30, z+x, "table name:");
21204      oputf("%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
21205      sqlite3_snprintf(30, z+x, "origin name:");
21206      oputf("%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
21207#endif
21208    }
21209  }
21210
21211  if( pArg->statsOn==3 ){
21212    if( pArg->pStmt ){
21213      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset);
21214      oputf("VM-steps: %d\n", iCur);
21215    }
21216    return 0;
21217  }
21218
21219  displayStatLine("Memory Used:",
21220     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
21221  displayStatLine("Number of Outstanding Allocations:",
21222     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
21223  if( pArg->shellFlgs & SHFLG_Pagecache ){
21224    displayStatLine("Number of Pcache Pages Used:",
21225       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
21226  }
21227  displayStatLine("Number of Pcache Overflow Bytes:",
21228     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
21229  displayStatLine("Largest Allocation:",
21230     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
21231  displayStatLine("Largest Pcache Allocation:",
21232     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
21233#ifdef YYTRACKMAXSTACKDEPTH
21234  displayStatLine("Deepest Parser Stack:",
21235     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
21236#endif
21237
21238  if( db ){
21239    if( pArg->shellFlgs & SHFLG_Lookaside ){
21240      iHiwtr = iCur = -1;
21241      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
21242                        &iCur, &iHiwtr, bReset);
21243      oputf("Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
21244      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
21245                        &iCur, &iHiwtr, bReset);
21246      oputf("Successful lookaside attempts:       %d\n", iHiwtr);
21247      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
21248                        &iCur, &iHiwtr, bReset);
21249      oputf("Lookaside failures due to size:      %d\n", iHiwtr);
21250      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
21251                        &iCur, &iHiwtr, bReset);
21252      oputf("Lookaside failures due to OOM:       %d\n", iHiwtr);
21253    }
21254    iHiwtr = iCur = -1;
21255    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
21256    oputf("Pager Heap Usage:                    %d bytes\n", iCur);
21257    iHiwtr = iCur = -1;
21258    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
21259    oputf("Page cache hits:                     %d\n", iCur);
21260    iHiwtr = iCur = -1;
21261    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
21262    oputf("Page cache misses:                   %d\n", iCur);
21263    iHiwtr = iCur = -1;
21264    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
21265    oputf("Page cache writes:                   %d\n", iCur);
21266    iHiwtr = iCur = -1;
21267    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
21268    oputf("Page cache spills:                   %d\n", iCur);
21269    iHiwtr = iCur = -1;
21270    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
21271    oputf("Schema Heap Usage:                   %d bytes\n", iCur);
21272    iHiwtr = iCur = -1;
21273    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
21274    oputf("Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
21275  }
21276
21277  if( pArg->pStmt ){
21278    int iHit, iMiss;
21279    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
21280                               bReset);
21281    oputf("Fullscan Steps:                      %d\n", iCur);
21282    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
21283    oputf("Sort Operations:                     %d\n", iCur);
21284    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
21285    oputf("Autoindex Inserts:                   %d\n", iCur);
21286    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT,
21287                               bReset);
21288    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS,
21289                                bReset);
21290    if( iHit || iMiss ){
21291      oputf("Bloom filter bypass taken:           %d/%d\n", iHit, iHit+iMiss);
21292    }
21293    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
21294    oputf("Virtual Machine Steps:               %d\n", iCur);
21295    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
21296    oputf("Reprepare operations:                %d\n", iCur);
21297    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
21298    oputf("Number of times run:                 %d\n", iCur);
21299    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
21300    oputf("Memory used by prepared stmt:        %d\n", iCur);
21301  }
21302
21303#ifdef __linux__
21304  displayLinuxIoStats();
21305#endif
21306
21307  /* Do not remove this machine readable comment: extra-stats-output-here */
21308
21309  return 0;
21310}
21311
21312
21313#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
21314static int scanStatsHeight(sqlite3_stmt *p, int iEntry){
21315  int iPid = 0;
21316  int ret = 1;
21317  sqlite3_stmt_scanstatus_v2(p, iEntry,
21318      SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
21319  );
21320  while( iPid!=0 ){
21321    int ii;
21322    for(ii=0; 1; ii++){
21323      int iId;
21324      int res;
21325      res = sqlite3_stmt_scanstatus_v2(p, ii,
21326          SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId
21327      );
21328      if( res ) break;
21329      if( iId==iPid ){
21330        sqlite3_stmt_scanstatus_v2(p, ii,
21331            SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid
21332        );
21333      }
21334    }
21335    ret++;
21336  }
21337  return ret;
21338}
21339#endif
21340
21341#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
21342static void display_explain_scanstats(
21343  sqlite3 *db,                    /* Database to query */
21344  ShellState *pArg                /* Pointer to ShellState */
21345){
21346  static const int f = SQLITE_SCANSTAT_COMPLEX;
21347  sqlite3_stmt *p = pArg->pStmt;
21348  int ii = 0;
21349  i64 nTotal = 0;
21350  int nWidth = 0;
21351  eqp_reset(pArg);
21352
21353  for(ii=0; 1; ii++){
21354    const char *z = 0;
21355    int n = 0;
21356    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){
21357      break;
21358    }
21359    n = (int)strlen(z) + scanStatsHeight(p, ii)*3;
21360    if( n>nWidth ) nWidth = n;
21361  }
21362  nWidth += 4;
21363
21364  sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal);
21365  for(ii=0; 1; ii++){
21366    i64 nLoop = 0;
21367    i64 nRow = 0;
21368    i64 nCycle = 0;
21369    int iId = 0;
21370    int iPid = 0;
21371    const char *zo = 0;
21372    const char *zName = 0;
21373    char *zText = 0;
21374    double rEst = 0.0;
21375
21376    if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){
21377      break;
21378    }
21379    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst);
21380    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop);
21381    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow);
21382    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle);
21383    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId);
21384    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid);
21385    sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName);
21386
21387    zText = sqlite3_mprintf("%s", zo);
21388    if( nCycle>=0 || nLoop>=0 || nRow>=0 ){
21389      char *z = 0;
21390      if( nCycle>=0 && nTotal>0 ){
21391        z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z,
21392            nCycle, ((nCycle*100)+nTotal/2) / nTotal
21393        );
21394      }
21395      if( nLoop>=0 ){
21396        z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop);
21397      }
21398      if( nRow>=0 ){
21399        z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow);
21400      }
21401
21402      if( zName && pArg->scanstatsOn>1 ){
21403        double rpl = (double)nRow / (double)nLoop;
21404        z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst);
21405      }
21406
21407      zText = sqlite3_mprintf(
21408          "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z
21409      );
21410    }
21411
21412    eqp_append(pArg, iId, iPid, zText);
21413    sqlite3_free(zText);
21414  }
21415
21416  eqp_render(pArg, nTotal);
21417}
21418#endif
21419
21420
21421/*
21422** Parameter azArray points to a zero-terminated array of strings. zStr
21423** points to a single nul-terminated string. Return non-zero if zStr
21424** is equal, according to strcmp(), to any of the strings in the array.
21425** Otherwise, return zero.
21426*/
21427static int str_in_array(const char *zStr, const char **azArray){
21428  int i;
21429  for(i=0; azArray[i]; i++){
21430    if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
21431  }
21432  return 0;
21433}
21434
21435/*
21436** If compiled statement pSql appears to be an EXPLAIN statement, allocate
21437** and populate the ShellState.aiIndent[] array with the number of
21438** spaces each opcode should be indented before it is output.
21439**
21440** The indenting rules are:
21441**
21442**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
21443**       all opcodes that occur between the p2 jump destination and the opcode
21444**       itself by 2 spaces.
21445**
21446**     * Do the previous for "Return" instructions for when P2 is positive.
21447**       See tag-20220407a in wherecode.c and vdbe.c.
21448**
21449**     * For each "Goto", if the jump destination is earlier in the program
21450**       and ends on one of:
21451**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
21452**       or if the P1 parameter is one instead of zero,
21453**       then indent all opcodes between the earlier instruction
21454**       and "Goto" by 2 spaces.
21455*/
21456static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
21457  int *abYield = 0;               /* True if op is an OP_Yield */
21458  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
21459  int iOp;                        /* Index of operation in p->aiIndent[] */
21460
21461  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
21462                           "Return", 0 };
21463  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
21464                            "Rewind", 0 };
21465  const char *azGoto[] = { "Goto", 0 };
21466
21467  /* The caller guarantees that the leftmost 4 columns of the statement
21468  ** passed to this function are equivalent to the leftmost 4 columns
21469  ** of EXPLAIN statement output. In practice the statement may be
21470  ** an EXPLAIN, or it may be a query on the bytecode() virtual table.  */
21471  assert( sqlite3_column_count(pSql)>=4 );
21472  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) );
21473  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) );
21474  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) );
21475  assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) );
21476
21477  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
21478    int i;
21479    int iAddr = sqlite3_column_int(pSql, 0);
21480    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
21481    int p1 = sqlite3_column_int(pSql, 2);
21482    int p2 = sqlite3_column_int(pSql, 3);
21483
21484    /* Assuming that p2 is an instruction address, set variable p2op to the
21485    ** index of that instruction in the aiIndent[] array. p2 and p2op may be
21486    ** different if the current instruction is part of a sub-program generated
21487    ** by an SQL trigger or foreign key.  */
21488    int p2op = (p2 + (iOp-iAddr));
21489
21490    /* Grow the p->aiIndent array as required */
21491    if( iOp>=nAlloc ){
21492      nAlloc += 100;
21493      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
21494      shell_check_oom(p->aiIndent);
21495      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
21496      shell_check_oom(abYield);
21497    }
21498
21499    abYield[iOp] = str_in_array(zOp, azYield);
21500    p->aiIndent[iOp] = 0;
21501    p->nIndent = iOp+1;
21502    if( str_in_array(zOp, azNext) && p2op>0 ){
21503      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
21504    }
21505    if( str_in_array(zOp, azGoto) && p2op<iOp && (abYield[p2op] || p1) ){
21506      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
21507    }
21508  }
21509
21510  p->iIndent = 0;
21511  sqlite3_free(abYield);
21512  sqlite3_reset(pSql);
21513}
21514
21515/*
21516** Free the array allocated by explain_data_prepare().
21517*/
21518static void explain_data_delete(ShellState *p){
21519  sqlite3_free(p->aiIndent);
21520  p->aiIndent = 0;
21521  p->nIndent = 0;
21522  p->iIndent = 0;
21523}
21524
21525static void exec_prepared_stmt(ShellState*, sqlite3_stmt*);
21526
21527/*
21528** Display scan stats.
21529*/
21530static void display_scanstats(
21531  sqlite3 *db,                    /* Database to query */
21532  ShellState *pArg                /* Pointer to ShellState */
21533){
21534#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
21535  UNUSED_PARAMETER(db);
21536  UNUSED_PARAMETER(pArg);
21537#else
21538  if( pArg->scanstatsOn==3 ){
21539    const char *zSql =
21540      "  SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec,"
21541      "   round(ncycle*100.0 / (sum(ncycle) OVER ()), 2)||'%' AS cycles"
21542      "   FROM bytecode(?)";
21543
21544    int rc = SQLITE_OK;
21545    sqlite3_stmt *pStmt = 0;
21546    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
21547    if( rc==SQLITE_OK ){
21548      sqlite3_stmt *pSave = pArg->pStmt;
21549      pArg->pStmt = pStmt;
21550      sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0);
21551
21552      pArg->cnt = 0;
21553      pArg->cMode = MODE_ScanExp;
21554      explain_data_prepare(pArg, pStmt);
21555      exec_prepared_stmt(pArg, pStmt);
21556      explain_data_delete(pArg);
21557
21558      sqlite3_finalize(pStmt);
21559      pArg->pStmt = pSave;
21560    }
21561  }else{
21562    display_explain_scanstats(db, pArg);
21563  }
21564#endif
21565}
21566
21567/*
21568** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
21569*/
21570static unsigned int savedSelectTrace;
21571static unsigned int savedWhereTrace;
21572static void disable_debug_trace_modes(void){
21573  unsigned int zero = 0;
21574  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
21575  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
21576  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
21577  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
21578}
21579static void restore_debug_trace_modes(void){
21580  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
21581  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
21582}
21583
21584/* Create the TEMP table used to store parameter bindings */
21585static void bind_table_init(ShellState *p){
21586  int wrSchema = 0;
21587  int defensiveMode = 0;
21588  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
21589  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
21590  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
21591  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
21592  sqlite3_exec(p->db,
21593    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
21594    "  key TEXT PRIMARY KEY,\n"
21595    "  value\n"
21596    ") WITHOUT ROWID;",
21597    0, 0, 0);
21598  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
21599  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
21600}
21601
21602/*
21603** Bind parameters on a prepared statement.
21604**
21605** Parameter bindings are taken from a TEMP table of the form:
21606**
21607**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
21608**    WITHOUT ROWID;
21609**
21610** No bindings occur if this table does not exist.  The name of the table
21611** begins with "sqlite_" so that it will not collide with ordinary application
21612** tables.  The table must be in the TEMP schema.
21613*/
21614static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
21615  int nVar;
21616  int i;
21617  int rc;
21618  sqlite3_stmt *pQ = 0;
21619
21620  nVar = sqlite3_bind_parameter_count(pStmt);
21621  if( nVar==0 ) return;  /* Nothing to do */
21622  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
21623                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
21624    rc = SQLITE_NOTFOUND;
21625    pQ = 0;
21626  }else{
21627    rc = sqlite3_prepare_v2(pArg->db,
21628            "SELECT value FROM temp.sqlite_parameters"
21629            " WHERE key=?1", -1, &pQ, 0);
21630  }
21631  for(i=1; i<=nVar; i++){
21632    char zNum[30];
21633    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
21634    if( zVar==0 ){
21635      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
21636      zVar = zNum;
21637    }
21638    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
21639    if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){
21640      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
21641#ifdef NAN
21642    }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){
21643      sqlite3_bind_double(pStmt, i, NAN);
21644#endif
21645#ifdef INFINITY
21646    }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){
21647      sqlite3_bind_double(pStmt, i, INFINITY);
21648#endif
21649    }else{
21650      sqlite3_bind_null(pStmt, i);
21651    }
21652    sqlite3_reset(pQ);
21653  }
21654  sqlite3_finalize(pQ);
21655}
21656
21657/*
21658** UTF8 box-drawing characters.  Imagine box lines like this:
21659**
21660**           1
21661**           |
21662**       4 --+-- 2
21663**           |
21664**           3
21665**
21666** Each box characters has between 2 and 4 of the lines leading from
21667** the center.  The characters are here identified by the numbers of
21668** their corresponding lines.
21669*/
21670#define BOX_24   "\342\224\200"  /* U+2500 --- */
21671#define BOX_13   "\342\224\202"  /* U+2502  |  */
21672#define BOX_23   "\342\224\214"  /* U+250c  ,- */
21673#define BOX_34   "\342\224\220"  /* U+2510 -,  */
21674#define BOX_12   "\342\224\224"  /* U+2514  '- */
21675#define BOX_14   "\342\224\230"  /* U+2518 -'  */
21676#define BOX_123  "\342\224\234"  /* U+251c  |- */
21677#define BOX_134  "\342\224\244"  /* U+2524 -|  */
21678#define BOX_234  "\342\224\254"  /* U+252c -,- */
21679#define BOX_124  "\342\224\264"  /* U+2534 -'- */
21680#define BOX_1234 "\342\224\274"  /* U+253c -|- */
21681
21682/* Draw horizontal line N characters long using unicode box
21683** characters
21684*/
21685static void print_box_line(int N){
21686  const char zDash[] =
21687      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
21688      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
21689  const int nDash = sizeof(zDash) - 1;
21690  N *= 3;
21691  while( N>nDash ){
21692    oputz(zDash);
21693    N -= nDash;
21694  }
21695  oputf("%.*s", N, zDash);
21696}
21697
21698/*
21699** Draw a horizontal separator for a MODE_Box table.
21700*/
21701static void print_box_row_separator(
21702  ShellState *p,
21703  int nArg,
21704  const char *zSep1,
21705  const char *zSep2,
21706  const char *zSep3
21707){
21708  int i;
21709  if( nArg>0 ){
21710    oputz(zSep1);
21711    print_box_line(p->actualWidth[0]+2);
21712    for(i=1; i<nArg; i++){
21713      oputz(zSep2);
21714      print_box_line(p->actualWidth[i]+2);
21715    }
21716    oputz(zSep3);
21717  }
21718  oputz("\n");
21719}
21720
21721/*
21722** z[] is a line of text that is to be displayed the .mode box or table or
21723** similar tabular formats.  z[] might contain control characters such
21724** as \n, \t, \f, or \r.
21725**
21726** Compute characters to display on the first line of z[].  Stop at the
21727** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
21728** from malloc()) of that first line, which caller should free sometime.
21729** Write anything to display on the next line into *pzTail.  If this is
21730** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
21731*/
21732static char *translateForDisplayAndDup(
21733  const unsigned char *z,            /* Input text to be transformed */
21734  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
21735  int mxWidth,                       /* Max width.  0 means no limit */
21736  u8 bWordWrap                       /* If true, avoid breaking mid-word */
21737){
21738  int i;                 /* Input bytes consumed */
21739  int j;                 /* Output bytes generated */
21740  int k;                 /* Input bytes to be displayed */
21741  int n;                 /* Output column number */
21742  unsigned char *zOut;   /* Output text */
21743
21744  if( z==0 ){
21745    *pzTail = 0;
21746    return 0;
21747  }
21748  if( mxWidth<0 ) mxWidth = -mxWidth;
21749  if( mxWidth==0 ) mxWidth = 1000000;
21750  i = j = n = 0;
21751  while( n<mxWidth ){
21752    if( z[i]>=' ' ){
21753      n++;
21754      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
21755      continue;
21756    }
21757    if( z[i]=='\t' ){
21758      do{
21759        n++;
21760        j++;
21761      }while( (n&7)!=0 && n<mxWidth );
21762      i++;
21763      continue;
21764    }
21765    break;
21766  }
21767  if( n>=mxWidth && bWordWrap  ){
21768    /* Perhaps try to back up to a better place to break the line */
21769    for(k=i; k>i/2; k--){
21770      if( isspace(z[k-1]) ) break;
21771    }
21772    if( k<=i/2 ){
21773      for(k=i; k>i/2; k--){
21774        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
21775      }
21776    }
21777    if( k<=i/2 ){
21778      k = i;
21779    }else{
21780      i = k;
21781      while( z[i]==' ' ) i++;
21782    }
21783  }else{
21784    k = i;
21785  }
21786  if( n>=mxWidth && z[i]>=' ' ){
21787   *pzTail = &z[i];
21788  }else if( z[i]=='\r' && z[i+1]=='\n' ){
21789    *pzTail = z[i+2] ? &z[i+2] : 0;
21790  }else if( z[i]==0 || z[i+1]==0 ){
21791    *pzTail = 0;
21792  }else{
21793    *pzTail = &z[i+1];
21794  }
21795  zOut = malloc( j+1 );
21796  shell_check_oom(zOut);
21797  i = j = n = 0;
21798  while( i<k ){
21799    if( z[i]>=' ' ){
21800      n++;
21801      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
21802      continue;
21803    }
21804    if( z[i]=='\t' ){
21805      do{
21806        n++;
21807        zOut[j++] = ' ';
21808      }while( (n&7)!=0 && n<mxWidth );
21809      i++;
21810      continue;
21811    }
21812    break;
21813  }
21814  zOut[j] = 0;
21815  return (char*)zOut;
21816}
21817
21818/* Extract the value of the i-th current column for pStmt as an SQL literal
21819** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
21820** the caller.
21821*/
21822static char *quoted_column(sqlite3_stmt *pStmt, int i){
21823  switch( sqlite3_column_type(pStmt, i) ){
21824    case SQLITE_NULL: {
21825      return sqlite3_mprintf("NULL");
21826    }
21827    case SQLITE_INTEGER:
21828    case SQLITE_FLOAT: {
21829      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
21830    }
21831    case SQLITE_TEXT: {
21832      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
21833    }
21834    case SQLITE_BLOB: {
21835      int j;
21836      sqlite3_str *pStr = sqlite3_str_new(0);
21837      const unsigned char *a = sqlite3_column_blob(pStmt,i);
21838      int n = sqlite3_column_bytes(pStmt,i);
21839      sqlite3_str_append(pStr, "x'", 2);
21840      for(j=0; j<n; j++){
21841        sqlite3_str_appendf(pStr, "%02x", a[j]);
21842      }
21843      sqlite3_str_append(pStr, "'", 1);
21844      return sqlite3_str_finish(pStr);
21845    }
21846  }
21847  return 0; /* Not reached */
21848}
21849
21850/*
21851** Run a prepared statement and output the result in one of the
21852** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
21853** or MODE_Box.
21854**
21855** This is different from ordinary exec_prepared_stmt() in that
21856** it has to run the entire query and gather the results into memory
21857** first, in order to determine column widths, before providing
21858** any output.
21859*/
21860static void exec_prepared_stmt_columnar(
21861  ShellState *p,                        /* Pointer to ShellState */
21862  sqlite3_stmt *pStmt                   /* Statement to run */
21863){
21864  sqlite3_int64 nRow = 0;
21865  int nColumn = 0;
21866  char **azData = 0;
21867  sqlite3_int64 nAlloc = 0;
21868  char *abRowDiv = 0;
21869  const unsigned char *uz;
21870  const char *z;
21871  char **azQuoted = 0;
21872  int rc;
21873  sqlite3_int64 i, nData;
21874  int j, nTotal, w, n;
21875  const char *colSep = 0;
21876  const char *rowSep = 0;
21877  const unsigned char **azNextLine = 0;
21878  int bNextLine = 0;
21879  int bMultiLineRowExists = 0;
21880  int bw = p->cmOpts.bWordWrap;
21881  const char *zEmpty = "";
21882  const char *zShowNull = p->nullValue;
21883
21884  rc = sqlite3_step(pStmt);
21885  if( rc!=SQLITE_ROW ) return;
21886  nColumn = sqlite3_column_count(pStmt);
21887  if( nColumn==0 ) goto columnar_end;
21888  nAlloc = nColumn*4;
21889  if( nAlloc<=0 ) nAlloc = 1;
21890  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
21891  shell_check_oom(azData);
21892  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
21893  shell_check_oom(azNextLine);
21894  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
21895  if( p->cmOpts.bQuote ){
21896    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
21897    shell_check_oom(azQuoted);
21898    memset(azQuoted, 0, nColumn*sizeof(char*) );
21899  }
21900  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
21901  shell_check_oom(abRowDiv);
21902  if( nColumn>p->nWidth ){
21903    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
21904    shell_check_oom(p->colWidth);
21905    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
21906    p->nWidth = nColumn;
21907    p->actualWidth = &p->colWidth[nColumn];
21908  }
21909  memset(p->actualWidth, 0, nColumn*sizeof(int));
21910  for(i=0; i<nColumn; i++){
21911    w = p->colWidth[i];
21912    if( w<0 ) w = -w;
21913    p->actualWidth[i] = w;
21914  }
21915  for(i=0; i<nColumn; i++){
21916    const unsigned char *zNotUsed;
21917    int wx = p->colWidth[i];
21918    if( wx==0 ){
21919      wx = p->cmOpts.iWrap;
21920    }
21921    if( wx<0 ) wx = -wx;
21922    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
21923    if( uz==0 ) uz = (u8*)"";
21924    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
21925  }
21926  do{
21927    int useNextLine = bNextLine;
21928    bNextLine = 0;
21929    if( (nRow+2)*nColumn >= nAlloc ){
21930      nAlloc *= 2;
21931      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
21932      shell_check_oom(azData);
21933      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
21934      shell_check_oom(abRowDiv);
21935    }
21936    abRowDiv[nRow] = 1;
21937    nRow++;
21938    for(i=0; i<nColumn; i++){
21939      int wx = p->colWidth[i];
21940      if( wx==0 ){
21941        wx = p->cmOpts.iWrap;
21942      }
21943      if( wx<0 ) wx = -wx;
21944      if( useNextLine ){
21945        uz = azNextLine[i];
21946        if( uz==0 ) uz = (u8*)zEmpty;
21947      }else if( p->cmOpts.bQuote ){
21948        sqlite3_free(azQuoted[i]);
21949        azQuoted[i] = quoted_column(pStmt,i);
21950        uz = (const unsigned char*)azQuoted[i];
21951      }else{
21952        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
21953        if( uz==0 ) uz = (u8*)zShowNull;
21954      }
21955      azData[nRow*nColumn + i]
21956        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
21957      if( azNextLine[i] ){
21958        bNextLine = 1;
21959        abRowDiv[nRow-1] = 0;
21960        bMultiLineRowExists = 1;
21961      }
21962    }
21963  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
21964  nTotal = nColumn*(nRow+1);
21965  for(i=0; i<nTotal; i++){
21966    z = azData[i];
21967    if( z==0 ) z = (char*)zEmpty;
21968    n = strlenChar(z);
21969    j = i%nColumn;
21970    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
21971  }
21972  if( seenInterrupt ) goto columnar_end;
21973  switch( p->cMode ){
21974    case MODE_Column: {
21975      colSep = "  ";
21976      rowSep = "\n";
21977      if( p->showHeader ){
21978        for(i=0; i<nColumn; i++){
21979          w = p->actualWidth[i];
21980          if( p->colWidth[i]<0 ) w = -w;
21981          utf8_width_print(w, azData[i]);
21982          fputs(i==nColumn-1?"\n":"  ", p->out);
21983        }
21984        for(i=0; i<nColumn; i++){
21985          print_dashes(p->actualWidth[i]);
21986          fputs(i==nColumn-1?"\n":"  ", p->out);
21987        }
21988      }
21989      break;
21990    }
21991    case MODE_Table: {
21992      colSep = " | ";
21993      rowSep = " |\n";
21994      print_row_separator(p, nColumn, "+");
21995      fputs("| ", p->out);
21996      for(i=0; i<nColumn; i++){
21997        w = p->actualWidth[i];
21998        n = strlenChar(azData[i]);
21999        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
22000        oputz(i==nColumn-1?" |\n":" | ");
22001      }
22002      print_row_separator(p, nColumn, "+");
22003      break;
22004    }
22005    case MODE_Markdown: {
22006      colSep = " | ";
22007      rowSep = " |\n";
22008      fputs("| ", p->out);
22009      for(i=0; i<nColumn; i++){
22010        w = p->actualWidth[i];
22011        n = strlenChar(azData[i]);
22012        oputf("%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
22013        oputz(i==nColumn-1?" |\n":" | ");
22014      }
22015      print_row_separator(p, nColumn, "|");
22016      break;
22017    }
22018    case MODE_Box: {
22019      colSep = " " BOX_13 " ";
22020      rowSep = " " BOX_13 "\n";
22021      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
22022      oputz(BOX_13 " ");
22023      for(i=0; i<nColumn; i++){
22024        w = p->actualWidth[i];
22025        n = strlenChar(azData[i]);
22026        oputf("%*s%s%*s%s",
22027              (w-n)/2, "", azData[i], (w-n+1)/2, "",
22028              i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
22029      }
22030      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
22031      break;
22032    }
22033  }
22034  for(i=nColumn, j=0; i<nTotal; i++, j++){
22035    if( j==0 && p->cMode!=MODE_Column ){
22036      oputz(p->cMode==MODE_Box?BOX_13" ":"| ");
22037    }
22038    z = azData[i];
22039    if( z==0 ) z = p->nullValue;
22040    w = p->actualWidth[j];
22041    if( p->colWidth[j]<0 ) w = -w;
22042    utf8_width_print(w, z);
22043    if( j==nColumn-1 ){
22044      oputz(rowSep);
22045      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
22046        if( p->cMode==MODE_Table ){
22047          print_row_separator(p, nColumn, "+");
22048        }else if( p->cMode==MODE_Box ){
22049          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
22050        }else if( p->cMode==MODE_Column ){
22051          oputz("\n");
22052        }
22053      }
22054      j = -1;
22055      if( seenInterrupt ) goto columnar_end;
22056    }else{
22057      oputz(colSep);
22058    }
22059  }
22060  if( p->cMode==MODE_Table ){
22061    print_row_separator(p, nColumn, "+");
22062  }else if( p->cMode==MODE_Box ){
22063    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
22064  }
22065columnar_end:
22066  if( seenInterrupt ){
22067    oputz("Interrupt\n");
22068  }
22069  nData = (nRow+1)*nColumn;
22070  for(i=0; i<nData; i++){
22071    z = azData[i];
22072    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
22073  }
22074  sqlite3_free(azData);
22075  sqlite3_free((void*)azNextLine);
22076  sqlite3_free(abRowDiv);
22077  if( azQuoted ){
22078    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
22079    sqlite3_free(azQuoted);
22080  }
22081}
22082
22083/*
22084** Run a prepared statement
22085*/
22086static void exec_prepared_stmt(
22087  ShellState *pArg,                                /* Pointer to ShellState */
22088  sqlite3_stmt *pStmt                              /* Statement to run */
22089){
22090  int rc;
22091  sqlite3_uint64 nRow = 0;
22092
22093  if( pArg->cMode==MODE_Column
22094   || pArg->cMode==MODE_Table
22095   || pArg->cMode==MODE_Box
22096   || pArg->cMode==MODE_Markdown
22097  ){
22098    exec_prepared_stmt_columnar(pArg, pStmt);
22099    return;
22100  }
22101
22102  /* perform the first step.  this will tell us if we
22103  ** have a result set or not and how wide it is.
22104  */
22105  rc = sqlite3_step(pStmt);
22106  /* if we have a result set... */
22107  if( SQLITE_ROW == rc ){
22108    /* allocate space for col name ptr, value ptr, and type */
22109    int nCol = sqlite3_column_count(pStmt);
22110    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
22111    if( !pData ){
22112      shell_out_of_memory();
22113    }else{
22114      char **azCols = (char **)pData;      /* Names of result columns */
22115      char **azVals = &azCols[nCol];       /* Results */
22116      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
22117      int i, x;
22118      assert(sizeof(int) <= sizeof(char *));
22119      /* save off ptrs to column names */
22120      for(i=0; i<nCol; i++){
22121        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
22122      }
22123      do{
22124        nRow++;
22125        /* extract the data and data types */
22126        for(i=0; i<nCol; i++){
22127          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
22128          if( x==SQLITE_BLOB
22129           && pArg
22130           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
22131          ){
22132            azVals[i] = "";
22133          }else{
22134            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
22135          }
22136          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
22137            rc = SQLITE_NOMEM;
22138            break; /* from for */
22139          }
22140        } /* end for */
22141
22142        /* if data and types extracted successfully... */
22143        if( SQLITE_ROW == rc ){
22144          /* call the supplied callback with the result row data */
22145          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
22146            rc = SQLITE_ABORT;
22147          }else{
22148            rc = sqlite3_step(pStmt);
22149          }
22150        }
22151      } while( SQLITE_ROW == rc );
22152      sqlite3_free(pData);
22153      if( pArg->cMode==MODE_Json ){
22154        fputs("]\n", pArg->out);
22155      }else if( pArg->cMode==MODE_Count ){
22156        char zBuf[200];
22157        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
22158                         nRow, nRow!=1 ? "s" : "");
22159        printf("%s", zBuf);
22160      }
22161    }
22162  }
22163}
22164
22165#ifndef SQLITE_OMIT_VIRTUALTABLE
22166/*
22167** This function is called to process SQL if the previous shell command
22168** was ".expert". It passes the SQL in the second argument directly to
22169** the sqlite3expert object.
22170**
22171** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
22172** code. In this case, (*pzErr) may be set to point to a buffer containing
22173** an English language error message. It is the responsibility of the
22174** caller to eventually free this buffer using sqlite3_free().
22175*/
22176static int expertHandleSQL(
22177  ShellState *pState,
22178  const char *zSql,
22179  char **pzErr
22180){
22181  assert( pState->expert.pExpert );
22182  assert( pzErr==0 || *pzErr==0 );
22183  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
22184}
22185
22186/*
22187** This function is called either to silently clean up the object
22188** created by the ".expert" command (if bCancel==1), or to generate a
22189** report from it and then clean it up (if bCancel==0).
22190**
22191** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
22192** code. In this case, (*pzErr) may be set to point to a buffer containing
22193** an English language error message. It is the responsibility of the
22194** caller to eventually free this buffer using sqlite3_free().
22195*/
22196static int expertFinish(
22197  ShellState *pState,
22198  int bCancel,
22199  char **pzErr
22200){
22201  int rc = SQLITE_OK;
22202  sqlite3expert *p = pState->expert.pExpert;
22203  assert( p );
22204  assert( bCancel || pzErr==0 || *pzErr==0 );
22205  if( bCancel==0 ){
22206    int bVerbose = pState->expert.bVerbose;
22207
22208    rc = sqlite3_expert_analyze(p, pzErr);
22209    if( rc==SQLITE_OK ){
22210      int nQuery = sqlite3_expert_count(p);
22211      int i;
22212
22213      if( bVerbose ){
22214        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
22215        oputz("-- Candidates -----------------------------\n");
22216        oputf("%s\n", zCand);
22217      }
22218      for(i=0; i<nQuery; i++){
22219        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
22220        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
22221        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
22222        if( zIdx==0 ) zIdx = "(no new indexes)\n";
22223        if( bVerbose ){
22224          oputf("-- Query %d --------------------------------\n",i+1);
22225          oputf("%s\n\n", zSql);
22226        }
22227        oputf("%s\n", zIdx);
22228        oputf("%s\n", zEQP);
22229      }
22230    }
22231  }
22232  sqlite3_expert_destroy(p);
22233  pState->expert.pExpert = 0;
22234  return rc;
22235}
22236
22237/*
22238** Implementation of ".expert" dot command.
22239*/
22240static int expertDotCommand(
22241  ShellState *pState,             /* Current shell tool state */
22242  char **azArg,                   /* Array of arguments passed to dot command */
22243  int nArg                        /* Number of entries in azArg[] */
22244){
22245  int rc = SQLITE_OK;
22246  char *zErr = 0;
22247  int i;
22248  int iSample = 0;
22249
22250  assert( pState->expert.pExpert==0 );
22251  memset(&pState->expert, 0, sizeof(ExpertInfo));
22252
22253  for(i=1; rc==SQLITE_OK && i<nArg; i++){
22254    char *z = azArg[i];
22255    int n;
22256    if( z[0]=='-' && z[1]=='-' ) z++;
22257    n = strlen30(z);
22258    if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
22259      pState->expert.bVerbose = 1;
22260    }
22261    else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
22262      if( i==(nArg-1) ){
22263        eputf("option requires an argument: %s\n", z);
22264        rc = SQLITE_ERROR;
22265      }else{
22266        iSample = (int)integerValue(azArg[++i]);
22267        if( iSample<0 || iSample>100 ){
22268          eputf("value out of range: %s\n", azArg[i]);
22269          rc = SQLITE_ERROR;
22270        }
22271      }
22272    }
22273    else{
22274      eputf("unknown option: %s\n", z);
22275      rc = SQLITE_ERROR;
22276    }
22277  }
22278
22279  if( rc==SQLITE_OK ){
22280    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
22281    if( pState->expert.pExpert==0 ){
22282      eputf("sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
22283      rc = SQLITE_ERROR;
22284    }else{
22285      sqlite3_expert_config(
22286          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
22287      );
22288    }
22289  }
22290  sqlite3_free(zErr);
22291
22292  return rc;
22293}
22294#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
22295
22296/*
22297** Execute a statement or set of statements.  Print
22298** any result rows/columns depending on the current mode
22299** set via the supplied callback.
22300**
22301** This is very similar to SQLite's built-in sqlite3_exec()
22302** function except it takes a slightly different callback
22303** and callback data argument.
22304*/
22305static int shell_exec(
22306  ShellState *pArg,                         /* Pointer to ShellState */
22307  const char *zSql,                         /* SQL to be evaluated */
22308  char **pzErrMsg                           /* Error msg written here */
22309){
22310  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
22311  int rc = SQLITE_OK;             /* Return Code */
22312  int rc2;
22313  const char *zLeftover;          /* Tail of unprocessed SQL */
22314  sqlite3 *db = pArg->db;
22315
22316  if( pzErrMsg ){
22317    *pzErrMsg = NULL;
22318  }
22319
22320#ifndef SQLITE_OMIT_VIRTUALTABLE
22321  if( pArg->expert.pExpert ){
22322    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
22323    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
22324  }
22325#endif
22326
22327  while( zSql[0] && (SQLITE_OK == rc) ){
22328    static const char *zStmtSql;
22329    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
22330    if( SQLITE_OK != rc ){
22331      if( pzErrMsg ){
22332        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
22333      }
22334    }else{
22335      if( !pStmt ){
22336        /* this happens for a comment or white-space */
22337        zSql = zLeftover;
22338        while( IsSpace(zSql[0]) ) zSql++;
22339        continue;
22340      }
22341      zStmtSql = sqlite3_sql(pStmt);
22342      if( zStmtSql==0 ) zStmtSql = "";
22343      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
22344
22345      /* save off the prepared statement handle and reset row count */
22346      if( pArg ){
22347        pArg->pStmt = pStmt;
22348        pArg->cnt = 0;
22349      }
22350
22351      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
22352      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
22353        sqlite3_stmt *pExplain;
22354        int triggerEQP = 0;
22355        disable_debug_trace_modes();
22356        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
22357        if( pArg->autoEQP>=AUTOEQP_trigger ){
22358          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
22359        }
22360        pExplain = pStmt;
22361        sqlite3_reset(pExplain);
22362        rc = sqlite3_stmt_explain(pExplain, 2);
22363        if( rc==SQLITE_OK ){
22364          while( sqlite3_step(pExplain)==SQLITE_ROW ){
22365            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
22366            int iEqpId = sqlite3_column_int(pExplain, 0);
22367            int iParentId = sqlite3_column_int(pExplain, 1);
22368            if( zEQPLine==0 ) zEQPLine = "";
22369            if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
22370            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
22371          }
22372          eqp_render(pArg, 0);
22373        }
22374        if( pArg->autoEQP>=AUTOEQP_full ){
22375          /* Also do an EXPLAIN for ".eqp full" mode */
22376          sqlite3_reset(pExplain);
22377          rc = sqlite3_stmt_explain(pExplain, 1);
22378          if( rc==SQLITE_OK ){
22379            pArg->cMode = MODE_Explain;
22380            assert( sqlite3_stmt_isexplain(pExplain)==1 );
22381            explain_data_prepare(pArg, pExplain);
22382            exec_prepared_stmt(pArg, pExplain);
22383            explain_data_delete(pArg);
22384          }
22385        }
22386        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
22387          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
22388        }
22389        sqlite3_reset(pStmt);
22390        sqlite3_stmt_explain(pStmt, 0);
22391        restore_debug_trace_modes();
22392      }
22393
22394      if( pArg ){
22395        int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
22396        pArg->cMode = pArg->mode;
22397        if( pArg->autoExplain ){
22398          if( bIsExplain ){
22399            pArg->cMode = MODE_Explain;
22400          }
22401          if( sqlite3_stmt_isexplain(pStmt)==2 ){
22402            pArg->cMode = MODE_EQP;
22403          }
22404        }
22405
22406        /* If the shell is currently in ".explain" mode, gather the extra
22407        ** data required to add indents to the output.*/
22408        if( pArg->cMode==MODE_Explain && bIsExplain ){
22409          explain_data_prepare(pArg, pStmt);
22410        }
22411      }
22412
22413      bind_prepared_stmt(pArg, pStmt);
22414      exec_prepared_stmt(pArg, pStmt);
22415      explain_data_delete(pArg);
22416      eqp_render(pArg, 0);
22417
22418      /* print usage stats if stats on */
22419      if( pArg && pArg->statsOn ){
22420        display_stats(db, pArg, 0);
22421      }
22422
22423      /* print loop-counters if required */
22424      if( pArg && pArg->scanstatsOn ){
22425        display_scanstats(db, pArg);
22426      }
22427
22428      /* Finalize the statement just executed. If this fails, save a
22429      ** copy of the error message. Otherwise, set zSql to point to the
22430      ** next statement to execute. */
22431      rc2 = sqlite3_finalize(pStmt);
22432      if( rc!=SQLITE_NOMEM ) rc = rc2;
22433      if( rc==SQLITE_OK ){
22434        zSql = zLeftover;
22435        while( IsSpace(zSql[0]) ) zSql++;
22436      }else if( pzErrMsg ){
22437        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
22438      }
22439
22440      /* clear saved stmt handle */
22441      if( pArg ){
22442        pArg->pStmt = NULL;
22443      }
22444    }
22445  } /* end while */
22446
22447  return rc;
22448}
22449
22450/*
22451** Release memory previously allocated by tableColumnList().
22452*/
22453static void freeColumnList(char **azCol){
22454  int i;
22455  for(i=1; azCol[i]; i++){
22456    sqlite3_free(azCol[i]);
22457  }
22458  /* azCol[0] is a static string */
22459  sqlite3_free(azCol);
22460}
22461
22462/*
22463** Return a list of pointers to strings which are the names of all
22464** columns in table zTab.   The memory to hold the names is dynamically
22465** allocated and must be released by the caller using a subsequent call
22466** to freeColumnList().
22467**
22468** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
22469** value that needs to be preserved, then azCol[0] is filled in with the
22470** name of the rowid column.
22471**
22472** The first regular column in the table is azCol[1].  The list is terminated
22473** by an entry with azCol[i]==0.
22474*/
22475static char **tableColumnList(ShellState *p, const char *zTab){
22476  char **azCol = 0;
22477  sqlite3_stmt *pStmt;
22478  char *zSql;
22479  int nCol = 0;
22480  int nAlloc = 0;
22481  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
22482  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
22483  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
22484  int rc;
22485
22486  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
22487  shell_check_oom(zSql);
22488  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
22489  sqlite3_free(zSql);
22490  if( rc ) return 0;
22491  while( sqlite3_step(pStmt)==SQLITE_ROW ){
22492    if( nCol>=nAlloc-2 ){
22493      nAlloc = nAlloc*2 + nCol + 10;
22494      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
22495      shell_check_oom(azCol);
22496    }
22497    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
22498    shell_check_oom(azCol[nCol]);
22499    if( sqlite3_column_int(pStmt, 5) ){
22500      nPK++;
22501      if( nPK==1
22502       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
22503                          "INTEGER")==0
22504      ){
22505        isIPK = 1;
22506      }else{
22507        isIPK = 0;
22508      }
22509    }
22510  }
22511  sqlite3_finalize(pStmt);
22512  if( azCol==0 ) return 0;
22513  azCol[0] = 0;
22514  azCol[nCol+1] = 0;
22515
22516  /* The decision of whether or not a rowid really needs to be preserved
22517  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
22518  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
22519  ** rowids on tables where the rowid is inaccessible because there are other
22520  ** columns in the table named "rowid", "_rowid_", and "oid".
22521  */
22522  if( preserveRowid && isIPK ){
22523    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
22524    ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
22525    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
22526    ** ROWID aliases.  To distinguish these cases, check to see if
22527    ** there is a "pk" entry in "PRAGMA index_list".  There will be
22528    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
22529    */
22530    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
22531                           " WHERE origin='pk'", zTab);
22532    shell_check_oom(zSql);
22533    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
22534    sqlite3_free(zSql);
22535    if( rc ){
22536      freeColumnList(azCol);
22537      return 0;
22538    }
22539    rc = sqlite3_step(pStmt);
22540    sqlite3_finalize(pStmt);
22541    preserveRowid = rc==SQLITE_ROW;
22542  }
22543  if( preserveRowid ){
22544    /* Only preserve the rowid if we can find a name to use for the
22545    ** rowid */
22546    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
22547    int i, j;
22548    for(j=0; j<3; j++){
22549      for(i=1; i<=nCol; i++){
22550        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
22551      }
22552      if( i>nCol ){
22553        /* At this point, we know that azRowid[j] is not the name of any
22554        ** ordinary column in the table.  Verify that azRowid[j] is a valid
22555        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
22556        ** tables will fail this last check */
22557        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
22558        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
22559        break;
22560      }
22561    }
22562  }
22563  return azCol;
22564}
22565
22566/*
22567** Toggle the reverse_unordered_selects setting.
22568*/
22569static void toggleSelectOrder(sqlite3 *db){
22570  sqlite3_stmt *pStmt = 0;
22571  int iSetting = 0;
22572  char zStmt[100];
22573  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
22574  if( sqlite3_step(pStmt)==SQLITE_ROW ){
22575    iSetting = sqlite3_column_int(pStmt, 0);
22576  }
22577  sqlite3_finalize(pStmt);
22578  sqlite3_snprintf(sizeof(zStmt), zStmt,
22579       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
22580  sqlite3_exec(db, zStmt, 0, 0, 0);
22581}
22582
22583/*
22584** This is a different callback routine used for dumping the database.
22585** Each row received by this callback consists of a table name,
22586** the table type ("index" or "table") and SQL to create the table.
22587** This routine should print text sufficient to recreate the table.
22588*/
22589static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
22590  int rc;
22591  const char *zTable;
22592  const char *zType;
22593  const char *zSql;
22594  ShellState *p = (ShellState *)pArg;
22595  int dataOnly;
22596  int noSys;
22597
22598  UNUSED_PARAMETER(azNotUsed);
22599  if( nArg!=3 || azArg==0 ) return 0;
22600  zTable = azArg[0];
22601  zType = azArg[1];
22602  zSql = azArg[2];
22603  if( zTable==0 ) return 0;
22604  if( zType==0 ) return 0;
22605  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
22606  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
22607
22608  if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
22609    if( !dataOnly ) oputz("DELETE FROM sqlite_sequence;\n");
22610  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
22611    if( !dataOnly ) oputz("ANALYZE sqlite_schema;\n");
22612  }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
22613    return 0;
22614  }else if( dataOnly ){
22615    /* no-op */
22616  }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
22617    char *zIns;
22618    if( !p->writableSchema ){
22619      oputz("PRAGMA writable_schema=ON;\n");
22620      p->writableSchema = 1;
22621    }
22622    zIns = sqlite3_mprintf(
22623       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
22624       "VALUES('table','%q','%q',0,'%q');",
22625       zTable, zTable, zSql);
22626    shell_check_oom(zIns);
22627    oputf("%s\n", zIns);
22628    sqlite3_free(zIns);
22629    return 0;
22630  }else{
22631    printSchemaLine(zSql, ";\n");
22632  }
22633
22634  if( cli_strcmp(zType, "table")==0 ){
22635    ShellText sSelect;
22636    ShellText sTable;
22637    char **azCol;
22638    int i;
22639    char *savedDestTable;
22640    int savedMode;
22641
22642    azCol = tableColumnList(p, zTable);
22643    if( azCol==0 ){
22644      p->nErr++;
22645      return 0;
22646    }
22647
22648    /* Always quote the table name, even if it appears to be pure ascii,
22649    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
22650    initText(&sTable);
22651    appendText(&sTable, zTable, quoteChar(zTable));
22652    /* If preserving the rowid, add a column list after the table name.
22653    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
22654    ** instead of the usual "INSERT INTO tab VALUES(...)".
22655    */
22656    if( azCol[0] ){
22657      appendText(&sTable, "(", 0);
22658      appendText(&sTable, azCol[0], 0);
22659      for(i=1; azCol[i]; i++){
22660        appendText(&sTable, ",", 0);
22661        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
22662      }
22663      appendText(&sTable, ")", 0);
22664    }
22665
22666    /* Build an appropriate SELECT statement */
22667    initText(&sSelect);
22668    appendText(&sSelect, "SELECT ", 0);
22669    if( azCol[0] ){
22670      appendText(&sSelect, azCol[0], 0);
22671      appendText(&sSelect, ",", 0);
22672    }
22673    for(i=1; azCol[i]; i++){
22674      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
22675      if( azCol[i+1] ){
22676        appendText(&sSelect, ",", 0);
22677      }
22678    }
22679    freeColumnList(azCol);
22680    appendText(&sSelect, " FROM ", 0);
22681    appendText(&sSelect, zTable, quoteChar(zTable));
22682
22683    savedDestTable = p->zDestTable;
22684    savedMode = p->mode;
22685    p->zDestTable = sTable.z;
22686    p->mode = p->cMode = MODE_Insert;
22687    rc = shell_exec(p, sSelect.z, 0);
22688    if( (rc&0xff)==SQLITE_CORRUPT ){
22689      oputz("/****** CORRUPTION ERROR *******/\n");
22690      toggleSelectOrder(p->db);
22691      shell_exec(p, sSelect.z, 0);
22692      toggleSelectOrder(p->db);
22693    }
22694    p->zDestTable = savedDestTable;
22695    p->mode = savedMode;
22696    freeText(&sTable);
22697    freeText(&sSelect);
22698    if( rc ) p->nErr++;
22699  }
22700  return 0;
22701}
22702
22703/*
22704** Run zQuery.  Use dump_callback() as the callback routine so that
22705** the contents of the query are output as SQL statements.
22706**
22707** If we get a SQLITE_CORRUPT error, rerun the query after appending
22708** "ORDER BY rowid DESC" to the end.
22709*/
22710static int run_schema_dump_query(
22711  ShellState *p,
22712  const char *zQuery
22713){
22714  int rc;
22715  char *zErr = 0;
22716  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
22717  if( rc==SQLITE_CORRUPT ){
22718    char *zQ2;
22719    int len = strlen30(zQuery);
22720    oputz("/****** CORRUPTION ERROR *******/\n");
22721    if( zErr ){
22722      oputf("/****** %s ******/\n", zErr);
22723      sqlite3_free(zErr);
22724      zErr = 0;
22725    }
22726    zQ2 = malloc( len+100 );
22727    if( zQ2==0 ) return rc;
22728    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
22729    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
22730    if( rc ){
22731      oputf("/****** ERROR: %s ******/\n", zErr);
22732    }else{
22733      rc = SQLITE_CORRUPT;
22734    }
22735    sqlite3_free(zErr);
22736    free(zQ2);
22737  }
22738  return rc;
22739}
22740
22741/*
22742** Text of help messages.
22743**
22744** The help text for each individual command begins with a line that starts
22745** with ".".  Subsequent lines are supplemental information.
22746**
22747** There must be two or more spaces between the end of the command and the
22748** start of the description of what that command does.
22749*/
22750static const char *(azHelp[]) = {
22751#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
22752  && !defined(SQLITE_SHELL_FIDDLE)
22753  ".archive ...             Manage SQL archives",
22754  "   Each command must have exactly one of the following options:",
22755  "     -c, --create               Create a new archive",
22756  "     -u, --update               Add or update files with changed mtime",
22757  "     -i, --insert               Like -u but always add even if unchanged",
22758  "     -r, --remove               Remove files from archive",
22759  "     -t, --list                 List contents of archive",
22760  "     -x, --extract              Extract files from archive",
22761  "   Optional arguments:",
22762  "     -v, --verbose              Print each filename as it is processed",
22763  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
22764  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
22765  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
22766  "     -g, --glob                 Use glob matching for names in archive",
22767  "     -n, --dryrun               Show the SQL that would have occurred",
22768  "   Examples:",
22769  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
22770  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
22771  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
22772  "   See also:",
22773  "      http://sqlite.org/cli.html#sqlite_archive_support",
22774#endif
22775#ifndef SQLITE_OMIT_AUTHORIZATION
22776  ".auth ON|OFF             Show authorizer callbacks",
22777#endif
22778#ifndef SQLITE_SHELL_FIDDLE
22779  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
22780  "   Options:",
22781  "       --append            Use the appendvfs",
22782  "       --async             Write to FILE without journal and fsync()",
22783#endif
22784  ".bail on|off             Stop after hitting an error.  Default OFF",
22785#ifndef SQLITE_SHELL_FIDDLE
22786  ".cd DIRECTORY            Change the working directory to DIRECTORY",
22787#endif
22788  ".changes on|off          Show number of rows changed by SQL",
22789#ifndef SQLITE_SHELL_FIDDLE
22790  ".check GLOB              Fail if output since .testcase does not match",
22791  ".clone NEWDB             Clone data into NEWDB from the existing database",
22792#endif
22793  ".connection [close] [#]  Open or close an auxiliary database connection",
22794#if defined(_WIN32) || defined(WIN32)
22795  ".crnl on|off             Translate \\n to \\r\\n.  Default ON",
22796#endif
22797  ".databases               List names and files of attached databases",
22798  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
22799#if SQLITE_SHELL_HAVE_RECOVER
22800  ".dbinfo ?DB?             Show status information about the database",
22801#endif
22802  ".dump ?OBJECTS?          Render database content as SQL",
22803  "   Options:",
22804  "     --data-only            Output only INSERT statements",
22805  "     --newlines             Allow unescaped newline characters in output",
22806  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
22807  "     --preserve-rowids      Include ROWID values in the output",
22808  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
22809  "   Additional LIKE patterns can be given in subsequent arguments",
22810  ".echo on|off             Turn command echo on or off",
22811  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
22812  "   Other Modes:",
22813#ifdef SQLITE_DEBUG
22814  "      test                  Show raw EXPLAIN QUERY PLAN output",
22815  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
22816#endif
22817  "      trigger               Like \"full\" but also show trigger bytecode",
22818#ifndef SQLITE_SHELL_FIDDLE
22819  ".excel                   Display the output of next command in spreadsheet",
22820  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
22821#endif
22822#ifndef SQLITE_SHELL_FIDDLE
22823  ".exit ?CODE?             Exit this program with return-code CODE",
22824#endif
22825  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
22826  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
22827  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
22828  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
22829  "   --help                  Show CMD details",
22830  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
22831  ".headers on|off          Turn display of headers on or off",
22832  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
22833#ifndef SQLITE_SHELL_FIDDLE
22834  ".import FILE TABLE       Import data from FILE into TABLE",
22835  "   Options:",
22836  "     --ascii               Use \\037 and \\036 as column and row separators",
22837  "     --csv                 Use , and \\n as column and row separators",
22838  "     --skip N              Skip the first N rows of input",
22839  "     --schema S            Target table to be S.TABLE",
22840  "     -v                    \"Verbose\" - increase auxiliary output",
22841  "   Notes:",
22842  "     *  If TABLE does not exist, it is created.  The first row of input",
22843  "        determines the column names.",
22844  "     *  If neither --csv or --ascii are used, the input mode is derived",
22845  "        from the \".mode\" output mode",
22846  "     *  If FILE begins with \"|\" then it is a command that generates the",
22847  "        input text.",
22848#endif
22849#ifndef SQLITE_OMIT_TEST_CONTROL
22850  ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
22851#endif
22852  ".indexes ?TABLE?         Show names of indexes",
22853  "                           If TABLE is specified, only show indexes for",
22854  "                           tables matching TABLE using the LIKE operator.",
22855  ".intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db",
22856#ifdef SQLITE_ENABLE_IOTRACE
22857  ",iotrace FILE            Enable I/O diagnostic logging to FILE",
22858#endif
22859  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
22860  ".lint OPTIONS            Report potential schema issues.",
22861  "     Options:",
22862  "        fkey-indexes     Find missing foreign key indexes",
22863#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
22864  ".load FILE ?ENTRY?       Load an extension library",
22865#endif
22866#if !defined(SQLITE_SHELL_FIDDLE)
22867  ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
22868#else
22869  ".log on|off              Turn logging on or off.",
22870#endif
22871  ".mode MODE ?OPTIONS?     Set output mode",
22872  "   MODE is one of:",
22873  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
22874  "     box         Tables using unicode box-drawing characters",
22875  "     csv         Comma-separated values",
22876  "     column      Output in columns.  (See .width)",
22877  "     html        HTML <table> code",
22878  "     insert      SQL insert statements for TABLE",
22879  "     json        Results in a JSON array",
22880  "     line        One value per line",
22881  "     list        Values delimited by \"|\"",
22882  "     markdown    Markdown table format",
22883  "     qbox        Shorthand for \"box --wrap 60 --quote\"",
22884  "     quote       Escape answers as for SQL",
22885  "     table       ASCII-art table",
22886  "     tabs        Tab-separated values",
22887  "     tcl         TCL list elements",
22888  "   OPTIONS: (for columnar modes or insert mode):",
22889  "     --wrap N       Wrap output lines to no longer than N characters",
22890  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
22891  "     --ww           Shorthand for \"--wordwrap 1\"",
22892  "     --quote        Quote output text as SQL literals",
22893  "     --noquote      Do not quote output text",
22894  "     TABLE          The name of SQL table used for \"insert\" mode",
22895#ifndef SQLITE_SHELL_FIDDLE
22896  ".nonce STRING            Suspend safe mode for one command if nonce matches",
22897#endif
22898  ".nullvalue STRING        Use STRING in place of NULL values",
22899#ifndef SQLITE_SHELL_FIDDLE
22900  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
22901  "     If FILE begins with '|' then open as a pipe",
22902  "       --bom  Put a UTF8 byte-order mark at the beginning",
22903  "       -e     Send output to the system text editor",
22904  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
22905  /* Note that .open is (partially) available in WASM builds but is
22906  ** currently only intended to be used by the fiddle tool, not
22907  ** end users, so is "undocumented." */
22908  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
22909  "     Options:",
22910  "        --append        Use appendvfs to append database to the end of FILE",
22911#endif
22912#ifndef SQLITE_OMIT_DESERIALIZE
22913  "        --deserialize   Load into memory using sqlite3_deserialize()",
22914  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
22915  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
22916#endif
22917  "        --new           Initialize FILE to an empty database",
22918  "        --nofollow      Do not follow symbolic links",
22919  "        --readonly      Open FILE readonly",
22920  "        --zip           FILE is a ZIP archive",
22921#ifndef SQLITE_SHELL_FIDDLE
22922  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
22923  "   If FILE begins with '|' then open it as a pipe.",
22924  "   Options:",
22925  "     --bom                 Prefix output with a UTF8 byte-order mark",
22926  "     -e                    Send output to the system text editor",
22927  "     -x                    Send output as CSV to a spreadsheet",
22928#endif
22929  ".parameter CMD ...       Manage SQL parameter bindings",
22930  "   clear                   Erase all bindings",
22931  "   init                    Initialize the TEMP table that holds bindings",
22932  "   list                    List the current parameter bindings",
22933  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
22934  "                           PARAMETER should start with one of: $ : @ ?",
22935  "   unset PARAMETER         Remove PARAMETER from the binding table",
22936  ".print STRING...         Print literal STRING",
22937#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
22938  ".progress N              Invoke progress handler after every N opcodes",
22939  "   --limit N                 Interrupt after N progress callbacks",
22940  "   --once                    Do no more than one progress interrupt",
22941  "   --quiet|-q                No output except at interrupts",
22942  "   --reset                   Reset the count for each input and interrupt",
22943#endif
22944  ".prompt MAIN CONTINUE    Replace the standard prompts",
22945#ifndef SQLITE_SHELL_FIDDLE
22946  ".quit                    Stop interpreting input stream, exit if primary.",
22947  ".read FILE               Read input from FILE or command output",
22948  "    If FILE begins with \"|\", it is a command that generates the input.",
22949#endif
22950#if SQLITE_SHELL_HAVE_RECOVER
22951  ".recover                 Recover as much data as possible from corrupt db.",
22952  "   --ignore-freelist        Ignore pages that appear to be on db freelist",
22953  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
22954  "   --no-rowids              Do not attempt to recover rowid values",
22955  "                            that are not also INTEGER PRIMARY KEYs",
22956#endif
22957#ifndef SQLITE_SHELL_FIDDLE
22958  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
22959  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
22960#endif
22961  ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
22962  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
22963  "   Options:",
22964  "      --indent             Try to pretty-print the schema",
22965  "      --nosys              Omit objects whose names start with \"sqlite_\"",
22966  ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
22967  "    Options:",
22968  "       --init               Create a new SELFTEST table",
22969  "       -v                   Verbose output",
22970  ".separator COL ?ROW?     Change the column and row separators",
22971#if defined(SQLITE_ENABLE_SESSION)
22972  ".session ?NAME? CMD ...  Create or control sessions",
22973  "   Subcommands:",
22974  "     attach TABLE             Attach TABLE",
22975  "     changeset FILE           Write a changeset into FILE",
22976  "     close                    Close one session",
22977  "     enable ?BOOLEAN?         Set or query the enable bit",
22978  "     filter GLOB...           Reject tables matching GLOBs",
22979  "     indirect ?BOOLEAN?       Mark or query the indirect status",
22980  "     isempty                  Query whether the session is empty",
22981  "     list                     List currently open session names",
22982  "     open DB NAME             Open a new session on DB",
22983  "     patchset FILE            Write a patchset into FILE",
22984  "   If ?NAME? is omitted, the first defined session is used.",
22985#endif
22986  ".sha3sum ...             Compute a SHA3 hash of database content",
22987  "    Options:",
22988  "      --schema              Also hash the sqlite_schema table",
22989  "      --sha3-224            Use the sha3-224 algorithm",
22990  "      --sha3-256            Use the sha3-256 algorithm (default)",
22991  "      --sha3-384            Use the sha3-384 algorithm",
22992  "      --sha3-512            Use the sha3-512 algorithm",
22993  "    Any other argument is a LIKE pattern for tables to hash",
22994#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
22995  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
22996#endif
22997  ".show                    Show the current values for various settings",
22998  ".stats ?ARG?             Show stats or turn stats on or off",
22999  "   off                      Turn off automatic stat display",
23000  "   on                       Turn on automatic stat display",
23001  "   stmt                     Show statement stats",
23002  "   vmstep                   Show the virtual machine step count only",
23003#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
23004  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
23005#endif
23006  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
23007#ifndef SQLITE_SHELL_FIDDLE
23008  ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
23009#endif
23010  ",testctrl CMD ...        Run various sqlite3_test_control() operations",
23011  "                           Run \".testctrl\" with no arguments for details",
23012  ".timeout MS              Try opening locked tables for MS milliseconds",
23013  ".timer on|off            Turn SQL timer on or off",
23014#ifndef SQLITE_OMIT_TRACE
23015  ".trace ?OPTIONS?         Output each SQL statement as it is run",
23016  "    FILE                    Send output to FILE",
23017  "    stdout                  Send output to stdout",
23018  "    stderr                  Send output to stderr",
23019  "    off                     Disable tracing",
23020  "    --expanded              Expand query parameters",
23021#ifdef SQLITE_ENABLE_NORMALIZE
23022  "    --normalized            Normal the SQL statements",
23023#endif
23024  "    --plain                 Show SQL as it is input",
23025  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
23026  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
23027  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
23028  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
23029#endif /* SQLITE_OMIT_TRACE */
23030#ifdef SQLITE_DEBUG
23031  ".unmodule NAME ...       Unregister virtual table modules",
23032  "    --allexcept             Unregister everything except those named",
23033#endif
23034  ".version                 Show source, library and compiler versions",
23035  ".vfsinfo ?AUX?           Information about the top-level VFS",
23036  ".vfslist                 List all available VFSes",
23037  ".vfsname ?AUX?           Print the name of the VFS stack",
23038  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
23039  "     Negative values right-justify",
23040};
23041
23042/*
23043** Output help text.
23044**
23045** zPattern describes the set of commands for which help text is provided.
23046** If zPattern is NULL, then show all commands, but only give a one-line
23047** description of each.
23048**
23049** Return the number of matches.
23050*/
23051static int showHelp(FILE *out, const char *zPattern){
23052  int i = 0;
23053  int j = 0;
23054  int n = 0;
23055  char *zPat;
23056  if( zPattern==0
23057   || zPattern[0]=='0'
23058   || cli_strcmp(zPattern,"-a")==0
23059   || cli_strcmp(zPattern,"-all")==0
23060   || cli_strcmp(zPattern,"--all")==0
23061  ){
23062    enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
23063    enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
23064    /* Show all or most commands
23065    ** *zPattern==0   => summary of documented commands only
23066    ** *zPattern=='0' => whole help for undocumented commands
23067    ** Otherwise      => whole help for documented commands
23068    */
23069    enum HelpWanted hw = HW_SummaryOnly;
23070    enum HelpHave hh = HH_More;
23071    if( zPattern!=0 ){
23072      hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
23073    }
23074    for(i=0; i<ArraySize(azHelp); i++){
23075      switch( azHelp[i][0] ){
23076      case ',':
23077        hh = HH_Summary|HH_Undoc;
23078        break;
23079      case '.':
23080        hh = HH_Summary;
23081        break;
23082      default:
23083        hh &= ~HH_Summary;
23084        break;
23085      }
23086      if( ((hw^hh)&HH_Undoc)==0 ){
23087        if( (hh&HH_Summary)!=0 ){
23088          sputf(out, ".%s\n", azHelp[i]+1);
23089          ++n;
23090        }else if( (hw&HW_SummaryOnly)==0 ){
23091          sputf(out, "%s\n", azHelp[i]);
23092        }
23093      }
23094    }
23095  }else{
23096    /* Seek documented commands for which zPattern is an exact prefix */
23097    zPat = sqlite3_mprintf(".%s*", zPattern);
23098    shell_check_oom(zPat);
23099    for(i=0; i<ArraySize(azHelp); i++){
23100      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
23101        sputf(out, "%s\n", azHelp[i]);
23102        j = i+1;
23103        n++;
23104      }
23105    }
23106    sqlite3_free(zPat);
23107    if( n ){
23108      if( n==1 ){
23109        /* when zPattern is a prefix of exactly one command, then include
23110        ** the details of that command, which should begin at offset j */
23111        while( j<ArraySize(azHelp)-1 && azHelp[j][0]==' ' ){
23112          sputf(out, "%s\n", azHelp[j]);
23113          j++;
23114        }
23115      }
23116      return n;
23117    }
23118    /* Look for documented commands that contain zPattern anywhere.
23119    ** Show complete text of all documented commands that match. */
23120    zPat = sqlite3_mprintf("%%%s%%", zPattern);
23121    shell_check_oom(zPat);
23122    for(i=0; i<ArraySize(azHelp); i++){
23123      if( azHelp[i][0]==',' ){
23124        while( i<ArraySize(azHelp)-1 && azHelp[i+1][0]==' ' ) ++i;
23125        continue;
23126      }
23127      if( azHelp[i][0]=='.' ) j = i;
23128      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
23129        sputf(out, "%s\n", azHelp[j]);
23130        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]==' ' ){
23131          j++;
23132          sputf(out, "%s\n", azHelp[j]);
23133        }
23134        i = j;
23135        n++;
23136      }
23137    }
23138    sqlite3_free(zPat);
23139  }
23140  return n;
23141}
23142
23143/* Forward reference */
23144static int process_input(ShellState *p);
23145
23146/*
23147** Read the content of file zName into memory obtained from sqlite3_malloc64()
23148** and return a pointer to the buffer. The caller is responsible for freeing
23149** the memory.
23150**
23151** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
23152** read.
23153**
23154** For convenience, a nul-terminator byte is always appended to the data read
23155** from the file before the buffer is returned. This byte is not included in
23156** the final value of (*pnByte), if applicable.
23157**
23158** NULL is returned if any error is encountered. The final value of *pnByte
23159** is undefined in this case.
23160*/
23161static char *readFile(const char *zName, int *pnByte){
23162  FILE *in = fopen(zName, "rb");
23163  long nIn;
23164  size_t nRead;
23165  char *pBuf;
23166  int rc;
23167  if( in==0 ) return 0;
23168  rc = fseek(in, 0, SEEK_END);
23169  if( rc!=0 ){
23170    eputf("Error: '%s' not seekable\n", zName);
23171    fclose(in);
23172    return 0;
23173  }
23174  nIn = ftell(in);
23175  rewind(in);
23176  pBuf = sqlite3_malloc64( nIn+1 );
23177  if( pBuf==0 ){
23178    eputz("Error: out of memory\n");
23179    fclose(in);
23180    return 0;
23181  }
23182  nRead = fread(pBuf, nIn, 1, in);
23183  fclose(in);
23184  if( nRead!=1 ){
23185    sqlite3_free(pBuf);
23186    eputf("Error: cannot read '%s'\n", zName);
23187    return 0;
23188  }
23189  pBuf[nIn] = 0;
23190  if( pnByte ) *pnByte = nIn;
23191  return pBuf;
23192}
23193
23194#if defined(SQLITE_ENABLE_SESSION)
23195/*
23196** Close a single OpenSession object and release all of its associated
23197** resources.
23198*/
23199static void session_close(OpenSession *pSession){
23200  int i;
23201  sqlite3session_delete(pSession->p);
23202  sqlite3_free(pSession->zName);
23203  for(i=0; i<pSession->nFilter; i++){
23204    sqlite3_free(pSession->azFilter[i]);
23205  }
23206  sqlite3_free(pSession->azFilter);
23207  memset(pSession, 0, sizeof(OpenSession));
23208}
23209#endif
23210
23211/*
23212** Close all OpenSession objects and release all associated resources.
23213*/
23214#if defined(SQLITE_ENABLE_SESSION)
23215static void session_close_all(ShellState *p, int i){
23216  int j;
23217  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
23218  for(j=0; j<pAuxDb->nSession; j++){
23219    session_close(&pAuxDb->aSession[j]);
23220  }
23221  pAuxDb->nSession = 0;
23222}
23223#else
23224# define session_close_all(X,Y)
23225#endif
23226
23227/*
23228** Implementation of the xFilter function for an open session.  Omit
23229** any tables named by ".session filter" but let all other table through.
23230*/
23231#if defined(SQLITE_ENABLE_SESSION)
23232static int session_filter(void *pCtx, const char *zTab){
23233  OpenSession *pSession = (OpenSession*)pCtx;
23234  int i;
23235  for(i=0; i<pSession->nFilter; i++){
23236    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
23237  }
23238  return 1;
23239}
23240#endif
23241
23242/*
23243** Try to deduce the type of file for zName based on its content.  Return
23244** one of the SHELL_OPEN_* constants.
23245**
23246** If the file does not exist or is empty but its name looks like a ZIP
23247** archive and the dfltZip flag is true, then assume it is a ZIP archive.
23248** Otherwise, assume an ordinary database regardless of the filename if
23249** the type cannot be determined from content.
23250*/
23251int deduceDatabaseType(const char *zName, int dfltZip){
23252  FILE *f = fopen(zName, "rb");
23253  size_t n;
23254  int rc = SHELL_OPEN_UNSPEC;
23255  char zBuf[100];
23256  if( f==0 ){
23257    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
23258       return SHELL_OPEN_ZIPFILE;
23259    }else{
23260       return SHELL_OPEN_NORMAL;
23261    }
23262  }
23263  n = fread(zBuf, 16, 1, f);
23264  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
23265    fclose(f);
23266    return SHELL_OPEN_NORMAL;
23267  }
23268  fseek(f, -25, SEEK_END);
23269  n = fread(zBuf, 25, 1, f);
23270  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
23271    rc = SHELL_OPEN_APPENDVFS;
23272  }else{
23273    fseek(f, -22, SEEK_END);
23274    n = fread(zBuf, 22, 1, f);
23275    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
23276       && zBuf[3]==0x06 ){
23277      rc = SHELL_OPEN_ZIPFILE;
23278    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
23279      rc = SHELL_OPEN_ZIPFILE;
23280    }
23281  }
23282  fclose(f);
23283  return rc;
23284}
23285
23286#ifndef SQLITE_OMIT_DESERIALIZE
23287/*
23288** Reconstruct an in-memory database using the output from the "dbtotxt"
23289** program.  Read content from the file in p->aAuxDb[].zDbFilename.
23290** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
23291*/
23292static unsigned char *readHexDb(ShellState *p, int *pnData){
23293  unsigned char *a = 0;
23294  int nLine;
23295  int n = 0;
23296  int pgsz = 0;
23297  int iOffset = 0;
23298  int j, k;
23299  int rc;
23300  FILE *in;
23301  const char *zDbFilename = p->pAuxDb->zDbFilename;
23302  unsigned int x[16];
23303  char zLine[1000];
23304  if( zDbFilename ){
23305    in = fopen(zDbFilename, "r");
23306    if( in==0 ){
23307      eputf("cannot open \"%s\" for reading\n", zDbFilename);
23308      return 0;
23309    }
23310    nLine = 0;
23311  }else{
23312    in = p->in;
23313    nLine = p->lineno;
23314    if( in==0 ) in = stdin;
23315  }
23316  *pnData = 0;
23317  nLine++;
23318  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
23319  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
23320  if( rc!=2 ) goto readHexDb_error;
23321  if( n<0 ) goto readHexDb_error;
23322  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
23323  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
23324  a = sqlite3_malloc( n ? n : 1 );
23325  shell_check_oom(a);
23326  memset(a, 0, n);
23327  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
23328    eputz("invalid pagesize\n");
23329    goto readHexDb_error;
23330  }
23331  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
23332    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
23333    if( rc==2 ){
23334      iOffset = k;
23335      continue;
23336    }
23337    if( cli_strncmp(zLine, "| end ", 6)==0 ){
23338      break;
23339    }
23340    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
23341                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
23342                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
23343    if( rc==17 ){
23344      k = iOffset+j;
23345      if( k+16<=n && k>=0 ){
23346        int ii;
23347        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
23348      }
23349    }
23350  }
23351  *pnData = n;
23352  if( in!=p->in ){
23353    fclose(in);
23354  }else{
23355    p->lineno = nLine;
23356  }
23357  return a;
23358
23359readHexDb_error:
23360  if( in!=p->in ){
23361    fclose(in);
23362  }else{
23363    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
23364      nLine++;
23365      if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
23366    }
23367    p->lineno = nLine;
23368  }
23369  sqlite3_free(a);
23370  eputf("Error on line %d of --hexdb input\n", nLine);
23371  return 0;
23372}
23373#endif /* SQLITE_OMIT_DESERIALIZE */
23374
23375/*
23376** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
23377*/
23378static void shellUSleepFunc(
23379  sqlite3_context *context,
23380  int argcUnused,
23381  sqlite3_value **argv
23382){
23383  int sleep = sqlite3_value_int(argv[0]);
23384  (void)argcUnused;
23385  sqlite3_sleep(sleep/1000);
23386  sqlite3_result_int(context, sleep);
23387}
23388
23389/* Flags for open_db().
23390**
23391** The default behavior of open_db() is to exit(1) if the database fails to
23392** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
23393** but still returns without calling exit.
23394**
23395** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
23396** ZIP archive if the file does not exist or is empty and its name matches
23397** the *.zip pattern.
23398*/
23399#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
23400#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
23401
23402/*
23403** Make sure the database is open.  If it is not, then open it.  If
23404** the database fails to open, print an error message and exit.
23405*/
23406static void open_db(ShellState *p, int openFlags){
23407  if( p->db==0 ){
23408    const char *zDbFilename = p->pAuxDb->zDbFilename;
23409    if( p->openMode==SHELL_OPEN_UNSPEC ){
23410      if( zDbFilename==0 || zDbFilename[0]==0 ){
23411        p->openMode = SHELL_OPEN_NORMAL;
23412      }else{
23413        p->openMode = (u8)deduceDatabaseType(zDbFilename,
23414                             (openFlags & OPEN_DB_ZIPFILE)!=0);
23415      }
23416    }
23417    switch( p->openMode ){
23418      case SHELL_OPEN_APPENDVFS: {
23419        sqlite3_open_v2(zDbFilename, &p->db,
23420           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
23421        break;
23422      }
23423      case SHELL_OPEN_HEXDB:
23424      case SHELL_OPEN_DESERIALIZE: {
23425        sqlite3_open(0, &p->db);
23426        break;
23427      }
23428      case SHELL_OPEN_ZIPFILE: {
23429        sqlite3_open(":memory:", &p->db);
23430        break;
23431      }
23432      case SHELL_OPEN_READONLY: {
23433        sqlite3_open_v2(zDbFilename, &p->db,
23434            SQLITE_OPEN_READONLY|p->openFlags, 0);
23435        break;
23436      }
23437      case SHELL_OPEN_UNSPEC:
23438      case SHELL_OPEN_NORMAL: {
23439        sqlite3_open_v2(zDbFilename, &p->db,
23440           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
23441        break;
23442      }
23443    }
23444    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
23445      eputf("Error: unable to open database \"%s\": %s\n",
23446            zDbFilename, sqlite3_errmsg(p->db));
23447      if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
23448        exit(1);
23449      }
23450      sqlite3_close(p->db);
23451      sqlite3_open(":memory:", &p->db);
23452      if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
23453        eputz("Also: unable to open substitute in-memory database.\n");
23454        exit(1);
23455      }else{
23456        eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
23457              zDbFilename);
23458      }
23459    }
23460    globalDb = p->db;
23461    sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
23462
23463    /* Reflect the use or absence of --unsafe-testing invocation. */
23464    {
23465      int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
23466      sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
23467      sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
23468    }
23469
23470#ifndef SQLITE_OMIT_LOAD_EXTENSION
23471    sqlite3_enable_load_extension(p->db, 1);
23472#endif
23473    sqlite3_shathree_init(p->db, 0, 0);
23474    sqlite3_uint_init(p->db, 0, 0);
23475    sqlite3_decimal_init(p->db, 0, 0);
23476    sqlite3_base64_init(p->db, 0, 0);
23477    sqlite3_base85_init(p->db, 0, 0);
23478    sqlite3_regexp_init(p->db, 0, 0);
23479    sqlite3_ieee_init(p->db, 0, 0);
23480    sqlite3_series_init(p->db, 0, 0);
23481#ifndef SQLITE_SHELL_FIDDLE
23482    sqlite3_fileio_init(p->db, 0, 0);
23483    sqlite3_completion_init(p->db, 0, 0);
23484#endif
23485#ifdef SQLITE_HAVE_ZLIB
23486    if( !p->bSafeModePersist ){
23487      sqlite3_zipfile_init(p->db, 0, 0);
23488      sqlite3_sqlar_init(p->db, 0, 0);
23489    }
23490#endif
23491#ifdef SQLITE_SHELL_EXTFUNCS
23492    /* Create a preprocessing mechanism for extensions to make
23493     * their own provisions for being built into the shell.
23494     * This is a short-span macro. See further below for usage.
23495     */
23496#define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
23497#define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
23498    /* Let custom-included extensions get their ..._init() called.
23499     * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
23500     * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
23501     * initialization routine to be called.
23502     */
23503    {
23504      int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
23505    /* Let custom-included extensions expose their functionality.
23506     * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
23507     * the SQL functions, virtual tables, collating sequences or
23508     * VFS's implemented by the extension to be registered.
23509     */
23510      if( irc==SQLITE_OK
23511          || irc==SQLITE_OK_LOAD_PERMANENTLY ){
23512        SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
23513      }
23514#undef SHELL_SUB_MACRO
23515#undef SHELL_SUBMACRO
23516    }
23517#endif
23518
23519    sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
23520                            shellStrtod, 0, 0);
23521    sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
23522                            shellDtostr, 0, 0);
23523    sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
23524                            shellDtostr, 0, 0);
23525    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
23526                            shellAddSchemaName, 0, 0);
23527    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
23528                            shellModuleSchema, 0, 0);
23529    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
23530                            shellPutsFunc, 0, 0);
23531    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
23532                            shellUSleepFunc, 0, 0);
23533#ifndef SQLITE_NOHAVE_SYSTEM
23534    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
23535                            editFunc, 0, 0);
23536    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
23537                            editFunc, 0, 0);
23538#endif
23539
23540    if( p->openMode==SHELL_OPEN_ZIPFILE ){
23541      char *zSql = sqlite3_mprintf(
23542         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
23543      shell_check_oom(zSql);
23544      sqlite3_exec(p->db, zSql, 0, 0, 0);
23545      sqlite3_free(zSql);
23546    }
23547#ifndef SQLITE_OMIT_DESERIALIZE
23548    else
23549    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
23550      int rc;
23551      int nData = 0;
23552      unsigned char *aData;
23553      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
23554        aData = (unsigned char*)readFile(zDbFilename, &nData);
23555      }else{
23556        aData = readHexDb(p, &nData);
23557      }
23558      if( aData==0 ){
23559        return;
23560      }
23561      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
23562                   SQLITE_DESERIALIZE_RESIZEABLE |
23563                   SQLITE_DESERIALIZE_FREEONCLOSE);
23564      if( rc ){
23565        eputf("Error: sqlite3_deserialize() returns %d\n", rc);
23566      }
23567      if( p->szMax>0 ){
23568        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
23569      }
23570    }
23571#endif
23572  }
23573  if( p->db!=0 ){
23574    if( p->bSafeModePersist ){
23575      sqlite3_set_authorizer(p->db, safeModeAuth, p);
23576    }
23577    sqlite3_db_config(
23578        p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
23579    );
23580  }
23581}
23582
23583/*
23584** Attempt to close the database connection.  Report errors.
23585*/
23586void close_db(sqlite3 *db){
23587  int rc = sqlite3_close(db);
23588  if( rc ){
23589    eputf("Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
23590  }
23591}
23592
23593#if HAVE_READLINE || HAVE_EDITLINE
23594/*
23595** Readline completion callbacks
23596*/
23597static char *readline_completion_generator(const char *text, int state){
23598  static sqlite3_stmt *pStmt = 0;
23599  char *zRet;
23600  if( state==0 ){
23601    char *zSql;
23602    sqlite3_finalize(pStmt);
23603    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
23604                           "  FROM completion(%Q) ORDER BY 1", text);
23605    shell_check_oom(zSql);
23606    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
23607    sqlite3_free(zSql);
23608  }
23609  if( sqlite3_step(pStmt)==SQLITE_ROW ){
23610    const char *z = (const char*)sqlite3_column_text(pStmt,0);
23611    zRet = z ? strdup(z) : 0;
23612  }else{
23613    sqlite3_finalize(pStmt);
23614    pStmt = 0;
23615    zRet = 0;
23616  }
23617  return zRet;
23618}
23619static char **readline_completion(const char *zText, int iStart, int iEnd){
23620  (void)iStart;
23621  (void)iEnd;
23622  rl_attempted_completion_over = 1;
23623  return rl_completion_matches(zText, readline_completion_generator);
23624}
23625
23626#elif HAVE_LINENOISE
23627/*
23628** Linenoise completion callback
23629*/
23630static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
23631  i64 nLine = strlen(zLine);
23632  i64 i, iStart;
23633  sqlite3_stmt *pStmt = 0;
23634  char *zSql;
23635  char zBuf[1000];
23636
23637  if( nLine>(i64)sizeof(zBuf)-30 ) return;
23638  if( zLine[0]=='.' || zLine[0]=='#') return;
23639  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
23640  if( i==nLine-1 ) return;
23641  iStart = i+1;
23642  memcpy(zBuf, zLine, iStart);
23643  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
23644                         "  FROM completion(%Q,%Q) ORDER BY 1",
23645                         &zLine[iStart], zLine);
23646  shell_check_oom(zSql);
23647  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
23648  sqlite3_free(zSql);
23649  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
23650  while( sqlite3_step(pStmt)==SQLITE_ROW ){
23651    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
23652    int nCompletion = sqlite3_column_bytes(pStmt, 0);
23653    if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
23654      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
23655      linenoiseAddCompletion(lc, zBuf);
23656    }
23657  }
23658  sqlite3_finalize(pStmt);
23659}
23660#endif
23661
23662/*
23663** Do C-language style dequoting.
23664**
23665**    \a    -> alarm
23666**    \b    -> backspace
23667**    \t    -> tab
23668**    \n    -> newline
23669**    \v    -> vertical tab
23670**    \f    -> form feed
23671**    \r    -> carriage return
23672**    \s    -> space
23673**    \"    -> "
23674**    \'    -> '
23675**    \\    -> backslash
23676**    \NNN  -> ascii character NNN in octal
23677**    \xHH  -> ascii character HH in hexadecimal
23678*/
23679static void resolve_backslashes(char *z){
23680  int i, j;
23681  char c;
23682  while( *z && *z!='\\' ) z++;
23683  for(i=j=0; (c = z[i])!=0; i++, j++){
23684    if( c=='\\' && z[i+1]!=0 ){
23685      c = z[++i];
23686      if( c=='a' ){
23687        c = '\a';
23688      }else if( c=='b' ){
23689        c = '\b';
23690      }else if( c=='t' ){
23691        c = '\t';
23692      }else if( c=='n' ){
23693        c = '\n';
23694      }else if( c=='v' ){
23695        c = '\v';
23696      }else if( c=='f' ){
23697        c = '\f';
23698      }else if( c=='r' ){
23699        c = '\r';
23700      }else if( c=='"' ){
23701        c = '"';
23702      }else if( c=='\'' ){
23703        c = '\'';
23704      }else if( c=='\\' ){
23705        c = '\\';
23706      }else if( c=='x' ){
23707        int nhd = 0, hdv;
23708        u8 hv = 0;
23709        while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
23710          hv = (u8)((hv<<4)|hdv);
23711          ++nhd;
23712        }
23713        i += nhd;
23714        c = (u8)hv;
23715      }else if( c>='0' && c<='7' ){
23716        c -= '0';
23717        if( z[i+1]>='0' && z[i+1]<='7' ){
23718          i++;
23719          c = (c<<3) + z[i] - '0';
23720          if( z[i+1]>='0' && z[i+1]<='7' ){
23721            i++;
23722            c = (c<<3) + z[i] - '0';
23723          }
23724        }
23725      }
23726    }
23727    z[j] = c;
23728  }
23729  if( j<i ) z[j] = 0;
23730}
23731
23732/*
23733** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
23734** for TRUE and FALSE.  Return the integer value if appropriate.
23735*/
23736static int booleanValue(const char *zArg){
23737  int i;
23738  if( zArg[0]=='0' && zArg[1]=='x' ){
23739    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
23740  }else{
23741    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
23742  }
23743  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
23744  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
23745    return 1;
23746  }
23747  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
23748    return 0;
23749  }
23750  eputf("ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
23751  return 0;
23752}
23753
23754/*
23755** Set or clear a shell flag according to a boolean value.
23756*/
23757static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
23758  if( booleanValue(zArg) ){
23759    ShellSetFlag(p, mFlag);
23760  }else{
23761    ShellClearFlag(p, mFlag);
23762  }
23763}
23764
23765/*
23766** Close an output file, assuming it is not stderr or stdout
23767*/
23768static void output_file_close(FILE *f){
23769  if( f && f!=stdout && f!=stderr ) fclose(f);
23770}
23771
23772/*
23773** Try to open an output file.   The names "stdout" and "stderr" are
23774** recognized and do the right thing.  NULL is returned if the output
23775** filename is "off".
23776*/
23777static FILE *output_file_open(const char *zFile, int bTextMode){
23778  FILE *f;
23779  if( cli_strcmp(zFile,"stdout")==0 ){
23780    f = stdout;
23781  }else if( cli_strcmp(zFile, "stderr")==0 ){
23782    f = stderr;
23783  }else if( cli_strcmp(zFile, "off")==0 ){
23784    f = 0;
23785  }else{
23786    f = fopen(zFile, bTextMode ? "w" : "wb");
23787    if( f==0 ){
23788      eputf("Error: cannot open \"%s\"\n", zFile);
23789    }
23790  }
23791  return f;
23792}
23793
23794#ifndef SQLITE_OMIT_TRACE
23795/*
23796** A routine for handling output from sqlite3_trace().
23797*/
23798static int sql_trace_callback(
23799  unsigned mType,         /* The trace type */
23800  void *pArg,             /* The ShellState pointer */
23801  void *pP,               /* Usually a pointer to sqlite_stmt */
23802  void *pX                /* Auxiliary output */
23803){
23804  ShellState *p = (ShellState*)pArg;
23805  sqlite3_stmt *pStmt;
23806  const char *zSql;
23807  i64 nSql;
23808  if( p->traceOut==0 ) return 0;
23809  if( mType==SQLITE_TRACE_CLOSE ){
23810    sputz(p->traceOut, "-- closing database connection\n");
23811    return 0;
23812  }
23813  if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
23814    zSql = (const char*)pX;
23815  }else{
23816    pStmt = (sqlite3_stmt*)pP;
23817    switch( p->eTraceType ){
23818      case SHELL_TRACE_EXPANDED: {
23819        zSql = sqlite3_expanded_sql(pStmt);
23820        break;
23821      }
23822#ifdef SQLITE_ENABLE_NORMALIZE
23823      case SHELL_TRACE_NORMALIZED: {
23824        zSql = sqlite3_normalized_sql(pStmt);
23825        break;
23826      }
23827#endif
23828      default: {
23829        zSql = sqlite3_sql(pStmt);
23830        break;
23831      }
23832    }
23833  }
23834  if( zSql==0 ) return 0;
23835  nSql = strlen(zSql);
23836  if( nSql>1000000000 ) nSql = 1000000000;
23837  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
23838  switch( mType ){
23839    case SQLITE_TRACE_ROW:
23840    case SQLITE_TRACE_STMT: {
23841      sputf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
23842      break;
23843    }
23844    case SQLITE_TRACE_PROFILE: {
23845      sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
23846      sputf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
23847      break;
23848    }
23849  }
23850  return 0;
23851}
23852#endif
23853
23854/*
23855** A no-op routine that runs with the ".breakpoint" doc-command.  This is
23856** a useful spot to set a debugger breakpoint.
23857**
23858** This routine does not do anything practical.  The code are there simply
23859** to prevent the compiler from optimizing this routine out.
23860*/
23861static void test_breakpoint(void){
23862  static unsigned int nCall = 0;
23863  if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
23864}
23865
23866/*
23867** An object used to read a CSV and other files for import.
23868*/
23869typedef struct ImportCtx ImportCtx;
23870struct ImportCtx {
23871  const char *zFile;  /* Name of the input file */
23872  FILE *in;           /* Read the CSV text from this input stream */
23873  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
23874  char *z;            /* Accumulated text for a field */
23875  int n;              /* Number of bytes in z */
23876  int nAlloc;         /* Space allocated for z[] */
23877  int nLine;          /* Current line number */
23878  int nRow;           /* Number of rows imported */
23879  int nErr;           /* Number of errors encountered */
23880  int bNotFirst;      /* True if one or more bytes already read */
23881  int cTerm;          /* Character that terminated the most recent field */
23882  int cColSep;        /* The column separator character.  (Usually ",") */
23883  int cRowSep;        /* The row separator character.  (Usually "\n") */
23884};
23885
23886/* Clean up resourced used by an ImportCtx */
23887static void import_cleanup(ImportCtx *p){
23888  if( p->in!=0 && p->xCloser!=0 ){
23889    p->xCloser(p->in);
23890    p->in = 0;
23891  }
23892  sqlite3_free(p->z);
23893  p->z = 0;
23894}
23895
23896/* Append a single byte to z[] */
23897static void import_append_char(ImportCtx *p, int c){
23898  if( p->n+1>=p->nAlloc ){
23899    p->nAlloc += p->nAlloc + 100;
23900    p->z = sqlite3_realloc64(p->z, p->nAlloc);
23901    shell_check_oom(p->z);
23902  }
23903  p->z[p->n++] = (char)c;
23904}
23905
23906/* Read a single field of CSV text.  Compatible with rfc4180 and extended
23907** with the option of having a separator other than ",".
23908**
23909**   +  Input comes from p->in.
23910**   +  Store results in p->z of length p->n.  Space to hold p->z comes
23911**      from sqlite3_malloc64().
23912**   +  Use p->cSep as the column separator.  The default is ",".
23913**   +  Use p->rSep as the row separator.  The default is "\n".
23914**   +  Keep track of the line number in p->nLine.
23915**   +  Store the character that terminates the field in p->cTerm.  Store
23916**      EOF on end-of-file.
23917**   +  Report syntax errors on stderr
23918*/
23919static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
23920  int c;
23921  int cSep = (u8)p->cColSep;
23922  int rSep = (u8)p->cRowSep;
23923  p->n = 0;
23924  c = fgetc(p->in);
23925  if( c==EOF || seenInterrupt ){
23926    p->cTerm = EOF;
23927    return 0;
23928  }
23929  if( c=='"' ){
23930    int pc, ppc;
23931    int startLine = p->nLine;
23932    int cQuote = c;
23933    pc = ppc = 0;
23934    while( 1 ){
23935      c = fgetc(p->in);
23936      if( c==rSep ) p->nLine++;
23937      if( c==cQuote ){
23938        if( pc==cQuote ){
23939          pc = 0;
23940          continue;
23941        }
23942      }
23943      if( (c==cSep && pc==cQuote)
23944       || (c==rSep && pc==cQuote)
23945       || (c==rSep && pc=='\r' && ppc==cQuote)
23946       || (c==EOF && pc==cQuote)
23947      ){
23948        do{ p->n--; }while( p->z[p->n]!=cQuote );
23949        p->cTerm = c;
23950        break;
23951      }
23952      if( pc==cQuote && c!='\r' ){
23953        eputf("%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote);
23954      }
23955      if( c==EOF ){
23956        eputf("%s:%d: unterminated %c-quoted field\n",
23957              p->zFile, startLine, cQuote);
23958        p->cTerm = c;
23959        break;
23960      }
23961      import_append_char(p, c);
23962      ppc = pc;
23963      pc = c;
23964    }
23965  }else{
23966    /* If this is the first field being parsed and it begins with the
23967    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
23968    if( (c&0xff)==0xef && p->bNotFirst==0 ){
23969      import_append_char(p, c);
23970      c = fgetc(p->in);
23971      if( (c&0xff)==0xbb ){
23972        import_append_char(p, c);
23973        c = fgetc(p->in);
23974        if( (c&0xff)==0xbf ){
23975          p->bNotFirst = 1;
23976          p->n = 0;
23977          return csv_read_one_field(p);
23978        }
23979      }
23980    }
23981    while( c!=EOF && c!=cSep && c!=rSep ){
23982      import_append_char(p, c);
23983      c = fgetc(p->in);
23984    }
23985    if( c==rSep ){
23986      p->nLine++;
23987      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
23988    }
23989    p->cTerm = c;
23990  }
23991  if( p->z ) p->z[p->n] = 0;
23992  p->bNotFirst = 1;
23993  return p->z;
23994}
23995
23996/* Read a single field of ASCII delimited text.
23997**
23998**   +  Input comes from p->in.
23999**   +  Store results in p->z of length p->n.  Space to hold p->z comes
24000**      from sqlite3_malloc64().
24001**   +  Use p->cSep as the column separator.  The default is "\x1F".
24002**   +  Use p->rSep as the row separator.  The default is "\x1E".
24003**   +  Keep track of the row number in p->nLine.
24004**   +  Store the character that terminates the field in p->cTerm.  Store
24005**      EOF on end-of-file.
24006**   +  Report syntax errors on stderr
24007*/
24008static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
24009  int c;
24010  int cSep = (u8)p->cColSep;
24011  int rSep = (u8)p->cRowSep;
24012  p->n = 0;
24013  c = fgetc(p->in);
24014  if( c==EOF || seenInterrupt ){
24015    p->cTerm = EOF;
24016    return 0;
24017  }
24018  while( c!=EOF && c!=cSep && c!=rSep ){
24019    import_append_char(p, c);
24020    c = fgetc(p->in);
24021  }
24022  if( c==rSep ){
24023    p->nLine++;
24024  }
24025  p->cTerm = c;
24026  if( p->z ) p->z[p->n] = 0;
24027  return p->z;
24028}
24029
24030/*
24031** Try to transfer data for table zTable.  If an error is seen while
24032** moving forward, try to go backwards.  The backwards movement won't
24033** work for WITHOUT ROWID tables.
24034*/
24035static void tryToCloneData(
24036  ShellState *p,
24037  sqlite3 *newDb,
24038  const char *zTable
24039){
24040  sqlite3_stmt *pQuery = 0;
24041  sqlite3_stmt *pInsert = 0;
24042  char *zQuery = 0;
24043  char *zInsert = 0;
24044  int rc;
24045  int i, j, n;
24046  int nTable = strlen30(zTable);
24047  int k = 0;
24048  int cnt = 0;
24049  const int spinRate = 10000;
24050
24051  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
24052  shell_check_oom(zQuery);
24053  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24054  if( rc ){
24055    eputf("Error %d: %s on [%s]\n",
24056          sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
24057    goto end_data_xfer;
24058  }
24059  n = sqlite3_column_count(pQuery);
24060  zInsert = sqlite3_malloc64(200 + nTable + n*3);
24061  shell_check_oom(zInsert);
24062  sqlite3_snprintf(200+nTable,zInsert,
24063                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
24064  i = strlen30(zInsert);
24065  for(j=1; j<n; j++){
24066    memcpy(zInsert+i, ",?", 2);
24067    i += 2;
24068  }
24069  memcpy(zInsert+i, ");", 3);
24070  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
24071  if( rc ){
24072    eputf("Error %d: %s on [%s]\n",
24073          sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zInsert);
24074    goto end_data_xfer;
24075  }
24076  for(k=0; k<2; k++){
24077    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
24078      for(i=0; i<n; i++){
24079        switch( sqlite3_column_type(pQuery, i) ){
24080          case SQLITE_NULL: {
24081            sqlite3_bind_null(pInsert, i+1);
24082            break;
24083          }
24084          case SQLITE_INTEGER: {
24085            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
24086            break;
24087          }
24088          case SQLITE_FLOAT: {
24089            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
24090            break;
24091          }
24092          case SQLITE_TEXT: {
24093            sqlite3_bind_text(pInsert, i+1,
24094                             (const char*)sqlite3_column_text(pQuery,i),
24095                             -1, SQLITE_STATIC);
24096            break;
24097          }
24098          case SQLITE_BLOB: {
24099            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
24100                                            sqlite3_column_bytes(pQuery,i),
24101                                            SQLITE_STATIC);
24102            break;
24103          }
24104        }
24105      } /* End for */
24106      rc = sqlite3_step(pInsert);
24107      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
24108        eputf("Error %d: %s\n",
24109              sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb));
24110      }
24111      sqlite3_reset(pInsert);
24112      cnt++;
24113      if( (cnt%spinRate)==0 ){
24114        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
24115        fflush(stdout);
24116      }
24117    } /* End while */
24118    if( rc==SQLITE_DONE ) break;
24119    sqlite3_finalize(pQuery);
24120    sqlite3_free(zQuery);
24121    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
24122                             zTable);
24123    shell_check_oom(zQuery);
24124    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24125    if( rc ){
24126      eputf("Warning: cannot step \"%s\" backwards", zTable);
24127      break;
24128    }
24129  } /* End for(k=0...) */
24130
24131end_data_xfer:
24132  sqlite3_finalize(pQuery);
24133  sqlite3_finalize(pInsert);
24134  sqlite3_free(zQuery);
24135  sqlite3_free(zInsert);
24136}
24137
24138
24139/*
24140** Try to transfer all rows of the schema that match zWhere.  For
24141** each row, invoke xForEach() on the object defined by that row.
24142** If an error is encountered while moving forward through the
24143** sqlite_schema table, try again moving backwards.
24144*/
24145static void tryToCloneSchema(
24146  ShellState *p,
24147  sqlite3 *newDb,
24148  const char *zWhere,
24149  void (*xForEach)(ShellState*,sqlite3*,const char*)
24150){
24151  sqlite3_stmt *pQuery = 0;
24152  char *zQuery = 0;
24153  int rc;
24154  const unsigned char *zName;
24155  const unsigned char *zSql;
24156  char *zErrMsg = 0;
24157
24158  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
24159                           " WHERE %s ORDER BY rowid ASC", zWhere);
24160  shell_check_oom(zQuery);
24161  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24162  if( rc ){
24163    eputf("Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
24164          sqlite3_errmsg(p->db), zQuery);
24165    goto end_schema_xfer;
24166  }
24167  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
24168    zName = sqlite3_column_text(pQuery, 0);
24169    zSql = sqlite3_column_text(pQuery, 1);
24170    if( zName==0 || zSql==0 ) continue;
24171    if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
24172      sputf(stdout, "%s... ", zName); fflush(stdout);
24173      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
24174      if( zErrMsg ){
24175        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
24176        sqlite3_free(zErrMsg);
24177        zErrMsg = 0;
24178      }
24179    }
24180    if( xForEach ){
24181      xForEach(p, newDb, (const char*)zName);
24182    }
24183    sputz(stdout, "done\n");
24184  }
24185  if( rc!=SQLITE_DONE ){
24186    sqlite3_finalize(pQuery);
24187    sqlite3_free(zQuery);
24188    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
24189                             " WHERE %s ORDER BY rowid DESC", zWhere);
24190    shell_check_oom(zQuery);
24191    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
24192    if( rc ){
24193      eputf("Error: (%d) %s on [%s]\n",
24194            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
24195      goto end_schema_xfer;
24196    }
24197    while( sqlite3_step(pQuery)==SQLITE_ROW ){
24198      zName = sqlite3_column_text(pQuery, 0);
24199      zSql = sqlite3_column_text(pQuery, 1);
24200      if( zName==0 || zSql==0 ) continue;
24201      if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
24202      sputf(stdout, "%s... ", zName); fflush(stdout);
24203      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
24204      if( zErrMsg ){
24205        eputf("Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
24206        sqlite3_free(zErrMsg);
24207        zErrMsg = 0;
24208      }
24209      if( xForEach ){
24210        xForEach(p, newDb, (const char*)zName);
24211      }
24212      sputz(stdout, "done\n");
24213    }
24214  }
24215end_schema_xfer:
24216  sqlite3_finalize(pQuery);
24217  sqlite3_free(zQuery);
24218}
24219
24220/*
24221** Open a new database file named "zNewDb".  Try to recover as much information
24222** as possible out of the main database (which might be corrupt) and write it
24223** into zNewDb.
24224*/
24225static void tryToClone(ShellState *p, const char *zNewDb){
24226  int rc;
24227  sqlite3 *newDb = 0;
24228  if( access(zNewDb,0)==0 ){
24229    eputf("File \"%s\" already exists.\n", zNewDb);
24230    return;
24231  }
24232  rc = sqlite3_open(zNewDb, &newDb);
24233  if( rc ){
24234    eputf("Cannot create output database: %s\n", sqlite3_errmsg(newDb));
24235  }else{
24236    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
24237    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
24238    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
24239    tryToCloneSchema(p, newDb, "type!='table'", 0);
24240    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
24241    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
24242  }
24243  close_db(newDb);
24244}
24245
24246#ifndef SQLITE_SHELL_FIDDLE
24247/*
24248** Change the output stream (file or pipe or console) to something else.
24249*/
24250static void output_redir(ShellState *p, FILE *pfNew){
24251  if( p->out != stdout ) eputz("Output already redirected.\n");
24252  else{
24253    p->out = pfNew;
24254    setOutputStream(pfNew);
24255  }
24256}
24257
24258/*
24259** Change the output file back to stdout.
24260**
24261** If the p->doXdgOpen flag is set, that means the output was being
24262** redirected to a temporary file named by p->zTempFile.  In that case,
24263** launch start/open/xdg-open on that temporary file.
24264*/
24265static void output_reset(ShellState *p){
24266  if( p->outfile[0]=='|' ){
24267#ifndef SQLITE_OMIT_POPEN
24268    pclose(p->out);
24269#endif
24270  }else{
24271    output_file_close(p->out);
24272#ifndef SQLITE_NOHAVE_SYSTEM
24273    if( p->doXdgOpen ){
24274      const char *zXdgOpenCmd =
24275#if defined(_WIN32)
24276      "start";
24277#elif defined(__APPLE__)
24278      "open";
24279#else
24280      "xdg-open";
24281#endif
24282      char *zCmd;
24283      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
24284      if( system(zCmd) ){
24285        eputf("Failed: [%s]\n", zCmd);
24286      }else{
24287        /* Give the start/open/xdg-open command some time to get
24288        ** going before we continue, and potential delete the
24289        ** p->zTempFile data file out from under it */
24290        sqlite3_sleep(2000);
24291      }
24292      sqlite3_free(zCmd);
24293      outputModePop(p);
24294      p->doXdgOpen = 0;
24295    }
24296#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
24297  }
24298  p->outfile[0] = 0;
24299  p->out = stdout;
24300  setOutputStream(stdout);
24301}
24302#else
24303# define output_redir(SS,pfO)
24304# define output_reset(SS)
24305#endif
24306
24307/*
24308** Run an SQL command and return the single integer result.
24309*/
24310static int db_int(sqlite3 *db, const char *zSql){
24311  sqlite3_stmt *pStmt;
24312  int res = 0;
24313  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
24314  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
24315    res = sqlite3_column_int(pStmt,0);
24316  }
24317  sqlite3_finalize(pStmt);
24318  return res;
24319}
24320
24321#if SQLITE_SHELL_HAVE_RECOVER
24322/*
24323** Convert a 2-byte or 4-byte big-endian integer into a native integer
24324*/
24325static unsigned int get2byteInt(unsigned char *a){
24326  return (a[0]<<8) + a[1];
24327}
24328static unsigned int get4byteInt(unsigned char *a){
24329  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
24330}
24331
24332/*
24333** Implementation of the ".dbinfo" command.
24334**
24335** Return 1 on error, 2 to exit, and 0 otherwise.
24336*/
24337static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
24338  static const struct { const char *zName; int ofst; } aField[] = {
24339     { "file change counter:",  24  },
24340     { "database page count:",  28  },
24341     { "freelist page count:",  36  },
24342     { "schema cookie:",        40  },
24343     { "schema format:",        44  },
24344     { "default cache size:",   48  },
24345     { "autovacuum top root:",  52  },
24346     { "incremental vacuum:",   64  },
24347     { "text encoding:",        56  },
24348     { "user version:",         60  },
24349     { "application id:",       68  },
24350     { "software version:",     96  },
24351  };
24352  static const struct { const char *zName; const char *zSql; } aQuery[] = {
24353     { "number of tables:",
24354       "SELECT count(*) FROM %s WHERE type='table'" },
24355     { "number of indexes:",
24356       "SELECT count(*) FROM %s WHERE type='index'" },
24357     { "number of triggers:",
24358       "SELECT count(*) FROM %s WHERE type='trigger'" },
24359     { "number of views:",
24360       "SELECT count(*) FROM %s WHERE type='view'" },
24361     { "schema size:",
24362       "SELECT total(length(sql)) FROM %s" },
24363  };
24364  int i, rc;
24365  unsigned iDataVersion;
24366  char *zSchemaTab;
24367  char *zDb = nArg>=2 ? azArg[1] : "main";
24368  sqlite3_stmt *pStmt = 0;
24369  unsigned char aHdr[100];
24370  open_db(p, 0);
24371  if( p->db==0 ) return 1;
24372  rc = sqlite3_prepare_v2(p->db,
24373             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
24374             -1, &pStmt, 0);
24375  if( rc ){
24376    eputf("error: %s\n", sqlite3_errmsg(p->db));
24377    sqlite3_finalize(pStmt);
24378    return 1;
24379  }
24380  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
24381  if( sqlite3_step(pStmt)==SQLITE_ROW
24382   && sqlite3_column_bytes(pStmt,0)>100
24383  ){
24384    const u8 *pb = sqlite3_column_blob(pStmt,0);
24385    shell_check_oom(pb);
24386    memcpy(aHdr, pb, 100);
24387    sqlite3_finalize(pStmt);
24388  }else{
24389    eputz("unable to read database header\n");
24390    sqlite3_finalize(pStmt);
24391    return 1;
24392  }
24393  i = get2byteInt(aHdr+16);
24394  if( i==1 ) i = 65536;
24395  oputf("%-20s %d\n", "database page size:", i);
24396  oputf("%-20s %d\n", "write format:", aHdr[18]);
24397  oputf("%-20s %d\n", "read format:", aHdr[19]);
24398  oputf("%-20s %d\n", "reserved bytes:", aHdr[20]);
24399  for(i=0; i<ArraySize(aField); i++){
24400    int ofst = aField[i].ofst;
24401    unsigned int val = get4byteInt(aHdr + ofst);
24402    oputf("%-20s %u", aField[i].zName, val);
24403    switch( ofst ){
24404      case 56: {
24405        if( val==1 ) oputz(" (utf8)");
24406        if( val==2 ) oputz(" (utf16le)");
24407        if( val==3 ) oputz(" (utf16be)");
24408      }
24409    }
24410    oputz("\n");
24411  }
24412  if( zDb==0 ){
24413    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
24414  }else if( cli_strcmp(zDb,"temp")==0 ){
24415    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
24416  }else{
24417    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
24418  }
24419  for(i=0; i<ArraySize(aQuery); i++){
24420    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
24421    int val = db_int(p->db, zSql);
24422    sqlite3_free(zSql);
24423    oputf("%-20s %d\n", aQuery[i].zName, val);
24424  }
24425  sqlite3_free(zSchemaTab);
24426  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
24427  oputf("%-20s %u\n", "data version", iDataVersion);
24428  return 0;
24429}
24430#endif /* SQLITE_SHELL_HAVE_RECOVER */
24431
24432/*
24433** Print the current sqlite3_errmsg() value to stderr and return 1.
24434*/
24435static int shellDatabaseError(sqlite3 *db){
24436  const char *zErr = sqlite3_errmsg(db);
24437  eputf("Error: %s\n", zErr);
24438  return 1;
24439}
24440
24441/*
24442** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
24443** if they match and FALSE (0) if they do not match.
24444**
24445** Globbing rules:
24446**
24447**      '*'       Matches any sequence of zero or more characters.
24448**
24449**      '?'       Matches exactly one character.
24450**
24451**     [...]      Matches one character from the enclosed list of
24452**                characters.
24453**
24454**     [^...]     Matches one character not in the enclosed list.
24455**
24456**      '#'       Matches any sequence of one or more digits with an
24457**                optional + or - sign in front
24458**
24459**      ' '       Any span of whitespace matches any other span of
24460**                whitespace.
24461**
24462** Extra whitespace at the end of z[] is ignored.
24463*/
24464static int testcase_glob(const char *zGlob, const char *z){
24465  int c, c2;
24466  int invert;
24467  int seen;
24468
24469  while( (c = (*(zGlob++)))!=0 ){
24470    if( IsSpace(c) ){
24471      if( !IsSpace(*z) ) return 0;
24472      while( IsSpace(*zGlob) ) zGlob++;
24473      while( IsSpace(*z) ) z++;
24474    }else if( c=='*' ){
24475      while( (c=(*(zGlob++))) == '*' || c=='?' ){
24476        if( c=='?' && (*(z++))==0 ) return 0;
24477      }
24478      if( c==0 ){
24479        return 1;
24480      }else if( c=='[' ){
24481        while( *z && testcase_glob(zGlob-1,z)==0 ){
24482          z++;
24483        }
24484        return (*z)!=0;
24485      }
24486      while( (c2 = (*(z++)))!=0 ){
24487        while( c2!=c ){
24488          c2 = *(z++);
24489          if( c2==0 ) return 0;
24490        }
24491        if( testcase_glob(zGlob,z) ) return 1;
24492      }
24493      return 0;
24494    }else if( c=='?' ){
24495      if( (*(z++))==0 ) return 0;
24496    }else if( c=='[' ){
24497      int prior_c = 0;
24498      seen = 0;
24499      invert = 0;
24500      c = *(z++);
24501      if( c==0 ) return 0;
24502      c2 = *(zGlob++);
24503      if( c2=='^' ){
24504        invert = 1;
24505        c2 = *(zGlob++);
24506      }
24507      if( c2==']' ){
24508        if( c==']' ) seen = 1;
24509        c2 = *(zGlob++);
24510      }
24511      while( c2 && c2!=']' ){
24512        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
24513          c2 = *(zGlob++);
24514          if( c>=prior_c && c<=c2 ) seen = 1;
24515          prior_c = 0;
24516        }else{
24517          if( c==c2 ){
24518            seen = 1;
24519          }
24520          prior_c = c2;
24521        }
24522        c2 = *(zGlob++);
24523      }
24524      if( c2==0 || (seen ^ invert)==0 ) return 0;
24525    }else if( c=='#' ){
24526      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
24527      if( !IsDigit(z[0]) ) return 0;
24528      z++;
24529      while( IsDigit(z[0]) ){ z++; }
24530    }else{
24531      if( c!=(*(z++)) ) return 0;
24532    }
24533  }
24534  while( IsSpace(*z) ){ z++; }
24535  return *z==0;
24536}
24537
24538
24539/*
24540** Compare the string as a command-line option with either one or two
24541** initial "-" characters.
24542*/
24543static int optionMatch(const char *zStr, const char *zOpt){
24544  if( zStr[0]!='-' ) return 0;
24545  zStr++;
24546  if( zStr[0]=='-' ) zStr++;
24547  return cli_strcmp(zStr, zOpt)==0;
24548}
24549
24550/*
24551** Delete a file.
24552*/
24553int shellDeleteFile(const char *zFilename){
24554  int rc;
24555#ifdef _WIN32
24556  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
24557  rc = _wunlink(z);
24558  sqlite3_free(z);
24559#else
24560  rc = unlink(zFilename);
24561#endif
24562  return rc;
24563}
24564
24565/*
24566** Try to delete the temporary file (if there is one) and free the
24567** memory used to hold the name of the temp file.
24568*/
24569static void clearTempFile(ShellState *p){
24570  if( p->zTempFile==0 ) return;
24571  if( p->doXdgOpen ) return;
24572  if( shellDeleteFile(p->zTempFile) ) return;
24573  sqlite3_free(p->zTempFile);
24574  p->zTempFile = 0;
24575}
24576
24577/*
24578** Create a new temp file name with the given suffix.
24579*/
24580static void newTempFile(ShellState *p, const char *zSuffix){
24581  clearTempFile(p);
24582  sqlite3_free(p->zTempFile);
24583  p->zTempFile = 0;
24584  if( p->db ){
24585    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
24586  }
24587  if( p->zTempFile==0 ){
24588    /* If p->db is an in-memory database then the TEMPFILENAME file-control
24589    ** will not work and we will need to fallback to guessing */
24590    char *zTemp;
24591    sqlite3_uint64 r;
24592    sqlite3_randomness(sizeof(r), &r);
24593    zTemp = getenv("TEMP");
24594    if( zTemp==0 ) zTemp = getenv("TMP");
24595    if( zTemp==0 ){
24596#ifdef _WIN32
24597      zTemp = "\\tmp";
24598#else
24599      zTemp = "/tmp";
24600#endif
24601    }
24602    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
24603  }else{
24604    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
24605  }
24606  shell_check_oom(p->zTempFile);
24607}
24608
24609
24610/*
24611** The implementation of SQL scalar function fkey_collate_clause(), used
24612** by the ".lint fkey-indexes" command. This scalar function is always
24613** called with four arguments - the parent table name, the parent column name,
24614** the child table name and the child column name.
24615**
24616**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
24617**
24618** If either of the named tables or columns do not exist, this function
24619** returns an empty string. An empty string is also returned if both tables
24620** and columns exist but have the same default collation sequence. Or,
24621** if both exist but the default collation sequences are different, this
24622** function returns the string " COLLATE <parent-collation>", where
24623** <parent-collation> is the default collation sequence of the parent column.
24624*/
24625static void shellFkeyCollateClause(
24626  sqlite3_context *pCtx,
24627  int nVal,
24628  sqlite3_value **apVal
24629){
24630  sqlite3 *db = sqlite3_context_db_handle(pCtx);
24631  const char *zParent;
24632  const char *zParentCol;
24633  const char *zParentSeq;
24634  const char *zChild;
24635  const char *zChildCol;
24636  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
24637  int rc;
24638
24639  assert( nVal==4 );
24640  zParent = (const char*)sqlite3_value_text(apVal[0]);
24641  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
24642  zChild = (const char*)sqlite3_value_text(apVal[2]);
24643  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
24644
24645  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
24646  rc = sqlite3_table_column_metadata(
24647      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
24648  );
24649  if( rc==SQLITE_OK ){
24650    rc = sqlite3_table_column_metadata(
24651        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
24652    );
24653  }
24654
24655  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
24656    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
24657    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
24658    sqlite3_free(z);
24659  }
24660}
24661
24662
24663/*
24664** The implementation of dot-command ".lint fkey-indexes".
24665*/
24666static int lintFkeyIndexes(
24667  ShellState *pState,             /* Current shell tool state */
24668  char **azArg,                   /* Array of arguments passed to dot command */
24669  int nArg                        /* Number of entries in azArg[] */
24670){
24671  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
24672  int bVerbose = 0;               /* If -verbose is present */
24673  int bGroupByParent = 0;         /* If -groupbyparent is present */
24674  int i;                          /* To iterate through azArg[] */
24675  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
24676  int rc;                         /* Return code */
24677  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
24678
24679  /*
24680  ** This SELECT statement returns one row for each foreign key constraint
24681  ** in the schema of the main database. The column values are:
24682  **
24683  ** 0. The text of an SQL statement similar to:
24684  **
24685  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
24686  **
24687  **    This SELECT is similar to the one that the foreign keys implementation
24688  **    needs to run internally on child tables. If there is an index that can
24689  **    be used to optimize this query, then it can also be used by the FK
24690  **    implementation to optimize DELETE or UPDATE statements on the parent
24691  **    table.
24692  **
24693  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
24694  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
24695  **    contains an index that can be used to optimize the query.
24696  **
24697  ** 2. Human readable text that describes the child table and columns. e.g.
24698  **
24699  **       "child_table(child_key1, child_key2)"
24700  **
24701  ** 3. Human readable text that describes the parent table and columns. e.g.
24702  **
24703  **       "parent_table(parent_key1, parent_key2)"
24704  **
24705  ** 4. A full CREATE INDEX statement for an index that could be used to
24706  **    optimize DELETE or UPDATE statements on the parent table. e.g.
24707  **
24708  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
24709  **
24710  ** 5. The name of the parent table.
24711  **
24712  ** These six values are used by the C logic below to generate the report.
24713  */
24714  const char *zSql =
24715  "SELECT "
24716    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
24717    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
24718    "  || fkey_collate_clause("
24719    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
24720    ", "
24721    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
24722    "  || group_concat('*=?', ' AND ') || ')'"
24723    ", "
24724    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
24725    ", "
24726    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
24727    ", "
24728    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
24729    "  || ' ON ' || quote(s.name) || '('"
24730    "  || group_concat(quote(f.[from]) ||"
24731    "        fkey_collate_clause("
24732    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
24733    "  || ');'"
24734    ", "
24735    "     f.[table] "
24736    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
24737    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
24738    "GROUP BY s.name, f.id "
24739    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
24740  ;
24741  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
24742
24743  for(i=2; i<nArg; i++){
24744    int n = strlen30(azArg[i]);
24745    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
24746      bVerbose = 1;
24747    }
24748    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
24749      bGroupByParent = 1;
24750      zIndent = "    ";
24751    }
24752    else{
24753      eputf("Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]);
24754      return SQLITE_ERROR;
24755    }
24756  }
24757
24758  /* Register the fkey_collate_clause() SQL function */
24759  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
24760      0, shellFkeyCollateClause, 0, 0
24761  );
24762
24763
24764  if( rc==SQLITE_OK ){
24765    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
24766  }
24767  if( rc==SQLITE_OK ){
24768    sqlite3_bind_int(pSql, 1, bGroupByParent);
24769  }
24770
24771  if( rc==SQLITE_OK ){
24772    int rc2;
24773    char *zPrev = 0;
24774    while( SQLITE_ROW==sqlite3_step(pSql) ){
24775      int res = -1;
24776      sqlite3_stmt *pExplain = 0;
24777      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
24778      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
24779      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
24780      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
24781      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
24782      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
24783
24784      if( zEQP==0 ) continue;
24785      if( zGlob==0 ) continue;
24786      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
24787      if( rc!=SQLITE_OK ) break;
24788      if( SQLITE_ROW==sqlite3_step(pExplain) ){
24789        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
24790        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
24791                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
24792      }
24793      rc = sqlite3_finalize(pExplain);
24794      if( rc!=SQLITE_OK ) break;
24795
24796      if( res<0 ){
24797        eputz("Error: internal error");
24798        break;
24799      }else{
24800        if( bGroupByParent
24801        && (bVerbose || res==0)
24802        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
24803        ){
24804          oputf("-- Parent table %s\n", zParent);
24805          sqlite3_free(zPrev);
24806          zPrev = sqlite3_mprintf("%s", zParent);
24807        }
24808
24809        if( res==0 ){
24810          oputf("%s%s --> %s\n", zIndent, zCI, zTarget);
24811        }else if( bVerbose ){
24812          oputf("%s/* no extra indexes required for %s -> %s */\n",
24813                zIndent, zFrom, zTarget
24814          );
24815        }
24816      }
24817    }
24818    sqlite3_free(zPrev);
24819
24820    if( rc!=SQLITE_OK ){
24821      eputf("%s\n", sqlite3_errmsg(db));
24822    }
24823
24824    rc2 = sqlite3_finalize(pSql);
24825    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
24826      rc = rc2;
24827      eputf("%s\n", sqlite3_errmsg(db));
24828    }
24829  }else{
24830    eputf("%s\n", sqlite3_errmsg(db));
24831  }
24832
24833  return rc;
24834}
24835
24836/*
24837** Implementation of ".lint" dot command.
24838*/
24839static int lintDotCommand(
24840  ShellState *pState,             /* Current shell tool state */
24841  char **azArg,                   /* Array of arguments passed to dot command */
24842  int nArg                        /* Number of entries in azArg[] */
24843){
24844  int n;
24845  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
24846  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
24847  return lintFkeyIndexes(pState, azArg, nArg);
24848
24849 usage:
24850  eputf("Usage %s sub-command ?switches...?\n", azArg[0]);
24851  eputz("Where sub-commands are:\n");
24852  eputz("    fkey-indexes\n");
24853  return SQLITE_ERROR;
24854}
24855
24856static void shellPrepare(
24857  sqlite3 *db,
24858  int *pRc,
24859  const char *zSql,
24860  sqlite3_stmt **ppStmt
24861){
24862  *ppStmt = 0;
24863  if( *pRc==SQLITE_OK ){
24864    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
24865    if( rc!=SQLITE_OK ){
24866      eputf("sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db));
24867      *pRc = rc;
24868    }
24869  }
24870}
24871
24872/*
24873** Create a prepared statement using printf-style arguments for the SQL.
24874*/
24875static void shellPreparePrintf(
24876  sqlite3 *db,
24877  int *pRc,
24878  sqlite3_stmt **ppStmt,
24879  const char *zFmt,
24880  ...
24881){
24882  *ppStmt = 0;
24883  if( *pRc==SQLITE_OK ){
24884    va_list ap;
24885    char *z;
24886    va_start(ap, zFmt);
24887    z = sqlite3_vmprintf(zFmt, ap);
24888    va_end(ap);
24889    if( z==0 ){
24890      *pRc = SQLITE_NOMEM;
24891    }else{
24892      shellPrepare(db, pRc, z, ppStmt);
24893      sqlite3_free(z);
24894    }
24895  }
24896}
24897
24898/*
24899** Finalize the prepared statement created using shellPreparePrintf().
24900*/
24901static void shellFinalize(
24902  int *pRc,
24903  sqlite3_stmt *pStmt
24904){
24905  if( pStmt ){
24906    sqlite3 *db = sqlite3_db_handle(pStmt);
24907    int rc = sqlite3_finalize(pStmt);
24908    if( *pRc==SQLITE_OK ){
24909      if( rc!=SQLITE_OK ){
24910        eputf("SQL error: %s\n", sqlite3_errmsg(db));
24911      }
24912      *pRc = rc;
24913    }
24914  }
24915}
24916
24917#if !defined SQLITE_OMIT_VIRTUALTABLE
24918/* Reset the prepared statement created using shellPreparePrintf().
24919**
24920** This routine is could be marked "static".  But it is not always used,
24921** depending on compile-time options.  By omitting the "static", we avoid
24922** nuisance compiler warnings about "defined but not used".
24923*/
24924void shellReset(
24925  int *pRc,
24926  sqlite3_stmt *pStmt
24927){
24928  int rc = sqlite3_reset(pStmt);
24929  if( *pRc==SQLITE_OK ){
24930    if( rc!=SQLITE_OK ){
24931      sqlite3 *db = sqlite3_db_handle(pStmt);
24932      eputf("SQL error: %s\n", sqlite3_errmsg(db));
24933    }
24934    *pRc = rc;
24935  }
24936}
24937#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
24938
24939#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
24940/******************************************************************************
24941** The ".archive" or ".ar" command.
24942*/
24943/*
24944** Structure representing a single ".ar" command.
24945*/
24946typedef struct ArCommand ArCommand;
24947struct ArCommand {
24948  u8 eCmd;                        /* An AR_CMD_* value */
24949  u8 bVerbose;                    /* True if --verbose */
24950  u8 bZip;                        /* True if the archive is a ZIP */
24951  u8 bDryRun;                     /* True if --dry-run */
24952  u8 bAppend;                     /* True if --append */
24953  u8 bGlob;                       /* True if --glob */
24954  u8 fromCmdLine;                 /* Run from -A instead of .archive */
24955  int nArg;                       /* Number of command arguments */
24956  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
24957  const char *zFile;              /* --file argument, or NULL */
24958  const char *zDir;               /* --directory argument, or NULL */
24959  char **azArg;                   /* Array of command arguments */
24960  ShellState *p;                  /* Shell state */
24961  sqlite3 *db;                    /* Database containing the archive */
24962};
24963
24964/*
24965** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
24966*/
24967static int arUsage(FILE *f){
24968  showHelp(f,"archive");
24969  return SQLITE_ERROR;
24970}
24971
24972/*
24973** Print an error message for the .ar command to stderr and return
24974** SQLITE_ERROR.
24975*/
24976static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
24977  va_list ap;
24978  char *z;
24979  va_start(ap, zFmt);
24980  z = sqlite3_vmprintf(zFmt, ap);
24981  va_end(ap);
24982  eputf("Error: %s\n", z);
24983  if( pAr->fromCmdLine ){
24984    eputz("Use \"-A\" for more help\n");
24985  }else{
24986    eputz("Use \".archive --help\" for more help\n");
24987  }
24988  sqlite3_free(z);
24989  return SQLITE_ERROR;
24990}
24991
24992/*
24993** Values for ArCommand.eCmd.
24994*/
24995#define AR_CMD_CREATE       1
24996#define AR_CMD_UPDATE       2
24997#define AR_CMD_INSERT       3
24998#define AR_CMD_EXTRACT      4
24999#define AR_CMD_LIST         5
25000#define AR_CMD_HELP         6
25001#define AR_CMD_REMOVE       7
25002
25003/*
25004** Other (non-command) switches.
25005*/
25006#define AR_SWITCH_VERBOSE     8
25007#define AR_SWITCH_FILE        9
25008#define AR_SWITCH_DIRECTORY  10
25009#define AR_SWITCH_APPEND     11
25010#define AR_SWITCH_DRYRUN     12
25011#define AR_SWITCH_GLOB       13
25012
25013static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
25014  switch( eSwitch ){
25015    case AR_CMD_CREATE:
25016    case AR_CMD_EXTRACT:
25017    case AR_CMD_LIST:
25018    case AR_CMD_REMOVE:
25019    case AR_CMD_UPDATE:
25020    case AR_CMD_INSERT:
25021    case AR_CMD_HELP:
25022      if( pAr->eCmd ){
25023        return arErrorMsg(pAr, "multiple command options");
25024      }
25025      pAr->eCmd = eSwitch;
25026      break;
25027
25028    case AR_SWITCH_DRYRUN:
25029      pAr->bDryRun = 1;
25030      break;
25031    case AR_SWITCH_GLOB:
25032      pAr->bGlob = 1;
25033      break;
25034    case AR_SWITCH_VERBOSE:
25035      pAr->bVerbose = 1;
25036      break;
25037    case AR_SWITCH_APPEND:
25038      pAr->bAppend = 1;
25039      deliberate_fall_through;
25040    case AR_SWITCH_FILE:
25041      pAr->zFile = zArg;
25042      break;
25043    case AR_SWITCH_DIRECTORY:
25044      pAr->zDir = zArg;
25045      break;
25046  }
25047
25048  return SQLITE_OK;
25049}
25050
25051/*
25052** Parse the command line for an ".ar" command. The results are written into
25053** structure (*pAr). SQLITE_OK is returned if the command line is parsed
25054** successfully, otherwise an error message is written to stderr and
25055** SQLITE_ERROR returned.
25056*/
25057static int arParseCommand(
25058  char **azArg,                   /* Array of arguments passed to dot command */
25059  int nArg,                       /* Number of entries in azArg[] */
25060  ArCommand *pAr                  /* Populate this object */
25061){
25062  struct ArSwitch {
25063    const char *zLong;
25064    char cShort;
25065    u8 eSwitch;
25066    u8 bArg;
25067  } aSwitch[] = {
25068    { "create",    'c', AR_CMD_CREATE,       0 },
25069    { "extract",   'x', AR_CMD_EXTRACT,      0 },
25070    { "insert",    'i', AR_CMD_INSERT,       0 },
25071    { "list",      't', AR_CMD_LIST,         0 },
25072    { "remove",    'r', AR_CMD_REMOVE,       0 },
25073    { "update",    'u', AR_CMD_UPDATE,       0 },
25074    { "help",      'h', AR_CMD_HELP,         0 },
25075    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
25076    { "file",      'f', AR_SWITCH_FILE,      1 },
25077    { "append",    'a', AR_SWITCH_APPEND,    1 },
25078    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
25079    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
25080    { "glob",      'g', AR_SWITCH_GLOB,      0 },
25081  };
25082  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
25083  struct ArSwitch *pEnd = &aSwitch[nSwitch];
25084
25085  if( nArg<=1 ){
25086    eputz("Wrong number of arguments.  Usage:\n");
25087    return arUsage(stderr);
25088  }else{
25089    char *z = azArg[1];
25090    if( z[0]!='-' ){
25091      /* Traditional style [tar] invocation */
25092      int i;
25093      int iArg = 2;
25094      for(i=0; z[i]; i++){
25095        const char *zArg = 0;
25096        struct ArSwitch *pOpt;
25097        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25098          if( z[i]==pOpt->cShort ) break;
25099        }
25100        if( pOpt==pEnd ){
25101          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
25102        }
25103        if( pOpt->bArg ){
25104          if( iArg>=nArg ){
25105            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
25106          }
25107          zArg = azArg[iArg++];
25108        }
25109        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
25110      }
25111      pAr->nArg = nArg-iArg;
25112      if( pAr->nArg>0 ){
25113        pAr->azArg = &azArg[iArg];
25114      }
25115    }else{
25116      /* Non-traditional invocation */
25117      int iArg;
25118      for(iArg=1; iArg<nArg; iArg++){
25119        int n;
25120        z = azArg[iArg];
25121        if( z[0]!='-' ){
25122          /* All remaining command line words are command arguments. */
25123          pAr->azArg = &azArg[iArg];
25124          pAr->nArg = nArg-iArg;
25125          break;
25126        }
25127        n = strlen30(z);
25128
25129        if( z[1]!='-' ){
25130          int i;
25131          /* One or more short options */
25132          for(i=1; i<n; i++){
25133            const char *zArg = 0;
25134            struct ArSwitch *pOpt;
25135            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25136              if( z[i]==pOpt->cShort ) break;
25137            }
25138            if( pOpt==pEnd ){
25139              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
25140            }
25141            if( pOpt->bArg ){
25142              if( i<(n-1) ){
25143                zArg = &z[i+1];
25144                i = n;
25145              }else{
25146                if( iArg>=(nArg-1) ){
25147                  return arErrorMsg(pAr, "option requires an argument: %c",
25148                                    z[i]);
25149                }
25150                zArg = azArg[++iArg];
25151              }
25152            }
25153            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
25154          }
25155        }else if( z[2]=='\0' ){
25156          /* A -- option, indicating that all remaining command line words
25157          ** are command arguments.  */
25158          pAr->azArg = &azArg[iArg+1];
25159          pAr->nArg = nArg-iArg-1;
25160          break;
25161        }else{
25162          /* A long option */
25163          const char *zArg = 0;             /* Argument for option, if any */
25164          struct ArSwitch *pMatch = 0;      /* Matching option */
25165          struct ArSwitch *pOpt;            /* Iterator */
25166          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
25167            const char *zLong = pOpt->zLong;
25168            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
25169              if( pMatch ){
25170                return arErrorMsg(pAr, "ambiguous option: %s",z);
25171              }else{
25172                pMatch = pOpt;
25173              }
25174            }
25175          }
25176
25177          if( pMatch==0 ){
25178            return arErrorMsg(pAr, "unrecognized option: %s", z);
25179          }
25180          if( pMatch->bArg ){
25181            if( iArg>=(nArg-1) ){
25182              return arErrorMsg(pAr, "option requires an argument: %s", z);
25183            }
25184            zArg = azArg[++iArg];
25185          }
25186          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
25187        }
25188      }
25189    }
25190  }
25191  if( pAr->eCmd==0 ){
25192    eputz("Required argument missing.  Usage:\n");
25193    return arUsage(stderr);
25194  }
25195  return SQLITE_OK;
25196}
25197
25198/*
25199** This function assumes that all arguments within the ArCommand.azArg[]
25200** array refer to archive members, as for the --extract, --list or --remove
25201** commands. It checks that each of them are "present". If any specified
25202** file is not present in the archive, an error is printed to stderr and an
25203** error code returned. Otherwise, if all specified arguments are present
25204** in the archive, SQLITE_OK is returned. Here, "present" means either an
25205** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
25206** when pAr->bGlob is true.
25207**
25208** This function strips any trailing '/' characters from each argument.
25209** This is consistent with the way the [tar] command seems to work on
25210** Linux.
25211*/
25212static int arCheckEntries(ArCommand *pAr){
25213  int rc = SQLITE_OK;
25214  if( pAr->nArg ){
25215    int i, j;
25216    sqlite3_stmt *pTest = 0;
25217    const char *zSel = (pAr->bGlob)
25218      ? "SELECT name FROM %s WHERE glob($name,name)"
25219      : "SELECT name FROM %s WHERE name=$name";
25220
25221    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
25222    j = sqlite3_bind_parameter_index(pTest, "$name");
25223    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
25224      char *z = pAr->azArg[i];
25225      int n = strlen30(z);
25226      int bOk = 0;
25227      while( n>0 && z[n-1]=='/' ) n--;
25228      z[n] = '\0';
25229      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
25230      if( SQLITE_ROW==sqlite3_step(pTest) ){
25231        bOk = 1;
25232      }
25233      shellReset(&rc, pTest);
25234      if( rc==SQLITE_OK && bOk==0 ){
25235        eputf("not found in archive: %s\n", z);
25236        rc = SQLITE_ERROR;
25237      }
25238    }
25239    shellFinalize(&rc, pTest);
25240  }
25241  return rc;
25242}
25243
25244/*
25245** Format a WHERE clause that can be used against the "sqlar" table to
25246** identify all archive members that match the command arguments held
25247** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
25248** The caller is responsible for eventually calling sqlite3_free() on
25249** any non-NULL (*pzWhere) value. Here, "match" means strict equality
25250** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
25251*/
25252static void arWhereClause(
25253  int *pRc,
25254  ArCommand *pAr,
25255  char **pzWhere                  /* OUT: New WHERE clause */
25256){
25257  char *zWhere = 0;
25258  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
25259  if( *pRc==SQLITE_OK ){
25260    if( pAr->nArg==0 ){
25261      zWhere = sqlite3_mprintf("1");
25262    }else{
25263      int i;
25264      const char *zSep = "";
25265      for(i=0; i<pAr->nArg; i++){
25266        const char *z = pAr->azArg[i];
25267        zWhere = sqlite3_mprintf(
25268          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
25269          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
25270        );
25271        if( zWhere==0 ){
25272          *pRc = SQLITE_NOMEM;
25273          break;
25274        }
25275        zSep = " OR ";
25276      }
25277    }
25278  }
25279  *pzWhere = zWhere;
25280}
25281
25282/*
25283** Implementation of .ar "lisT" command.
25284*/
25285static int arListCommand(ArCommand *pAr){
25286  const char *zSql = "SELECT %s FROM %s WHERE %s";
25287  const char *azCols[] = {
25288    "name",
25289    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
25290  };
25291
25292  char *zWhere = 0;
25293  sqlite3_stmt *pSql = 0;
25294  int rc;
25295
25296  rc = arCheckEntries(pAr);
25297  arWhereClause(&rc, pAr, &zWhere);
25298
25299  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
25300                     pAr->zSrcTable, zWhere);
25301  if( pAr->bDryRun ){
25302    oputf("%s\n", sqlite3_sql(pSql));
25303  }else{
25304    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
25305      if( pAr->bVerbose ){
25306        oputf("%s % 10d  %s  %s\n",
25307              sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1),
25308              sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3));
25309      }else{
25310        oputf("%s\n", sqlite3_column_text(pSql, 0));
25311      }
25312    }
25313  }
25314  shellFinalize(&rc, pSql);
25315  sqlite3_free(zWhere);
25316  return rc;
25317}
25318
25319/*
25320** Implementation of .ar "Remove" command.
25321*/
25322static int arRemoveCommand(ArCommand *pAr){
25323  int rc = 0;
25324  char *zSql = 0;
25325  char *zWhere = 0;
25326
25327  if( pAr->nArg ){
25328    /* Verify that args actually exist within the archive before proceeding.
25329    ** And formulate a WHERE clause to match them.  */
25330    rc = arCheckEntries(pAr);
25331    arWhereClause(&rc, pAr, &zWhere);
25332  }
25333  if( rc==SQLITE_OK ){
25334    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
25335                           pAr->zSrcTable, zWhere);
25336    if( pAr->bDryRun ){
25337      oputf("%s\n", zSql);
25338    }else{
25339      char *zErr = 0;
25340      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
25341      if( rc==SQLITE_OK ){
25342        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
25343        if( rc!=SQLITE_OK ){
25344          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
25345        }else{
25346          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
25347        }
25348      }
25349      if( zErr ){
25350        sputf(stdout, "ERROR: %s\n", zErr); /* stdout? */
25351        sqlite3_free(zErr);
25352      }
25353    }
25354  }
25355  sqlite3_free(zWhere);
25356  sqlite3_free(zSql);
25357  return rc;
25358}
25359
25360/*
25361** Implementation of .ar "eXtract" command.
25362*/
25363static int arExtractCommand(ArCommand *pAr){
25364  const char *zSql1 =
25365    "SELECT "
25366    " ($dir || name),"
25367    " writefile(($dir || name), %s, mode, mtime) "
25368    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
25369    " AND name NOT GLOB '*..[/\\]*'";
25370
25371  const char *azExtraArg[] = {
25372    "sqlar_uncompress(data, sz)",
25373    "data"
25374  };
25375
25376  sqlite3_stmt *pSql = 0;
25377  int rc = SQLITE_OK;
25378  char *zDir = 0;
25379  char *zWhere = 0;
25380  int i, j;
25381
25382  /* If arguments are specified, check that they actually exist within
25383  ** the archive before proceeding. And formulate a WHERE clause to
25384  ** match them.  */
25385  rc = arCheckEntries(pAr);
25386  arWhereClause(&rc, pAr, &zWhere);
25387
25388  if( rc==SQLITE_OK ){
25389    if( pAr->zDir ){
25390      zDir = sqlite3_mprintf("%s/", pAr->zDir);
25391    }else{
25392      zDir = sqlite3_mprintf("");
25393    }
25394    if( zDir==0 ) rc = SQLITE_NOMEM;
25395  }
25396
25397  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
25398      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
25399  );
25400
25401  if( rc==SQLITE_OK ){
25402    j = sqlite3_bind_parameter_index(pSql, "$dir");
25403    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
25404
25405    /* Run the SELECT statement twice. The first time, writefile() is called
25406    ** for all archive members that should be extracted. The second time,
25407    ** only for the directories. This is because the timestamps for
25408    ** extracted directories must be reset after they are populated (as
25409    ** populating them changes the timestamp).  */
25410    for(i=0; i<2; i++){
25411      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
25412      sqlite3_bind_int(pSql, j, i);
25413      if( pAr->bDryRun ){
25414        oputf("%s\n", sqlite3_sql(pSql));
25415      }else{
25416        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
25417          if( i==0 && pAr->bVerbose ){
25418            oputf("%s\n", sqlite3_column_text(pSql, 0));
25419          }
25420        }
25421      }
25422      shellReset(&rc, pSql);
25423    }
25424    shellFinalize(&rc, pSql);
25425  }
25426
25427  sqlite3_free(zDir);
25428  sqlite3_free(zWhere);
25429  return rc;
25430}
25431
25432/*
25433** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
25434*/
25435static int arExecSql(ArCommand *pAr, const char *zSql){
25436  int rc;
25437  if( pAr->bDryRun ){
25438    oputf("%s\n", zSql);
25439    rc = SQLITE_OK;
25440  }else{
25441    char *zErr = 0;
25442    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
25443    if( zErr ){
25444      sputf(stdout, "ERROR: %s\n", zErr);
25445      sqlite3_free(zErr);
25446    }
25447  }
25448  return rc;
25449}
25450
25451
25452/*
25453** Implementation of .ar "create", "insert", and "update" commands.
25454**
25455**     create    ->     Create a new SQL archive
25456**     insert    ->     Insert or reinsert all files listed
25457**     update    ->     Insert files that have changed or that were not
25458**                      previously in the archive
25459**
25460** Create the "sqlar" table in the database if it does not already exist.
25461** Then add each file in the azFile[] array to the archive. Directories
25462** are added recursively. If argument bVerbose is non-zero, a message is
25463** printed on stdout for each file archived.
25464**
25465** The create command is the same as update, except that it drops
25466** any existing "sqlar" table before beginning.  The "insert" command
25467** always overwrites every file named on the command-line, where as
25468** "update" only overwrites if the size or mtime or mode has changed.
25469*/
25470static int arCreateOrUpdateCommand(
25471  ArCommand *pAr,                 /* Command arguments and options */
25472  int bUpdate,                    /* true for a --create. */
25473  int bOnlyIfChanged              /* Only update if file has changed */
25474){
25475  const char *zCreate =
25476      "CREATE TABLE IF NOT EXISTS sqlar(\n"
25477      "  name TEXT PRIMARY KEY,  -- name of the file\n"
25478      "  mode INT,               -- access permissions\n"
25479      "  mtime INT,              -- last modification time\n"
25480      "  sz INT,                 -- original file size\n"
25481      "  data BLOB               -- compressed content\n"
25482      ")";
25483  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
25484  const char *zInsertFmt[2] = {
25485     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
25486     "  SELECT\n"
25487     "    %s,\n"
25488     "    mode,\n"
25489     "    mtime,\n"
25490     "    CASE substr(lsmode(mode),1,1)\n"
25491     "      WHEN '-' THEN length(data)\n"
25492     "      WHEN 'd' THEN 0\n"
25493     "      ELSE -1 END,\n"
25494     "    sqlar_compress(data)\n"
25495     "  FROM fsdir(%Q,%Q) AS disk\n"
25496     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
25497     ,
25498     "REPLACE INTO %s(name,mode,mtime,data)\n"
25499     "  SELECT\n"
25500     "    %s,\n"
25501     "    mode,\n"
25502     "    mtime,\n"
25503     "    data\n"
25504     "  FROM fsdir(%Q,%Q) AS disk\n"
25505     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
25506  };
25507  int i;                          /* For iterating through azFile[] */
25508  int rc;                         /* Return code */
25509  const char *zTab = 0;           /* SQL table into which to insert */
25510  char *zSql;
25511  char zTemp[50];
25512  char *zExists = 0;
25513
25514  arExecSql(pAr, "PRAGMA page_size=512");
25515  rc = arExecSql(pAr, "SAVEPOINT ar;");
25516  if( rc!=SQLITE_OK ) return rc;
25517  zTemp[0] = 0;
25518  if( pAr->bZip ){
25519    /* Initialize the zipfile virtual table, if necessary */
25520    if( pAr->zFile ){
25521      sqlite3_uint64 r;
25522      sqlite3_randomness(sizeof(r),&r);
25523      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
25524      zTab = zTemp;
25525      zSql = sqlite3_mprintf(
25526         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
25527         zTab, pAr->zFile
25528      );
25529      rc = arExecSql(pAr, zSql);
25530      sqlite3_free(zSql);
25531    }else{
25532      zTab = "zip";
25533    }
25534  }else{
25535    /* Initialize the table for an SQLAR */
25536    zTab = "sqlar";
25537    if( bUpdate==0 ){
25538      rc = arExecSql(pAr, zDrop);
25539      if( rc!=SQLITE_OK ) goto end_ar_transaction;
25540    }
25541    rc = arExecSql(pAr, zCreate);
25542  }
25543  if( bOnlyIfChanged ){
25544    zExists = sqlite3_mprintf(
25545      " AND NOT EXISTS("
25546          "SELECT 1 FROM %s AS mem"
25547          " WHERE mem.name=disk.name"
25548          " AND mem.mtime=disk.mtime"
25549          " AND mem.mode=disk.mode)", zTab);
25550  }else{
25551    zExists = sqlite3_mprintf("");
25552  }
25553  if( zExists==0 ) rc = SQLITE_NOMEM;
25554  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
25555    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
25556        pAr->bVerbose ? "shell_putsnl(name)" : "name",
25557        pAr->azArg[i], pAr->zDir, zExists);
25558    rc = arExecSql(pAr, zSql2);
25559    sqlite3_free(zSql2);
25560  }
25561end_ar_transaction:
25562  if( rc!=SQLITE_OK ){
25563    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
25564  }else{
25565    rc = arExecSql(pAr, "RELEASE ar;");
25566    if( pAr->bZip && pAr->zFile ){
25567      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
25568      arExecSql(pAr, zSql);
25569      sqlite3_free(zSql);
25570    }
25571  }
25572  sqlite3_free(zExists);
25573  return rc;
25574}
25575
25576/*
25577** Implementation of ".ar" dot command.
25578*/
25579static int arDotCommand(
25580  ShellState *pState,          /* Current shell tool state */
25581  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
25582  char **azArg,                /* Array of arguments passed to dot command */
25583  int nArg                     /* Number of entries in azArg[] */
25584){
25585  ArCommand cmd;
25586  int rc;
25587  memset(&cmd, 0, sizeof(cmd));
25588  cmd.fromCmdLine = fromCmdLine;
25589  rc = arParseCommand(azArg, nArg, &cmd);
25590  if( rc==SQLITE_OK ){
25591    int eDbType = SHELL_OPEN_UNSPEC;
25592    cmd.p = pState;
25593    cmd.db = pState->db;
25594    if( cmd.zFile ){
25595      eDbType = deduceDatabaseType(cmd.zFile, 1);
25596    }else{
25597      eDbType = pState->openMode;
25598    }
25599    if( eDbType==SHELL_OPEN_ZIPFILE ){
25600      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
25601        if( cmd.zFile==0 ){
25602          cmd.zSrcTable = sqlite3_mprintf("zip");
25603        }else{
25604          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
25605        }
25606      }
25607      cmd.bZip = 1;
25608    }else if( cmd.zFile ){
25609      int flags;
25610      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
25611      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
25612           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
25613        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
25614      }else{
25615        flags = SQLITE_OPEN_READONLY;
25616      }
25617      cmd.db = 0;
25618      if( cmd.bDryRun ){
25619        oputf("-- open database '%s'%s\n", cmd.zFile,
25620              eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
25621      }
25622      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
25623             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
25624      if( rc!=SQLITE_OK ){
25625        eputf("cannot open file: %s (%s)\n", cmd.zFile, sqlite3_errmsg(cmd.db));
25626        goto end_ar_command;
25627      }
25628      sqlite3_fileio_init(cmd.db, 0, 0);
25629      sqlite3_sqlar_init(cmd.db, 0, 0);
25630      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
25631                              shellPutsFunc, 0, 0);
25632
25633    }
25634    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
25635      if( cmd.eCmd!=AR_CMD_CREATE
25636       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
25637      ){
25638        eputz("database does not contain an 'sqlar' table\n");
25639        rc = SQLITE_ERROR;
25640        goto end_ar_command;
25641      }
25642      cmd.zSrcTable = sqlite3_mprintf("sqlar");
25643    }
25644
25645    switch( cmd.eCmd ){
25646      case AR_CMD_CREATE:
25647        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
25648        break;
25649
25650      case AR_CMD_EXTRACT:
25651        rc = arExtractCommand(&cmd);
25652        break;
25653
25654      case AR_CMD_LIST:
25655        rc = arListCommand(&cmd);
25656        break;
25657
25658      case AR_CMD_HELP:
25659        arUsage(pState->out);
25660        break;
25661
25662      case AR_CMD_INSERT:
25663        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
25664        break;
25665
25666      case AR_CMD_REMOVE:
25667        rc = arRemoveCommand(&cmd);
25668        break;
25669
25670      default:
25671        assert( cmd.eCmd==AR_CMD_UPDATE );
25672        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
25673        break;
25674    }
25675  }
25676end_ar_command:
25677  if( cmd.db!=pState->db ){
25678    close_db(cmd.db);
25679  }
25680  sqlite3_free(cmd.zSrcTable);
25681
25682  return rc;
25683}
25684/* End of the ".archive" or ".ar" command logic
25685*******************************************************************************/
25686#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
25687
25688#if SQLITE_SHELL_HAVE_RECOVER
25689
25690/*
25691** This function is used as a callback by the recover extension. Simply
25692** print the supplied SQL statement to stdout.
25693*/
25694static int recoverSqlCb(void *pCtx, const char *zSql){
25695  ShellState *pState = (ShellState*)pCtx;
25696  sputf(pState->out, "%s;\n", zSql);
25697  return SQLITE_OK;
25698}
25699
25700/*
25701** This function is called to recover data from the database. A script
25702** to construct a new database containing all recovered data is output
25703** on stream pState->out.
25704*/
25705static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
25706  int rc = SQLITE_OK;
25707  const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
25708  const char *zLAF = "lost_and_found";
25709  int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
25710  int bRowids = 1;                /* 0 if --no-rowids */
25711  sqlite3_recover *p = 0;
25712  int i = 0;
25713
25714  for(i=1; i<nArg; i++){
25715    char *z = azArg[i];
25716    int n;
25717    if( z[0]=='-' && z[1]=='-' ) z++;
25718    n = strlen30(z);
25719    if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
25720      bFreelist = 0;
25721    }else
25722    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
25723      /* This option determines the name of the ATTACH-ed database used
25724      ** internally by the recovery extension.  The default is "" which
25725      ** means to use a temporary database that is automatically deleted
25726      ** when closed.  This option is undocumented and might disappear at
25727      ** any moment. */
25728      i++;
25729      zRecoveryDb = azArg[i];
25730    }else
25731    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
25732      i++;
25733      zLAF = azArg[i];
25734    }else
25735    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
25736      bRowids = 0;
25737    }
25738    else{
25739      eputf("unexpected option: %s\n", azArg[i]);
25740      showHelp(pState->out, azArg[0]);
25741      return 1;
25742    }
25743  }
25744
25745  p = sqlite3_recover_init_sql(
25746      pState->db, "main", recoverSqlCb, (void*)pState
25747  );
25748
25749  sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
25750  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
25751  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
25752  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
25753
25754  sqlite3_recover_run(p);
25755  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
25756    const char *zErr = sqlite3_recover_errmsg(p);
25757    int errCode = sqlite3_recover_errcode(p);
25758    eputf("sql error: %s (%d)\n", zErr, errCode);
25759  }
25760  rc = sqlite3_recover_finish(p);
25761  return rc;
25762}
25763#endif /* SQLITE_SHELL_HAVE_RECOVER */
25764
25765/*
25766** Implementation of ".intck STEPS_PER_UNLOCK" command.
25767*/
25768static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){
25769  sqlite3_intck *p = 0;
25770  int rc = SQLITE_OK;
25771
25772  rc = sqlite3_intck_open(pState->db, "main", &p);
25773  if( rc==SQLITE_OK ){
25774    i64 nStep = 0;
25775    i64 nError = 0;
25776    const char *zErr = 0;
25777    while( SQLITE_OK==sqlite3_intck_step(p) ){
25778      const char *zMsg = sqlite3_intck_message(p);
25779      if( zMsg ){
25780        oputf("%s\n", zMsg);
25781        nError++;
25782      }
25783      nStep++;
25784      if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){
25785        sqlite3_intck_unlock(p);
25786      }
25787    }
25788    rc = sqlite3_intck_error(p, &zErr);
25789    if( zErr ){
25790      eputf("%s\n", zErr);
25791    }
25792    sqlite3_intck_close(p);
25793
25794    oputf("%lld steps, %lld errors\n", nStep, nError);
25795  }
25796
25797  return rc;
25798}
25799
25800/*
25801 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
25802 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
25803 *   close db and set it to 0, and return the columns spec, to later
25804 *   be sqlite3_free()'ed by the caller.
25805 * The return is 0 when either:
25806 *   (a) The db was not initialized and zCol==0 (There are no columns.)
25807 *   (b) zCol!=0  (Column was added, db initialized as needed.)
25808 * The 3rd argument, pRenamed, references an out parameter. If the
25809 * pointer is non-zero, its referent will be set to a summary of renames
25810 * done if renaming was necessary, or set to 0 if none was done. The out
25811 * string (if any) must be sqlite3_free()'ed by the caller.
25812 */
25813#ifdef SHELL_DEBUG
25814#define rc_err_oom_die(rc) \
25815  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
25816  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
25817    eputf("E:%d\n",rc), assert(0)
25818#else
25819static void rc_err_oom_die(int rc){
25820  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
25821  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
25822}
25823#endif
25824
25825#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
25826static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
25827#else  /* Otherwise, memory is faster/better for the transient DB. */
25828static const char *zCOL_DB = ":memory:";
25829#endif
25830
25831/* Define character (as C string) to separate generated column ordinal
25832 * from protected part of incoming column names. This defaults to "_"
25833 * so that incoming column identifiers that did not need not be quoted
25834 * remain usable without being quoted. It must be one character.
25835 */
25836#ifndef SHELL_AUTOCOLUMN_SEP
25837# define AUTOCOLUMN_SEP "_"
25838#else
25839# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
25840#endif
25841
25842static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
25843  /* Queries and D{D,M}L used here */
25844  static const char * const zTabMake = "\
25845CREATE TABLE ColNames(\
25846 cpos INTEGER PRIMARY KEY,\
25847 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
25848CREATE VIEW RepeatedNames AS \
25849SELECT DISTINCT t.name FROM ColNames t \
25850WHERE t.name COLLATE NOCASE IN (\
25851 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
25852);\
25853";
25854  static const char * const zTabFill = "\
25855INSERT INTO ColNames(name,nlen,chop,reps,suff)\
25856 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
25857";
25858  static const char * const zHasDupes = "\
25859SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
25860 <count(name) FROM ColNames\
25861";
25862#ifdef SHELL_COLUMN_RENAME_CLEAN
25863  static const char * const zDedoctor = "\
25864UPDATE ColNames SET chop=iif(\
25865  (substring(name,nlen,1) BETWEEN '0' AND '9')\
25866  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
25867 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
25868 0\
25869)\
25870";
25871#endif
25872  static const char * const zSetReps = "\
25873UPDATE ColNames AS t SET reps=\
25874(SELECT count(*) FROM ColNames d \
25875 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
25876 COLLATE NOCASE\
25877)\
25878";
25879#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
25880  static const char * const zColDigits = "\
25881SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
25882";
25883#else
25884  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
25885  static const char * const zColDigits = "\
25886SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
25887 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
25888 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
25889";
25890#endif
25891  static const char * const zRenameRank =
25892#ifdef SHELL_COLUMN_RENAME_CLEAN
25893    "UPDATE ColNames AS t SET suff="
25894    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
25895#else /* ...RENAME_MINIMAL_ONE_PASS */
25896"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
25897"  SELECT 0 AS nlz"
25898"  UNION"
25899"  SELECT nlz+1 AS nlz FROM Lzn"
25900"  WHERE EXISTS("
25901"   SELECT 1"
25902"   FROM ColNames t, ColNames o"
25903"   WHERE"
25904"    iif(t.name IN (SELECT * FROM RepeatedNames),"
25905"     printf('%s"AUTOCOLUMN_SEP"%s',"
25906"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
25907"     t.name"
25908"    )"
25909"    ="
25910"    iif(o.name IN (SELECT * FROM RepeatedNames),"
25911"     printf('%s"AUTOCOLUMN_SEP"%s',"
25912"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
25913"     o.name"
25914"    )"
25915"    COLLATE NOCASE"
25916"    AND o.cpos<>t.cpos"
25917"   GROUP BY t.cpos"
25918"  )"
25919") UPDATE Colnames AS t SET"
25920" chop = 0," /* No chopping, never touch incoming names. */
25921" suff = iif(name IN (SELECT * FROM RepeatedNames),"
25922"  printf('"AUTOCOLUMN_SEP"%s', substring("
25923"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
25924"  ''"
25925" )"
25926#endif
25927    ;
25928  static const char * const zCollectVar = "\
25929SELECT\
25930 '('||x'0a'\
25931 || group_concat(\
25932  cname||' TEXT',\
25933  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
25934 ||')' AS ColsSpec \
25935FROM (\
25936 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
25937 FROM ColNames ORDER BY cpos\
25938)";
25939  static const char * const zRenamesDone =
25940    "SELECT group_concat("
25941    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
25942    " ','||x'0a')"
25943    "FROM ColNames WHERE suff<>'' OR chop!=0"
25944    ;
25945  int rc;
25946  sqlite3_stmt *pStmt = 0;
25947  assert(pDb!=0);
25948  if( zColNew ){
25949    /* Add initial or additional column. Init db if necessary. */
25950    if( *pDb==0 ){
25951      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
25952#ifdef SHELL_COLFIX_DB
25953      if(*zCOL_DB!=':')
25954        sqlite3_exec(*pDb,"drop table if exists ColNames;"
25955                     "drop view if exists RepeatedNames;",0,0,0);
25956#endif
25957#undef SHELL_COLFIX_DB
25958      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
25959      rc_err_oom_die(rc);
25960    }
25961    assert(*pDb!=0);
25962    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
25963    rc_err_oom_die(rc);
25964    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
25965    rc_err_oom_die(rc);
25966    rc = sqlite3_step(pStmt);
25967    rc_err_oom_die(rc);
25968    sqlite3_finalize(pStmt);
25969    return 0;
25970  }else if( *pDb==0 ){
25971    return 0;
25972  }else{
25973    /* Formulate the columns spec, close the DB, zero *pDb. */
25974    char *zColsSpec = 0;
25975    int hasDupes = db_int(*pDb, zHasDupes);
25976    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
25977    if( hasDupes ){
25978#ifdef SHELL_COLUMN_RENAME_CLEAN
25979      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
25980      rc_err_oom_die(rc);
25981#endif
25982      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
25983      rc_err_oom_die(rc);
25984      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
25985      rc_err_oom_die(rc);
25986      sqlite3_bind_int(pStmt, 1, nDigits);
25987      rc = sqlite3_step(pStmt);
25988      sqlite3_finalize(pStmt);
25989      if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM);
25990    }
25991    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
25992    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
25993    rc_err_oom_die(rc);
25994    rc = sqlite3_step(pStmt);
25995    if( rc==SQLITE_ROW ){
25996      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
25997    }else{
25998      zColsSpec = 0;
25999    }
26000    if( pzRenamed!=0 ){
26001      if( !hasDupes ) *pzRenamed = 0;
26002      else{
26003        sqlite3_finalize(pStmt);
26004        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
26005            && SQLITE_ROW==sqlite3_step(pStmt) ){
26006          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
26007        }else
26008          *pzRenamed = 0;
26009      }
26010    }
26011    sqlite3_finalize(pStmt);
26012    sqlite3_close(*pDb);
26013    *pDb = 0;
26014    return zColsSpec;
26015  }
26016}
26017
26018/*
26019** Check if the sqlite_schema table contains one or more virtual tables. If
26020** parameter zLike is not NULL, then it is an SQL expression that the
26021** sqlite_schema row must also match. If one or more such rows are found,
26022** print the following warning to the output:
26023**
26024** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
26025*/
26026static int outputDumpWarning(ShellState *p, const char *zLike){
26027  int rc = SQLITE_OK;
26028  sqlite3_stmt *pStmt = 0;
26029  shellPreparePrintf(p->db, &rc, &pStmt,
26030    "SELECT 1 FROM sqlite_schema o WHERE "
26031    "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
26032  );
26033  if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
26034    oputz("/* WARNING: "
26035          "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
26036    );
26037  }
26038  shellFinalize(&rc, pStmt);
26039  return rc;
26040}
26041
26042/*
26043** Fault-Simulator state and logic.
26044*/
26045static struct {
26046  int iId;           /* ID that triggers a simulated fault.  -1 means "any" */
26047  int iErr;          /* The error code to return on a fault */
26048  int iCnt;          /* Trigger the fault only if iCnt is already zero */
26049  int iInterval;     /* Reset iCnt to this value after each fault */
26050  int eVerbose;      /* When to print output */
26051  int nHit;          /* Number of hits seen so far */
26052  int nRepeat;       /* Turn off after this many hits.  0 for never */
26053  int nSkip;         /* Skip this many before first fault */
26054} faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0};
26055
26056/*
26057** This is the fault-sim callback
26058*/
26059static int faultsim_callback(int iArg){
26060  if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){
26061    return SQLITE_OK;
26062  }
26063  if( faultsim_state.iCnt ){
26064    if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--;
26065    if( faultsim_state.eVerbose>=2 ){
26066      oputf("FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt);
26067    }
26068    return SQLITE_OK;
26069  }
26070  if( faultsim_state.eVerbose>=1 ){
26071    oputf("FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr);
26072  }
26073  faultsim_state.iCnt = faultsim_state.iInterval;
26074  faultsim_state.nHit++;
26075  if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){
26076    faultsim_state.iCnt = -1;
26077  }
26078  return faultsim_state.iErr;
26079}
26080
26081/*
26082** If an input line begins with "." then invoke this routine to
26083** process that line.
26084**
26085** Return 1 on error, 2 to exit, and 0 otherwise.
26086*/
26087static int do_meta_command(char *zLine, ShellState *p){
26088  int h = 1;
26089  int nArg = 0;
26090  int n, c;
26091  int rc = 0;
26092  char *azArg[52];
26093
26094#ifndef SQLITE_OMIT_VIRTUALTABLE
26095  if( p->expert.pExpert ){
26096    expertFinish(p, 1, 0);
26097  }
26098#endif
26099
26100  /* Parse the input line into tokens.
26101  */
26102  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
26103    while( IsSpace(zLine[h]) ){ h++; }
26104    if( zLine[h]==0 ) break;
26105    if( zLine[h]=='\'' || zLine[h]=='"' ){
26106      int delim = zLine[h++];
26107      azArg[nArg++] = &zLine[h];
26108      while( zLine[h] && zLine[h]!=delim ){
26109        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
26110        h++;
26111      }
26112      if( zLine[h]==delim ){
26113        zLine[h++] = 0;
26114      }
26115      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
26116    }else{
26117      azArg[nArg++] = &zLine[h];
26118      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
26119      if( zLine[h] ) zLine[h++] = 0;
26120    }
26121  }
26122  azArg[nArg] = 0;
26123
26124  /* Process the input line.
26125  */
26126  if( nArg==0 ) return 0; /* no tokens, no error */
26127  n = strlen30(azArg[0]);
26128  c = azArg[0][0];
26129  clearTempFile(p);
26130
26131#ifndef SQLITE_OMIT_AUTHORIZATION
26132  if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
26133    if( nArg!=2 ){
26134      eputz("Usage: .auth ON|OFF\n");
26135      rc = 1;
26136      goto meta_command_exit;
26137    }
26138    open_db(p, 0);
26139    if( booleanValue(azArg[1]) ){
26140      sqlite3_set_authorizer(p->db, shellAuth, p);
26141    }else if( p->bSafeModePersist ){
26142      sqlite3_set_authorizer(p->db, safeModeAuth, p);
26143    }else{
26144      sqlite3_set_authorizer(p->db, 0, 0);
26145    }
26146  }else
26147#endif
26148
26149#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
26150  && !defined(SQLITE_SHELL_FIDDLE)
26151  if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
26152    open_db(p, 0);
26153    failIfSafeMode(p, "cannot run .archive in safe mode");
26154    rc = arDotCommand(p, 0, azArg, nArg);
26155  }else
26156#endif
26157
26158#ifndef SQLITE_SHELL_FIDDLE
26159  if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
26160   || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
26161  ){
26162    const char *zDestFile = 0;
26163    const char *zDb = 0;
26164    sqlite3 *pDest;
26165    sqlite3_backup *pBackup;
26166    int j;
26167    int bAsync = 0;
26168    const char *zVfs = 0;
26169    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
26170    for(j=1; j<nArg; j++){
26171      const char *z = azArg[j];
26172      if( z[0]=='-' ){
26173        if( z[1]=='-' ) z++;
26174        if( cli_strcmp(z, "-append")==0 ){
26175          zVfs = "apndvfs";
26176        }else
26177        if( cli_strcmp(z, "-async")==0 ){
26178          bAsync = 1;
26179        }else
26180        {
26181          eputf("unknown option: %s\n", azArg[j]);
26182          return 1;
26183        }
26184      }else if( zDestFile==0 ){
26185        zDestFile = azArg[j];
26186      }else if( zDb==0 ){
26187        zDb = zDestFile;
26188        zDestFile = azArg[j];
26189      }else{
26190        eputz("Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
26191        return 1;
26192      }
26193    }
26194    if( zDestFile==0 ){
26195      eputz("missing FILENAME argument on .backup\n");
26196      return 1;
26197    }
26198    if( zDb==0 ) zDb = "main";
26199    rc = sqlite3_open_v2(zDestFile, &pDest,
26200                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
26201    if( rc!=SQLITE_OK ){
26202      eputf("Error: cannot open \"%s\"\n", zDestFile);
26203      close_db(pDest);
26204      return 1;
26205    }
26206    if( bAsync ){
26207      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
26208                   0, 0, 0);
26209    }
26210    open_db(p, 0);
26211    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
26212    if( pBackup==0 ){
26213      eputf("Error: %s\n", sqlite3_errmsg(pDest));
26214      close_db(pDest);
26215      return 1;
26216    }
26217    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
26218    sqlite3_backup_finish(pBackup);
26219    if( rc==SQLITE_DONE ){
26220      rc = 0;
26221    }else{
26222      eputf("Error: %s\n", sqlite3_errmsg(pDest));
26223      rc = 1;
26224    }
26225    close_db(pDest);
26226  }else
26227#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26228
26229  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
26230    if( nArg==2 ){
26231      bail_on_error = booleanValue(azArg[1]);
26232    }else{
26233      eputz("Usage: .bail on|off\n");
26234      rc = 1;
26235    }
26236  }else
26237
26238  /* Undocumented.  Legacy only.  See "crnl" below */
26239  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
26240    if( nArg==2 ){
26241      if( booleanValue(azArg[1]) ){
26242        setBinaryMode(p->out, 1);
26243      }else{
26244        setTextMode(p->out, 1);
26245      }
26246    }else{
26247      eputz("The \".binary\" command is deprecated. Use \".crnl\" instead.\n"
26248            "Usage: .binary on|off\n");
26249      rc = 1;
26250    }
26251  }else
26252
26253  /* The undocumented ".breakpoint" command causes a call to the no-op
26254  ** routine named test_breakpoint().
26255  */
26256  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
26257    test_breakpoint();
26258  }else
26259
26260#ifndef SQLITE_SHELL_FIDDLE
26261  if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
26262    failIfSafeMode(p, "cannot run .cd in safe mode");
26263    if( nArg==2 ){
26264#if defined(_WIN32) || defined(WIN32)
26265      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
26266      rc = !SetCurrentDirectoryW(z);
26267      sqlite3_free(z);
26268#else
26269      rc = chdir(azArg[1]);
26270#endif
26271      if( rc ){
26272        eputf("Cannot change to directory \"%s\"\n", azArg[1]);
26273        rc = 1;
26274      }
26275    }else{
26276      eputz("Usage: .cd DIRECTORY\n");
26277      rc = 1;
26278    }
26279  }else
26280#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26281
26282  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
26283    if( nArg==2 ){
26284      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
26285    }else{
26286      eputz("Usage: .changes on|off\n");
26287      rc = 1;
26288    }
26289  }else
26290
26291#ifndef SQLITE_SHELL_FIDDLE
26292  /* Cancel output redirection, if it is currently set (by .testcase)
26293  ** Then read the content of the testcase-out.txt file and compare against
26294  ** azArg[1].  If there are differences, report an error and exit.
26295  */
26296  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
26297    char *zRes = 0;
26298    output_reset(p);
26299    if( nArg!=2 ){
26300      eputz("Usage: .check GLOB-PATTERN\n");
26301      rc = 2;
26302    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
26303      rc = 2;
26304    }else if( testcase_glob(azArg[1],zRes)==0 ){
26305      eputf("testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
26306            p->zTestcase, azArg[1], zRes);
26307      rc = 1;
26308    }else{
26309      oputf("testcase-%s ok\n", p->zTestcase);
26310      p->nCheck++;
26311    }
26312    sqlite3_free(zRes);
26313  }else
26314#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26315
26316#ifndef SQLITE_SHELL_FIDDLE
26317  if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
26318    failIfSafeMode(p, "cannot run .clone in safe mode");
26319    if( nArg==2 ){
26320      tryToClone(p, azArg[1]);
26321    }else{
26322      eputz("Usage: .clone FILENAME\n");
26323      rc = 1;
26324    }
26325  }else
26326#endif /* !defined(SQLITE_SHELL_FIDDLE) */
26327
26328  if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
26329    if( nArg==1 ){
26330      /* List available connections */
26331      int i;
26332      for(i=0; i<ArraySize(p->aAuxDb); i++){
26333        const char *zFile = p->aAuxDb[i].zDbFilename;
26334        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
26335          zFile = "(not open)";
26336        }else if( zFile==0 ){
26337          zFile = "(memory)";
26338        }else if( zFile[0]==0 ){
26339          zFile = "(temporary-file)";
26340        }
26341        if( p->pAuxDb == &p->aAuxDb[i] ){
26342          sputf(stdout, "ACTIVE %d: %s\n", i, zFile);
26343        }else if( p->aAuxDb[i].db!=0 ){
26344          sputf(stdout, "       %d: %s\n", i, zFile);
26345        }
26346      }
26347    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
26348      int i = azArg[1][0] - '0';
26349      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
26350        p->pAuxDb->db = p->db;
26351        p->pAuxDb = &p->aAuxDb[i];
26352        globalDb = p->db = p->pAuxDb->db;
26353        p->pAuxDb->db = 0;
26354      }
26355    }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
26356           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
26357      int i = azArg[2][0] - '0';
26358      if( i<0 || i>=ArraySize(p->aAuxDb) ){
26359        /* No-op */
26360      }else if( p->pAuxDb == &p->aAuxDb[i] ){
26361        eputz("cannot close the active database connection\n");
26362        rc = 1;
26363      }else if( p->aAuxDb[i].db ){
26364        session_close_all(p, i);
26365        close_db(p->aAuxDb[i].db);
26366        p->aAuxDb[i].db = 0;
26367      }
26368    }else{
26369      eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n");
26370      rc = 1;
26371    }
26372  }else
26373
26374  if( c=='c' && n==4 && cli_strncmp(azArg[0], "crnl", n)==0 ){
26375    if( nArg==2 ){
26376      if( booleanValue(azArg[1]) ){
26377        setTextMode(p->out, 1);
26378      }else{
26379        setBinaryMode(p->out, 1);
26380      }
26381    }else{
26382#if !defined(_WIN32) && !defined(WIN32)
26383      eputz("The \".crnl\" is a no-op on non-Windows machines.\n");
26384#endif
26385      eputz("Usage: .crnl on|off\n");
26386      rc = 1;
26387    }
26388  }else
26389
26390  if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
26391    char **azName = 0;
26392    int nName = 0;
26393    sqlite3_stmt *pStmt;
26394    int i;
26395    open_db(p, 0);
26396    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
26397    if( rc ){
26398      eputf("Error: %s\n", sqlite3_errmsg(p->db));
26399      rc = 1;
26400    }else{
26401      while( sqlite3_step(pStmt)==SQLITE_ROW ){
26402        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
26403        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
26404        if( zSchema==0 || zFile==0 ) continue;
26405        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
26406        shell_check_oom(azName);
26407        azName[nName*2] = strdup(zSchema);
26408        azName[nName*2+1] = strdup(zFile);
26409        nName++;
26410      }
26411    }
26412    sqlite3_finalize(pStmt);
26413    for(i=0; i<nName; i++){
26414      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
26415      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
26416      const char *z = azName[i*2+1];
26417      oputf("%s: %s %s%s\n",
26418            azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w",
26419            eTxn==SQLITE_TXN_NONE ? "" :
26420            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
26421      free(azName[i*2]);
26422      free(azName[i*2+1]);
26423    }
26424    sqlite3_free(azName);
26425  }else
26426
26427  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
26428    static const struct DbConfigChoices {
26429      const char *zName;
26430      int op;
26431    } aDbConfig[] = {
26432        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
26433        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
26434        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
26435        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
26436        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
26437        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
26438        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
26439        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
26440        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
26441        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
26442        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
26443        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
26444        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
26445        { "reverse_scanorder",  SQLITE_DBCONFIG_REVERSE_SCANORDER     },
26446        { "stmt_scanstatus",    SQLITE_DBCONFIG_STMT_SCANSTATUS       },
26447        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
26448        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
26449        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
26450    };
26451    int ii, v;
26452    open_db(p, 0);
26453    for(ii=0; ii<ArraySize(aDbConfig); ii++){
26454      if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
26455      if( nArg>=3 ){
26456        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
26457      }
26458      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
26459      oputf("%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
26460      if( nArg>1 ) break;
26461    }
26462    if( nArg>1 && ii==ArraySize(aDbConfig) ){
26463      eputf("Error: unknown dbconfig \"%s\"\n", azArg[1]);
26464      eputz("Enter \".dbconfig\" with no arguments for a list\n");
26465    }
26466  }else
26467
26468#if SQLITE_SHELL_HAVE_RECOVER
26469  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
26470    rc = shell_dbinfo_command(p, nArg, azArg);
26471  }else
26472
26473  if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
26474    open_db(p, 0);
26475    rc = recoverDatabaseCmd(p, nArg, azArg);
26476  }else
26477#endif /* SQLITE_SHELL_HAVE_RECOVER */
26478
26479  if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
26480    char *zLike = 0;
26481    char *zSql;
26482    int i;
26483    int savedShowHeader = p->showHeader;
26484    int savedShellFlags = p->shellFlgs;
26485    ShellClearFlag(p,
26486       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
26487       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
26488    for(i=1; i<nArg; i++){
26489      if( azArg[i][0]=='-' ){
26490        const char *z = azArg[i]+1;
26491        if( z[0]=='-' ) z++;
26492        if( cli_strcmp(z,"preserve-rowids")==0 ){
26493#ifdef SQLITE_OMIT_VIRTUALTABLE
26494          eputz("The --preserve-rowids option is not compatible"
26495                " with SQLITE_OMIT_VIRTUALTABLE\n");
26496          rc = 1;
26497          sqlite3_free(zLike);
26498          goto meta_command_exit;
26499#else
26500          ShellSetFlag(p, SHFLG_PreserveRowid);
26501#endif
26502        }else
26503        if( cli_strcmp(z,"newlines")==0 ){
26504          ShellSetFlag(p, SHFLG_Newlines);
26505        }else
26506        if( cli_strcmp(z,"data-only")==0 ){
26507          ShellSetFlag(p, SHFLG_DumpDataOnly);
26508        }else
26509        if( cli_strcmp(z,"nosys")==0 ){
26510          ShellSetFlag(p, SHFLG_DumpNoSys);
26511        }else
26512        {
26513          eputf("Unknown option \"%s\" on \".dump\"\n", azArg[i]);
26514          rc = 1;
26515          sqlite3_free(zLike);
26516          goto meta_command_exit;
26517        }
26518      }else{
26519        /* azArg[i] contains a LIKE pattern. This ".dump" request should
26520        ** only dump data for tables for which either the table name matches
26521        ** the LIKE pattern, or the table appears to be a shadow table of
26522        ** a virtual table for which the name matches the LIKE pattern.
26523        */
26524        char *zExpr = sqlite3_mprintf(
26525            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
26526            "  SELECT 1 FROM sqlite_schema WHERE "
26527            "    name LIKE %Q ESCAPE '\\' AND"
26528            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
26529            "    substr(o.name, 1, length(name)+1) == (name||'_')"
26530            ")", azArg[i], azArg[i]
26531        );
26532
26533        if( zLike ){
26534          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
26535        }else{
26536          zLike = zExpr;
26537        }
26538      }
26539    }
26540
26541    open_db(p, 0);
26542
26543    outputDumpWarning(p, zLike);
26544    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26545      /* When playing back a "dump", the content might appear in an order
26546      ** which causes immediate foreign key constraints to be violated.
26547      ** So disable foreign-key constraint enforcement to prevent problems. */
26548      oputz("PRAGMA foreign_keys=OFF;\n");
26549      oputz("BEGIN TRANSACTION;\n");
26550    }
26551    p->writableSchema = 0;
26552    p->showHeader = 0;
26553    /* Set writable_schema=ON since doing so forces SQLite to initialize
26554    ** as much of the schema as it can even if the sqlite_schema table is
26555    ** corrupt. */
26556    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
26557    p->nErr = 0;
26558    if( zLike==0 ) zLike = sqlite3_mprintf("true");
26559    zSql = sqlite3_mprintf(
26560      "SELECT name, type, sql FROM sqlite_schema AS o "
26561      "WHERE (%s) AND type=='table'"
26562      "  AND sql NOT NULL"
26563      " ORDER BY tbl_name='sqlite_sequence', rowid",
26564      zLike
26565    );
26566    run_schema_dump_query(p,zSql);
26567    sqlite3_free(zSql);
26568    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26569      zSql = sqlite3_mprintf(
26570        "SELECT sql FROM sqlite_schema AS o "
26571        "WHERE (%s) AND sql NOT NULL"
26572        "  AND type IN ('index','trigger','view') "
26573        "ORDER BY type COLLATE NOCASE DESC",
26574        zLike
26575      );
26576      run_table_dump_query(p, zSql);
26577      sqlite3_free(zSql);
26578    }
26579    sqlite3_free(zLike);
26580    if( p->writableSchema ){
26581      oputz("PRAGMA writable_schema=OFF;\n");
26582      p->writableSchema = 0;
26583    }
26584    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
26585    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
26586    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
26587      oputz(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
26588    }
26589    p->showHeader = savedShowHeader;
26590    p->shellFlgs = savedShellFlags;
26591  }else
26592
26593  if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
26594    if( nArg==2 ){
26595      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
26596    }else{
26597      eputz("Usage: .echo on|off\n");
26598      rc = 1;
26599    }
26600  }else
26601
26602  if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
26603    if( nArg==2 ){
26604      p->autoEQPtest = 0;
26605      if( p->autoEQPtrace ){
26606        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
26607        p->autoEQPtrace = 0;
26608      }
26609      if( cli_strcmp(azArg[1],"full")==0 ){
26610        p->autoEQP = AUTOEQP_full;
26611      }else if( cli_strcmp(azArg[1],"trigger")==0 ){
26612        p->autoEQP = AUTOEQP_trigger;
26613#ifdef SQLITE_DEBUG
26614      }else if( cli_strcmp(azArg[1],"test")==0 ){
26615        p->autoEQP = AUTOEQP_on;
26616        p->autoEQPtest = 1;
26617      }else if( cli_strcmp(azArg[1],"trace")==0 ){
26618        p->autoEQP = AUTOEQP_full;
26619        p->autoEQPtrace = 1;
26620        open_db(p, 0);
26621        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
26622        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
26623#endif
26624      }else{
26625        p->autoEQP = (u8)booleanValue(azArg[1]);
26626      }
26627    }else{
26628      eputz("Usage: .eqp off|on|trace|trigger|full\n");
26629      rc = 1;
26630    }
26631  }else
26632
26633#ifndef SQLITE_SHELL_FIDDLE
26634  if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
26635    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
26636    rc = 2;
26637  }else
26638#endif
26639
26640  /* The ".explain" command is automatic now.  It is largely pointless.  It
26641  ** retained purely for backwards compatibility */
26642  if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
26643    int val = 1;
26644    if( nArg>=2 ){
26645      if( cli_strcmp(azArg[1],"auto")==0 ){
26646        val = 99;
26647      }else{
26648        val =  booleanValue(azArg[1]);
26649      }
26650    }
26651    if( val==1 && p->mode!=MODE_Explain ){
26652      p->normalMode = p->mode;
26653      p->mode = MODE_Explain;
26654      p->autoExplain = 0;
26655    }else if( val==0 ){
26656      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
26657      p->autoExplain = 0;
26658    }else if( val==99 ){
26659      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
26660      p->autoExplain = 1;
26661    }
26662  }else
26663
26664#ifndef SQLITE_OMIT_VIRTUALTABLE
26665  if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
26666    if( p->bSafeMode ){
26667      eputf("Cannot run experimental commands such as \"%s\" in safe mode\n",
26668            azArg[0]);
26669      rc = 1;
26670    }else{
26671      open_db(p, 0);
26672      expertDotCommand(p, azArg, nArg);
26673    }
26674  }else
26675#endif
26676
26677  if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
26678    static const struct {
26679       const char *zCtrlName;   /* Name of a test-control option */
26680       int ctrlCode;            /* Integer code for that option */
26681       const char *zUsage;      /* Usage notes */
26682    } aCtrl[] = {
26683      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
26684      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
26685      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
26686      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
26687      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
26688   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
26689      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
26690      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
26691      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
26692      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
26693   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
26694    };
26695    int filectrl = -1;
26696    int iCtrl = -1;
26697    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
26698    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
26699    int n2, i;
26700    const char *zCmd = 0;
26701    const char *zSchema = 0;
26702
26703    open_db(p, 0);
26704    zCmd = nArg>=2 ? azArg[1] : "help";
26705
26706    if( zCmd[0]=='-'
26707     && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
26708     && nArg>=4
26709    ){
26710      zSchema = azArg[2];
26711      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
26712      nArg -= 2;
26713      zCmd = azArg[1];
26714    }
26715
26716    /* The argument can optionally begin with "-" or "--" */
26717    if( zCmd[0]=='-' && zCmd[1] ){
26718      zCmd++;
26719      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
26720    }
26721
26722    /* --help lists all file-controls */
26723    if( cli_strcmp(zCmd,"help")==0 ){
26724      oputz("Available file-controls:\n");
26725      for(i=0; i<ArraySize(aCtrl); i++){
26726        oputf("  .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage);
26727      }
26728      rc = 1;
26729      goto meta_command_exit;
26730    }
26731
26732    /* convert filectrl text option to value. allow any unique prefix
26733    ** of the option name, or a numerical value. */
26734    n2 = strlen30(zCmd);
26735    for(i=0; i<ArraySize(aCtrl); i++){
26736      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
26737        if( filectrl<0 ){
26738          filectrl = aCtrl[i].ctrlCode;
26739          iCtrl = i;
26740        }else{
26741          eputf("Error: ambiguous file-control: \"%s\"\n"
26742                "Use \".filectrl --help\" for help\n", zCmd);
26743          rc = 1;
26744          goto meta_command_exit;
26745        }
26746      }
26747    }
26748    if( filectrl<0 ){
26749      eputf("Error: unknown file-control: %s\n"
26750            "Use \".filectrl --help\" for help\n", zCmd);
26751    }else{
26752      switch(filectrl){
26753        case SQLITE_FCNTL_SIZE_LIMIT: {
26754          if( nArg!=2 && nArg!=3 ) break;
26755          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
26756          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
26757          isOk = 1;
26758          break;
26759        }
26760        case SQLITE_FCNTL_LOCK_TIMEOUT:
26761        case SQLITE_FCNTL_CHUNK_SIZE: {
26762          int x;
26763          if( nArg!=3 ) break;
26764          x = (int)integerValue(azArg[2]);
26765          sqlite3_file_control(p->db, zSchema, filectrl, &x);
26766          isOk = 2;
26767          break;
26768        }
26769        case SQLITE_FCNTL_PERSIST_WAL:
26770        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26771          int x;
26772          if( nArg!=2 && nArg!=3 ) break;
26773          x = nArg==3 ? booleanValue(azArg[2]) : -1;
26774          sqlite3_file_control(p->db, zSchema, filectrl, &x);
26775          iRes = x;
26776          isOk = 1;
26777          break;
26778        }
26779        case SQLITE_FCNTL_DATA_VERSION:
26780        case SQLITE_FCNTL_HAS_MOVED: {
26781          int x;
26782          if( nArg!=2 ) break;
26783          sqlite3_file_control(p->db, zSchema, filectrl, &x);
26784          iRes = x;
26785          isOk = 1;
26786          break;
26787        }
26788        case SQLITE_FCNTL_TEMPFILENAME: {
26789          char *z = 0;
26790          if( nArg!=2 ) break;
26791          sqlite3_file_control(p->db, zSchema, filectrl, &z);
26792          if( z ){
26793            oputf("%s\n", z);
26794            sqlite3_free(z);
26795          }
26796          isOk = 2;
26797          break;
26798        }
26799        case SQLITE_FCNTL_RESERVE_BYTES: {
26800          int x;
26801          if( nArg>=3 ){
26802            x = atoi(azArg[2]);
26803            sqlite3_file_control(p->db, zSchema, filectrl, &x);
26804          }
26805          x = -1;
26806          sqlite3_file_control(p->db, zSchema, filectrl, &x);
26807          oputf("%d\n", x);
26808          isOk = 2;
26809          break;
26810        }
26811      }
26812    }
26813    if( isOk==0 && iCtrl>=0 ){
26814      oputf("Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
26815      rc = 1;
26816    }else if( isOk==1 ){
26817      char zBuf[100];
26818      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
26819      oputf("%s\n", zBuf);
26820    }
26821  }else
26822
26823  if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
26824    ShellState data;
26825    int doStats = 0;
26826    memcpy(&data, p, sizeof(data));
26827    data.showHeader = 0;
26828    data.cMode = data.mode = MODE_Semi;
26829    if( nArg==2 && optionMatch(azArg[1], "indent") ){
26830      data.cMode = data.mode = MODE_Pretty;
26831      nArg = 1;
26832    }
26833    if( nArg!=1 ){
26834      eputz("Usage: .fullschema ?--indent?\n");
26835      rc = 1;
26836      goto meta_command_exit;
26837    }
26838    open_db(p, 0);
26839    rc = sqlite3_exec(p->db,
26840       "SELECT sql FROM"
26841       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
26842       "     FROM sqlite_schema UNION ALL"
26843       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
26844       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
26845       "ORDER BY x",
26846       callback, &data, 0
26847    );
26848    if( rc==SQLITE_OK ){
26849      sqlite3_stmt *pStmt;
26850      rc = sqlite3_prepare_v2(p->db,
26851               "SELECT rowid FROM sqlite_schema"
26852               " WHERE name GLOB 'sqlite_stat[134]'",
26853               -1, &pStmt, 0);
26854      if( rc==SQLITE_OK ){
26855        doStats = sqlite3_step(pStmt)==SQLITE_ROW;
26856        sqlite3_finalize(pStmt);
26857      }
26858    }
26859    if( doStats==0 ){
26860      oputz("/* No STAT tables available */\n");
26861    }else{
26862      oputz("ANALYZE sqlite_schema;\n");
26863      data.cMode = data.mode = MODE_Insert;
26864      data.zDestTable = "sqlite_stat1";
26865      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
26866      data.zDestTable = "sqlite_stat4";
26867      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
26868      oputz("ANALYZE sqlite_schema;\n");
26869    }
26870  }else
26871
26872  if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
26873    if( nArg==2 ){
26874      p->showHeader = booleanValue(azArg[1]);
26875      p->shellFlgs |= SHFLG_HeaderSet;
26876    }else{
26877      eputz("Usage: .headers on|off\n");
26878      rc = 1;
26879    }
26880  }else
26881
26882  if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
26883    if( nArg>=2 ){
26884      n = showHelp(p->out, azArg[1]);
26885      if( n==0 ){
26886        oputf("Nothing matches '%s'\n", azArg[1]);
26887      }
26888    }else{
26889      showHelp(p->out, 0);
26890    }
26891  }else
26892
26893#ifndef SQLITE_SHELL_FIDDLE
26894  if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
26895    char *zTable = 0;           /* Insert data into this table */
26896    char *zSchema = 0;          /* Schema of zTable */
26897    char *zFile = 0;            /* Name of file to extra content from */
26898    sqlite3_stmt *pStmt = NULL; /* A statement */
26899    int nCol;                   /* Number of columns in the table */
26900    i64 nByte;                  /* Number of bytes in an SQL string */
26901    int i, j;                   /* Loop counters */
26902    int needCommit;             /* True to COMMIT or ROLLBACK at end */
26903    int nSep;                   /* Number of bytes in p->colSeparator[] */
26904    char *zSql = 0;             /* An SQL statement */
26905    ImportCtx sCtx;             /* Reader context */
26906    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
26907    int eVerbose = 0;           /* Larger for more console output */
26908    int nSkip = 0;              /* Initial lines to skip */
26909    int useOutputMode = 1;      /* Use output mode to determine separators */
26910    char *zCreate = 0;          /* CREATE TABLE statement text */
26911
26912    failIfSafeMode(p, "cannot run .import in safe mode");
26913    memset(&sCtx, 0, sizeof(sCtx));
26914    if( p->mode==MODE_Ascii ){
26915      xRead = ascii_read_one_field;
26916    }else{
26917      xRead = csv_read_one_field;
26918    }
26919    rc = 1;
26920    for(i=1; i<nArg; i++){
26921      char *z = azArg[i];
26922      if( z[0]=='-' && z[1]=='-' ) z++;
26923      if( z[0]!='-' ){
26924        if( zFile==0 ){
26925          zFile = z;
26926        }else if( zTable==0 ){
26927          zTable = z;
26928        }else{
26929          oputf("ERROR: extra argument: \"%s\".  Usage:\n", z);
26930          showHelp(p->out, "import");
26931          goto meta_command_exit;
26932        }
26933      }else if( cli_strcmp(z,"-v")==0 ){
26934        eVerbose++;
26935      }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
26936        zSchema = azArg[++i];
26937      }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
26938        nSkip = integerValue(azArg[++i]);
26939      }else if( cli_strcmp(z,"-ascii")==0 ){
26940        sCtx.cColSep = SEP_Unit[0];
26941        sCtx.cRowSep = SEP_Record[0];
26942        xRead = ascii_read_one_field;
26943        useOutputMode = 0;
26944      }else if( cli_strcmp(z,"-csv")==0 ){
26945        sCtx.cColSep = ',';
26946        sCtx.cRowSep = '\n';
26947        xRead = csv_read_one_field;
26948        useOutputMode = 0;
26949      }else{
26950        oputf("ERROR: unknown option: \"%s\".  Usage:\n", z);
26951        showHelp(p->out, "import");
26952        goto meta_command_exit;
26953      }
26954    }
26955    if( zTable==0 ){
26956      oputf("ERROR: missing %s argument. Usage:\n",
26957            zFile==0 ? "FILE" : "TABLE");
26958      showHelp(p->out, "import");
26959      goto meta_command_exit;
26960    }
26961    seenInterrupt = 0;
26962    open_db(p, 0);
26963    if( useOutputMode ){
26964      /* If neither the --csv or --ascii options are specified, then set
26965      ** the column and row separator characters from the output mode. */
26966      nSep = strlen30(p->colSeparator);
26967      if( nSep==0 ){
26968        eputz("Error: non-null column separator required for import\n");
26969        goto meta_command_exit;
26970      }
26971      if( nSep>1 ){
26972        eputz("Error: multi-character column separators not allowed"
26973              " for import\n");
26974        goto meta_command_exit;
26975      }
26976      nSep = strlen30(p->rowSeparator);
26977      if( nSep==0 ){
26978        eputz("Error: non-null row separator required for import\n");
26979        goto meta_command_exit;
26980      }
26981      if( nSep==2 && p->mode==MODE_Csv
26982       && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
26983      ){
26984        /* When importing CSV (only), if the row separator is set to the
26985        ** default output row separator, change it to the default input
26986        ** row separator.  This avoids having to maintain different input
26987        ** and output row separators. */
26988        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
26989        nSep = strlen30(p->rowSeparator);
26990      }
26991      if( nSep>1 ){
26992        eputz("Error: multi-character row separators not allowed"
26993              " for import\n");
26994        goto meta_command_exit;
26995      }
26996      sCtx.cColSep = (u8)p->colSeparator[0];
26997      sCtx.cRowSep = (u8)p->rowSeparator[0];
26998    }
26999    sCtx.zFile = zFile;
27000    sCtx.nLine = 1;
27001    if( sCtx.zFile[0]=='|' ){
27002#ifdef SQLITE_OMIT_POPEN
27003      eputz("Error: pipes are not supported in this OS\n");
27004      goto meta_command_exit;
27005#else
27006      sCtx.in = popen(sCtx.zFile+1, "r");
27007      sCtx.zFile = "<pipe>";
27008      sCtx.xCloser = pclose;
27009#endif
27010    }else{
27011      sCtx.in = fopen(sCtx.zFile, "rb");
27012      sCtx.xCloser = fclose;
27013    }
27014    if( sCtx.in==0 ){
27015      eputf("Error: cannot open \"%s\"\n", zFile);
27016      goto meta_command_exit;
27017    }
27018    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
27019      char zSep[2];
27020      zSep[1] = 0;
27021      zSep[0] = sCtx.cColSep;
27022      oputz("Column separator ");
27023      output_c_string(zSep);
27024      oputz(", row separator ");
27025      zSep[0] = sCtx.cRowSep;
27026      output_c_string(zSep);
27027      oputz("\n");
27028    }
27029    sCtx.z = sqlite3_malloc64(120);
27030    if( sCtx.z==0 ){
27031      import_cleanup(&sCtx);
27032      shell_out_of_memory();
27033    }
27034    /* Below, resources must be freed before exit. */
27035    while( (nSkip--)>0 ){
27036      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
27037    }
27038    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
27039    if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) ){
27040      /* Table does not exist.  Create it. */
27041      sqlite3 *dbCols = 0;
27042      char *zRenames = 0;
27043      char *zColDefs;
27044      zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
27045                    zSchema ? zSchema : "main", zTable);
27046      while( xRead(&sCtx) ){
27047        zAutoColumn(sCtx.z, &dbCols, 0);
27048        if( sCtx.cTerm!=sCtx.cColSep ) break;
27049      }
27050      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
27051      if( zRenames!=0 ){
27052        sputf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
27053              "Columns renamed during .import %s due to duplicates:\n"
27054              "%s\n", sCtx.zFile, zRenames);
27055        sqlite3_free(zRenames);
27056      }
27057      assert(dbCols==0);
27058      if( zColDefs==0 ){
27059        eputf("%s: empty file\n", sCtx.zFile);
27060        import_cleanup(&sCtx);
27061        rc = 1;
27062        goto meta_command_exit;
27063      }
27064      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
27065      if( zCreate==0 ){
27066        import_cleanup(&sCtx);
27067        shell_out_of_memory();
27068      }
27069      if( eVerbose>=1 ){
27070        oputf("%s\n", zCreate);
27071      }
27072      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
27073      sqlite3_free(zCreate);
27074      zCreate = 0;
27075      if( rc ){
27076        eputf("%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
27077        import_cleanup(&sCtx);
27078        rc = 1;
27079        goto meta_command_exit;
27080      }
27081    }
27082    zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);",
27083                           zTable, zSchema);
27084    if( zSql==0 ){
27085      import_cleanup(&sCtx);
27086      shell_out_of_memory();
27087    }
27088    nByte = strlen(zSql);
27089    rc =  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27090    sqlite3_free(zSql);
27091    zSql = 0;
27092    if( rc ){
27093      if (pStmt) sqlite3_finalize(pStmt);
27094      eputf("Error: %s\n", sqlite3_errmsg(p->db));
27095      import_cleanup(&sCtx);
27096      rc = 1;
27097      goto meta_command_exit;
27098    }
27099    if( sqlite3_step(pStmt)==SQLITE_ROW ){
27100      nCol = sqlite3_column_int(pStmt, 0);
27101    }else{
27102      nCol = 0;
27103    }
27104    sqlite3_finalize(pStmt);
27105    pStmt = 0;
27106    if( nCol==0 ) return 0; /* no columns, no error */
27107    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
27108    if( zSql==0 ){
27109      import_cleanup(&sCtx);
27110      shell_out_of_memory();
27111    }
27112    if( zSchema ){
27113      sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
27114                       zSchema, zTable);
27115    }else{
27116      sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
27117    }
27118    j = strlen30(zSql);
27119    for(i=1; i<nCol; i++){
27120      zSql[j++] = ',';
27121      zSql[j++] = '?';
27122    }
27123    zSql[j++] = ')';
27124    zSql[j] = 0;
27125    if( eVerbose>=2 ){
27126      oputf("Insert using: %s\n", zSql);
27127    }
27128    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27129    sqlite3_free(zSql);
27130    zSql = 0;
27131    if( rc ){
27132      eputf("Error: %s\n", sqlite3_errmsg(p->db));
27133      if (pStmt) sqlite3_finalize(pStmt);
27134      import_cleanup(&sCtx);
27135      rc = 1;
27136      goto meta_command_exit;
27137    }
27138    needCommit = sqlite3_get_autocommit(p->db);
27139    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
27140    do{
27141      int startLine = sCtx.nLine;
27142      for(i=0; i<nCol; i++){
27143        char *z = xRead(&sCtx);
27144        /*
27145        ** Did we reach end-of-file before finding any columns?
27146        ** If so, stop instead of NULL filling the remaining columns.
27147        */
27148        if( z==0 && i==0 ) break;
27149        /*
27150        ** Did we reach end-of-file OR end-of-line before finding any
27151        ** columns in ASCII mode?  If so, stop instead of NULL filling
27152        ** the remaining columns.
27153        */
27154        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
27155        /*
27156        ** For CSV mode, per RFC 4180, accept EOF in lieu of final
27157        ** record terminator but only for last field of multi-field row.
27158        ** (If there are too few fields, it's not valid CSV anyway.)
27159        */
27160        if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){
27161          z = "";
27162        }
27163        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
27164        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
27165          eputf("%s:%d: expected %d columns but found %d"
27166                " - filling the rest with NULL\n",
27167                sCtx.zFile, startLine, nCol, i+1);
27168          i += 2;
27169          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
27170        }
27171      }
27172      if( sCtx.cTerm==sCtx.cColSep ){
27173        do{
27174          xRead(&sCtx);
27175          i++;
27176        }while( sCtx.cTerm==sCtx.cColSep );
27177        eputf("%s:%d: expected %d columns but found %d - extras ignored\n",
27178              sCtx.zFile, startLine, nCol, i);
27179      }
27180      if( i>=nCol ){
27181        sqlite3_step(pStmt);
27182        rc = sqlite3_reset(pStmt);
27183        if( rc!=SQLITE_OK ){
27184          eputf("%s:%d: INSERT failed: %s\n",
27185                sCtx.zFile, startLine, sqlite3_errmsg(p->db));
27186          sCtx.nErr++;
27187        }else{
27188          sCtx.nRow++;
27189        }
27190      }
27191    }while( sCtx.cTerm!=EOF );
27192
27193    import_cleanup(&sCtx);
27194    sqlite3_finalize(pStmt);
27195    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
27196    if( eVerbose>0 ){
27197      oputf("Added %d rows with %d errors using %d lines of input\n",
27198            sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
27199    }
27200  }else
27201#endif /* !defined(SQLITE_SHELL_FIDDLE) */
27202
27203#ifndef SQLITE_UNTESTABLE
27204  if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
27205    char *zSql;
27206    char *zCollist = 0;
27207    sqlite3_stmt *pStmt;
27208    int tnum = 0;
27209    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
27210    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
27211    int i;
27212    if( !ShellHasFlag(p,SHFLG_TestingMode) ){
27213      eputf(".%s unavailable without --unsafe-testing\n",
27214            "imposter");
27215      rc = 1;
27216      goto meta_command_exit;
27217    }
27218    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
27219      eputz("Usage: .imposter INDEX IMPOSTER\n"
27220            "       .imposter off\n");
27221      /* Also allowed, but not documented:
27222      **
27223      **    .imposter TABLE IMPOSTER
27224      **
27225      ** where TABLE is a WITHOUT ROWID table.  In that case, the
27226      ** imposter is another WITHOUT ROWID table with the columns in
27227      ** storage order. */
27228      rc = 1;
27229      goto meta_command_exit;
27230    }
27231    open_db(p, 0);
27232    if( nArg==2 ){
27233      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
27234      goto meta_command_exit;
27235    }
27236    zSql = sqlite3_mprintf(
27237      "SELECT rootpage, 0 FROM sqlite_schema"
27238      " WHERE name='%q' AND type='index'"
27239      "UNION ALL "
27240      "SELECT rootpage, 1 FROM sqlite_schema"
27241      " WHERE name='%q' AND type='table'"
27242      "   AND sql LIKE '%%without%%rowid%%'",
27243      azArg[1], azArg[1]
27244    );
27245    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27246    sqlite3_free(zSql);
27247    if( sqlite3_step(pStmt)==SQLITE_ROW ){
27248      tnum = sqlite3_column_int(pStmt, 0);
27249      isWO = sqlite3_column_int(pStmt, 1);
27250    }
27251    sqlite3_finalize(pStmt);
27252    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
27253    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27254    sqlite3_free(zSql);
27255    i = 0;
27256    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27257      char zLabel[20];
27258      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
27259      i++;
27260      if( zCol==0 ){
27261        if( sqlite3_column_int(pStmt,1)==-1 ){
27262          zCol = "_ROWID_";
27263        }else{
27264          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
27265          zCol = zLabel;
27266        }
27267      }
27268      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
27269        lenPK = (int)strlen(zCollist);
27270      }
27271      if( zCollist==0 ){
27272        zCollist = sqlite3_mprintf("\"%w\"", zCol);
27273      }else{
27274        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
27275      }
27276    }
27277    sqlite3_finalize(pStmt);
27278    if( i==0 || tnum==0 ){
27279      eputf("no such index: \"%s\"\n", azArg[1]);
27280      rc = 1;
27281      sqlite3_free(zCollist);
27282      goto meta_command_exit;
27283    }
27284    if( lenPK==0 ) lenPK = 100000;
27285    zSql = sqlite3_mprintf(
27286          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
27287          azArg[2], zCollist, lenPK, zCollist);
27288    sqlite3_free(zCollist);
27289    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
27290    if( rc==SQLITE_OK ){
27291      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
27292      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
27293      if( rc ){
27294        eputf("Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
27295      }else{
27296        sputf(stdout, "%s;\n", zSql);
27297        sputf(stdout, "WARNING: writing to an imposter table will corrupt"
27298              " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index");
27299      }
27300    }else{
27301      eputf("SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
27302      rc = 1;
27303    }
27304    sqlite3_free(zSql);
27305  }else
27306#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
27307
27308  if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
27309    i64 iArg = 0;
27310    if( nArg==2 ){
27311      iArg = integerValue(azArg[1]);
27312      if( iArg==0 ) iArg = -1;
27313    }
27314    if( (nArg!=1 && nArg!=2) || iArg<0 ){
27315      eputf("%s","Usage: .intck STEPS_PER_UNLOCK\n");
27316      rc = 1;
27317      goto meta_command_exit;
27318    }
27319    open_db(p, 0);
27320    rc = intckDatabaseCmd(p, iArg);
27321  }else
27322
27323#ifdef SQLITE_ENABLE_IOTRACE
27324  if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
27325    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
27326    if( iotrace && iotrace!=stdout ) fclose(iotrace);
27327    iotrace = 0;
27328    if( nArg<2 ){
27329      sqlite3IoTrace = 0;
27330    }else if( cli_strcmp(azArg[1], "-")==0 ){
27331      sqlite3IoTrace = iotracePrintf;
27332      iotrace = stdout;
27333    }else{
27334      iotrace = fopen(azArg[1], "w");
27335      if( iotrace==0 ){
27336        eputf("Error: cannot open \"%s\"\n", azArg[1]);
27337        sqlite3IoTrace = 0;
27338        rc = 1;
27339      }else{
27340        sqlite3IoTrace = iotracePrintf;
27341      }
27342    }
27343  }else
27344#endif
27345
27346  if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
27347    static const struct {
27348       const char *zLimitName;   /* Name of a limit */
27349       int limitCode;            /* Integer code for that limit */
27350    } aLimit[] = {
27351      { "length",                SQLITE_LIMIT_LENGTH                    },
27352      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
27353      { "column",                SQLITE_LIMIT_COLUMN                    },
27354      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
27355      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
27356      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
27357      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
27358      { "attached",              SQLITE_LIMIT_ATTACHED                  },
27359      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
27360      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
27361      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
27362      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
27363    };
27364    int i, n2;
27365    open_db(p, 0);
27366    if( nArg==1 ){
27367      for(i=0; i<ArraySize(aLimit); i++){
27368        sputf(stdout, "%20s %d\n", aLimit[i].zLimitName,
27369              sqlite3_limit(p->db, aLimit[i].limitCode, -1));
27370      }
27371    }else if( nArg>3 ){
27372      eputz("Usage: .limit NAME ?NEW-VALUE?\n");
27373      rc = 1;
27374      goto meta_command_exit;
27375    }else{
27376      int iLimit = -1;
27377      n2 = strlen30(azArg[1]);
27378      for(i=0; i<ArraySize(aLimit); i++){
27379        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
27380          if( iLimit<0 ){
27381            iLimit = i;
27382          }else{
27383            eputf("ambiguous limit: \"%s\"\n", azArg[1]);
27384            rc = 1;
27385            goto meta_command_exit;
27386          }
27387        }
27388      }
27389      if( iLimit<0 ){
27390        eputf("unknown limit: \"%s\"\n"
27391              "enter \".limits\" with no arguments for a list.\n",
27392              azArg[1]);
27393        rc = 1;
27394        goto meta_command_exit;
27395      }
27396      if( nArg==3 ){
27397        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
27398                      (int)integerValue(azArg[2]));
27399      }
27400      sputf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName,
27401            sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
27402    }
27403  }else
27404
27405  if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
27406    open_db(p, 0);
27407    lintDotCommand(p, azArg, nArg);
27408  }else
27409
27410#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
27411  if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
27412    const char *zFile, *zProc;
27413    char *zErrMsg = 0;
27414    failIfSafeMode(p, "cannot run .load in safe mode");
27415    if( nArg<2 || azArg[1][0]==0 ){
27416      /* Must have a non-empty FILE. (Will not load self.) */
27417      eputz("Usage: .load FILE ?ENTRYPOINT?\n");
27418      rc = 1;
27419      goto meta_command_exit;
27420    }
27421    zFile = azArg[1];
27422    zProc = nArg>=3 ? azArg[2] : 0;
27423    open_db(p, 0);
27424    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
27425    if( rc!=SQLITE_OK ){
27426      eputf("Error: %s\n", zErrMsg);
27427      sqlite3_free(zErrMsg);
27428      rc = 1;
27429    }
27430  }else
27431#endif
27432
27433  if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
27434    if( nArg!=2 ){
27435      eputz("Usage: .log FILENAME\n");
27436      rc = 1;
27437    }else{
27438      const char *zFile = azArg[1];
27439      if( p->bSafeMode
27440       && cli_strcmp(zFile,"on")!=0
27441       && cli_strcmp(zFile,"off")!=0
27442      ){
27443        sputz(stdout, "cannot set .log to anything other"
27444              " than \"on\" or \"off\"\n");
27445        zFile = "off";
27446      }
27447      output_file_close(p->pLog);
27448      if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout";
27449      p->pLog = output_file_open(zFile, 0);
27450    }
27451  }else
27452
27453  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
27454    const char *zMode = 0;
27455    const char *zTabname = 0;
27456    int i, n2;
27457    ColModeOpts cmOpts = ColModeOpts_default;
27458    for(i=1; i<nArg; i++){
27459      const char *z = azArg[i];
27460      if( optionMatch(z,"wrap") && i+1<nArg ){
27461        cmOpts.iWrap = integerValue(azArg[++i]);
27462      }else if( optionMatch(z,"ww") ){
27463        cmOpts.bWordWrap = 1;
27464      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
27465        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
27466      }else if( optionMatch(z,"quote") ){
27467        cmOpts.bQuote = 1;
27468      }else if( optionMatch(z,"noquote") ){
27469        cmOpts.bQuote = 0;
27470      }else if( zMode==0 ){
27471        zMode = z;
27472        /* Apply defaults for qbox pseudo-mode.  If that
27473         * overwrites already-set values, user was informed of this.
27474         */
27475        if( cli_strcmp(z, "qbox")==0 ){
27476          ColModeOpts cmo = ColModeOpts_default_qbox;
27477          zMode = "box";
27478          cmOpts = cmo;
27479        }
27480      }else if( zTabname==0 ){
27481        zTabname = z;
27482      }else if( z[0]=='-' ){
27483        eputf("unknown option: %s\n", z);
27484        eputz("options:\n"
27485              "  --noquote\n"
27486              "  --quote\n"
27487              "  --wordwrap on/off\n"
27488              "  --wrap N\n"
27489              "  --ww\n");
27490        rc = 1;
27491        goto meta_command_exit;
27492      }else{
27493        eputf("extra argument: \"%s\"\n", z);
27494        rc = 1;
27495        goto meta_command_exit;
27496      }
27497    }
27498    if( zMode==0 ){
27499      if( p->mode==MODE_Column
27500       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
27501      ){
27502        oputf("current output mode: %s --wrap %d --wordwrap %s --%squote\n",
27503              modeDescr[p->mode], p->cmOpts.iWrap,
27504              p->cmOpts.bWordWrap ? "on" : "off",
27505              p->cmOpts.bQuote ? "" : "no");
27506      }else{
27507        oputf("current output mode: %s\n", modeDescr[p->mode]);
27508      }
27509      zMode = modeDescr[p->mode];
27510    }
27511    n2 = strlen30(zMode);
27512    if( cli_strncmp(zMode,"lines",n2)==0 ){
27513      p->mode = MODE_Line;
27514      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27515    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
27516      p->mode = MODE_Column;
27517      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
27518        p->showHeader = 1;
27519      }
27520      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27521      p->cmOpts = cmOpts;
27522    }else if( cli_strncmp(zMode,"list",n2)==0 ){
27523      p->mode = MODE_List;
27524      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
27525      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27526    }else if( cli_strncmp(zMode,"html",n2)==0 ){
27527      p->mode = MODE_Html;
27528    }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
27529      p->mode = MODE_Tcl;
27530      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
27531      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27532    }else if( cli_strncmp(zMode,"csv",n2)==0 ){
27533      p->mode = MODE_Csv;
27534      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27535      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
27536    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
27537      p->mode = MODE_List;
27538      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
27539    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
27540      p->mode = MODE_Insert;
27541      set_table_name(p, zTabname ? zTabname : "table");
27542    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
27543      p->mode = MODE_Quote;
27544      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27545      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
27546    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
27547      p->mode = MODE_Ascii;
27548      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
27549      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
27550    }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
27551      p->mode = MODE_Markdown;
27552      p->cmOpts = cmOpts;
27553    }else if( cli_strncmp(zMode,"table",n2)==0 ){
27554      p->mode = MODE_Table;
27555      p->cmOpts = cmOpts;
27556    }else if( cli_strncmp(zMode,"box",n2)==0 ){
27557      p->mode = MODE_Box;
27558      p->cmOpts = cmOpts;
27559    }else if( cli_strncmp(zMode,"count",n2)==0 ){
27560      p->mode = MODE_Count;
27561    }else if( cli_strncmp(zMode,"off",n2)==0 ){
27562      p->mode = MODE_Off;
27563    }else if( cli_strncmp(zMode,"json",n2)==0 ){
27564      p->mode = MODE_Json;
27565    }else{
27566      eputz("Error: mode should be one of: "
27567            "ascii box column csv html insert json line list markdown "
27568            "qbox quote table tabs tcl\n");
27569      rc = 1;
27570    }
27571    p->cMode = p->mode;
27572  }else
27573
27574#ifndef SQLITE_SHELL_FIDDLE
27575  if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
27576    if( nArg!=2 ){
27577      eputz("Usage: .nonce NONCE\n");
27578      rc = 1;
27579    }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
27580      eputf("line %d: incorrect nonce: \"%s\"\n",
27581            p->lineno, azArg[1]);
27582      exit(1);
27583    }else{
27584      p->bSafeMode = 0;
27585      return 0;  /* Return immediately to bypass the safe mode reset
27586                 ** at the end of this procedure */
27587    }
27588  }else
27589#endif /* !defined(SQLITE_SHELL_FIDDLE) */
27590
27591  if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
27592    if( nArg==2 ){
27593      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
27594                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
27595    }else{
27596      eputz("Usage: .nullvalue STRING\n");
27597      rc = 1;
27598    }
27599  }else
27600
27601  if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
27602    const char *zFN = 0;     /* Pointer to constant filename */
27603    char *zNewFilename = 0;  /* Name of the database file to open */
27604    int iName = 1;           /* Index in azArg[] of the filename */
27605    int newFlag = 0;         /* True to delete file before opening */
27606    int openMode = SHELL_OPEN_UNSPEC;
27607
27608    /* Check for command-line arguments */
27609    for(iName=1; iName<nArg; iName++){
27610      const char *z = azArg[iName];
27611#ifndef SQLITE_SHELL_FIDDLE
27612      if( optionMatch(z,"new") ){
27613        newFlag = 1;
27614#ifdef SQLITE_HAVE_ZLIB
27615      }else if( optionMatch(z, "zip") ){
27616        openMode = SHELL_OPEN_ZIPFILE;
27617#endif
27618      }else if( optionMatch(z, "append") ){
27619        openMode = SHELL_OPEN_APPENDVFS;
27620      }else if( optionMatch(z, "readonly") ){
27621        openMode = SHELL_OPEN_READONLY;
27622      }else if( optionMatch(z, "nofollow") ){
27623        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
27624#ifndef SQLITE_OMIT_DESERIALIZE
27625      }else if( optionMatch(z, "deserialize") ){
27626        openMode = SHELL_OPEN_DESERIALIZE;
27627      }else if( optionMatch(z, "hexdb") ){
27628        openMode = SHELL_OPEN_HEXDB;
27629      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
27630        p->szMax = integerValue(azArg[++iName]);
27631#endif /* SQLITE_OMIT_DESERIALIZE */
27632      }else
27633#endif /* !SQLITE_SHELL_FIDDLE */
27634      if( z[0]=='-' ){
27635        eputf("unknown option: %s\n", z);
27636        rc = 1;
27637        goto meta_command_exit;
27638      }else if( zFN ){
27639        eputf("extra argument: \"%s\"\n", z);
27640        rc = 1;
27641        goto meta_command_exit;
27642      }else{
27643        zFN = z;
27644      }
27645    }
27646
27647    /* Close the existing database */
27648    session_close_all(p, -1);
27649    close_db(p->db);
27650    p->db = 0;
27651    p->pAuxDb->zDbFilename = 0;
27652    sqlite3_free(p->pAuxDb->zFreeOnClose);
27653    p->pAuxDb->zFreeOnClose = 0;
27654    p->openMode = openMode;
27655    p->openFlags = 0;
27656    p->szMax = 0;
27657
27658    /* If a filename is specified, try to open it first */
27659    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
27660      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
27661#ifndef SQLITE_SHELL_FIDDLE
27662      if( p->bSafeMode
27663       && p->openMode!=SHELL_OPEN_HEXDB
27664       && zFN
27665       && cli_strcmp(zFN,":memory:")!=0
27666      ){
27667        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
27668      }
27669#else
27670      /* WASM mode has its own sandboxed pseudo-filesystem. */
27671#endif
27672      if( zFN ){
27673        zNewFilename = sqlite3_mprintf("%s", zFN);
27674        shell_check_oom(zNewFilename);
27675      }else{
27676        zNewFilename = 0;
27677      }
27678      p->pAuxDb->zDbFilename = zNewFilename;
27679      open_db(p, OPEN_DB_KEEPALIVE);
27680      if( p->db==0 ){
27681        eputf("Error: cannot open '%s'\n", zNewFilename);
27682        sqlite3_free(zNewFilename);
27683      }else{
27684        p->pAuxDb->zFreeOnClose = zNewFilename;
27685      }
27686    }
27687    if( p->db==0 ){
27688      /* As a fall-back open a TEMP database */
27689      p->pAuxDb->zDbFilename = 0;
27690      open_db(p, 0);
27691    }
27692  }else
27693
27694#ifndef SQLITE_SHELL_FIDDLE
27695  if( (c=='o'
27696        && (cli_strncmp(azArg[0], "output", n)==0
27697            || cli_strncmp(azArg[0], "once", n)==0))
27698   || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
27699  ){
27700    char *zFile = 0;
27701    int bTxtMode = 0;
27702    int i;
27703    int eMode = 0;
27704    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
27705    static const char *zBomUtf8 = "\xef\xbb\xbf���";
27706    const char *zBom = 0;
27707
27708    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
27709    if( c=='e' ){
27710      eMode = 'x';
27711      bOnce = 2;
27712    }else if( cli_strncmp(azArg[0],"once",n)==0 ){
27713      bOnce = 1;
27714    }
27715    for(i=1; i<nArg; i++){
27716      char *z = azArg[i];
27717      if( z[0]=='-' ){
27718        if( z[1]=='-' ) z++;
27719        if( cli_strcmp(z,"-bom")==0 ){
27720          zBom = zBomUtf8;
27721        }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
27722          eMode = 'x';  /* spreadsheet */
27723        }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
27724          eMode = 'e';  /* text editor */
27725        }else{
27726          oputf("ERROR: unknown option: \"%s\".  Usage:\n", azArg[i]);
27727          showHelp(p->out, azArg[0]);
27728          rc = 1;
27729          goto meta_command_exit;
27730        }
27731      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
27732        zFile = sqlite3_mprintf("%s", z);
27733        if( zFile && zFile[0]=='|' ){
27734          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
27735          break;
27736        }
27737      }else{
27738        oputf("ERROR: extra parameter: \"%s\".  Usage:\n", azArg[i]);
27739        showHelp(p->out, azArg[0]);
27740        rc = 1;
27741        sqlite3_free(zFile);
27742        goto meta_command_exit;
27743      }
27744    }
27745    if( zFile==0 ){
27746      zFile = sqlite3_mprintf("stdout");
27747    }
27748    if( bOnce ){
27749      p->outCount = 2;
27750    }else{
27751      p->outCount = 0;
27752    }
27753    output_reset(p);
27754#ifndef SQLITE_NOHAVE_SYSTEM
27755    if( eMode=='e' || eMode=='x' ){
27756      p->doXdgOpen = 1;
27757      outputModePush(p);
27758      if( eMode=='x' ){
27759        /* spreadsheet mode.  Output as CSV. */
27760        newTempFile(p, "csv");
27761        ShellClearFlag(p, SHFLG_Echo);
27762        p->mode = MODE_Csv;
27763        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
27764        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
27765      }else{
27766        /* text editor mode */
27767        newTempFile(p, "txt");
27768        bTxtMode = 1;
27769      }
27770      sqlite3_free(zFile);
27771      zFile = sqlite3_mprintf("%s", p->zTempFile);
27772    }
27773#endif /* SQLITE_NOHAVE_SYSTEM */
27774    shell_check_oom(zFile);
27775    if( zFile[0]=='|' ){
27776#ifdef SQLITE_OMIT_POPEN
27777      eputz("Error: pipes are not supported in this OS\n");
27778      rc = 1;
27779      output_redir(p, stdout);
27780#else
27781      FILE *pfPipe = popen(zFile + 1, "w");
27782      if( pfPipe==0 ){
27783        eputf("Error: cannot open pipe \"%s\"\n", zFile + 1);
27784        rc = 1;
27785      }else{
27786        output_redir(p, pfPipe);
27787        if( zBom ) oputz(zBom);
27788        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
27789      }
27790#endif
27791    }else{
27792      FILE *pfFile = output_file_open(zFile, bTxtMode);
27793      if( pfFile==0 ){
27794        if( cli_strcmp(zFile,"off")!=0 ){
27795          eputf("Error: cannot write to \"%s\"\n", zFile);
27796        }
27797        rc = 1;
27798      } else {
27799        output_redir(p, pfFile);
27800        if( zBom ) oputz(zBom);
27801        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
27802      }
27803    }
27804    sqlite3_free(zFile);
27805  }else
27806#endif /* !defined(SQLITE_SHELL_FIDDLE) */
27807
27808  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
27809    open_db(p,0);
27810    if( nArg<=1 ) goto parameter_syntax_error;
27811
27812    /* .parameter clear
27813    ** Clear all bind parameters by dropping the TEMP table that holds them.
27814    */
27815    if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
27816      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
27817                   0, 0, 0);
27818    }else
27819
27820    /* .parameter list
27821    ** List all bind parameters.
27822    */
27823    if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
27824      sqlite3_stmt *pStmt = 0;
27825      int rx;
27826      int len = 0;
27827      rx = sqlite3_prepare_v2(p->db,
27828             "SELECT max(length(key)) "
27829             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
27830      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27831        len = sqlite3_column_int(pStmt, 0);
27832        if( len>40 ) len = 40;
27833      }
27834      sqlite3_finalize(pStmt);
27835      pStmt = 0;
27836      if( len ){
27837        rx = sqlite3_prepare_v2(p->db,
27838             "SELECT key, quote(value) "
27839             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
27840        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
27841          oputf("%-*s %s\n", len, sqlite3_column_text(pStmt,0),
27842                sqlite3_column_text(pStmt,1));
27843        }
27844        sqlite3_finalize(pStmt);
27845      }
27846    }else
27847
27848    /* .parameter init
27849    ** Make sure the TEMP table used to hold bind parameters exists.
27850    ** Create it if necessary.
27851    */
27852    if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
27853      bind_table_init(p);
27854    }else
27855
27856    /* .parameter set NAME VALUE
27857    ** Set or reset a bind parameter.  NAME should be the full parameter
27858    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
27859    ** VALUE can be in either SQL literal notation, or if not it will be
27860    ** understood to be a text string.
27861    */
27862    if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
27863      int rx;
27864      char *zSql;
27865      sqlite3_stmt *pStmt;
27866      const char *zKey = azArg[2];
27867      const char *zValue = azArg[3];
27868      bind_table_init(p);
27869      zSql = sqlite3_mprintf(
27870                  "REPLACE INTO temp.sqlite_parameters(key,value)"
27871                  "VALUES(%Q,%s);", zKey, zValue);
27872      shell_check_oom(zSql);
27873      pStmt = 0;
27874      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27875      sqlite3_free(zSql);
27876      if( rx!=SQLITE_OK ){
27877        sqlite3_finalize(pStmt);
27878        pStmt = 0;
27879        zSql = sqlite3_mprintf(
27880                   "REPLACE INTO temp.sqlite_parameters(key,value)"
27881                   "VALUES(%Q,%Q);", zKey, zValue);
27882        shell_check_oom(zSql);
27883        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
27884        sqlite3_free(zSql);
27885        if( rx!=SQLITE_OK ){
27886          oputf("Error: %s\n", sqlite3_errmsg(p->db));
27887          sqlite3_finalize(pStmt);
27888          pStmt = 0;
27889          rc = 1;
27890        }
27891      }
27892      sqlite3_step(pStmt);
27893      sqlite3_finalize(pStmt);
27894    }else
27895
27896    /* .parameter unset NAME
27897    ** Remove the NAME binding from the parameter binding table, if it
27898    ** exists.
27899    */
27900    if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
27901      char *zSql = sqlite3_mprintf(
27902          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
27903      shell_check_oom(zSql);
27904      sqlite3_exec(p->db, zSql, 0, 0, 0);
27905      sqlite3_free(zSql);
27906    }else
27907    /* If no command name matches, show a syntax error */
27908    parameter_syntax_error:
27909    showHelp(p->out, "parameter");
27910  }else
27911
27912  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
27913    int i;
27914    for(i=1; i<nArg; i++){
27915      if( i>1 ) oputz(" ");
27916      oputz(azArg[i]);
27917    }
27918    oputz("\n");
27919  }else
27920
27921#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
27922  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
27923    int i;
27924    int nn = 0;
27925    p->flgProgress = 0;
27926    p->mxProgress = 0;
27927    p->nProgress = 0;
27928    for(i=1; i<nArg; i++){
27929      const char *z = azArg[i];
27930      if( z[0]=='-' ){
27931        z++;
27932        if( z[0]=='-' ) z++;
27933        if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
27934          p->flgProgress |= SHELL_PROGRESS_QUIET;
27935          continue;
27936        }
27937        if( cli_strcmp(z,"reset")==0 ){
27938          p->flgProgress |= SHELL_PROGRESS_RESET;
27939          continue;
27940        }
27941        if( cli_strcmp(z,"once")==0 ){
27942          p->flgProgress |= SHELL_PROGRESS_ONCE;
27943          continue;
27944        }
27945        if( cli_strcmp(z,"limit")==0 ){
27946          if( i+1>=nArg ){
27947            eputz("Error: missing argument on --limit\n");
27948            rc = 1;
27949            goto meta_command_exit;
27950          }else{
27951            p->mxProgress = (int)integerValue(azArg[++i]);
27952          }
27953          continue;
27954        }
27955        eputf("Error: unknown option: \"%s\"\n", azArg[i]);
27956        rc = 1;
27957        goto meta_command_exit;
27958      }else{
27959        nn = (int)integerValue(z);
27960      }
27961    }
27962    open_db(p, 0);
27963    sqlite3_progress_handler(p->db, nn, progress_handler, p);
27964  }else
27965#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
27966
27967  if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
27968    if( nArg >= 2) {
27969      shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
27970    }
27971    if( nArg >= 3) {
27972      shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
27973    }
27974  }else
27975
27976#ifndef SQLITE_SHELL_FIDDLE
27977  if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
27978    rc = 2;
27979  }else
27980#endif
27981
27982#ifndef SQLITE_SHELL_FIDDLE
27983  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
27984    FILE *inSaved = p->in;
27985    int savedLineno = p->lineno;
27986    failIfSafeMode(p, "cannot run .read in safe mode");
27987    if( nArg!=2 ){
27988      eputz("Usage: .read FILE\n");
27989      rc = 1;
27990      goto meta_command_exit;
27991    }
27992    if( azArg[1][0]=='|' ){
27993#ifdef SQLITE_OMIT_POPEN
27994      eputz("Error: pipes are not supported in this OS\n");
27995      rc = 1;
27996      p->out = stdout;
27997#else
27998      p->in = popen(azArg[1]+1, "r");
27999      if( p->in==0 ){
28000        eputf("Error: cannot open \"%s\"\n", azArg[1]);
28001        rc = 1;
28002      }else{
28003        rc = process_input(p);
28004        pclose(p->in);
28005      }
28006#endif
28007    }else if( (p->in = openChrSource(azArg[1]))==0 ){
28008      eputf("Error: cannot open \"%s\"\n", azArg[1]);
28009      rc = 1;
28010    }else{
28011      rc = process_input(p);
28012      fclose(p->in);
28013    }
28014    p->in = inSaved;
28015    p->lineno = savedLineno;
28016  }else
28017#endif /* !defined(SQLITE_SHELL_FIDDLE) */
28018
28019#ifndef SQLITE_SHELL_FIDDLE
28020  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
28021    const char *zSrcFile;
28022    const char *zDb;
28023    sqlite3 *pSrc;
28024    sqlite3_backup *pBackup;
28025    int nTimeout = 0;
28026
28027    failIfSafeMode(p, "cannot run .restore in safe mode");
28028    if( nArg==2 ){
28029      zSrcFile = azArg[1];
28030      zDb = "main";
28031    }else if( nArg==3 ){
28032      zSrcFile = azArg[2];
28033      zDb = azArg[1];
28034    }else{
28035      eputz("Usage: .restore ?DB? FILE\n");
28036      rc = 1;
28037      goto meta_command_exit;
28038    }
28039    rc = sqlite3_open(zSrcFile, &pSrc);
28040    if( rc!=SQLITE_OK ){
28041      eputf("Error: cannot open \"%s\"\n", zSrcFile);
28042      close_db(pSrc);
28043      return 1;
28044    }
28045    open_db(p, 0);
28046    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
28047    if( pBackup==0 ){
28048      eputf("Error: %s\n", sqlite3_errmsg(p->db));
28049      close_db(pSrc);
28050      return 1;
28051    }
28052    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
28053          || rc==SQLITE_BUSY  ){
28054      if( rc==SQLITE_BUSY ){
28055        if( nTimeout++ >= 3 ) break;
28056        sqlite3_sleep(100);
28057      }
28058    }
28059    sqlite3_backup_finish(pBackup);
28060    if( rc==SQLITE_DONE ){
28061      rc = 0;
28062    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
28063      eputz("Error: source database is busy\n");
28064      rc = 1;
28065    }else{
28066      eputf("Error: %s\n", sqlite3_errmsg(p->db));
28067      rc = 1;
28068    }
28069    close_db(pSrc);
28070  }else
28071#endif /* !defined(SQLITE_SHELL_FIDDLE) */
28072
28073  if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
28074    if( nArg==2 ){
28075      if( cli_strcmp(azArg[1], "vm")==0 ){
28076        p->scanstatsOn = 3;
28077      }else
28078      if( cli_strcmp(azArg[1], "est")==0 ){
28079        p->scanstatsOn = 2;
28080      }else{
28081        p->scanstatsOn = (u8)booleanValue(azArg[1]);
28082      }
28083      open_db(p, 0);
28084      sqlite3_db_config(
28085          p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
28086      );
28087#if !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
28088      eputz("Warning: .scanstats not available in this build.\n");
28089#elif !defined(SQLITE_ENABLE_BYTECODE_VTAB)
28090      if( p->scanstatsOn==3 ){
28091        eputz("Warning: \".scanstats vm\" not available in this build.\n");
28092      }
28093#endif
28094    }else{
28095      eputz("Usage: .scanstats on|off|est\n");
28096      rc = 1;
28097    }
28098  }else
28099
28100  if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
28101    ShellText sSelect;
28102    ShellState data;
28103    char *zErrMsg = 0;
28104    const char *zDiv = "(";
28105    const char *zName = 0;
28106    int iSchema = 0;
28107    int bDebug = 0;
28108    int bNoSystemTabs = 0;
28109    int ii;
28110
28111    open_db(p, 0);
28112    memcpy(&data, p, sizeof(data));
28113    data.showHeader = 0;
28114    data.cMode = data.mode = MODE_Semi;
28115    initText(&sSelect);
28116    for(ii=1; ii<nArg; ii++){
28117      if( optionMatch(azArg[ii],"indent") ){
28118        data.cMode = data.mode = MODE_Pretty;
28119      }else if( optionMatch(azArg[ii],"debug") ){
28120        bDebug = 1;
28121      }else if( optionMatch(azArg[ii],"nosys") ){
28122        bNoSystemTabs = 1;
28123      }else if( azArg[ii][0]=='-' ){
28124        eputf("Unknown option: \"%s\"\n", azArg[ii]);
28125        rc = 1;
28126        goto meta_command_exit;
28127      }else if( zName==0 ){
28128        zName = azArg[ii];
28129      }else{
28130        eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
28131        rc = 1;
28132        goto meta_command_exit;
28133      }
28134    }
28135    if( zName!=0 ){
28136      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
28137                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
28138                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
28139                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
28140      if( isSchema ){
28141        char *new_argv[2], *new_colv[2];
28142        new_argv[0] = sqlite3_mprintf(
28143                      "CREATE TABLE %s (\n"
28144                      "  type text,\n"
28145                      "  name text,\n"
28146                      "  tbl_name text,\n"
28147                      "  rootpage integer,\n"
28148                      "  sql text\n"
28149                      ")", zName);
28150        shell_check_oom(new_argv[0]);
28151        new_argv[1] = 0;
28152        new_colv[0] = "sql";
28153        new_colv[1] = 0;
28154        callback(&data, 1, new_argv, new_colv);
28155        sqlite3_free(new_argv[0]);
28156      }
28157    }
28158    if( zDiv ){
28159      sqlite3_stmt *pStmt = 0;
28160      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
28161                              -1, &pStmt, 0);
28162      if( rc ){
28163        eputf("Error: %s\n", sqlite3_errmsg(p->db));
28164        sqlite3_finalize(pStmt);
28165        rc = 1;
28166        goto meta_command_exit;
28167      }
28168      appendText(&sSelect, "SELECT sql FROM", 0);
28169      iSchema = 0;
28170      while( sqlite3_step(pStmt)==SQLITE_ROW ){
28171        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
28172        char zScNum[30];
28173        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
28174        appendText(&sSelect, zDiv, 0);
28175        zDiv = " UNION ALL ";
28176        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
28177        if( sqlite3_stricmp(zDb, "main")!=0 ){
28178          appendText(&sSelect, zDb, '\'');
28179        }else{
28180          appendText(&sSelect, "NULL", 0);
28181        }
28182        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
28183        appendText(&sSelect, zScNum, 0);
28184        appendText(&sSelect, " AS snum, ", 0);
28185        appendText(&sSelect, zDb, '\'');
28186        appendText(&sSelect, " AS sname FROM ", 0);
28187        appendText(&sSelect, zDb, quoteChar(zDb));
28188        appendText(&sSelect, ".sqlite_schema", 0);
28189      }
28190      sqlite3_finalize(pStmt);
28191#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
28192      if( zName ){
28193        appendText(&sSelect,
28194           " UNION ALL SELECT shell_module_schema(name),"
28195           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
28196        0);
28197      }
28198#endif
28199      appendText(&sSelect, ") WHERE ", 0);
28200      if( zName ){
28201        char *zQarg = sqlite3_mprintf("%Q", zName);
28202        int bGlob;
28203        shell_check_oom(zQarg);
28204        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
28205                strchr(zName, '[') != 0;
28206        if( strchr(zName, '.') ){
28207          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
28208        }else{
28209          appendText(&sSelect, "lower(tbl_name)", 0);
28210        }
28211        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
28212        appendText(&sSelect, zQarg, 0);
28213        if( !bGlob ){
28214          appendText(&sSelect, " ESCAPE '\\' ", 0);
28215        }
28216        appendText(&sSelect, " AND ", 0);
28217        sqlite3_free(zQarg);
28218      }
28219      if( bNoSystemTabs ){
28220        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
28221      }
28222      appendText(&sSelect, "sql IS NOT NULL"
28223                           " ORDER BY snum, rowid", 0);
28224      if( bDebug ){
28225        oputf("SQL: %s;\n", sSelect.z);
28226      }else{
28227        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
28228      }
28229      freeText(&sSelect);
28230    }
28231    if( zErrMsg ){
28232      eputf("Error: %s\n", zErrMsg);
28233      sqlite3_free(zErrMsg);
28234      rc = 1;
28235    }else if( rc != SQLITE_OK ){
28236      eputz("Error: querying schema information\n");
28237      rc = 1;
28238    }else{
28239      rc = 0;
28240    }
28241  }else
28242
28243  if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
28244   || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
28245  ){
28246    unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
28247    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
28248  }else
28249
28250#if defined(SQLITE_ENABLE_SESSION)
28251  if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
28252    struct AuxDb *pAuxDb = p->pAuxDb;
28253    OpenSession *pSession = &pAuxDb->aSession[0];
28254    char **azCmd = &azArg[1];
28255    int iSes = 0;
28256    int nCmd = nArg - 1;
28257    int i;
28258    if( nArg<=1 ) goto session_syntax_error;
28259    open_db(p, 0);
28260    if( nArg>=3 ){
28261      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
28262        if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
28263      }
28264      if( iSes<pAuxDb->nSession ){
28265        pSession = &pAuxDb->aSession[iSes];
28266        azCmd++;
28267        nCmd--;
28268      }else{
28269        pSession = &pAuxDb->aSession[0];
28270        iSes = 0;
28271      }
28272    }
28273
28274    /* .session attach TABLE
28275    ** Invoke the sqlite3session_attach() interface to attach a particular
28276    ** table so that it is never filtered.
28277    */
28278    if( cli_strcmp(azCmd[0],"attach")==0 ){
28279      if( nCmd!=2 ) goto session_syntax_error;
28280      if( pSession->p==0 ){
28281        session_not_open:
28282        eputz("ERROR: No sessions are open\n");
28283      }else{
28284        rc = sqlite3session_attach(pSession->p, azCmd[1]);
28285        if( rc ){
28286          eputf("ERROR: sqlite3session_attach() returns %d\n",rc);
28287          rc = 0;
28288        }
28289      }
28290    }else
28291
28292    /* .session changeset FILE
28293    ** .session patchset FILE
28294    ** Write a changeset or patchset into a file.  The file is overwritten.
28295    */
28296    if( cli_strcmp(azCmd[0],"changeset")==0
28297     || cli_strcmp(azCmd[0],"patchset")==0
28298    ){
28299      FILE *out = 0;
28300      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
28301      if( nCmd!=2 ) goto session_syntax_error;
28302      if( pSession->p==0 ) goto session_not_open;
28303      out = fopen(azCmd[1], "wb");
28304      if( out==0 ){
28305        eputf("ERROR: cannot open \"%s\" for writing\n",
28306              azCmd[1]);
28307      }else{
28308        int szChng;
28309        void *pChng;
28310        if( azCmd[0][0]=='c' ){
28311          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
28312        }else{
28313          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
28314        }
28315        if( rc ){
28316          sputf(stdout, "Error: error code %d\n", rc);
28317          rc = 0;
28318        }
28319        if( pChng
28320          && fwrite(pChng, szChng, 1, out)!=1 ){
28321          eputf("ERROR: Failed to write entire %d-byte output\n", szChng);
28322        }
28323        sqlite3_free(pChng);
28324        fclose(out);
28325      }
28326    }else
28327
28328    /* .session close
28329    ** Close the identified session
28330    */
28331    if( cli_strcmp(azCmd[0], "close")==0 ){
28332      if( nCmd!=1 ) goto session_syntax_error;
28333      if( pAuxDb->nSession ){
28334        session_close(pSession);
28335        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
28336      }
28337    }else
28338
28339    /* .session enable ?BOOLEAN?
28340    ** Query or set the enable flag
28341    */
28342    if( cli_strcmp(azCmd[0], "enable")==0 ){
28343      int ii;
28344      if( nCmd>2 ) goto session_syntax_error;
28345      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
28346      if( pAuxDb->nSession ){
28347        ii = sqlite3session_enable(pSession->p, ii);
28348        oputf("session %s enable flag = %d\n", pSession->zName, ii);
28349      }
28350    }else
28351
28352    /* .session filter GLOB ....
28353    ** Set a list of GLOB patterns of table names to be excluded.
28354    */
28355    if( cli_strcmp(azCmd[0], "filter")==0 ){
28356      int ii, nByte;
28357      if( nCmd<2 ) goto session_syntax_error;
28358      if( pAuxDb->nSession ){
28359        for(ii=0; ii<pSession->nFilter; ii++){
28360          sqlite3_free(pSession->azFilter[ii]);
28361        }
28362        sqlite3_free(pSession->azFilter);
28363        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
28364        pSession->azFilter = sqlite3_malloc( nByte );
28365        shell_check_oom( pSession->azFilter );
28366        for(ii=1; ii<nCmd; ii++){
28367          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
28368          shell_check_oom(x);
28369        }
28370        pSession->nFilter = ii-1;
28371      }
28372    }else
28373
28374    /* .session indirect ?BOOLEAN?
28375    ** Query or set the indirect flag
28376    */
28377    if( cli_strcmp(azCmd[0], "indirect")==0 ){
28378      int ii;
28379      if( nCmd>2 ) goto session_syntax_error;
28380      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
28381      if( pAuxDb->nSession ){
28382        ii = sqlite3session_indirect(pSession->p, ii);
28383        oputf("session %s indirect flag = %d\n", pSession->zName, ii);
28384      }
28385    }else
28386
28387    /* .session isempty
28388    ** Determine if the session is empty
28389    */
28390    if( cli_strcmp(azCmd[0], "isempty")==0 ){
28391      int ii;
28392      if( nCmd!=1 ) goto session_syntax_error;
28393      if( pAuxDb->nSession ){
28394        ii = sqlite3session_isempty(pSession->p);
28395        oputf("session %s isempty flag = %d\n", pSession->zName, ii);
28396      }
28397    }else
28398
28399    /* .session list
28400    ** List all currently open sessions
28401    */
28402    if( cli_strcmp(azCmd[0],"list")==0 ){
28403      for(i=0; i<pAuxDb->nSession; i++){
28404        oputf("%d %s\n", i, pAuxDb->aSession[i].zName);
28405      }
28406    }else
28407
28408    /* .session open DB NAME
28409    ** Open a new session called NAME on the attached database DB.
28410    ** DB is normally "main".
28411    */
28412    if( cli_strcmp(azCmd[0],"open")==0 ){
28413      char *zName;
28414      if( nCmd!=3 ) goto session_syntax_error;
28415      zName = azCmd[2];
28416      if( zName[0]==0 ) goto session_syntax_error;
28417      for(i=0; i<pAuxDb->nSession; i++){
28418        if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
28419          eputf("Session \"%s\" already exists\n", zName);
28420          goto meta_command_exit;
28421        }
28422      }
28423      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
28424        eputf("Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
28425        goto meta_command_exit;
28426      }
28427      pSession = &pAuxDb->aSession[pAuxDb->nSession];
28428      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
28429      if( rc ){
28430        eputf("Cannot open session: error code=%d\n", rc);
28431        rc = 0;
28432        goto meta_command_exit;
28433      }
28434      pSession->nFilter = 0;
28435      sqlite3session_table_filter(pSession->p, session_filter, pSession);
28436      pAuxDb->nSession++;
28437      pSession->zName = sqlite3_mprintf("%s", zName);
28438      shell_check_oom(pSession->zName);
28439    }else
28440    /* If no command name matches, show a syntax error */
28441    session_syntax_error:
28442    showHelp(p->out, "session");
28443  }else
28444#endif
28445
28446#ifdef SQLITE_DEBUG
28447  /* Undocumented commands for internal testing.  Subject to change
28448  ** without notice. */
28449  if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
28450    if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
28451      int i, v;
28452      for(i=1; i<nArg; i++){
28453        v = booleanValue(azArg[i]);
28454        oputf("%s: %d 0x%x\n", azArg[i], v, v);
28455      }
28456    }
28457    if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
28458      int i; sqlite3_int64 v;
28459      for(i=1; i<nArg; i++){
28460        char zBuf[200];
28461        v = integerValue(azArg[i]);
28462        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
28463        oputz(zBuf);
28464      }
28465    }
28466  }else
28467#endif
28468
28469  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
28470    int bIsInit = 0;         /* True to initialize the SELFTEST table */
28471    int bVerbose = 0;        /* Verbose output */
28472    int bSelftestExists;     /* True if SELFTEST already exists */
28473    int i, k;                /* Loop counters */
28474    int nTest = 0;           /* Number of tests runs */
28475    int nErr = 0;            /* Number of errors seen */
28476    ShellText str;           /* Answer for a query */
28477    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
28478
28479    open_db(p,0);
28480    for(i=1; i<nArg; i++){
28481      const char *z = azArg[i];
28482      if( z[0]=='-' && z[1]=='-' ) z++;
28483      if( cli_strcmp(z,"-init")==0 ){
28484        bIsInit = 1;
28485      }else
28486      if( cli_strcmp(z,"-v")==0 ){
28487        bVerbose++;
28488      }else
28489      {
28490        eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
28491        eputz("Should be one of: --init -v\n");
28492        rc = 1;
28493        goto meta_command_exit;
28494      }
28495    }
28496    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
28497           != SQLITE_OK ){
28498      bSelftestExists = 0;
28499    }else{
28500      bSelftestExists = 1;
28501    }
28502    if( bIsInit ){
28503      createSelftestTable(p);
28504      bSelftestExists = 1;
28505    }
28506    initText(&str);
28507    appendText(&str, "x", 0);
28508    for(k=bSelftestExists; k>=0; k--){
28509      if( k==1 ){
28510        rc = sqlite3_prepare_v2(p->db,
28511            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
28512            -1, &pStmt, 0);
28513      }else{
28514        rc = sqlite3_prepare_v2(p->db,
28515          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
28516          "      (1,'run','PRAGMA integrity_check','ok')",
28517          -1, &pStmt, 0);
28518      }
28519      if( rc ){
28520        eputz("Error querying the selftest table\n");
28521        rc = 1;
28522        sqlite3_finalize(pStmt);
28523        goto meta_command_exit;
28524      }
28525      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
28526        int tno = sqlite3_column_int(pStmt, 0);
28527        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
28528        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
28529        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
28530
28531        if( zOp==0 ) continue;
28532        if( zSql==0 ) continue;
28533        if( zAns==0 ) continue;
28534        k = 0;
28535        if( bVerbose>0 ){
28536          sputf(stdout, "%d: %s %s\n", tno, zOp, zSql);
28537        }
28538        if( cli_strcmp(zOp,"memo")==0 ){
28539          oputf("%s\n", zSql);
28540        }else
28541        if( cli_strcmp(zOp,"run")==0 ){
28542          char *zErrMsg = 0;
28543          str.n = 0;
28544          str.z[0] = 0;
28545          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
28546          nTest++;
28547          if( bVerbose ){
28548            oputf("Result: %s\n", str.z);
28549          }
28550          if( rc || zErrMsg ){
28551            nErr++;
28552            rc = 1;
28553            oputf("%d: error-code-%d: %s\n", tno, rc, zErrMsg);
28554            sqlite3_free(zErrMsg);
28555          }else if( cli_strcmp(zAns,str.z)!=0 ){
28556            nErr++;
28557            rc = 1;
28558            oputf("%d: Expected: [%s]\n", tno, zAns);
28559            oputf("%d:      Got: [%s]\n", tno, str.z);
28560          }
28561        }
28562        else{
28563          eputf("Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
28564          rc = 1;
28565          break;
28566        }
28567      } /* End loop over rows of content from SELFTEST */
28568      sqlite3_finalize(pStmt);
28569    } /* End loop over k */
28570    freeText(&str);
28571    oputf("%d errors out of %d tests\n", nErr, nTest);
28572  }else
28573
28574  if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
28575    if( nArg<2 || nArg>3 ){
28576      eputz("Usage: .separator COL ?ROW?\n");
28577      rc = 1;
28578    }
28579    if( nArg>=2 ){
28580      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
28581                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
28582    }
28583    if( nArg>=3 ){
28584      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
28585                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
28586    }
28587  }else
28588
28589  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
28590    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
28591    int i;                   /* Loop counter */
28592    int bSchema = 0;         /* Also hash the schema */
28593    int bSeparate = 0;       /* Hash each table separately */
28594    int iSize = 224;         /* Hash algorithm to use */
28595    int bDebug = 0;          /* Only show the query that would have run */
28596    sqlite3_stmt *pStmt;     /* For querying tables names */
28597    char *zSql;              /* SQL to be run */
28598    char *zSep;              /* Separator */
28599    ShellText sSql;          /* Complete SQL for the query to run the hash */
28600    ShellText sQuery;        /* Set of queries used to read all content */
28601    open_db(p, 0);
28602    for(i=1; i<nArg; i++){
28603      const char *z = azArg[i];
28604      if( z[0]=='-' ){
28605        z++;
28606        if( z[0]=='-' ) z++;
28607        if( cli_strcmp(z,"schema")==0 ){
28608          bSchema = 1;
28609        }else
28610        if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
28611         || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
28612        ){
28613          iSize = atoi(&z[5]);
28614        }else
28615        if( cli_strcmp(z,"debug")==0 ){
28616          bDebug = 1;
28617        }else
28618        {
28619          eputf("Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]);
28620          showHelp(p->out, azArg[0]);
28621          rc = 1;
28622          goto meta_command_exit;
28623        }
28624      }else if( zLike ){
28625        eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
28626        rc = 1;
28627        goto meta_command_exit;
28628      }else{
28629        zLike = z;
28630        bSeparate = 1;
28631        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
28632      }
28633    }
28634    if( bSchema ){
28635      zSql = "SELECT lower(name) as tname FROM sqlite_schema"
28636             " WHERE type='table' AND coalesce(rootpage,0)>1"
28637             " UNION ALL SELECT 'sqlite_schema'"
28638             " ORDER BY 1 collate nocase";
28639    }else{
28640      zSql = "SELECT lower(name) as tname FROM sqlite_schema"
28641             " WHERE type='table' AND coalesce(rootpage,0)>1"
28642             " AND name NOT LIKE 'sqlite_%'"
28643             " ORDER BY 1 collate nocase";
28644    }
28645    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
28646    initText(&sQuery);
28647    initText(&sSql);
28648    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
28649    zSep = "VALUES(";
28650    while( SQLITE_ROW==sqlite3_step(pStmt) ){
28651      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
28652      if( zTab==0 ) continue;
28653      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
28654      if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
28655        appendText(&sQuery,"SELECT * FROM ", 0);
28656        appendText(&sQuery,zTab,'"');
28657        appendText(&sQuery," NOT INDEXED;", 0);
28658      }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
28659        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
28660                           " ORDER BY name;", 0);
28661      }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
28662        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
28663                           " ORDER BY name;", 0);
28664      }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
28665        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
28666                           " ORDER BY tbl,idx;", 0);
28667      }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
28668        appendText(&sQuery, "SELECT * FROM ", 0);
28669        appendText(&sQuery, zTab, 0);
28670        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
28671      }
28672      appendText(&sSql, zSep, 0);
28673      appendText(&sSql, sQuery.z, '\'');
28674      sQuery.n = 0;
28675      appendText(&sSql, ",", 0);
28676      appendText(&sSql, zTab, '\'');
28677      zSep = "),(";
28678    }
28679    sqlite3_finalize(pStmt);
28680    if( bSeparate ){
28681      zSql = sqlite3_mprintf(
28682          "%s))"
28683          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
28684          "   FROM [sha3sum$query]",
28685          sSql.z, iSize);
28686    }else{
28687      zSql = sqlite3_mprintf(
28688          "%s))"
28689          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
28690          "   FROM [sha3sum$query]",
28691          sSql.z, iSize);
28692    }
28693    shell_check_oom(zSql);
28694    freeText(&sQuery);
28695    freeText(&sSql);
28696    if( bDebug ){
28697      oputf("%s\n", zSql);
28698    }else{
28699      shell_exec(p, zSql, 0);
28700    }
28701#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE)
28702    {
28703      int lrc;
28704      char *zRevText = /* Query for reversible to-blob-to-text check */
28705        "SELECT lower(name) as tname FROM sqlite_schema\n"
28706        "WHERE type='table' AND coalesce(rootpage,0)>1\n"
28707        "AND name NOT LIKE 'sqlite_%%'%s\n"
28708        "ORDER BY 1 collate nocase";
28709      zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : "");
28710      zRevText = sqlite3_mprintf(
28711          /* lower-case query is first run, producing upper-case query. */
28712          "with tabcols as materialized(\n"
28713          "select tname, cname\n"
28714          "from ("
28715          " select printf('\"%%w\"',ss.tname) as tname,"
28716          " printf('\"%%w\"',ti.name) as cname\n"
28717          " from (%z) ss\n inner join pragma_table_info(tname) ti))\n"
28718          "select 'SELECT total(bad_text_count) AS bad_text_count\n"
28719          "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n"
28720          " from (select 'SELECT COUNT(*) AS bad_text_count\n"
28721          "FROM '||tname||' WHERE '\n"
28722          "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n"
28723          "|| ' AND typeof('||cname||')=''text'' ',\n"
28724          "' OR ') as query, tname from tabcols group by tname)"
28725          , zRevText);
28726      shell_check_oom(zRevText);
28727      if( bDebug ) oputf("%s\n", zRevText);
28728      lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0);
28729      if( lrc!=SQLITE_OK ){
28730        /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the
28731        ** user does cruel and unnatural things like ".limit expr_depth 0". */
28732        rc = 1;
28733      }else{
28734        if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC);
28735        lrc = SQLITE_ROW==sqlite3_step(pStmt);
28736        if( lrc ){
28737          const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0);
28738          sqlite3_stmt *pCheckStmt;
28739          lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0);
28740          if( bDebug ) oputf("%s\n", zGenQuery);
28741          if( lrc!=SQLITE_OK ){
28742            rc = 1;
28743          }else{
28744            if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){
28745              double countIrreversible = sqlite3_column_double(pCheckStmt, 0);
28746              if( countIrreversible>0 ){
28747                int sz = (int)(countIrreversible + 0.5);
28748                eputf("Digest includes %d invalidly encoded text field%s.\n",
28749                      sz, (sz>1)? "s": "");
28750              }
28751            }
28752            sqlite3_finalize(pCheckStmt);
28753          }
28754          sqlite3_finalize(pStmt);
28755        }
28756      }
28757      if( rc ) eputz(".sha3sum failed.\n");
28758      sqlite3_free(zRevText);
28759    }
28760#endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */
28761    sqlite3_free(zSql);
28762  }else
28763
28764#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
28765  if( c=='s'
28766   && (cli_strncmp(azArg[0], "shell", n)==0
28767       || cli_strncmp(azArg[0],"system",n)==0)
28768  ){
28769    char *zCmd;
28770    int i, x;
28771    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
28772    if( nArg<2 ){
28773      eputz("Usage: .system COMMAND\n");
28774      rc = 1;
28775      goto meta_command_exit;
28776    }
28777    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
28778    for(i=2; i<nArg && zCmd!=0; i++){
28779      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
28780                             zCmd, azArg[i]);
28781    }
28782    consoleRestore();
28783    x = zCmd!=0 ? system(zCmd) : 1;
28784    consoleRenewSetup();
28785    sqlite3_free(zCmd);
28786    if( x ) eputf("System command returns %d\n", x);
28787  }else
28788#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
28789
28790  if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
28791    static const char *azBool[] = { "off", "on", "trigger", "full"};
28792    const char *zOut;
28793    int i;
28794    if( nArg!=1 ){
28795      eputz("Usage: .show\n");
28796      rc = 1;
28797      goto meta_command_exit;
28798    }
28799    oputf("%12.12s: %s\n","echo",
28800          azBool[ShellHasFlag(p, SHFLG_Echo)]);
28801    oputf("%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
28802    oputf("%12.12s: %s\n","explain",
28803          p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
28804    oputf("%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
28805    if( p->mode==MODE_Column
28806     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
28807    ){
28808      oputf("%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
28809            modeDescr[p->mode], p->cmOpts.iWrap,
28810            p->cmOpts.bWordWrap ? "on" : "off",
28811            p->cmOpts.bQuote ? "" : "no");
28812    }else{
28813      oputf("%12.12s: %s\n","mode", modeDescr[p->mode]);
28814    }
28815    oputf("%12.12s: ", "nullvalue");
28816    output_c_string(p->nullValue);
28817    oputz("\n");
28818    oputf("%12.12s: %s\n","output",
28819          strlen30(p->outfile) ? p->outfile : "stdout");
28820    oputf("%12.12s: ", "colseparator");
28821     output_c_string(p->colSeparator);
28822     oputz("\n");
28823    oputf("%12.12s: ", "rowseparator");
28824     output_c_string(p->rowSeparator);
28825     oputz("\n");
28826    switch( p->statsOn ){
28827      case 0:  zOut = "off";     break;
28828      default: zOut = "on";      break;
28829      case 2:  zOut = "stmt";    break;
28830      case 3:  zOut = "vmstep";  break;
28831    }
28832    oputf("%12.12s: %s\n","stats", zOut);
28833    oputf("%12.12s: ", "width");
28834    for (i=0;i<p->nWidth;i++) {
28835      oputf("%d ", p->colWidth[i]);
28836    }
28837    oputz("\n");
28838    oputf("%12.12s: %s\n", "filename",
28839          p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
28840  }else
28841
28842  if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
28843    if( nArg==2 ){
28844      if( cli_strcmp(azArg[1],"stmt")==0 ){
28845        p->statsOn = 2;
28846      }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
28847        p->statsOn = 3;
28848      }else{
28849        p->statsOn = (u8)booleanValue(azArg[1]);
28850      }
28851    }else if( nArg==1 ){
28852      display_stats(p->db, p, 0);
28853    }else{
28854      eputz("Usage: .stats ?on|off|stmt|vmstep?\n");
28855      rc = 1;
28856    }
28857  }else
28858
28859  if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
28860   || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
28861                 || cli_strncmp(azArg[0], "indexes", n)==0) )
28862  ){
28863    sqlite3_stmt *pStmt;
28864    char **azResult;
28865    int nRow, nAlloc;
28866    int ii;
28867    ShellText s;
28868    initText(&s);
28869    open_db(p, 0);
28870    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
28871    if( rc ){
28872      sqlite3_finalize(pStmt);
28873      return shellDatabaseError(p->db);
28874    }
28875
28876    if( nArg>2 && c=='i' ){
28877      /* It is an historical accident that the .indexes command shows an error
28878      ** when called with the wrong number of arguments whereas the .tables
28879      ** command does not. */
28880      eputz("Usage: .indexes ?LIKE-PATTERN?\n");
28881      rc = 1;
28882      sqlite3_finalize(pStmt);
28883      goto meta_command_exit;
28884    }
28885    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
28886      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
28887      if( zDbName==0 ) continue;
28888      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
28889      if( sqlite3_stricmp(zDbName, "main")==0 ){
28890        appendText(&s, "SELECT name FROM ", 0);
28891      }else{
28892        appendText(&s, "SELECT ", 0);
28893        appendText(&s, zDbName, '\'');
28894        appendText(&s, "||'.'||name FROM ", 0);
28895      }
28896      appendText(&s, zDbName, '"');
28897      appendText(&s, ".sqlite_schema ", 0);
28898      if( c=='t' ){
28899        appendText(&s," WHERE type IN ('table','view')"
28900                      "   AND name NOT LIKE 'sqlite_%'"
28901                      "   AND name LIKE ?1", 0);
28902      }else{
28903        appendText(&s," WHERE type='index'"
28904                      "   AND tbl_name LIKE ?1", 0);
28905      }
28906    }
28907    rc = sqlite3_finalize(pStmt);
28908    if( rc==SQLITE_OK ){
28909      appendText(&s, " ORDER BY 1", 0);
28910      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
28911    }
28912    freeText(&s);
28913    if( rc ) return shellDatabaseError(p->db);
28914
28915    /* Run the SQL statement prepared by the above block. Store the results
28916    ** as an array of nul-terminated strings in azResult[].  */
28917    nRow = nAlloc = 0;
28918    azResult = 0;
28919    if( nArg>1 ){
28920      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
28921    }else{
28922      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
28923    }
28924    while( sqlite3_step(pStmt)==SQLITE_ROW ){
28925      if( nRow>=nAlloc ){
28926        char **azNew;
28927        int n2 = nAlloc*2 + 10;
28928        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
28929        shell_check_oom(azNew);
28930        nAlloc = n2;
28931        azResult = azNew;
28932      }
28933      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
28934      shell_check_oom(azResult[nRow]);
28935      nRow++;
28936    }
28937    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
28938      rc = shellDatabaseError(p->db);
28939    }
28940
28941    /* Pretty-print the contents of array azResult[] to the output */
28942    if( rc==0 && nRow>0 ){
28943      int len, maxlen = 0;
28944      int i, j;
28945      int nPrintCol, nPrintRow;
28946      for(i=0; i<nRow; i++){
28947        len = strlen30(azResult[i]);
28948        if( len>maxlen ) maxlen = len;
28949      }
28950      nPrintCol = 80/(maxlen+2);
28951      if( nPrintCol<1 ) nPrintCol = 1;
28952      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
28953      for(i=0; i<nPrintRow; i++){
28954        for(j=i; j<nRow; j+=nPrintRow){
28955          char *zSp = j<nPrintRow ? "" : "  ";
28956          oputf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:"");
28957        }
28958        oputz("\n");
28959      }
28960    }
28961
28962    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
28963    sqlite3_free(azResult);
28964  }else
28965
28966#ifndef SQLITE_SHELL_FIDDLE
28967  /* Begin redirecting output to the file "testcase-out.txt" */
28968  if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
28969    output_reset(p);
28970    p->out = output_file_open("testcase-out.txt", 0);
28971    if( p->out==0 ){
28972      eputz("Error: cannot open 'testcase-out.txt'\n");
28973    }
28974    if( nArg>=2 ){
28975      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
28976    }else{
28977      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
28978    }
28979  }else
28980#endif /* !defined(SQLITE_SHELL_FIDDLE) */
28981
28982#ifndef SQLITE_UNTESTABLE
28983  if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
28984    static const struct {
28985       const char *zCtrlName;   /* Name of a test-control option */
28986       int ctrlCode;            /* Integer code for that option */
28987       int unSafe;              /* Not valid unless --unsafe-testing */
28988       const char *zUsage;      /* Usage notes */
28989    } aCtrl[] = {
28990    {"always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
28991    {"assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
28992  /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
28993  /*{"bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
28994    {"byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
28995    {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
28996    {"fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..."       },
28997    {"fk_no_action",       SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN"       },
28998    {"imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
28999    {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
29000    {"json_selfcheck",     SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN"      },
29001    {"localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
29002    {"never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
29003    {"optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
29004#ifdef YYCOVERAGE
29005    {"parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
29006#endif
29007    {"pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
29008    {"prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
29009    {"prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
29010    {"prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
29011    {"seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
29012    {"sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
29013    {"tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
29014    {"uselongdouble",  SQLITE_TESTCTRL_USELONGDOUBLE,0,"?BOOLEAN|\"default\"?"},
29015    };
29016    int testctrl = -1;
29017    int iCtrl = -1;
29018    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
29019    int isOk = 0;
29020    int i, n2;
29021    const char *zCmd = 0;
29022
29023    open_db(p, 0);
29024    zCmd = nArg>=2 ? azArg[1] : "help";
29025
29026    /* The argument can optionally begin with "-" or "--" */
29027    if( zCmd[0]=='-' && zCmd[1] ){
29028      zCmd++;
29029      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
29030    }
29031
29032    /* --help lists all test-controls */
29033    if( cli_strcmp(zCmd,"help")==0 ){
29034      oputz("Available test-controls:\n");
29035      for(i=0; i<ArraySize(aCtrl); i++){
29036        if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
29037        oputf("  .testctrl %s %s\n",
29038              aCtrl[i].zCtrlName, aCtrl[i].zUsage);
29039      }
29040      rc = 1;
29041      goto meta_command_exit;
29042    }
29043
29044    /* convert testctrl text option to value. allow any unique prefix
29045    ** of the option name, or a numerical value. */
29046    n2 = strlen30(zCmd);
29047    for(i=0; i<ArraySize(aCtrl); i++){
29048      if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue;
29049      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
29050        if( testctrl<0 ){
29051          testctrl = aCtrl[i].ctrlCode;
29052          iCtrl = i;
29053        }else{
29054          eputf("Error: ambiguous test-control: \"%s\"\n"
29055                "Use \".testctrl --help\" for help\n", zCmd);
29056          rc = 1;
29057          goto meta_command_exit;
29058        }
29059      }
29060    }
29061    if( testctrl<0 ){
29062      eputf("Error: unknown test-control: %s\n"
29063            "Use \".testctrl --help\" for help\n", zCmd);
29064    }else{
29065      switch(testctrl){
29066
29067        /* sqlite3_test_control(int, db, int) */
29068        case SQLITE_TESTCTRL_OPTIMIZATIONS:
29069        case SQLITE_TESTCTRL_FK_NO_ACTION:
29070          if( nArg==3 ){
29071            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
29072            rc2 = sqlite3_test_control(testctrl, p->db, opt);
29073            isOk = 3;
29074          }
29075          break;
29076
29077        /* sqlite3_test_control(int) */
29078        case SQLITE_TESTCTRL_PRNG_SAVE:
29079        case SQLITE_TESTCTRL_PRNG_RESTORE:
29080        case SQLITE_TESTCTRL_BYTEORDER:
29081          if( nArg==2 ){
29082            rc2 = sqlite3_test_control(testctrl);
29083            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
29084          }
29085          break;
29086
29087        /* sqlite3_test_control(int, uint) */
29088        case SQLITE_TESTCTRL_PENDING_BYTE:
29089          if( nArg==3 ){
29090            unsigned int opt = (unsigned int)integerValue(azArg[2]);
29091            rc2 = sqlite3_test_control(testctrl, opt);
29092            isOk = 3;
29093          }
29094          break;
29095
29096        /* sqlite3_test_control(int, int, sqlite3*) */
29097        case SQLITE_TESTCTRL_PRNG_SEED:
29098          if( nArg==3 || nArg==4 ){
29099            int ii = (int)integerValue(azArg[2]);
29100            sqlite3 *db;
29101            if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
29102              sqlite3_randomness(sizeof(ii),&ii);
29103              sputf(stdout, "-- random seed: %d\n", ii);
29104            }
29105            if( nArg==3 ){
29106              db = 0;
29107            }else{
29108              db = p->db;
29109              /* Make sure the schema has been loaded */
29110              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
29111            }
29112            rc2 = sqlite3_test_control(testctrl, ii, db);
29113            isOk = 3;
29114          }
29115          break;
29116
29117        /* sqlite3_test_control(int, int) */
29118        case SQLITE_TESTCTRL_ASSERT:
29119        case SQLITE_TESTCTRL_ALWAYS:
29120          if( nArg==3 ){
29121            int opt = booleanValue(azArg[2]);
29122            rc2 = sqlite3_test_control(testctrl, opt);
29123            isOk = 1;
29124          }
29125          break;
29126
29127        /* sqlite3_test_control(int, int) */
29128        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
29129        case SQLITE_TESTCTRL_NEVER_CORRUPT:
29130          if( nArg==3 ){
29131            int opt = booleanValue(azArg[2]);
29132            rc2 = sqlite3_test_control(testctrl, opt);
29133            isOk = 3;
29134          }
29135          break;
29136
29137        /* sqlite3_test_control(int, int) */
29138        case SQLITE_TESTCTRL_USELONGDOUBLE: {
29139          int opt = -1;
29140          if( nArg==3 ){
29141            if( cli_strcmp(azArg[2],"default")==0 ){
29142              opt = 2;
29143            }else{
29144              opt = booleanValue(azArg[2]);
29145            }
29146          }
29147          rc2 = sqlite3_test_control(testctrl, opt);
29148          isOk = 1;
29149          break;
29150        }
29151
29152        /* sqlite3_test_control(sqlite3*) */
29153        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
29154          rc2 = sqlite3_test_control(testctrl, p->db);
29155          isOk = 3;
29156          break;
29157
29158        case SQLITE_TESTCTRL_IMPOSTER:
29159          if( nArg==5 ){
29160            rc2 = sqlite3_test_control(testctrl, p->db,
29161                          azArg[2],
29162                          integerValue(azArg[3]),
29163                          integerValue(azArg[4]));
29164            isOk = 3;
29165          }
29166          break;
29167
29168        case SQLITE_TESTCTRL_SEEK_COUNT: {
29169          u64 x = 0;
29170          rc2 = sqlite3_test_control(testctrl, p->db, &x);
29171          oputf("%llu\n", x);
29172          isOk = 3;
29173          break;
29174        }
29175
29176#ifdef YYCOVERAGE
29177        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
29178          if( nArg==2 ){
29179            sqlite3_test_control(testctrl, p->out);
29180            isOk = 3;
29181          }
29182          break;
29183        }
29184#endif
29185#ifdef SQLITE_DEBUG
29186        case SQLITE_TESTCTRL_TUNE: {
29187          if( nArg==4 ){
29188            int id = (int)integerValue(azArg[2]);
29189            int val = (int)integerValue(azArg[3]);
29190            sqlite3_test_control(testctrl, id, &val);
29191            isOk = 3;
29192          }else if( nArg==3 ){
29193            int id = (int)integerValue(azArg[2]);
29194            sqlite3_test_control(testctrl, -id, &rc2);
29195            isOk = 1;
29196          }else if( nArg==2 ){
29197            int id = 1;
29198            while(1){
29199              int val = 0;
29200              rc2 = sqlite3_test_control(testctrl, -id, &val);
29201              if( rc2!=SQLITE_OK ) break;
29202              if( id>1 ) oputz("  ");
29203              oputf("%d: %d", id, val);
29204              id++;
29205            }
29206            if( id>1 ) oputz("\n");
29207            isOk = 3;
29208          }
29209          break;
29210        }
29211#endif
29212        case SQLITE_TESTCTRL_SORTER_MMAP:
29213          if( nArg==3 ){
29214            int opt = (unsigned int)integerValue(azArg[2]);
29215            rc2 = sqlite3_test_control(testctrl, p->db, opt);
29216            isOk = 3;
29217          }
29218          break;
29219        case SQLITE_TESTCTRL_JSON_SELFCHECK:
29220          if( nArg==2 ){
29221            rc2 = -1;
29222            isOk = 1;
29223          }else{
29224            rc2 = booleanValue(azArg[2]);
29225            isOk = 3;
29226          }
29227          sqlite3_test_control(testctrl, &rc2);
29228          break;
29229        case SQLITE_TESTCTRL_FAULT_INSTALL: {
29230          int kk;
29231          int bShowHelp = nArg<=2;
29232          isOk = 3;
29233          for(kk=2; kk<nArg; kk++){
29234            const char *z = azArg[kk];
29235            if( z[0]=='-' && z[1]=='-' ) z++;
29236            if( cli_strcmp(z,"off")==0 ){
29237              sqlite3_test_control(testctrl, 0);
29238            }else if( cli_strcmp(z,"on")==0 ){
29239              faultsim_state.iCnt = faultsim_state.nSkip;
29240              if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1;
29241              faultsim_state.nHit = 0;
29242              sqlite3_test_control(testctrl, faultsim_callback);
29243            }else if( cli_strcmp(z,"reset")==0 ){
29244              faultsim_state.iCnt = faultsim_state.nSkip;
29245              faultsim_state.nHit = 0;
29246              sqlite3_test_control(testctrl, faultsim_callback);
29247            }else if( cli_strcmp(z,"status")==0 ){
29248              oputf("faultsim.iId:       %d\n", faultsim_state.iId);
29249              oputf("faultsim.iErr:      %d\n", faultsim_state.iErr);
29250              oputf("faultsim.iCnt:      %d\n", faultsim_state.iCnt);
29251              oputf("faultsim.nHit:      %d\n", faultsim_state.nHit);
29252              oputf("faultsim.iInterval: %d\n", faultsim_state.iInterval);
29253              oputf("faultsim.eVerbose:  %d\n", faultsim_state.eVerbose);
29254              oputf("faultsim.nRepeat:   %d\n", faultsim_state.nRepeat);
29255              oputf("faultsim.nSkip:     %d\n", faultsim_state.nSkip);
29256            }else if( cli_strcmp(z,"-v")==0 ){
29257              if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++;
29258            }else if( cli_strcmp(z,"-q")==0 ){
29259              if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--;
29260            }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){
29261              faultsim_state.iId = atoi(azArg[++kk]);
29262            }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){
29263              faultsim_state.iErr = atoi(azArg[++kk]);
29264            }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){
29265              faultsim_state.iInterval = atoi(azArg[++kk]);
29266            }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){
29267              faultsim_state.nRepeat = atoi(azArg[++kk]);
29268           }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){
29269              faultsim_state.nSkip = atoi(azArg[++kk]);
29270            }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){
29271              bShowHelp = 1;
29272            }else{
29273              eputf("Unrecognized fault_install argument: \"%s\"\n",
29274                  azArg[kk]);
29275              rc = 1;
29276              bShowHelp = 1;
29277              break;
29278            }
29279          }
29280          if( bShowHelp ){
29281            oputz(
29282               "Usage: .testctrl fault_install ARGS\n"
29283               "Possible arguments:\n"
29284               "   off               Disable faultsim\n"
29285               "   on                Activate faultsim\n"
29286               "   reset             Reset the trigger counter\n"
29287               "   status            Show current status\n"
29288               "   -v                Increase verbosity\n"
29289               "   -q                Decrease verbosity\n"
29290               "   --errcode N       When triggered, return N as error code\n"
29291               "   --id ID           Trigger only for the ID specified\n"
29292               "   --interval N      Trigger only after every N-th call\n"
29293               "   --repeat N        Turn off after N hits.  0 means never\n"
29294               "   --skip N          Skip the first N encounters\n"
29295            );
29296          }
29297          break;
29298        }
29299      }
29300    }
29301    if( isOk==0 && iCtrl>=0 ){
29302      oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
29303      rc = 1;
29304    }else if( isOk==1 ){
29305      oputf("%d\n", rc2);
29306    }else if( isOk==2 ){
29307      oputf("0x%08x\n", rc2);
29308    }
29309  }else
29310#endif /* !defined(SQLITE_UNTESTABLE) */
29311
29312  if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
29313    open_db(p, 0);
29314    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
29315  }else
29316
29317  if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
29318    if( nArg==2 ){
29319      enableTimer = booleanValue(azArg[1]);
29320      if( enableTimer && !HAS_TIMER ){
29321        eputz("Error: timer not available on this system.\n");
29322        enableTimer = 0;
29323      }
29324    }else{
29325      eputz("Usage: .timer on|off\n");
29326      rc = 1;
29327    }
29328  }else
29329
29330#ifndef SQLITE_OMIT_TRACE
29331  if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
29332    int mType = 0;
29333    int jj;
29334    open_db(p, 0);
29335    for(jj=1; jj<nArg; jj++){
29336      const char *z = azArg[jj];
29337      if( z[0]=='-' ){
29338        if( optionMatch(z, "expanded") ){
29339          p->eTraceType = SHELL_TRACE_EXPANDED;
29340        }
29341#ifdef SQLITE_ENABLE_NORMALIZE
29342        else if( optionMatch(z, "normalized") ){
29343          p->eTraceType = SHELL_TRACE_NORMALIZED;
29344        }
29345#endif
29346        else if( optionMatch(z, "plain") ){
29347          p->eTraceType = SHELL_TRACE_PLAIN;
29348        }
29349        else if( optionMatch(z, "profile") ){
29350          mType |= SQLITE_TRACE_PROFILE;
29351        }
29352        else if( optionMatch(z, "row") ){
29353          mType |= SQLITE_TRACE_ROW;
29354        }
29355        else if( optionMatch(z, "stmt") ){
29356          mType |= SQLITE_TRACE_STMT;
29357        }
29358        else if( optionMatch(z, "close") ){
29359          mType |= SQLITE_TRACE_CLOSE;
29360        }
29361        else {
29362          eputf("Unknown option \"%s\" on \".trace\"\n", z);
29363          rc = 1;
29364          goto meta_command_exit;
29365        }
29366      }else{
29367        output_file_close(p->traceOut);
29368        p->traceOut = output_file_open(z, 0);
29369      }
29370    }
29371    if( p->traceOut==0 ){
29372      sqlite3_trace_v2(p->db, 0, 0, 0);
29373    }else{
29374      if( mType==0 ) mType = SQLITE_TRACE_STMT;
29375      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
29376    }
29377  }else
29378#endif /* !defined(SQLITE_OMIT_TRACE) */
29379
29380#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
29381  if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
29382    int ii;
29383    int lenOpt;
29384    char *zOpt;
29385    if( nArg<2 ){
29386      eputz("Usage: .unmodule [--allexcept] NAME ...\n");
29387      rc = 1;
29388      goto meta_command_exit;
29389    }
29390    open_db(p, 0);
29391    zOpt = azArg[1];
29392    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
29393    lenOpt = (int)strlen(zOpt);
29394    if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
29395      assert( azArg[nArg]==0 );
29396      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
29397    }else{
29398      for(ii=1; ii<nArg; ii++){
29399        sqlite3_create_module(p->db, azArg[ii], 0, 0);
29400      }
29401    }
29402  }else
29403#endif
29404
29405#if SQLITE_USER_AUTHENTICATION
29406  if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
29407    if( nArg<2 ){
29408      eputz("Usage: .user SUBCOMMAND ...\n");
29409      rc = 1;
29410      goto meta_command_exit;
29411    }
29412    open_db(p, 0);
29413    if( cli_strcmp(azArg[1],"login")==0 ){
29414      if( nArg!=4 ){
29415        eputz("Usage: .user login USER PASSWORD\n");
29416        rc = 1;
29417        goto meta_command_exit;
29418      }
29419      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
29420                                     strlen30(azArg[3]));
29421      if( rc ){
29422        eputf("Authentication failed for user %s\n", azArg[2]);
29423        rc = 1;
29424      }
29425    }else if( cli_strcmp(azArg[1],"add")==0 ){
29426      if( nArg!=5 ){
29427        eputz("Usage: .user add USER PASSWORD ISADMIN\n");
29428        rc = 1;
29429        goto meta_command_exit;
29430      }
29431      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
29432                            booleanValue(azArg[4]));
29433      if( rc ){
29434        eputf("User-Add failed: %d\n", rc);
29435        rc = 1;
29436      }
29437    }else if( cli_strcmp(azArg[1],"edit")==0 ){
29438      if( nArg!=5 ){
29439        eputz("Usage: .user edit USER PASSWORD ISADMIN\n");
29440        rc = 1;
29441        goto meta_command_exit;
29442      }
29443      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
29444                              booleanValue(azArg[4]));
29445      if( rc ){
29446        eputf("User-Edit failed: %d\n", rc);
29447        rc = 1;
29448      }
29449    }else if( cli_strcmp(azArg[1],"delete")==0 ){
29450      if( nArg!=3 ){
29451        eputz("Usage: .user delete USER\n");
29452        rc = 1;
29453        goto meta_command_exit;
29454      }
29455      rc = sqlite3_user_delete(p->db, azArg[2]);
29456      if( rc ){
29457        eputf("User-Delete failed: %d\n", rc);
29458        rc = 1;
29459      }
29460    }else{
29461      eputz("Usage: .user login|add|edit|delete ...\n");
29462      rc = 1;
29463      goto meta_command_exit;
29464    }
29465  }else
29466#endif /* SQLITE_USER_AUTHENTICATION */
29467
29468  if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
29469    char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit";
29470    oputf("SQLite %s %s\n" /*extra-version-info*/,
29471          sqlite3_libversion(), sqlite3_sourceid());
29472#if SQLITE_HAVE_ZLIB
29473    oputf("zlib version %s\n", zlibVersion());
29474#endif
29475#define CTIMEOPT_VAL_(opt) #opt
29476#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
29477#if defined(__clang__) && defined(__clang_major__)
29478    oputf("clang-" CTIMEOPT_VAL(__clang_major__) "."
29479          CTIMEOPT_VAL(__clang_minor__) "."
29480          CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz);
29481#elif defined(_MSC_VER)
29482    oputf("msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz);
29483#elif defined(__GNUC__) && defined(__VERSION__)
29484    oputf("gcc-" __VERSION__ " (%s)\n", zPtrSz);
29485#endif
29486  }else
29487
29488  if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
29489    const char *zDbName = nArg==2 ? azArg[1] : "main";
29490    sqlite3_vfs *pVfs = 0;
29491    if( p->db ){
29492      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
29493      if( pVfs ){
29494        oputf("vfs.zName      = \"%s\"\n", pVfs->zName);
29495        oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
29496        oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
29497        oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
29498      }
29499    }
29500  }else
29501
29502  if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
29503    sqlite3_vfs *pVfs;
29504    sqlite3_vfs *pCurrent = 0;
29505    if( p->db ){
29506      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
29507    }
29508    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
29509      oputf("vfs.zName      = \"%s\"%s\n", pVfs->zName,
29510            pVfs==pCurrent ? "  <--- CURRENT" : "");
29511      oputf("vfs.iVersion   = %d\n", pVfs->iVersion);
29512      oputf("vfs.szOsFile   = %d\n", pVfs->szOsFile);
29513      oputf("vfs.mxPathname = %d\n", pVfs->mxPathname);
29514      if( pVfs->pNext ){
29515        oputz("-----------------------------------\n");
29516      }
29517    }
29518  }else
29519
29520  if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
29521    const char *zDbName = nArg==2 ? azArg[1] : "main";
29522    char *zVfsName = 0;
29523    if( p->db ){
29524      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
29525      if( zVfsName ){
29526        oputf("%s\n", zVfsName);
29527        sqlite3_free(zVfsName);
29528      }
29529    }
29530  }else
29531
29532  if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
29533    unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
29534    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
29535  }else
29536
29537  if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
29538    int j;
29539    assert( nArg<=ArraySize(azArg) );
29540    p->nWidth = nArg-1;
29541    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
29542    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
29543    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
29544    for(j=1; j<nArg; j++){
29545      p->colWidth[j-1] = (int)integerValue(azArg[j]);
29546    }
29547  }else
29548
29549  {
29550    eputf("Error: unknown command or invalid arguments: "
29551          " \"%s\". Enter \".help\" for help\n", azArg[0]);
29552    rc = 1;
29553  }
29554
29555meta_command_exit:
29556  if( p->outCount ){
29557    p->outCount--;
29558    if( p->outCount==0 ) output_reset(p);
29559  }
29560  p->bSafeMode = p->bSafeModePersist;
29561  return rc;
29562}
29563
29564/* Line scan result and intermediate states (supporting scan resumption)
29565*/
29566#ifndef CHAR_BIT
29567# define CHAR_BIT 8
29568#endif
29569typedef enum {
29570  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
29571  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
29572  QSS_Start = 0
29573} QuickScanState;
29574#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
29575#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
29576#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
29577#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
29578#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
29579
29580/*
29581** Scan line for classification to guide shell's handling.
29582** The scan is resumable for subsequent lines when prior
29583** return values are passed as the 2nd argument.
29584*/
29585static QuickScanState quickscan(char *zLine, QuickScanState qss,
29586                                SCAN_TRACKER_REFTYPE pst){
29587  char cin;
29588  char cWait = (char)qss; /* intentional narrowing loss */
29589  if( cWait==0 ){
29590  PlainScan:
29591    assert( cWait==0 );
29592    while( (cin = *zLine++)!=0 ){
29593      if( IsSpace(cin) )
29594        continue;
29595      switch (cin){
29596      case '-':
29597        if( *zLine!='-' )
29598          break;
29599        while((cin = *++zLine)!=0 )
29600          if( cin=='\n')
29601            goto PlainScan;
29602        return qss;
29603      case ';':
29604        qss |= QSS_EndingSemi;
29605        continue;
29606      case '/':
29607        if( *zLine=='*' ){
29608          ++zLine;
29609          cWait = '*';
29610          CONTINUE_PROMPT_AWAITS(pst, "/*");
29611          qss = QSS_SETV(qss, cWait);
29612          goto TermScan;
29613        }
29614        break;
29615      case '[':
29616        cin = ']';
29617        deliberate_fall_through;
29618      case '`': case '\'': case '"':
29619        cWait = cin;
29620        qss = QSS_HasDark | cWait;
29621        CONTINUE_PROMPT_AWAITC(pst, cin);
29622        goto TermScan;
29623      case '(':
29624        CONTINUE_PAREN_INCR(pst, 1);
29625        break;
29626      case ')':
29627        CONTINUE_PAREN_INCR(pst, -1);
29628        break;
29629      default:
29630        break;
29631      }
29632      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
29633    }
29634  }else{
29635  TermScan:
29636    while( (cin = *zLine++)!=0 ){
29637      if( cin==cWait ){
29638        switch( cWait ){
29639        case '*':
29640          if( *zLine != '/' )
29641            continue;
29642          ++zLine;
29643          cWait = 0;
29644          CONTINUE_PROMPT_AWAITC(pst, 0);
29645          qss = QSS_SETV(qss, 0);
29646          goto PlainScan;
29647        case '`': case '\'': case '"':
29648          if(*zLine==cWait){
29649            /* Swallow doubled end-delimiter.*/
29650            ++zLine;
29651            continue;
29652          }
29653          deliberate_fall_through;
29654        case ']':
29655          cWait = 0;
29656          CONTINUE_PROMPT_AWAITC(pst, 0);
29657          qss = QSS_SETV(qss, 0);
29658          goto PlainScan;
29659        default: assert(0);
29660        }
29661      }
29662    }
29663  }
29664  return qss;
29665}
29666
29667/*
29668** Return TRUE if the line typed in is an SQL command terminator other
29669** than a semi-colon.  The SQL Server style "go" command is understood
29670** as is the Oracle "/".
29671*/
29672static int line_is_command_terminator(char *zLine){
29673  while( IsSpace(zLine[0]) ){ zLine++; };
29674  if( zLine[0]=='/' )
29675    zLine += 1; /* Oracle */
29676  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
29677    zLine += 2; /* SQL Server */
29678  else
29679    return 0;
29680  return quickscan(zLine, QSS_Start, 0)==QSS_Start;
29681}
29682
29683/*
29684** The CLI needs a working sqlite3_complete() to work properly.  So error
29685** out of the build if compiling with SQLITE_OMIT_COMPLETE.
29686*/
29687#ifdef SQLITE_OMIT_COMPLETE
29688# error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE.
29689#endif
29690
29691/*
29692** Return true if zSql is a complete SQL statement.  Return false if it
29693** ends in the middle of a string literal or C-style comment.
29694*/
29695static int line_is_complete(char *zSql, int nSql){
29696  int rc;
29697  if( zSql==0 ) return 1;
29698  zSql[nSql] = ';';
29699  zSql[nSql+1] = 0;
29700  rc = sqlite3_complete(zSql);
29701  zSql[nSql] = 0;
29702  return rc;
29703}
29704
29705/*
29706** This function is called after processing each line of SQL in the
29707** runOneSqlLine() function. Its purpose is to detect scenarios where
29708** defensive mode should be automatically turned off. Specifically, when
29709**
29710**   1. The first line of input is "PRAGMA foreign_keys=OFF;",
29711**   2. The second line of input is "BEGIN TRANSACTION;",
29712**   3. The database is empty, and
29713**   4. The shell is not running in --safe mode.
29714**
29715** The implementation uses the ShellState.eRestoreState to maintain state:
29716**
29717**    0: Have not seen any SQL.
29718**    1: Have seen "PRAGMA foreign_keys=OFF;".
29719**    2-6: Currently running .dump transaction. If the "2" bit is set,
29720**         disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
29721**    7: Nothing left to do. This function becomes a no-op.
29722*/
29723static int doAutoDetectRestore(ShellState *p, const char *zSql){
29724  int rc = SQLITE_OK;
29725
29726  if( p->eRestoreState<7 ){
29727    switch( p->eRestoreState ){
29728      case 0: {
29729        const char *zExpect = "PRAGMA foreign_keys=OFF;";
29730        assert( strlen(zExpect)==24 );
29731        if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
29732          p->eRestoreState = 1;
29733        }else{
29734          p->eRestoreState = 7;
29735        }
29736        break;
29737      };
29738
29739      case 1: {
29740        int bIsDump = 0;
29741        const char *zExpect = "BEGIN TRANSACTION;";
29742        assert( strlen(zExpect)==18 );
29743        if( memcmp(zSql, zExpect, 19)==0 ){
29744          /* Now check if the database is empty. */
29745          const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
29746          sqlite3_stmt *pStmt = 0;
29747
29748          bIsDump = 1;
29749          shellPrepare(p->db, &rc, zQuery, &pStmt);
29750          if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
29751            bIsDump = 0;
29752          }
29753          shellFinalize(&rc, pStmt);
29754        }
29755        if( bIsDump && rc==SQLITE_OK ){
29756          int bDefense = 0;
29757          int bDqsDdl = 0;
29758          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
29759          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
29760          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
29761          sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
29762          p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
29763        }else{
29764          p->eRestoreState = 7;
29765        }
29766        break;
29767      }
29768
29769      default: {
29770        if( sqlite3_get_autocommit(p->db) ){
29771          if( (p->eRestoreState & 2) ){
29772            sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
29773          }
29774          if( (p->eRestoreState & 4) ){
29775            sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
29776          }
29777          p->eRestoreState = 7;
29778        }
29779        break;
29780      }
29781    }
29782  }
29783
29784  return rc;
29785}
29786
29787/*
29788** Run a single line of SQL.  Return the number of errors.
29789*/
29790static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
29791  int rc;
29792  char *zErrMsg = 0;
29793
29794  open_db(p, 0);
29795  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
29796  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
29797  BEGIN_TIMER;
29798  rc = shell_exec(p, zSql, &zErrMsg);
29799  END_TIMER;
29800  if( rc || zErrMsg ){
29801    char zPrefix[100];
29802    const char *zErrorTail;
29803    const char *zErrorType;
29804    if( zErrMsg==0 ){
29805      zErrorType = "Error";
29806      zErrorTail = sqlite3_errmsg(p->db);
29807    }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
29808      zErrorType = "Parse error";
29809      zErrorTail = &zErrMsg[12];
29810    }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
29811      zErrorType = "Runtime error";
29812      zErrorTail = &zErrMsg[10];
29813    }else{
29814      zErrorType = "Error";
29815      zErrorTail = zErrMsg;
29816    }
29817    if( in!=0 || !stdin_is_interactive ){
29818      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
29819                       "%s near line %d:", zErrorType, startline);
29820    }else{
29821      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
29822    }
29823    eputf("%s %s\n", zPrefix, zErrorTail);
29824    sqlite3_free(zErrMsg);
29825    zErrMsg = 0;
29826    return 1;
29827  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
29828    char zLineBuf[2000];
29829    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
29830            "changes: %lld   total_changes: %lld",
29831            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
29832    oputf("%s\n", zLineBuf);
29833  }
29834
29835  if( doAutoDetectRestore(p, zSql) ) return 1;
29836  return 0;
29837}
29838
29839static void echo_group_input(ShellState *p, const char *zDo){
29840  if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
29841}
29842
29843#ifdef SQLITE_SHELL_FIDDLE
29844/*
29845** Alternate one_input_line() impl for wasm mode. This is not in the primary
29846** impl because we need the global shellState and cannot access it from that
29847** function without moving lots of code around (creating a larger/messier diff).
29848*/
29849static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
29850  /* Parse the next line from shellState.wasm.zInput. */
29851  const char *zBegin = shellState.wasm.zPos;
29852  const char *z = zBegin;
29853  char *zLine = 0;
29854  i64 nZ = 0;
29855
29856  UNUSED_PARAMETER(in);
29857  UNUSED_PARAMETER(isContinuation);
29858  if(!z || !*z){
29859    return 0;
29860  }
29861  while(*z && isspace(*z)) ++z;
29862  zBegin = z;
29863  for(; *z && '\n'!=*z; ++nZ, ++z){}
29864  if(nZ>0 && '\r'==zBegin[nZ-1]){
29865    --nZ;
29866  }
29867  shellState.wasm.zPos = z;
29868  zLine = realloc(zPrior, nZ+1);
29869  shell_check_oom(zLine);
29870  memcpy(zLine, zBegin, nZ);
29871  zLine[nZ] = 0;
29872  return zLine;
29873}
29874#endif /* SQLITE_SHELL_FIDDLE */
29875
29876/*
29877** Read input from *in and process it.  If *in==0 then input
29878** is interactive - the user is typing it it.  Otherwise, input
29879** is coming from a file or device.  A prompt is issued and history
29880** is saved only if input is interactive.  An interrupt signal will
29881** cause this routine to exit immediately, unless input is interactive.
29882**
29883** Return the number of errors.
29884*/
29885static int process_input(ShellState *p){
29886  char *zLine = 0;          /* A single input line */
29887  char *zSql = 0;           /* Accumulated SQL text */
29888  i64 nLine;                /* Length of current line */
29889  i64 nSql = 0;             /* Bytes of zSql[] used */
29890  i64 nAlloc = 0;           /* Allocated zSql[] space */
29891  int rc;                   /* Error code */
29892  int errCnt = 0;           /* Number of errors seen */
29893  i64 startline = 0;        /* Line number for start of current input */
29894  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
29895
29896  if( p->inputNesting==MAX_INPUT_NESTING ){
29897    /* This will be more informative in a later version. */
29898    eputf("Input nesting limit (%d) reached at line %d."
29899          " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
29900    return 1;
29901  }
29902  ++p->inputNesting;
29903  p->lineno = 0;
29904  CONTINUE_PROMPT_RESET;
29905  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
29906    fflush(p->out);
29907    zLine = one_input_line(p->in, zLine, nSql>0);
29908    if( zLine==0 ){
29909      /* End of input */
29910      if( p->in==0 && stdin_is_interactive ) oputz("\n");
29911      break;
29912    }
29913    if( seenInterrupt ){
29914      if( p->in!=0 ) break;
29915      seenInterrupt = 0;
29916    }
29917    p->lineno++;
29918    if( QSS_INPLAIN(qss)
29919        && line_is_command_terminator(zLine)
29920        && line_is_complete(zSql, nSql) ){
29921      memcpy(zLine,";",2);
29922    }
29923    qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE);
29924    if( QSS_PLAINWHITE(qss) && nSql==0 ){
29925      /* Just swallow single-line whitespace */
29926      echo_group_input(p, zLine);
29927      qss = QSS_Start;
29928      continue;
29929    }
29930    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
29931      CONTINUE_PROMPT_RESET;
29932      echo_group_input(p, zLine);
29933      if( zLine[0]=='.' ){
29934        rc = do_meta_command(zLine, p);
29935        if( rc==2 ){ /* exit requested */
29936          break;
29937        }else if( rc ){
29938          errCnt++;
29939        }
29940      }
29941      qss = QSS_Start;
29942      continue;
29943    }
29944    /* No single-line dispositions remain; accumulate line(s). */
29945    nLine = strlen(zLine);
29946    if( nSql+nLine+2>=nAlloc ){
29947      /* Grow buffer by half-again increments when big. */
29948      nAlloc = nSql+(nSql>>1)+nLine+100;
29949      zSql = realloc(zSql, nAlloc);
29950      shell_check_oom(zSql);
29951    }
29952    if( nSql==0 ){
29953      i64 i;
29954      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
29955      assert( nAlloc>0 && zSql!=0 );
29956      memcpy(zSql, zLine+i, nLine+1-i);
29957      startline = p->lineno;
29958      nSql = nLine-i;
29959    }else{
29960      zSql[nSql++] = '\n';
29961      memcpy(zSql+nSql, zLine, nLine+1);
29962      nSql += nLine;
29963    }
29964    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
29965      echo_group_input(p, zSql);
29966      errCnt += runOneSqlLine(p, zSql, p->in, startline);
29967      CONTINUE_PROMPT_RESET;
29968      nSql = 0;
29969      if( p->outCount ){
29970        output_reset(p);
29971        p->outCount = 0;
29972      }else{
29973        clearTempFile(p);
29974      }
29975      p->bSafeMode = p->bSafeModePersist;
29976      qss = QSS_Start;
29977    }else if( nSql && QSS_PLAINWHITE(qss) ){
29978      echo_group_input(p, zSql);
29979      nSql = 0;
29980      qss = QSS_Start;
29981    }
29982  }
29983  if( nSql ){
29984    /* This may be incomplete. Let the SQL parser deal with that. */
29985    echo_group_input(p, zSql);
29986    errCnt += runOneSqlLine(p, zSql, p->in, startline);
29987    CONTINUE_PROMPT_RESET;
29988  }
29989  free(zSql);
29990  free(zLine);
29991  --p->inputNesting;
29992  return errCnt>0;
29993}
29994
29995/*
29996** Return a pathname which is the user's home directory.  A
29997** 0 return indicates an error of some kind.
29998*/
29999static char *find_home_dir(int clearFlag){
30000  static char *home_dir = NULL;
30001  if( clearFlag ){
30002    free(home_dir);
30003    home_dir = 0;
30004    return 0;
30005  }
30006  if( home_dir ) return home_dir;
30007
30008#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
30009     && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI)
30010  {
30011    struct passwd *pwent;
30012    uid_t uid = getuid();
30013    if( (pwent=getpwuid(uid)) != NULL) {
30014      home_dir = pwent->pw_dir;
30015    }
30016  }
30017#endif
30018
30019#if defined(_WIN32_WCE)
30020  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
30021   */
30022  home_dir = "/";
30023#else
30024
30025#if defined(_WIN32) || defined(WIN32)
30026  if (!home_dir) {
30027    home_dir = getenv("USERPROFILE");
30028  }
30029#endif
30030
30031  if (!home_dir) {
30032    home_dir = getenv("HOME");
30033  }
30034
30035#if defined(_WIN32) || defined(WIN32)
30036  if (!home_dir) {
30037    char *zDrive, *zPath;
30038    int n;
30039    zDrive = getenv("HOMEDRIVE");
30040    zPath = getenv("HOMEPATH");
30041    if( zDrive && zPath ){
30042      n = strlen30(zDrive) + strlen30(zPath) + 1;
30043      home_dir = malloc( n );
30044      if( home_dir==0 ) return 0;
30045      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
30046      return home_dir;
30047    }
30048    home_dir = "c:\\";
30049  }
30050#endif
30051
30052#endif /* !_WIN32_WCE */
30053
30054  if( home_dir ){
30055    i64 n = strlen(home_dir) + 1;
30056    char *z = malloc( n );
30057    if( z ) memcpy(z, home_dir, n);
30058    home_dir = z;
30059  }
30060
30061  return home_dir;
30062}
30063
30064/*
30065** On non-Windows platforms, look for $XDG_CONFIG_HOME.
30066** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return
30067** the path to it, else return 0. The result is cached for
30068** subsequent calls.
30069*/
30070static const char *find_xdg_config(void){
30071#if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \
30072     || defined(__RTP__) || defined(_WRS_KERNEL)
30073  return 0;
30074#else
30075  static int alreadyTried = 0;
30076  static char *zConfig = 0;
30077  const char *zXdgHome;
30078
30079  if( alreadyTried!=0 ){
30080    return zConfig;
30081  }
30082  alreadyTried = 1;
30083  zXdgHome = getenv("XDG_CONFIG_HOME");
30084  if( zXdgHome==0 ){
30085    return 0;
30086  }
30087  zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome);
30088  shell_check_oom(zConfig);
30089  if( access(zConfig,0)!=0 ){
30090    sqlite3_free(zConfig);
30091    zConfig = 0;
30092  }
30093  return zConfig;
30094#endif
30095}
30096
30097/*
30098** Read input from the file given by sqliterc_override.  Or if that
30099** parameter is NULL, take input from the first of find_xdg_config()
30100** or ~/.sqliterc which is found.
30101**
30102** Returns the number of errors.
30103*/
30104static void process_sqliterc(
30105  ShellState *p,                  /* Configuration data */
30106  const char *sqliterc_override   /* Name of config file. NULL to use default */
30107){
30108  char *home_dir = NULL;
30109  const char *sqliterc = sqliterc_override;
30110  char *zBuf = 0;
30111  FILE *inSaved = p->in;
30112  int savedLineno = p->lineno;
30113
30114  if( sqliterc == NULL ){
30115    sqliterc = find_xdg_config();
30116  }
30117  if( sqliterc == NULL ){
30118    home_dir = find_home_dir(0);
30119    if( home_dir==0 ){
30120      eputz("-- warning: cannot find home directory;"
30121            " cannot read ~/.sqliterc\n");
30122      return;
30123    }
30124    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
30125    shell_check_oom(zBuf);
30126    sqliterc = zBuf;
30127  }
30128  p->in = fopen(sqliterc,"rb");
30129  if( p->in ){
30130    if( stdin_is_interactive ){
30131      eputf("-- Loading resources from %s\n", sqliterc);
30132    }
30133    if( process_input(p) && bail_on_error ) exit(1);
30134    fclose(p->in);
30135  }else if( sqliterc_override!=0 ){
30136    eputf("cannot open: \"%s\"\n", sqliterc);
30137    if( bail_on_error ) exit(1);
30138  }
30139  p->in = inSaved;
30140  p->lineno = savedLineno;
30141  sqlite3_free(zBuf);
30142}
30143
30144/*
30145** Show available command line options
30146*/
30147static const char zOptions[] =
30148  "   --                   treat no subsequent arguments as options\n"
30149#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
30150  "   -A ARGS...           run \".archive ARGS\" and exit\n"
30151#endif
30152  "   -append              append the database to the end of the file\n"
30153  "   -ascii               set output mode to 'ascii'\n"
30154  "   -bail                stop after hitting an error\n"
30155  "   -batch               force batch I/O\n"
30156  "   -box                 set output mode to 'box'\n"
30157  "   -column              set output mode to 'column'\n"
30158  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
30159  "   -csv                 set output mode to 'csv'\n"
30160#if !defined(SQLITE_OMIT_DESERIALIZE)
30161  "   -deserialize         open the database using sqlite3_deserialize()\n"
30162#endif
30163  "   -echo                print inputs before execution\n"
30164  "   -init FILENAME       read/process named file\n"
30165  "   -[no]header          turn headers on or off\n"
30166#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
30167  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
30168#endif
30169  "   -help                show this message\n"
30170  "   -html                set output mode to HTML\n"
30171  "   -interactive         force interactive I/O\n"
30172  "   -json                set output mode to 'json'\n"
30173  "   -line                set output mode to 'line'\n"
30174  "   -list                set output mode to 'list'\n"
30175  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
30176  "   -markdown            set output mode to 'markdown'\n"
30177#if !defined(SQLITE_OMIT_DESERIALIZE)
30178  "   -maxsize N           maximum size for a --deserialize database\n"
30179#endif
30180  "   -memtrace            trace all memory allocations and deallocations\n"
30181  "   -mmap N              default mmap size set to N\n"
30182#ifdef SQLITE_ENABLE_MULTIPLEX
30183  "   -multiplex           enable the multiplexor VFS\n"
30184#endif
30185  "   -newline SEP         set output row separator. Default: '\\n'\n"
30186  "   -nofollow            refuse to open symbolic links to database files\n"
30187  "   -nonce STRING        set the safe-mode escape nonce\n"
30188  "   -no-rowid-in-view    Disable rowid-in-view using sqlite3_config()\n"
30189  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
30190  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
30191  "   -pcachetrace         trace all page cache operations\n"
30192  "   -quote               set output mode to 'quote'\n"
30193  "   -readonly            open the database read-only\n"
30194  "   -safe                enable safe-mode\n"
30195  "   -separator SEP       set output column separator. Default: '|'\n"
30196#ifdef SQLITE_ENABLE_SORTER_REFERENCES
30197  "   -sorterref SIZE      sorter references threshold size\n"
30198#endif
30199  "   -stats               print memory stats before each finalize\n"
30200  "   -table               set output mode to 'table'\n"
30201  "   -tabs                set output mode to 'tabs'\n"
30202  "   -unsafe-testing      allow unsafe commands and modes for testing\n"
30203  "   -version             show SQLite version\n"
30204  "   -vfs NAME            use NAME as the default VFS\n"
30205#ifdef SQLITE_ENABLE_VFSTRACE
30206  "   -vfstrace            enable tracing of all VFS calls\n"
30207#endif
30208#ifdef SQLITE_HAVE_ZLIB
30209  "   -zip                 open the file as a ZIP Archive\n"
30210#endif
30211;
30212static void usage(int showDetail){
30213  eputf("Usage: %s [OPTIONS] [FILENAME [SQL]]\n"
30214       "FILENAME is the name of an SQLite database. A new database is created\n"
30215       "if the file does not previously exist. Defaults to :memory:.\n", Argv0);
30216  if( showDetail ){
30217    eputf("OPTIONS include:\n%s", zOptions);
30218  }else{
30219    eputz("Use the -help option for additional information\n");
30220  }
30221  exit(0);
30222}
30223
30224/*
30225** Internal check:  Verify that the SQLite is uninitialized.  Print a
30226** error message if it is initialized.
30227*/
30228static void verify_uninitialized(void){
30229  if( sqlite3_config(-1)==SQLITE_MISUSE ){
30230    sputz(stdout, "WARNING: attempt to configure SQLite after"
30231          " initialization.\n");
30232  }
30233}
30234
30235/*
30236** Initialize the state information in data
30237*/
30238static void main_init(ShellState *data) {
30239  memset(data, 0, sizeof(*data));
30240  data->normalMode = data->cMode = data->mode = MODE_List;
30241  data->autoExplain = 1;
30242  data->pAuxDb = &data->aAuxDb[0];
30243  memcpy(data->colSeparator,SEP_Column, 2);
30244  memcpy(data->rowSeparator,SEP_Row, 2);
30245  data->showHeader = 0;
30246  data->shellFlgs = SHFLG_Lookaside;
30247  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
30248#if !defined(SQLITE_SHELL_FIDDLE)
30249  verify_uninitialized();
30250#endif
30251  sqlite3_config(SQLITE_CONFIG_URI, 1);
30252  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
30253  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
30254  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
30255}
30256
30257/*
30258** Output text to the console in a font that attracts extra attention.
30259*/
30260#if defined(_WIN32) || defined(WIN32)
30261static void printBold(const char *zText){
30262#if !SQLITE_OS_WINRT
30263  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
30264  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
30265  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
30266  SetConsoleTextAttribute(out,
30267         FOREGROUND_RED|FOREGROUND_INTENSITY
30268  );
30269#endif
30270  sputz(stdout, zText);
30271#if !SQLITE_OS_WINRT
30272  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
30273#endif
30274}
30275#else
30276static void printBold(const char *zText){
30277  sputf(stdout, "\033[1m%s\033[0m", zText);
30278}
30279#endif
30280
30281/*
30282** Get the argument to an --option.  Throw an error and die if no argument
30283** is available.
30284*/
30285static char *cmdline_option_value(int argc, char **argv, int i){
30286  if( i==argc ){
30287    eputf("%s: Error: missing argument to %s\n", argv[0], argv[argc-1]);
30288    exit(1);
30289  }
30290  return argv[i];
30291}
30292
30293static void sayAbnormalExit(void){
30294  if( seenInterrupt ) eputz("Program interrupted.\n");
30295}
30296
30297#ifndef SQLITE_SHELL_IS_UTF8
30298#  if (defined(_WIN32) || defined(WIN32)) \
30299   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
30300#    define SQLITE_SHELL_IS_UTF8          (0)
30301#  else
30302#    define SQLITE_SHELL_IS_UTF8          (1)
30303#  endif
30304#endif
30305
30306#ifdef SQLITE_SHELL_FIDDLE
30307#  define main fiddle_main
30308#endif
30309
30310#if SQLITE_SHELL_IS_UTF8
30311int SQLITE_CDECL main(int argc, char **argv){
30312#else
30313int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
30314  char **argv;
30315#endif
30316#ifdef SQLITE_DEBUG
30317  sqlite3_int64 mem_main_enter = 0;
30318#endif
30319  char *zErrMsg = 0;
30320#ifdef SQLITE_SHELL_FIDDLE
30321#  define data shellState
30322#else
30323  ShellState data;
30324  StreamsAreConsole consStreams = SAC_NoConsole;
30325#endif
30326  const char *zInitFile = 0;
30327  int i;
30328  int rc = 0;
30329  int warnInmemoryDb = 0;
30330  int readStdin = 1;
30331  int nCmd = 0;
30332  int nOptsEnd = argc;
30333  char **azCmd = 0;
30334  const char *zVfs = 0;           /* Value of -vfs command-line option */
30335#if !SQLITE_SHELL_IS_UTF8
30336  char **argvToFree = 0;
30337  int argcToFree = 0;
30338#endif
30339  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
30340
30341#ifdef SQLITE_SHELL_FIDDLE
30342  stdin_is_interactive = 0;
30343  stdout_is_console = 1;
30344  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
30345#else
30346  consStreams = consoleClassifySetup(stdin, stdout, stderr);
30347  stdin_is_interactive = (consStreams & SAC_InConsole)!=0;
30348  stdout_is_console = (consStreams & SAC_OutConsole)!=0;
30349  atexit(consoleRestore);
30350#endif
30351  atexit(sayAbnormalExit);
30352#ifdef SQLITE_DEBUG
30353  mem_main_enter = sqlite3_memory_used();
30354#endif
30355#if !defined(_WIN32_WCE)
30356  if( getenv("SQLITE_DEBUG_BREAK") ){
30357    if( isatty(0) && isatty(2) ){
30358      eputf("attach debugger to process %d and press any key to continue.\n",
30359            GETPID());
30360      fgetc(stdin);
30361    }else{
30362#if defined(_WIN32) || defined(WIN32)
30363#if SQLITE_OS_WINRT
30364      __debugbreak();
30365#else
30366      DebugBreak();
30367#endif
30368#elif defined(SIGTRAP)
30369      raise(SIGTRAP);
30370#endif
30371    }
30372  }
30373#endif
30374  /* Register a valid signal handler early, before much else is done. */
30375#ifdef SIGINT
30376  signal(SIGINT, interrupt_handler);
30377#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
30378  if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){
30379    eputz("No ^C handler.\n");
30380  }
30381#endif
30382
30383#if USE_SYSTEM_SQLITE+0!=1
30384  if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
30385    eputf("SQLite header and source version mismatch\n%s\n%s\n",
30386          sqlite3_sourceid(), SQLITE_SOURCE_ID);
30387    exit(1);
30388  }
30389#endif
30390  main_init(&data);
30391
30392  /* On Windows, we must translate command-line arguments into UTF-8.
30393  ** The SQLite memory allocator subsystem has to be enabled in order to
30394  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
30395  ** subsequent sqlite3_config() calls will work.  So copy all results into
30396  ** memory that does not come from the SQLite memory allocator.
30397  */
30398#if !SQLITE_SHELL_IS_UTF8
30399  sqlite3_initialize();
30400  argvToFree = malloc(sizeof(argv[0])*argc*2);
30401  shell_check_oom(argvToFree);
30402  argcToFree = argc;
30403  argv = argvToFree + argc;
30404  for(i=0; i<argc; i++){
30405    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
30406    i64 n;
30407    shell_check_oom(z);
30408    n = strlen(z);
30409    argv[i] = malloc( n+1 );
30410    shell_check_oom(argv[i]);
30411    memcpy(argv[i], z, n+1);
30412    argvToFree[i] = argv[i];
30413    sqlite3_free(z);
30414  }
30415  sqlite3_shutdown();
30416#endif
30417
30418  assert( argc>=1 && argv && argv[0] );
30419  Argv0 = argv[0];
30420
30421#ifdef SQLITE_SHELL_DBNAME_PROC
30422  {
30423    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
30424    ** of a C-function that will provide the name of the database file.  Use
30425    ** this compile-time option to embed this shell program in larger
30426    ** applications. */
30427    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
30428    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
30429    warnInmemoryDb = 0;
30430  }
30431#endif
30432
30433  /* Do an initial pass through the command-line argument to locate
30434  ** the name of the database file, the name of the initialization file,
30435  ** the size of the alternative malloc heap, options affecting commands
30436  ** or SQL run from the command line, and the first command to execute.
30437  */
30438#ifndef SQLITE_SHELL_FIDDLE
30439  verify_uninitialized();
30440#endif
30441  for(i=1; i<argc; i++){
30442    char *z;
30443    z = argv[i];
30444    if( z[0]!='-' || i>nOptsEnd ){
30445      if( data.aAuxDb->zDbFilename==0 ){
30446        data.aAuxDb->zDbFilename = z;
30447      }else{
30448        /* Excess arguments are interpreted as SQL (or dot-commands) and
30449        ** mean that nothing is read from stdin */
30450        readStdin = 0;
30451        nCmd++;
30452        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
30453        shell_check_oom(azCmd);
30454        azCmd[nCmd-1] = z;
30455      }
30456      continue;
30457    }
30458    if( z[1]=='-' ) z++;
30459    if( cli_strcmp(z, "-")==0 ){
30460      nOptsEnd = i;
30461      continue;
30462    }else if( cli_strcmp(z,"-separator")==0
30463     || cli_strcmp(z,"-nullvalue")==0
30464     || cli_strcmp(z,"-newline")==0
30465     || cli_strcmp(z,"-cmd")==0
30466    ){
30467      (void)cmdline_option_value(argc, argv, ++i);
30468    }else if( cli_strcmp(z,"-init")==0 ){
30469      zInitFile = cmdline_option_value(argc, argv, ++i);
30470    }else if( cli_strcmp(z,"-interactive")==0 ){
30471    }else if( cli_strcmp(z,"-batch")==0 ){
30472      /* Need to check for batch mode here to so we can avoid printing
30473      ** informational messages (like from process_sqliterc) before
30474      ** we do the actual processing of arguments later in a second pass.
30475      */
30476      stdin_is_interactive = 0;
30477    }else if( cli_strcmp(z,"-utf8")==0 ){
30478    }else if( cli_strcmp(z,"-no-utf8")==0 ){
30479    }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30480      int val = 0;
30481      sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val);
30482      assert( val==0 );
30483    }else if( cli_strcmp(z,"-heap")==0 ){
30484#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
30485      const char *zSize;
30486      sqlite3_int64 szHeap;
30487
30488      zSize = cmdline_option_value(argc, argv, ++i);
30489      szHeap = integerValue(zSize);
30490      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
30491      verify_uninitialized();
30492      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
30493#else
30494      (void)cmdline_option_value(argc, argv, ++i);
30495#endif
30496    }else if( cli_strcmp(z,"-pagecache")==0 ){
30497      sqlite3_int64 n, sz;
30498      sz = integerValue(cmdline_option_value(argc,argv,++i));
30499      if( sz>70000 ) sz = 70000;
30500      if( sz<0 ) sz = 0;
30501      n = integerValue(cmdline_option_value(argc,argv,++i));
30502      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
30503        n = 0xffffffffffffLL/sz;
30504      }
30505      verify_uninitialized();
30506      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
30507                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
30508      data.shellFlgs |= SHFLG_Pagecache;
30509    }else if( cli_strcmp(z,"-lookaside")==0 ){
30510      int n, sz;
30511      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
30512      if( sz<0 ) sz = 0;
30513      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
30514      if( n<0 ) n = 0;
30515      verify_uninitialized();
30516      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
30517      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
30518    }else if( cli_strcmp(z,"-threadsafe")==0 ){
30519      int n;
30520      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
30521      verify_uninitialized();
30522      switch( n ){
30523         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
30524         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
30525         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
30526      }
30527#ifdef SQLITE_ENABLE_VFSTRACE
30528    }else if( cli_strcmp(z,"-vfstrace")==0 ){
30529      extern int vfstrace_register(
30530         const char *zTraceName,
30531         const char *zOldVfsName,
30532         int (*xOut)(const char*,void*),
30533         void *pOutArg,
30534         int makeDefault
30535      );
30536      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
30537#endif
30538#ifdef SQLITE_ENABLE_MULTIPLEX
30539    }else if( cli_strcmp(z,"-multiplex")==0 ){
30540      extern int sqlite3_multiplex_initialize(const char*,int);
30541      sqlite3_multiplex_initialize(0, 1);
30542#endif
30543    }else if( cli_strcmp(z,"-mmap")==0 ){
30544      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
30545      verify_uninitialized();
30546      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
30547#if defined(SQLITE_ENABLE_SORTER_REFERENCES)
30548    }else if( cli_strcmp(z,"-sorterref")==0 ){
30549      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
30550      verify_uninitialized();
30551      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
30552#endif
30553    }else if( cli_strcmp(z,"-vfs")==0 ){
30554      zVfs = cmdline_option_value(argc, argv, ++i);
30555#ifdef SQLITE_HAVE_ZLIB
30556    }else if( cli_strcmp(z,"-zip")==0 ){
30557      data.openMode = SHELL_OPEN_ZIPFILE;
30558#endif
30559    }else if( cli_strcmp(z,"-append")==0 ){
30560      data.openMode = SHELL_OPEN_APPENDVFS;
30561#ifndef SQLITE_OMIT_DESERIALIZE
30562    }else if( cli_strcmp(z,"-deserialize")==0 ){
30563      data.openMode = SHELL_OPEN_DESERIALIZE;
30564    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30565      data.szMax = integerValue(argv[++i]);
30566#endif
30567    }else if( cli_strcmp(z,"-readonly")==0 ){
30568      data.openMode = SHELL_OPEN_READONLY;
30569    }else if( cli_strcmp(z,"-nofollow")==0 ){
30570      data.openFlags = SQLITE_OPEN_NOFOLLOW;
30571#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
30572    }else if( cli_strncmp(z, "-A",2)==0 ){
30573      /* All remaining command-line arguments are passed to the ".archive"
30574      ** command, so ignore them */
30575      break;
30576#endif
30577    }else if( cli_strcmp(z, "-memtrace")==0 ){
30578      sqlite3MemTraceActivate(stderr);
30579    }else if( cli_strcmp(z, "-pcachetrace")==0 ){
30580      sqlite3PcacheTraceActivate(stderr);
30581    }else if( cli_strcmp(z,"-bail")==0 ){
30582      bail_on_error = 1;
30583    }else if( cli_strcmp(z,"-nonce")==0 ){
30584      free(data.zNonce);
30585      data.zNonce = strdup(cmdline_option_value(argc, argv, ++i));
30586    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30587      ShellSetFlag(&data,SHFLG_TestingMode);
30588    }else if( cli_strcmp(z,"-safe")==0 ){
30589      /* no-op - catch this on the second pass */
30590    }
30591  }
30592#ifndef SQLITE_SHELL_FIDDLE
30593  verify_uninitialized();
30594#endif
30595
30596
30597#ifdef SQLITE_SHELL_INIT_PROC
30598  {
30599    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
30600    ** of a C-function that will perform initialization actions on SQLite that
30601    ** occur just before or after sqlite3_initialize(). Use this compile-time
30602    ** option to embed this shell program in larger applications. */
30603    extern void SQLITE_SHELL_INIT_PROC(void);
30604    SQLITE_SHELL_INIT_PROC();
30605  }
30606#else
30607  /* All the sqlite3_config() calls have now been made. So it is safe
30608  ** to call sqlite3_initialize() and process any command line -vfs option. */
30609  sqlite3_initialize();
30610#endif
30611
30612  if( zVfs ){
30613    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
30614    if( pVfs ){
30615      sqlite3_vfs_register(pVfs, 1);
30616    }else{
30617      eputf("no such VFS: \"%s\"\n", zVfs);
30618      exit(1);
30619    }
30620  }
30621
30622  if( data.pAuxDb->zDbFilename==0 ){
30623#ifndef SQLITE_OMIT_MEMORYDB
30624    data.pAuxDb->zDbFilename = ":memory:";
30625    warnInmemoryDb = argc==1;
30626#else
30627    eputf("%s: Error: no database filename specified\n", Argv0);
30628    return 1;
30629#endif
30630  }
30631  data.out = stdout;
30632#ifndef SQLITE_SHELL_FIDDLE
30633  sqlite3_appendvfs_init(0,0,0);
30634#endif
30635
30636  /* Go ahead and open the database file if it already exists.  If the
30637  ** file does not exist, delay opening it.  This prevents empty database
30638  ** files from being created if a user mistypes the database name argument
30639  ** to the sqlite command-line tool.
30640  */
30641  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
30642    open_db(&data, 0);
30643  }
30644
30645  /* Process the initialization file if there is one.  If no -init option
30646  ** is given on the command line, look for a file named ~/.sqliterc and
30647  ** try to process it.
30648  */
30649  process_sqliterc(&data,zInitFile);
30650
30651  /* Make a second pass through the command-line argument and set
30652  ** options.  This second pass is delayed until after the initialization
30653  ** file is processed so that the command-line arguments will override
30654  ** settings in the initialization file.
30655  */
30656  for(i=1; i<argc; i++){
30657    char *z = argv[i];
30658    if( z[0]!='-' || i>=nOptsEnd ) continue;
30659    if( z[1]=='-' ){ z++; }
30660    if( cli_strcmp(z,"-init")==0 ){
30661      i++;
30662    }else if( cli_strcmp(z,"-html")==0 ){
30663      data.mode = MODE_Html;
30664    }else if( cli_strcmp(z,"-list")==0 ){
30665      data.mode = MODE_List;
30666    }else if( cli_strcmp(z,"-quote")==0 ){
30667      data.mode = MODE_Quote;
30668      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
30669      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
30670    }else if( cli_strcmp(z,"-line")==0 ){
30671      data.mode = MODE_Line;
30672    }else if( cli_strcmp(z,"-column")==0 ){
30673      data.mode = MODE_Column;
30674    }else if( cli_strcmp(z,"-json")==0 ){
30675      data.mode = MODE_Json;
30676    }else if( cli_strcmp(z,"-markdown")==0 ){
30677      data.mode = MODE_Markdown;
30678    }else if( cli_strcmp(z,"-table")==0 ){
30679      data.mode = MODE_Table;
30680    }else if( cli_strcmp(z,"-box")==0 ){
30681      data.mode = MODE_Box;
30682    }else if( cli_strcmp(z,"-csv")==0 ){
30683      data.mode = MODE_Csv;
30684      memcpy(data.colSeparator,",",2);
30685#ifdef SQLITE_HAVE_ZLIB
30686    }else if( cli_strcmp(z,"-zip")==0 ){
30687      data.openMode = SHELL_OPEN_ZIPFILE;
30688#endif
30689    }else if( cli_strcmp(z,"-append")==0 ){
30690      data.openMode = SHELL_OPEN_APPENDVFS;
30691#ifndef SQLITE_OMIT_DESERIALIZE
30692    }else if( cli_strcmp(z,"-deserialize")==0 ){
30693      data.openMode = SHELL_OPEN_DESERIALIZE;
30694    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
30695      data.szMax = integerValue(argv[++i]);
30696#endif
30697    }else if( cli_strcmp(z,"-readonly")==0 ){
30698      data.openMode = SHELL_OPEN_READONLY;
30699    }else if( cli_strcmp(z,"-nofollow")==0 ){
30700      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
30701    }else if( cli_strcmp(z,"-ascii")==0 ){
30702      data.mode = MODE_Ascii;
30703      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit);
30704      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record);
30705    }else if( cli_strcmp(z,"-tabs")==0 ){
30706      data.mode = MODE_List;
30707      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab);
30708      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row);
30709    }else if( cli_strcmp(z,"-separator")==0 ){
30710      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
30711                       "%s",cmdline_option_value(argc,argv,++i));
30712    }else if( cli_strcmp(z,"-newline")==0 ){
30713      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
30714                       "%s",cmdline_option_value(argc,argv,++i));
30715    }else if( cli_strcmp(z,"-nullvalue")==0 ){
30716      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
30717                       "%s",cmdline_option_value(argc,argv,++i));
30718    }else if( cli_strcmp(z,"-header")==0 ){
30719      data.showHeader = 1;
30720      ShellSetFlag(&data, SHFLG_HeaderSet);
30721     }else if( cli_strcmp(z,"-noheader")==0 ){
30722      data.showHeader = 0;
30723      ShellSetFlag(&data, SHFLG_HeaderSet);
30724    }else if( cli_strcmp(z,"-echo")==0 ){
30725      ShellSetFlag(&data, SHFLG_Echo);
30726    }else if( cli_strcmp(z,"-eqp")==0 ){
30727      data.autoEQP = AUTOEQP_on;
30728    }else if( cli_strcmp(z,"-eqpfull")==0 ){
30729      data.autoEQP = AUTOEQP_full;
30730    }else if( cli_strcmp(z,"-stats")==0 ){
30731      data.statsOn = 1;
30732    }else if( cli_strcmp(z,"-scanstats")==0 ){
30733      data.scanstatsOn = 1;
30734    }else if( cli_strcmp(z,"-backslash")==0 ){
30735      /* Undocumented command-line option: -backslash
30736      ** Causes C-style backslash escapes to be evaluated in SQL statements
30737      ** prior to sending the SQL into SQLite.  Useful for injecting
30738      ** crazy bytes in the middle of SQL statements for testing and debugging.
30739      */
30740      ShellSetFlag(&data, SHFLG_Backslash);
30741    }else if( cli_strcmp(z,"-bail")==0 ){
30742      /* No-op.  The bail_on_error flag should already be set. */
30743    }else if( cli_strcmp(z,"-version")==0 ){
30744      sputf(stdout, "%s %s (%d-bit)\n",
30745            sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
30746      return 0;
30747    }else if( cli_strcmp(z,"-interactive")==0 ){
30748      /* Need to check for interactive override here to so that it can
30749      ** affect console setup (for Windows only) and testing thereof.
30750      */
30751      stdin_is_interactive = 1;
30752    }else if( cli_strcmp(z,"-batch")==0 ){
30753      /* already handled */
30754    }else if( cli_strcmp(z,"-utf8")==0 ){
30755      /* already handled */
30756    }else if( cli_strcmp(z,"-no-utf8")==0 ){
30757      /* already handled */
30758    }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){
30759      /* already handled */
30760    }else if( cli_strcmp(z,"-heap")==0 ){
30761      i++;
30762    }else if( cli_strcmp(z,"-pagecache")==0 ){
30763      i+=2;
30764    }else if( cli_strcmp(z,"-lookaside")==0 ){
30765      i+=2;
30766    }else if( cli_strcmp(z,"-threadsafe")==0 ){
30767      i+=2;
30768    }else if( cli_strcmp(z,"-nonce")==0 ){
30769      i += 2;
30770    }else if( cli_strcmp(z,"-mmap")==0 ){
30771      i++;
30772    }else if( cli_strcmp(z,"-memtrace")==0 ){
30773      i++;
30774    }else if( cli_strcmp(z,"-pcachetrace")==0 ){
30775      i++;
30776#ifdef SQLITE_ENABLE_SORTER_REFERENCES
30777    }else if( cli_strcmp(z,"-sorterref")==0 ){
30778      i++;
30779#endif
30780    }else if( cli_strcmp(z,"-vfs")==0 ){
30781      i++;
30782#ifdef SQLITE_ENABLE_VFSTRACE
30783    }else if( cli_strcmp(z,"-vfstrace")==0 ){
30784      i++;
30785#endif
30786#ifdef SQLITE_ENABLE_MULTIPLEX
30787    }else if( cli_strcmp(z,"-multiplex")==0 ){
30788      i++;
30789#endif
30790    }else if( cli_strcmp(z,"-help")==0 ){
30791      usage(1);
30792    }else if( cli_strcmp(z,"-cmd")==0 ){
30793      /* Run commands that follow -cmd first and separately from commands
30794      ** that simply appear on the command-line.  This seems goofy.  It would
30795      ** be better if all commands ran in the order that they appear.  But
30796      ** we retain the goofy behavior for historical compatibility. */
30797      if( i==argc-1 ) break;
30798      z = cmdline_option_value(argc,argv,++i);
30799      if( z[0]=='.' ){
30800        rc = do_meta_command(z, &data);
30801        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
30802      }else{
30803        open_db(&data, 0);
30804        rc = shell_exec(&data, z, &zErrMsg);
30805        if( zErrMsg!=0 ){
30806          eputf("Error: %s\n", zErrMsg);
30807          if( bail_on_error ) return rc!=0 ? rc : 1;
30808        }else if( rc!=0 ){
30809          eputf("Error: unable to process SQL \"%s\"\n", z);
30810          if( bail_on_error ) return rc;
30811        }
30812      }
30813#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
30814    }else if( cli_strncmp(z, "-A", 2)==0 ){
30815      if( nCmd>0 ){
30816        eputf("Error: cannot mix regular SQL or dot-commands"
30817              " with \"%s\"\n", z);
30818        return 1;
30819      }
30820      open_db(&data, OPEN_DB_ZIPFILE);
30821      if( z[2] ){
30822        argv[i] = &z[2];
30823        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
30824      }else{
30825        arDotCommand(&data, 1, argv+i, argc-i);
30826      }
30827      readStdin = 0;
30828      break;
30829#endif
30830    }else if( cli_strcmp(z,"-safe")==0 ){
30831      data.bSafeMode = data.bSafeModePersist = 1;
30832    }else if( cli_strcmp(z,"-unsafe-testing")==0 ){
30833      /* Acted upon in first pass. */
30834    }else{
30835      eputf("%s: Error: unknown option: %s\n", Argv0, z);
30836      eputz("Use -help for a list of options.\n");
30837      return 1;
30838    }
30839    data.cMode = data.mode;
30840  }
30841
30842  if( !readStdin ){
30843    /* Run all arguments that do not begin with '-' as if they were separate
30844    ** command-line inputs, except for the argToSkip argument which contains
30845    ** the database filename.
30846    */
30847    for(i=0; i<nCmd; i++){
30848      if( azCmd[i][0]=='.' ){
30849        rc = do_meta_command(azCmd[i], &data);
30850        if( rc ){
30851          free(azCmd);
30852          return rc==2 ? 0 : rc;
30853        }
30854      }else{
30855        open_db(&data, 0);
30856        echo_group_input(&data, azCmd[i]);
30857        rc = shell_exec(&data, azCmd[i], &zErrMsg);
30858        if( zErrMsg || rc ){
30859          if( zErrMsg!=0 ){
30860            eputf("Error: %s\n", zErrMsg);
30861          }else{
30862            eputf("Error: unable to process SQL: %s\n", azCmd[i]);
30863          }
30864          sqlite3_free(zErrMsg);
30865          free(azCmd);
30866          return rc!=0 ? rc : 1;
30867        }
30868      }
30869    }
30870  }else{
30871    /* Run commands received from standard input
30872    */
30873    if( stdin_is_interactive ){
30874      char *zHome;
30875      char *zHistory;
30876      int nHistory;
30877#if CIO_WIN_WC_XLATE
30878# define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
30879#else
30880# define SHELL_CIO_CHAR_SET ""
30881#endif
30882      sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
30883            "Enter \".help\" for usage hints.\n",
30884            sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
30885      if( warnInmemoryDb ){
30886        sputz(stdout, "Connected to a ");
30887        printBold("transient in-memory database");
30888        sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
30889              " persistent database.\n");
30890      }
30891      zHistory = getenv("SQLITE_HISTORY");
30892      if( zHistory ){
30893        zHistory = strdup(zHistory);
30894      }else if( (zHome = find_home_dir(0))!=0 ){
30895        nHistory = strlen30(zHome) + 20;
30896        if( (zHistory = malloc(nHistory))!=0 ){
30897          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
30898        }
30899      }
30900      if( zHistory ){ shell_read_history(zHistory); }
30901#if HAVE_READLINE || HAVE_EDITLINE
30902      rl_attempted_completion_function = readline_completion;
30903#elif HAVE_LINENOISE
30904      linenoiseSetCompletionCallback(linenoise_completion);
30905#endif
30906      data.in = 0;
30907      rc = process_input(&data);
30908      if( zHistory ){
30909        shell_stifle_history(2000);
30910        shell_write_history(zHistory);
30911        free(zHistory);
30912      }
30913    }else{
30914      data.in = stdin;
30915      rc = process_input(&data);
30916    }
30917  }
30918#ifndef SQLITE_SHELL_FIDDLE
30919  /* In WASM mode we have to leave the db state in place so that
30920  ** client code can "push" SQL into it after this call returns. */
30921#ifndef SQLITE_OMIT_VIRTUALTABLE
30922  if( data.expert.pExpert ){
30923    expertFinish(&data, 1, 0);
30924  }
30925#endif
30926  free(azCmd);
30927  set_table_name(&data, 0);
30928  if( data.db ){
30929    session_close_all(&data, -1);
30930    close_db(data.db);
30931  }
30932  for(i=0; i<ArraySize(data.aAuxDb); i++){
30933    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
30934    if( data.aAuxDb[i].db ){
30935      session_close_all(&data, i);
30936      close_db(data.aAuxDb[i].db);
30937    }
30938  }
30939  find_home_dir(1);
30940  output_reset(&data);
30941  data.doXdgOpen = 0;
30942  clearTempFile(&data);
30943#if !SQLITE_SHELL_IS_UTF8
30944  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
30945  free(argvToFree);
30946#endif
30947  free(data.colWidth);
30948  free(data.zNonce);
30949  /* Clear the global data structure so that valgrind will detect memory
30950  ** leaks */
30951  memset(&data, 0, sizeof(data));
30952#ifdef SQLITE_DEBUG
30953  if( sqlite3_memory_used()>mem_main_enter ){
30954    eputf("Memory leaked: %u bytes\n",
30955          (unsigned int)(sqlite3_memory_used()-mem_main_enter));
30956  }
30957#endif
30958#endif /* !SQLITE_SHELL_FIDDLE */
30959  return rc;
30960}
30961
30962
30963#ifdef SQLITE_SHELL_FIDDLE
30964/* Only for emcc experimentation purposes. */
30965int fiddle_experiment(int a,int b){
30966  return a + b;
30967}
30968
30969/*
30970** Returns a pointer to the current DB handle.
30971*/
30972sqlite3 * fiddle_db_handle(){
30973  return globalDb;
30974}
30975
30976/*
30977** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
30978** "main" is assumed. Returns 0 if no db with the given name is
30979** open.
30980*/
30981sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
30982  sqlite3_vfs * pVfs = 0;
30983  if(globalDb){
30984    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
30985                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
30986  }
30987  return pVfs;
30988}
30989
30990/* Only for emcc experimentation purposes. */
30991sqlite3 * fiddle_db_arg(sqlite3 *arg){
30992    oputf("fiddle_db_arg(%p)\n", (const void*)arg);
30993    return arg;
30994}
30995
30996/*
30997** Intended to be called via a SharedWorker() while a separate
30998** SharedWorker() (which manages the wasm module) is performing work
30999** which should be interrupted. Unfortunately, SharedWorker is not
31000** portable enough to make real use of.
31001*/
31002void fiddle_interrupt(void){
31003  if( globalDb ) sqlite3_interrupt(globalDb);
31004}
31005
31006/*
31007** Returns the filename of the given db name, assuming "main" if
31008** zDbName is NULL. Returns NULL if globalDb is not opened.
31009*/
31010const char * fiddle_db_filename(const char * zDbName){
31011    return globalDb
31012      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
31013      : NULL;
31014}
31015
31016/*
31017** Completely wipes out the contents of the currently-opened database
31018** but leaves its storage intact for reuse. If any transactions are
31019** active, they are forcibly rolled back.
31020*/
31021void fiddle_reset_db(void){
31022  if( globalDb ){
31023    int rc;
31024    while( sqlite3_txn_state(globalDb,0)>0 ){
31025      /*
31026      ** Resolve problem reported in
31027      ** https://sqlite.org/forum/forumpost/0b41a25d65
31028      */
31029      oputz("Rolling back in-progress transaction.\n");
31030      sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0);
31031    }
31032    rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
31033    if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
31034    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
31035  }
31036}
31037
31038/*
31039** Uses the current database's VFS xRead to stream the db file's
31040** contents out to the given callback. The callback gets a single
31041** chunk of size n (its 2nd argument) on each call and must return 0
31042** on success, non-0 on error. This function returns 0 on success,
31043** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
31044** code from the callback. Note that this is not thread-friendly: it
31045** expects that it will be the only thread reading the db file and
31046** takes no measures to ensure that is the case.
31047*/
31048int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
31049  sqlite3_int64 nSize = 0;
31050  sqlite3_int64 nPos = 0;
31051  sqlite3_file * pFile = 0;
31052  unsigned char buf[1024 * 8];
31053  int nBuf = (int)sizeof(buf);
31054  int rc = shellState.db
31055    ? sqlite3_file_control(shellState.db, "main",
31056                           SQLITE_FCNTL_FILE_POINTER, &pFile)
31057    : SQLITE_NOTFOUND;
31058  if( rc ) return rc;
31059  rc = pFile->pMethods->xFileSize(pFile, &nSize);
31060  if( rc ) return rc;
31061  if(nSize % nBuf){
31062    /* DB size is not an even multiple of the buffer size. Reduce
31063    ** buffer size so that we do not unduly inflate the db size when
31064    ** exporting. */
31065    if(0 == nSize % 4096) nBuf = 4096;
31066    else if(0 == nSize % 2048) nBuf = 2048;
31067    else if(0 == nSize % 1024) nBuf = 1024;
31068    else nBuf = 512;
31069  }
31070  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
31071    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
31072    if(SQLITE_IOERR_SHORT_READ == rc){
31073      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
31074    }
31075    if( 0==rc ) rc = xCallback(buf, nBuf);
31076  }
31077  return rc;
31078}
31079
31080/*
31081** Trivial exportable function for emscripten. It processes zSql as if
31082** it were input to the sqlite3 shell and redirects all output to the
31083** wasm binding. fiddle_main() must have been called before this
31084** is called, or results are undefined.
31085*/
31086void fiddle_exec(const char * zSql){
31087  if(zSql && *zSql){
31088    if('.'==*zSql) puts(zSql);
31089    shellState.wasm.zInput = zSql;
31090    shellState.wasm.zPos = zSql;
31091    process_input(&shellState);
31092    shellState.wasm.zInput = shellState.wasm.zPos = 0;
31093  }
31094}
31095#endif /* SQLITE_SHELL_FIDDLE */
31096