xref: /sqlite-3.40.0/src/shell.c.in (revision 181d75ef)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** Warning pragmas copied from msvc.h in the core.
42*/
43#if defined(_MSC_VER)
44#pragma warning(disable : 4054)
45#pragma warning(disable : 4055)
46#pragma warning(disable : 4100)
47#pragma warning(disable : 4127)
48#pragma warning(disable : 4130)
49#pragma warning(disable : 4152)
50#pragma warning(disable : 4189)
51#pragma warning(disable : 4206)
52#pragma warning(disable : 4210)
53#pragma warning(disable : 4232)
54#pragma warning(disable : 4244)
55#pragma warning(disable : 4305)
56#pragma warning(disable : 4306)
57#pragma warning(disable : 4702)
58#pragma warning(disable : 4706)
59#endif /* defined(_MSC_VER) */
60
61/*
62** No support for loadable extensions in VxWorks.
63*/
64#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
65# define SQLITE_OMIT_LOAD_EXTENSION 1
66#endif
67
68/*
69** Enable large-file support for fopen() and friends on unix.
70*/
71#ifndef SQLITE_DISABLE_LFS
72# define _LARGE_FILE       1
73# ifndef _FILE_OFFSET_BITS
74#   define _FILE_OFFSET_BITS 64
75# endif
76# define _LARGEFILE_SOURCE 1
77#endif
78
79#include <stdlib.h>
80#include <string.h>
81#include <stdio.h>
82#include <assert.h>
83#include "sqlite3.h"
84typedef sqlite3_int64 i64;
85typedef sqlite3_uint64 u64;
86typedef unsigned char u8;
87#if SQLITE_USER_AUTHENTICATION
88# include "sqlite3userauth.h"
89#endif
90#include <ctype.h>
91#include <stdarg.h>
92
93#if !defined(_WIN32) && !defined(WIN32)
94# include <signal.h>
95# if !defined(__RTP__) && !defined(_WRS_KERNEL)
96#  include <pwd.h>
97# endif
98#endif
99#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100# include <unistd.h>
101# include <dirent.h>
102# define GETPID getpid
103# if defined(__MINGW32__)
104#  define DIRENT dirent
105#  ifndef S_ISLNK
106#   define S_ISLNK(mode) (0)
107#  endif
108# endif
109#else
110# define GETPID (int)GetCurrentProcessId
111#endif
112#include <sys/types.h>
113#include <sys/stat.h>
114
115#if HAVE_READLINE
116# include <readline/readline.h>
117# include <readline/history.h>
118#endif
119
120#if HAVE_EDITLINE
121# include <editline/readline.h>
122#endif
123
124#if HAVE_EDITLINE || HAVE_READLINE
125
126# define shell_add_history(X) add_history(X)
127# define shell_read_history(X) read_history(X)
128# define shell_write_history(X) write_history(X)
129# define shell_stifle_history(X) stifle_history(X)
130# define shell_readline(X) readline(X)
131
132#elif HAVE_LINENOISE
133
134# include "linenoise.h"
135# define shell_add_history(X) linenoiseHistoryAdd(X)
136# define shell_read_history(X) linenoiseHistoryLoad(X)
137# define shell_write_history(X) linenoiseHistorySave(X)
138# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
139# define shell_readline(X) linenoise(X)
140
141#else
142
143# define shell_read_history(X)
144# define shell_write_history(X)
145# define shell_stifle_history(X)
146
147# define SHELL_USE_LOCAL_GETLINE 1
148#endif
149
150
151#if defined(_WIN32) || defined(WIN32)
152# if SQLITE_OS_WINRT
153#  define SQLITE_OMIT_POPEN 1
154# else
155#  include <io.h>
156#  include <fcntl.h>
157#  define isatty(h) _isatty(h)
158#  ifndef access
159#   define access(f,m) _access((f),(m))
160#  endif
161#  ifndef unlink
162#   define unlink _unlink
163#  endif
164#  ifndef strdup
165#   define strdup _strdup
166#  endif
167#  undef popen
168#  define popen _popen
169#  undef pclose
170#  define pclose _pclose
171# endif
172#else
173 /* Make sure isatty() has a prototype. */
174 extern int isatty(int);
175
176# if !defined(__RTP__) && !defined(_WRS_KERNEL)
177  /* popen and pclose are not C89 functions and so are
178  ** sometimes omitted from the <stdio.h> header */
179   extern FILE *popen(const char*,const char*);
180   extern int pclose(FILE*);
181# else
182#  define SQLITE_OMIT_POPEN 1
183# endif
184#endif
185
186#if defined(_WIN32_WCE)
187/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
188 * thus we always assume that we have a console. That can be
189 * overridden with the -batch command line option.
190 */
191#define isatty(x) 1
192#endif
193
194/* ctype macros that work with signed characters */
195#define IsSpace(X)  isspace((unsigned char)X)
196#define IsDigit(X)  isdigit((unsigned char)X)
197#define ToLower(X)  (char)tolower((unsigned char)X)
198
199#if defined(_WIN32) || defined(WIN32)
200#if SQLITE_OS_WINRT
201#include <intrin.h>
202#endif
203#include <windows.h>
204
205/* string conversion routines only needed on Win32 */
206extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
207extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
208extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
209extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
210#endif
211
212/* On Windows, we normally run with output mode of TEXT so that \n characters
213** are automatically translated into \r\n.  However, this behavior needs
214** to be disabled in some cases (ex: when generating CSV output and when
215** rendering quoted strings that contain \n characters).  The following
216** routines take care of that.
217*/
218#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
219static void setBinaryMode(FILE *file, int isOutput){
220  if( isOutput ) fflush(file);
221  _setmode(_fileno(file), _O_BINARY);
222}
223static void setTextMode(FILE *file, int isOutput){
224  if( isOutput ) fflush(file);
225  _setmode(_fileno(file), _O_TEXT);
226}
227#else
228# define setBinaryMode(X,Y)
229# define setTextMode(X,Y)
230#endif
231
232/*
233** When compiling with emcc (a.k.a. emscripten), we're building a
234** WebAssembly (WASM) bundle and need to disable and rewire a few
235** things.
236*/
237#ifdef __EMSCRIPTEN__
238#define SQLITE_SHELL_WASM_MODE
239#else
240#undef SQLITE_SHELL_WASM_MODE
241#endif
242
243/* True if the timer is enabled */
244static int enableTimer = 0;
245
246/* Return the current wall-clock time */
247static sqlite3_int64 timeOfDay(void){
248  static sqlite3_vfs *clockVfs = 0;
249  sqlite3_int64 t;
250  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
251  if( clockVfs==0 ) return 0;  /* Never actually happens */
252  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
253    clockVfs->xCurrentTimeInt64(clockVfs, &t);
254  }else{
255    double r;
256    clockVfs->xCurrentTime(clockVfs, &r);
257    t = (sqlite3_int64)(r*86400000.0);
258  }
259  return t;
260}
261
262#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
263#include <sys/time.h>
264#include <sys/resource.h>
265
266/* VxWorks does not support getrusage() as far as we can determine */
267#if defined(_WRS_KERNEL) || defined(__RTP__)
268struct rusage {
269  struct timeval ru_utime; /* user CPU time used */
270  struct timeval ru_stime; /* system CPU time used */
271};
272#define getrusage(A,B) memset(B,0,sizeof(*B))
273#endif
274
275/* Saved resource information for the beginning of an operation */
276static struct rusage sBegin;  /* CPU time at start */
277static sqlite3_int64 iBegin;  /* Wall-clock time at start */
278
279/*
280** Begin timing an operation
281*/
282static void beginTimer(void){
283  if( enableTimer ){
284    getrusage(RUSAGE_SELF, &sBegin);
285    iBegin = timeOfDay();
286  }
287}
288
289/* Return the difference of two time_structs in seconds */
290static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
291  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
292         (double)(pEnd->tv_sec - pStart->tv_sec);
293}
294
295/*
296** Print the timing results.
297*/
298static void endTimer(void){
299  if( enableTimer ){
300    sqlite3_int64 iEnd = timeOfDay();
301    struct rusage sEnd;
302    getrusage(RUSAGE_SELF, &sEnd);
303    printf("Run Time: real %.3f user %f sys %f\n",
304       (iEnd - iBegin)*0.001,
305       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
306       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
307  }
308}
309
310#define BEGIN_TIMER beginTimer()
311#define END_TIMER endTimer()
312#define HAS_TIMER 1
313
314#elif (defined(_WIN32) || defined(WIN32))
315
316/* Saved resource information for the beginning of an operation */
317static HANDLE hProcess;
318static FILETIME ftKernelBegin;
319static FILETIME ftUserBegin;
320static sqlite3_int64 ftWallBegin;
321typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
322                                    LPFILETIME, LPFILETIME);
323static GETPROCTIMES getProcessTimesAddr = NULL;
324
325/*
326** Check to see if we have timer support.  Return 1 if necessary
327** support found (or found previously).
328*/
329static int hasTimer(void){
330  if( getProcessTimesAddr ){
331    return 1;
332  } else {
333#if !SQLITE_OS_WINRT
334    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
335    ** versions. See if the version we are running on has it, and if it
336    ** does, save off a pointer to it and the current process handle.
337    */
338    hProcess = GetCurrentProcess();
339    if( hProcess ){
340      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
341      if( NULL != hinstLib ){
342        getProcessTimesAddr =
343            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
344        if( NULL != getProcessTimesAddr ){
345          return 1;
346        }
347        FreeLibrary(hinstLib);
348      }
349    }
350#endif
351  }
352  return 0;
353}
354
355/*
356** Begin timing an operation
357*/
358static void beginTimer(void){
359  if( enableTimer && getProcessTimesAddr ){
360    FILETIME ftCreation, ftExit;
361    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
362                        &ftKernelBegin,&ftUserBegin);
363    ftWallBegin = timeOfDay();
364  }
365}
366
367/* Return the difference of two FILETIME structs in seconds */
368static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
369  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
370  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
371  return (double) ((i64End - i64Start) / 10000000.0);
372}
373
374/*
375** Print the timing results.
376*/
377static void endTimer(void){
378  if( enableTimer && getProcessTimesAddr){
379    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
380    sqlite3_int64 ftWallEnd = timeOfDay();
381    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
382    printf("Run Time: real %.3f user %f sys %f\n",
383       (ftWallEnd - ftWallBegin)*0.001,
384       timeDiff(&ftUserBegin, &ftUserEnd),
385       timeDiff(&ftKernelBegin, &ftKernelEnd));
386  }
387}
388
389#define BEGIN_TIMER beginTimer()
390#define END_TIMER endTimer()
391#define HAS_TIMER hasTimer()
392
393#else
394#define BEGIN_TIMER
395#define END_TIMER
396#define HAS_TIMER 0
397#endif
398
399/*
400** Used to prevent warnings about unused parameters
401*/
402#define UNUSED_PARAMETER(x) (void)(x)
403
404/*
405** Number of elements in an array
406*/
407#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
408
409/*
410** If the following flag is set, then command execution stops
411** at an error if we are not interactive.
412*/
413static int bail_on_error = 0;
414
415/*
416** Threat stdin as an interactive input if the following variable
417** is true.  Otherwise, assume stdin is connected to a file or pipe.
418*/
419static int stdin_is_interactive = 1;
420
421/*
422** On Windows systems we have to know if standard output is a console
423** in order to translate UTF-8 into MBCS.  The following variable is
424** true if translation is required.
425*/
426static int stdout_is_console = 1;
427
428/*
429** The following is the open SQLite database.  We make a pointer
430** to this database a static variable so that it can be accessed
431** by the SIGINT handler to interrupt database processing.
432*/
433static sqlite3 *globalDb = 0;
434
435/*
436** True if an interrupt (Control-C) has been received.
437*/
438static volatile int seenInterrupt = 0;
439
440/*
441** This is the name of our program. It is set in main(), used
442** in a number of other places, mostly for error messages.
443*/
444static char *Argv0;
445
446/*
447** Prompt strings. Initialized in main. Settable with
448**   .prompt main continue
449*/
450static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
451static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
452
453/*
454** Render output like fprintf().  Except, if the output is going to the
455** console and if this is running on a Windows machine, translate the
456** output from UTF-8 into MBCS.
457*/
458#if defined(_WIN32) || defined(WIN32)
459void utf8_printf(FILE *out, const char *zFormat, ...){
460  va_list ap;
461  va_start(ap, zFormat);
462  if( stdout_is_console && (out==stdout || out==stderr) ){
463    char *z1 = sqlite3_vmprintf(zFormat, ap);
464    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
465    sqlite3_free(z1);
466    fputs(z2, out);
467    sqlite3_free(z2);
468  }else{
469    vfprintf(out, zFormat, ap);
470  }
471  va_end(ap);
472}
473#elif !defined(utf8_printf)
474# define utf8_printf fprintf
475#endif
476
477/*
478** Render output like fprintf().  This should not be used on anything that
479** includes string formatting (e.g. "%s").
480*/
481#if !defined(raw_printf)
482# define raw_printf fprintf
483#endif
484
485/* Indicate out-of-memory and exit. */
486static void shell_out_of_memory(void){
487  raw_printf(stderr,"Error: out of memory\n");
488  exit(1);
489}
490
491/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
492** out-of-memory error.
493*/
494static void shell_check_oom(void *p){
495  if( p==0 ) shell_out_of_memory();
496}
497
498/*
499** Write I/O traces to the following stream.
500*/
501#ifdef SQLITE_ENABLE_IOTRACE
502static FILE *iotrace = 0;
503#endif
504
505/*
506** This routine works like printf in that its first argument is a
507** format string and subsequent arguments are values to be substituted
508** in place of % fields.  The result of formatting this string
509** is written to iotrace.
510*/
511#ifdef SQLITE_ENABLE_IOTRACE
512static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
513  va_list ap;
514  char *z;
515  if( iotrace==0 ) return;
516  va_start(ap, zFormat);
517  z = sqlite3_vmprintf(zFormat, ap);
518  va_end(ap);
519  utf8_printf(iotrace, "%s", z);
520  sqlite3_free(z);
521}
522#endif
523
524/*
525** Output string zUtf to stream pOut as w characters.  If w is negative,
526** then right-justify the text.  W is the width in UTF-8 characters, not
527** in bytes.  This is different from the %*.*s specification in printf
528** since with %*.*s the width is measured in bytes, not characters.
529*/
530static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
531  int i;
532  int n;
533  int aw = w<0 ? -w : w;
534  for(i=n=0; zUtf[i]; i++){
535    if( (zUtf[i]&0xc0)!=0x80 ){
536      n++;
537      if( n==aw ){
538        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
539        break;
540      }
541    }
542  }
543  if( n>=aw ){
544    utf8_printf(pOut, "%.*s", i, zUtf);
545  }else if( w<0 ){
546    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
547  }else{
548    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
549  }
550}
551
552
553/*
554** Determines if a string is a number of not.
555*/
556static int isNumber(const char *z, int *realnum){
557  if( *z=='-' || *z=='+' ) z++;
558  if( !IsDigit(*z) ){
559    return 0;
560  }
561  z++;
562  if( realnum ) *realnum = 0;
563  while( IsDigit(*z) ){ z++; }
564  if( *z=='.' ){
565    z++;
566    if( !IsDigit(*z) ) return 0;
567    while( IsDigit(*z) ){ z++; }
568    if( realnum ) *realnum = 1;
569  }
570  if( *z=='e' || *z=='E' ){
571    z++;
572    if( *z=='+' || *z=='-' ) z++;
573    if( !IsDigit(*z) ) return 0;
574    while( IsDigit(*z) ){ z++; }
575    if( realnum ) *realnum = 1;
576  }
577  return *z==0;
578}
579
580/*
581** Compute a string length that is limited to what can be stored in
582** lower 30 bits of a 32-bit signed integer.
583*/
584static int strlen30(const char *z){
585  const char *z2 = z;
586  while( *z2 ){ z2++; }
587  return 0x3fffffff & (int)(z2 - z);
588}
589
590/*
591** Return the length of a string in characters.  Multibyte UTF8 characters
592** count as a single character.
593*/
594static int strlenChar(const char *z){
595  int n = 0;
596  while( *z ){
597    if( (0xc0&*(z++))!=0x80 ) n++;
598  }
599  return n;
600}
601
602/*
603** Return open FILE * if zFile exists, can be opened for read
604** and is an ordinary file or a character stream source.
605** Otherwise return 0.
606*/
607static FILE * openChrSource(const char *zFile){
608#ifdef _WIN32
609  struct _stat x = {0};
610# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
611  /* On Windows, open first, then check the stream nature. This order
612  ** is necessary because _stat() and sibs, when checking a named pipe,
613  ** effectively break the pipe as its supplier sees it. */
614  FILE *rv = fopen(zFile, "rb");
615  if( rv==0 ) return 0;
616  if( _fstat(_fileno(rv), &x) != 0
617      || !STAT_CHR_SRC(x.st_mode)){
618    fclose(rv);
619    rv = 0;
620  }
621  return rv;
622#else
623  struct stat x = {0};
624  int rc = stat(zFile, &x);
625# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
626  if( rc!=0 ) return 0;
627  if( STAT_CHR_SRC(x.st_mode) ){
628    return fopen(zFile, "rb");
629  }else{
630    return 0;
631  }
632#endif
633#undef STAT_CHR_SRC
634}
635
636/*
637** This routine reads a line of text from FILE in, stores
638** the text in memory obtained from malloc() and returns a pointer
639** to the text.  NULL is returned at end of file, or if malloc()
640** fails.
641**
642** If zLine is not NULL then it is a malloced buffer returned from
643** a previous call to this routine that may be reused.
644*/
645static char *local_getline(char *zLine, FILE *in){
646  int nLine = zLine==0 ? 0 : 100;
647  int n = 0;
648
649  while( 1 ){
650    if( n+100>nLine ){
651      nLine = nLine*2 + 100;
652      zLine = realloc(zLine, nLine);
653      shell_check_oom(zLine);
654    }
655    if( fgets(&zLine[n], nLine - n, in)==0 ){
656      if( n==0 ){
657        free(zLine);
658        return 0;
659      }
660      zLine[n] = 0;
661      break;
662    }
663    while( zLine[n] ) n++;
664    if( n>0 && zLine[n-1]=='\n' ){
665      n--;
666      if( n>0 && zLine[n-1]=='\r' ) n--;
667      zLine[n] = 0;
668      break;
669    }
670  }
671#if defined(_WIN32) || defined(WIN32)
672  /* For interactive input on Windows systems, translate the
673  ** multi-byte characterset characters into UTF-8. */
674  if( stdin_is_interactive && in==stdin ){
675    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
676    if( zTrans ){
677      int nTrans = strlen30(zTrans)+1;
678      if( nTrans>nLine ){
679        zLine = realloc(zLine, nTrans);
680        shell_check_oom(zLine);
681      }
682      memcpy(zLine, zTrans, nTrans);
683      sqlite3_free(zTrans);
684    }
685  }
686#endif /* defined(_WIN32) || defined(WIN32) */
687  return zLine;
688}
689
690/*
691** Retrieve a single line of input text.
692**
693** If in==0 then read from standard input and prompt before each line.
694** If isContinuation is true, then a continuation prompt is appropriate.
695** If isContinuation is zero, then the main prompt should be used.
696**
697** If zPrior is not NULL then it is a buffer from a prior call to this
698** routine that can be reused.
699**
700** The result is stored in space obtained from malloc() and must either
701** be freed by the caller or else passed back into this routine via the
702** zPrior argument for reuse.
703*/
704#ifndef SQLITE_SHELL_WASM_MODE
705static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
706  char *zPrompt;
707  char *zResult;
708  if( in!=0 ){
709    zResult = local_getline(zPrior, in);
710  }else{
711    zPrompt = isContinuation ? continuePrompt : mainPrompt;
712#if SHELL_USE_LOCAL_GETLINE
713    printf("%s", zPrompt);
714    fflush(stdout);
715    zResult = local_getline(zPrior, stdin);
716#else
717    free(zPrior);
718    zResult = shell_readline(zPrompt);
719    if( zResult && *zResult ) shell_add_history(zResult);
720#endif
721  }
722  return zResult;
723}
724#endif /* !SQLITE_SHELL_WASM_MODE */
725
726/*
727** Return the value of a hexadecimal digit.  Return -1 if the input
728** is not a hex digit.
729*/
730static int hexDigitValue(char c){
731  if( c>='0' && c<='9' ) return c - '0';
732  if( c>='a' && c<='f' ) return c - 'a' + 10;
733  if( c>='A' && c<='F' ) return c - 'A' + 10;
734  return -1;
735}
736
737/*
738** Interpret zArg as an integer value, possibly with suffixes.
739*/
740static sqlite3_int64 integerValue(const char *zArg){
741  sqlite3_int64 v = 0;
742  static const struct { char *zSuffix; int iMult; } aMult[] = {
743    { "KiB", 1024 },
744    { "MiB", 1024*1024 },
745    { "GiB", 1024*1024*1024 },
746    { "KB",  1000 },
747    { "MB",  1000000 },
748    { "GB",  1000000000 },
749    { "K",   1000 },
750    { "M",   1000000 },
751    { "G",   1000000000 },
752  };
753  int i;
754  int isNeg = 0;
755  if( zArg[0]=='-' ){
756    isNeg = 1;
757    zArg++;
758  }else if( zArg[0]=='+' ){
759    zArg++;
760  }
761  if( zArg[0]=='0' && zArg[1]=='x' ){
762    int x;
763    zArg += 2;
764    while( (x = hexDigitValue(zArg[0]))>=0 ){
765      v = (v<<4) + x;
766      zArg++;
767    }
768  }else{
769    while( IsDigit(zArg[0]) ){
770      v = v*10 + zArg[0] - '0';
771      zArg++;
772    }
773  }
774  for(i=0; i<ArraySize(aMult); i++){
775    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
776      v *= aMult[i].iMult;
777      break;
778    }
779  }
780  return isNeg? -v : v;
781}
782
783/*
784** A variable length string to which one can append text.
785*/
786typedef struct ShellText ShellText;
787struct ShellText {
788  char *z;
789  int n;
790  int nAlloc;
791};
792
793/*
794** Initialize and destroy a ShellText object
795*/
796static void initText(ShellText *p){
797  memset(p, 0, sizeof(*p));
798}
799static void freeText(ShellText *p){
800  free(p->z);
801  initText(p);
802}
803
804/* zIn is either a pointer to a NULL-terminated string in memory obtained
805** from malloc(), or a NULL pointer. The string pointed to by zAppend is
806** added to zIn, and the result returned in memory obtained from malloc().
807** zIn, if it was not NULL, is freed.
808**
809** If the third argument, quote, is not '\0', then it is used as a
810** quote character for zAppend.
811*/
812static void appendText(ShellText *p, const char *zAppend, char quote){
813  int len;
814  int i;
815  int nAppend = strlen30(zAppend);
816
817  len = nAppend+p->n+1;
818  if( quote ){
819    len += 2;
820    for(i=0; i<nAppend; i++){
821      if( zAppend[i]==quote ) len++;
822    }
823  }
824
825  if( p->z==0 || p->n+len>=p->nAlloc ){
826    p->nAlloc = p->nAlloc*2 + len + 20;
827    p->z = realloc(p->z, p->nAlloc);
828    shell_check_oom(p->z);
829  }
830
831  if( quote ){
832    char *zCsr = p->z+p->n;
833    *zCsr++ = quote;
834    for(i=0; i<nAppend; i++){
835      *zCsr++ = zAppend[i];
836      if( zAppend[i]==quote ) *zCsr++ = quote;
837    }
838    *zCsr++ = quote;
839    p->n = (int)(zCsr - p->z);
840    *zCsr = '\0';
841  }else{
842    memcpy(p->z+p->n, zAppend, nAppend);
843    p->n += nAppend;
844    p->z[p->n] = '\0';
845  }
846}
847
848/*
849** Attempt to determine if identifier zName needs to be quoted, either
850** because it contains non-alphanumeric characters, or because it is an
851** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
852** that quoting is required.
853**
854** Return '"' if quoting is required.  Return 0 if no quoting is required.
855*/
856static char quoteChar(const char *zName){
857  int i;
858  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
859  for(i=0; zName[i]; i++){
860    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
861  }
862  return sqlite3_keyword_check(zName, i) ? '"' : 0;
863}
864
865/*
866** Construct a fake object name and column list to describe the structure
867** of the view, virtual table, or table valued function zSchema.zName.
868*/
869static char *shellFakeSchema(
870  sqlite3 *db,            /* The database connection containing the vtab */
871  const char *zSchema,    /* Schema of the database holding the vtab */
872  const char *zName       /* The name of the virtual table */
873){
874  sqlite3_stmt *pStmt = 0;
875  char *zSql;
876  ShellText s;
877  char cQuote;
878  char *zDiv = "(";
879  int nRow = 0;
880
881  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
882                         zSchema ? zSchema : "main", zName);
883  shell_check_oom(zSql);
884  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
885  sqlite3_free(zSql);
886  initText(&s);
887  if( zSchema ){
888    cQuote = quoteChar(zSchema);
889    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
890    appendText(&s, zSchema, cQuote);
891    appendText(&s, ".", 0);
892  }
893  cQuote = quoteChar(zName);
894  appendText(&s, zName, cQuote);
895  while( sqlite3_step(pStmt)==SQLITE_ROW ){
896    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
897    nRow++;
898    appendText(&s, zDiv, 0);
899    zDiv = ",";
900    if( zCol==0 ) zCol = "";
901    cQuote = quoteChar(zCol);
902    appendText(&s, zCol, cQuote);
903  }
904  appendText(&s, ")", 0);
905  sqlite3_finalize(pStmt);
906  if( nRow==0 ){
907    freeText(&s);
908    s.z = 0;
909  }
910  return s.z;
911}
912
913/*
914** SQL function:  shell_module_schema(X)
915**
916** Return a fake schema for the table-valued function or eponymous virtual
917** table X.
918*/
919static void shellModuleSchema(
920  sqlite3_context *pCtx,
921  int nVal,
922  sqlite3_value **apVal
923){
924  const char *zName;
925  char *zFake;
926  UNUSED_PARAMETER(nVal);
927  zName = (const char*)sqlite3_value_text(apVal[0]);
928  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
929  if( zFake ){
930    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
931                        -1, sqlite3_free);
932    free(zFake);
933  }
934}
935
936/*
937** SQL function:  shell_add_schema(S,X)
938**
939** Add the schema name X to the CREATE statement in S and return the result.
940** Examples:
941**
942**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
943**
944** Also works on
945**
946**    CREATE INDEX
947**    CREATE UNIQUE INDEX
948**    CREATE VIEW
949**    CREATE TRIGGER
950**    CREATE VIRTUAL TABLE
951**
952** This UDF is used by the .schema command to insert the schema name of
953** attached databases into the middle of the sqlite_schema.sql field.
954*/
955static void shellAddSchemaName(
956  sqlite3_context *pCtx,
957  int nVal,
958  sqlite3_value **apVal
959){
960  static const char *aPrefix[] = {
961     "TABLE",
962     "INDEX",
963     "UNIQUE INDEX",
964     "VIEW",
965     "TRIGGER",
966     "VIRTUAL TABLE"
967  };
968  int i = 0;
969  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
970  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
971  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
972  sqlite3 *db = sqlite3_context_db_handle(pCtx);
973  UNUSED_PARAMETER(nVal);
974  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
975    for(i=0; i<ArraySize(aPrefix); i++){
976      int n = strlen30(aPrefix[i]);
977      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
978        char *z = 0;
979        char *zFake = 0;
980        if( zSchema ){
981          char cQuote = quoteChar(zSchema);
982          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
983            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
984          }else{
985            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
986          }
987        }
988        if( zName
989         && aPrefix[i][0]=='V'
990         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
991        ){
992          if( z==0 ){
993            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
994          }else{
995            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
996          }
997          free(zFake);
998        }
999        if( z ){
1000          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1001          return;
1002        }
1003      }
1004    }
1005  }
1006  sqlite3_result_value(pCtx, apVal[0]);
1007}
1008
1009/*
1010** The source code for several run-time loadable extensions is inserted
1011** below by the ../tool/mkshellc.tcl script.  Before processing that included
1012** code, we need to override some macros to make the included program code
1013** work here in the middle of this regular program.
1014*/
1015#define SQLITE_EXTENSION_INIT1
1016#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1017
1018#if defined(_WIN32) && defined(_MSC_VER)
1019INCLUDE test_windirent.h
1020INCLUDE test_windirent.c
1021#define dirent DIRENT
1022#endif
1023INCLUDE ../ext/misc/memtrace.c
1024INCLUDE ../ext/misc/shathree.c
1025INCLUDE ../ext/misc/uint.c
1026INCLUDE ../ext/misc/decimal.c
1027INCLUDE ../ext/misc/ieee754.c
1028INCLUDE ../ext/misc/series.c
1029INCLUDE ../ext/misc/regexp.c
1030#ifndef SQLITE_SHELL_WASM_MODE
1031INCLUDE ../ext/misc/fileio.c
1032INCLUDE ../ext/misc/completion.c
1033INCLUDE ../ext/misc/appendvfs.c
1034#endif
1035#ifdef SQLITE_HAVE_ZLIB
1036INCLUDE ../ext/misc/zipfile.c
1037INCLUDE ../ext/misc/sqlar.c
1038#endif
1039INCLUDE ../ext/expert/sqlite3expert.h
1040INCLUDE ../ext/expert/sqlite3expert.c
1041
1042#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1043INCLUDE ../ext/misc/dbdata.c
1044#endif
1045
1046#if defined(SQLITE_ENABLE_SESSION)
1047/*
1048** State information for a single open session
1049*/
1050typedef struct OpenSession OpenSession;
1051struct OpenSession {
1052  char *zName;             /* Symbolic name for this session */
1053  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1054  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1055  sqlite3_session *p;      /* The open session */
1056};
1057#endif
1058
1059typedef struct ExpertInfo ExpertInfo;
1060struct ExpertInfo {
1061  sqlite3expert *pExpert;
1062  int bVerbose;
1063};
1064
1065/* A single line in the EQP output */
1066typedef struct EQPGraphRow EQPGraphRow;
1067struct EQPGraphRow {
1068  int iEqpId;           /* ID for this row */
1069  int iParentId;        /* ID of the parent row */
1070  EQPGraphRow *pNext;   /* Next row in sequence */
1071  char zText[1];        /* Text to display for this row */
1072};
1073
1074/* All EQP output is collected into an instance of the following */
1075typedef struct EQPGraph EQPGraph;
1076struct EQPGraph {
1077  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1078  EQPGraphRow *pLast;   /* Last element of the pRow list */
1079  char zPrefix[100];    /* Graph prefix */
1080};
1081
1082/* Parameters affecting columnar mode result display (defaulting together) */
1083typedef struct ColModeOpts {
1084  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1085  u8 bQuote;            /* Quote results for .mode box and table */
1086  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1087} ColModeOpts;
1088#define ColModeOpts_default { 60, 0, 0 }
1089#define ColModeOpts_default_qbox { 60, 1, 0 }
1090
1091/*
1092** State information about the database connection is contained in an
1093** instance of the following structure.
1094*/
1095typedef struct ShellState ShellState;
1096struct ShellState {
1097  sqlite3 *db;           /* The database */
1098  u8 autoExplain;        /* Automatically turn on .explain mode */
1099  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1100  u8 autoEQPtest;        /* autoEQP is in test mode */
1101  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1102  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1103  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1104  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1105  u8 nEqpLevel;          /* Depth of the EQP output graph */
1106  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1107  u8 bSafeMode;          /* True to prohibit unsafe operations */
1108  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1109  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1110  unsigned statsOn;      /* True to display memory stats before each finalize */
1111  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1112  int inputNesting;      /* Track nesting level of .read and other redirects */
1113  int outCount;          /* Revert to stdout when reaching zero */
1114  int cnt;               /* Number of records displayed so far */
1115  int lineno;            /* Line number of last line read from in */
1116  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1117  FILE *in;              /* Read commands from this stream */
1118  FILE *out;             /* Write results here */
1119  FILE *traceOut;        /* Output for sqlite3_trace() */
1120  int nErr;              /* Number of errors seen */
1121  int mode;              /* An output mode setting */
1122  int modePrior;         /* Saved mode */
1123  int cMode;             /* temporary output mode for the current query */
1124  int normalMode;        /* Output mode before ".explain on" */
1125  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1126  int showHeader;        /* True to show column names in List or Column mode */
1127  int nCheck;            /* Number of ".check" commands run */
1128  unsigned nProgress;    /* Number of progress callbacks encountered */
1129  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1130  unsigned flgProgress;  /* Flags for the progress callback */
1131  unsigned shellFlgs;    /* Various flags */
1132  unsigned priorShFlgs;  /* Saved copy of flags */
1133  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1134  char *zDestTable;      /* Name of destination table when MODE_Insert */
1135  char *zTempFile;       /* Temporary file that might need deleting */
1136  char zTestcase[30];    /* Name of current test case */
1137  char colSeparator[20]; /* Column separator character for several modes */
1138  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1139  char colSepPrior[20];  /* Saved column separator */
1140  char rowSepPrior[20];  /* Saved row separator */
1141  int *colWidth;         /* Requested width of each column in columnar modes */
1142  int *actualWidth;      /* Actual width of each column */
1143  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1144  char nullValue[20];    /* The text to print when a NULL comes back from
1145                         ** the database */
1146  char outfile[FILENAME_MAX]; /* Filename for *out */
1147  sqlite3_stmt *pStmt;   /* Current statement if any. */
1148  FILE *pLog;            /* Write log output here */
1149  struct AuxDb {         /* Storage space for auxiliary database connections */
1150    sqlite3 *db;               /* Connection pointer */
1151    const char *zDbFilename;   /* Filename used to open the connection */
1152    char *zFreeOnClose;        /* Free this memory allocation on close */
1153#if defined(SQLITE_ENABLE_SESSION)
1154    int nSession;              /* Number of active sessions */
1155    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1156#endif
1157  } aAuxDb[5],           /* Array of all database connections */
1158    *pAuxDb;             /* Currently active database connection */
1159  int *aiIndent;         /* Array of indents used in MODE_Explain */
1160  int nIndent;           /* Size of array aiIndent[] */
1161  int iIndent;           /* Index of current op in aiIndent[] */
1162  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1163  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1164  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1165#ifdef SQLITE_SHELL_WASM_MODE
1166  struct {
1167    const char * zInput; /* Input string from wasm/JS proxy */
1168    const char * zPos;   /* Cursor pos into zInput */
1169  } wasm;
1170#endif
1171};
1172
1173#ifdef SQLITE_SHELL_WASM_MODE
1174static ShellState shellState;
1175#endif
1176
1177
1178/* Allowed values for ShellState.autoEQP
1179*/
1180#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1181#define AUTOEQP_on       1           /* Automatic EQP is on */
1182#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1183#define AUTOEQP_full     3           /* Show full EXPLAIN */
1184
1185/* Allowed values for ShellState.openMode
1186*/
1187#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1188#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1189#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1190#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1191#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1192#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1193#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1194
1195/* Allowed values for ShellState.eTraceType
1196*/
1197#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1198#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1199#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1200
1201/* Bits in the ShellState.flgProgress variable */
1202#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1203#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1204                                   ** callback limit is reached, and for each
1205                                   ** top-level SQL statement */
1206#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1207
1208/*
1209** These are the allowed shellFlgs values
1210*/
1211#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1212#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1213#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1214#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1215#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1216#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1217#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1218#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1219#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1220#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1221
1222/*
1223** Macros for testing and setting shellFlgs
1224*/
1225#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1226#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1227#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1228
1229/*
1230** These are the allowed modes.
1231*/
1232#define MODE_Line     0  /* One column per line.  Blank line between records */
1233#define MODE_Column   1  /* One record per line in neat columns */
1234#define MODE_List     2  /* One record per line with a separator */
1235#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1236#define MODE_Html     4  /* Generate an XHTML table */
1237#define MODE_Insert   5  /* Generate SQL "insert" statements */
1238#define MODE_Quote    6  /* Quote values as for SQL */
1239#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1240#define MODE_Csv      8  /* Quote strings, numbers are plain */
1241#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1242#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1243#define MODE_Pretty  11  /* Pretty-print schemas */
1244#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1245#define MODE_Json    13  /* Output JSON */
1246#define MODE_Markdown 14 /* Markdown formatting */
1247#define MODE_Table   15  /* MySQL-style table formatting */
1248#define MODE_Box     16  /* Unicode box-drawing characters */
1249#define MODE_Count   17  /* Output only a count of the rows of output */
1250#define MODE_Off     18  /* No query output shown */
1251
1252static const char *modeDescr[] = {
1253  "line",
1254  "column",
1255  "list",
1256  "semi",
1257  "html",
1258  "insert",
1259  "quote",
1260  "tcl",
1261  "csv",
1262  "explain",
1263  "ascii",
1264  "prettyprint",
1265  "eqp",
1266  "json",
1267  "markdown",
1268  "table",
1269  "box",
1270  "count",
1271  "off"
1272};
1273
1274/*
1275** These are the column/row/line separators used by the various
1276** import/export modes.
1277*/
1278#define SEP_Column    "|"
1279#define SEP_Row       "\n"
1280#define SEP_Tab       "\t"
1281#define SEP_Space     " "
1282#define SEP_Comma     ","
1283#define SEP_CrLf      "\r\n"
1284#define SEP_Unit      "\x1F"
1285#define SEP_Record    "\x1E"
1286
1287/*
1288** Limit input nesting via .read or any other input redirect.
1289** It's not too expensive, so a generous allowance can be made.
1290*/
1291#define MAX_INPUT_NESTING 25
1292
1293/*
1294** A callback for the sqlite3_log() interface.
1295*/
1296static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1297  ShellState *p = (ShellState*)pArg;
1298  if( p->pLog==0 ) return;
1299  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1300  fflush(p->pLog);
1301}
1302
1303/*
1304** SQL function:  shell_putsnl(X)
1305**
1306** Write the text X to the screen (or whatever output is being directed)
1307** adding a newline at the end, and then return X.
1308*/
1309static void shellPutsFunc(
1310  sqlite3_context *pCtx,
1311  int nVal,
1312  sqlite3_value **apVal
1313){
1314  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1315  (void)nVal;
1316  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1317  sqlite3_result_value(pCtx, apVal[0]);
1318}
1319
1320/*
1321** If in safe mode, print an error message described by the arguments
1322** and exit immediately.
1323*/
1324static void failIfSafeMode(
1325  ShellState *p,
1326  const char *zErrMsg,
1327  ...
1328){
1329  if( p->bSafeMode ){
1330    va_list ap;
1331    char *zMsg;
1332    va_start(ap, zErrMsg);
1333    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1334    va_end(ap);
1335    raw_printf(stderr, "line %d: ", p->lineno);
1336    utf8_printf(stderr, "%s\n", zMsg);
1337    exit(1);
1338  }
1339}
1340
1341/*
1342** SQL function:   edit(VALUE)
1343**                 edit(VALUE,EDITOR)
1344**
1345** These steps:
1346**
1347**     (1) Write VALUE into a temporary file.
1348**     (2) Run program EDITOR on that temporary file.
1349**     (3) Read the temporary file back and return its content as the result.
1350**     (4) Delete the temporary file
1351**
1352** If the EDITOR argument is omitted, use the value in the VISUAL
1353** environment variable.  If still there is no EDITOR, through an error.
1354**
1355** Also throw an error if the EDITOR program returns a non-zero exit code.
1356*/
1357#ifndef SQLITE_NOHAVE_SYSTEM
1358static void editFunc(
1359  sqlite3_context *context,
1360  int argc,
1361  sqlite3_value **argv
1362){
1363  const char *zEditor;
1364  char *zTempFile = 0;
1365  sqlite3 *db;
1366  char *zCmd = 0;
1367  int bBin;
1368  int rc;
1369  int hasCRNL = 0;
1370  FILE *f = 0;
1371  sqlite3_int64 sz;
1372  sqlite3_int64 x;
1373  unsigned char *p = 0;
1374
1375  if( argc==2 ){
1376    zEditor = (const char*)sqlite3_value_text(argv[1]);
1377  }else{
1378    zEditor = getenv("VISUAL");
1379  }
1380  if( zEditor==0 ){
1381    sqlite3_result_error(context, "no editor for edit()", -1);
1382    return;
1383  }
1384  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1385    sqlite3_result_error(context, "NULL input to edit()", -1);
1386    return;
1387  }
1388  db = sqlite3_context_db_handle(context);
1389  zTempFile = 0;
1390  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1391  if( zTempFile==0 ){
1392    sqlite3_uint64 r = 0;
1393    sqlite3_randomness(sizeof(r), &r);
1394    zTempFile = sqlite3_mprintf("temp%llx", r);
1395    if( zTempFile==0 ){
1396      sqlite3_result_error_nomem(context);
1397      return;
1398    }
1399  }
1400  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1401  /* When writing the file to be edited, do \n to \r\n conversions on systems
1402  ** that want \r\n line endings */
1403  f = fopen(zTempFile, bBin ? "wb" : "w");
1404  if( f==0 ){
1405    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1406    goto edit_func_end;
1407  }
1408  sz = sqlite3_value_bytes(argv[0]);
1409  if( bBin ){
1410    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1411  }else{
1412    const char *z = (const char*)sqlite3_value_text(argv[0]);
1413    /* Remember whether or not the value originally contained \r\n */
1414    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1415    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1416  }
1417  fclose(f);
1418  f = 0;
1419  if( x!=sz ){
1420    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1421    goto edit_func_end;
1422  }
1423  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1424  if( zCmd==0 ){
1425    sqlite3_result_error_nomem(context);
1426    goto edit_func_end;
1427  }
1428  rc = system(zCmd);
1429  sqlite3_free(zCmd);
1430  if( rc ){
1431    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1432    goto edit_func_end;
1433  }
1434  f = fopen(zTempFile, "rb");
1435  if( f==0 ){
1436    sqlite3_result_error(context,
1437      "edit() cannot reopen temp file after edit", -1);
1438    goto edit_func_end;
1439  }
1440  fseek(f, 0, SEEK_END);
1441  sz = ftell(f);
1442  rewind(f);
1443  p = sqlite3_malloc64( sz+1 );
1444  if( p==0 ){
1445    sqlite3_result_error_nomem(context);
1446    goto edit_func_end;
1447  }
1448  x = fread(p, 1, (size_t)sz, f);
1449  fclose(f);
1450  f = 0;
1451  if( x!=sz ){
1452    sqlite3_result_error(context, "could not read back the whole file", -1);
1453    goto edit_func_end;
1454  }
1455  if( bBin ){
1456    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1457  }else{
1458    sqlite3_int64 i, j;
1459    if( hasCRNL ){
1460      /* If the original contains \r\n then do no conversions back to \n */
1461    }else{
1462      /* If the file did not originally contain \r\n then convert any new
1463      ** \r\n back into \n */
1464      for(i=j=0; i<sz; i++){
1465        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1466        p[j++] = p[i];
1467      }
1468      sz = j;
1469      p[sz] = 0;
1470    }
1471    sqlite3_result_text64(context, (const char*)p, sz,
1472                          sqlite3_free, SQLITE_UTF8);
1473  }
1474  p = 0;
1475
1476edit_func_end:
1477  if( f ) fclose(f);
1478  unlink(zTempFile);
1479  sqlite3_free(zTempFile);
1480  sqlite3_free(p);
1481}
1482#endif /* SQLITE_NOHAVE_SYSTEM */
1483
1484/*
1485** Save or restore the current output mode
1486*/
1487static void outputModePush(ShellState *p){
1488  p->modePrior = p->mode;
1489  p->priorShFlgs = p->shellFlgs;
1490  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1491  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1492}
1493static void outputModePop(ShellState *p){
1494  p->mode = p->modePrior;
1495  p->shellFlgs = p->priorShFlgs;
1496  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1497  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1498}
1499
1500/*
1501** Output the given string as a hex-encoded blob (eg. X'1234' )
1502*/
1503static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1504  int i;
1505  char *zBlob = (char *)pBlob;
1506  raw_printf(out,"X'");
1507  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1508  raw_printf(out,"'");
1509}
1510
1511/*
1512** Find a string that is not found anywhere in z[].  Return a pointer
1513** to that string.
1514**
1515** Try to use zA and zB first.  If both of those are already found in z[]
1516** then make up some string and store it in the buffer zBuf.
1517*/
1518static const char *unused_string(
1519  const char *z,                    /* Result must not appear anywhere in z */
1520  const char *zA, const char *zB,   /* Try these first */
1521  char *zBuf                        /* Space to store a generated string */
1522){
1523  unsigned i = 0;
1524  if( strstr(z, zA)==0 ) return zA;
1525  if( strstr(z, zB)==0 ) return zB;
1526  do{
1527    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1528  }while( strstr(z,zBuf)!=0 );
1529  return zBuf;
1530}
1531
1532/*
1533** Output the given string as a quoted string using SQL quoting conventions.
1534**
1535** See also: output_quoted_escaped_string()
1536*/
1537static void output_quoted_string(FILE *out, const char *z){
1538  int i;
1539  char c;
1540  setBinaryMode(out, 1);
1541  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1542  if( c==0 ){
1543    utf8_printf(out,"'%s'",z);
1544  }else{
1545    raw_printf(out, "'");
1546    while( *z ){
1547      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1548      if( c=='\'' ) i++;
1549      if( i ){
1550        utf8_printf(out, "%.*s", i, z);
1551        z += i;
1552      }
1553      if( c=='\'' ){
1554        raw_printf(out, "'");
1555        continue;
1556      }
1557      if( c==0 ){
1558        break;
1559      }
1560      z++;
1561    }
1562    raw_printf(out, "'");
1563  }
1564  setTextMode(out, 1);
1565}
1566
1567/*
1568** Output the given string as a quoted string using SQL quoting conventions.
1569** Additionallly , escape the "\n" and "\r" characters so that they do not
1570** get corrupted by end-of-line translation facilities in some operating
1571** systems.
1572**
1573** This is like output_quoted_string() but with the addition of the \r\n
1574** escape mechanism.
1575*/
1576static void output_quoted_escaped_string(FILE *out, const char *z){
1577  int i;
1578  char c;
1579  setBinaryMode(out, 1);
1580  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1581  if( c==0 ){
1582    utf8_printf(out,"'%s'",z);
1583  }else{
1584    const char *zNL = 0;
1585    const char *zCR = 0;
1586    int nNL = 0;
1587    int nCR = 0;
1588    char zBuf1[20], zBuf2[20];
1589    for(i=0; z[i]; i++){
1590      if( z[i]=='\n' ) nNL++;
1591      if( z[i]=='\r' ) nCR++;
1592    }
1593    if( nNL ){
1594      raw_printf(out, "replace(");
1595      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1596    }
1597    if( nCR ){
1598      raw_printf(out, "replace(");
1599      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1600    }
1601    raw_printf(out, "'");
1602    while( *z ){
1603      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1604      if( c=='\'' ) i++;
1605      if( i ){
1606        utf8_printf(out, "%.*s", i, z);
1607        z += i;
1608      }
1609      if( c=='\'' ){
1610        raw_printf(out, "'");
1611        continue;
1612      }
1613      if( c==0 ){
1614        break;
1615      }
1616      z++;
1617      if( c=='\n' ){
1618        raw_printf(out, "%s", zNL);
1619        continue;
1620      }
1621      raw_printf(out, "%s", zCR);
1622    }
1623    raw_printf(out, "'");
1624    if( nCR ){
1625      raw_printf(out, ",'%s',char(13))", zCR);
1626    }
1627    if( nNL ){
1628      raw_printf(out, ",'%s',char(10))", zNL);
1629    }
1630  }
1631  setTextMode(out, 1);
1632}
1633
1634/*
1635** Output the given string as a quoted according to C or TCL quoting rules.
1636*/
1637static void output_c_string(FILE *out, const char *z){
1638  unsigned int c;
1639  fputc('"', out);
1640  while( (c = *(z++))!=0 ){
1641    if( c=='\\' ){
1642      fputc(c, out);
1643      fputc(c, out);
1644    }else if( c=='"' ){
1645      fputc('\\', out);
1646      fputc('"', out);
1647    }else if( c=='\t' ){
1648      fputc('\\', out);
1649      fputc('t', out);
1650    }else if( c=='\n' ){
1651      fputc('\\', out);
1652      fputc('n', out);
1653    }else if( c=='\r' ){
1654      fputc('\\', out);
1655      fputc('r', out);
1656    }else if( !isprint(c&0xff) ){
1657      raw_printf(out, "\\%03o", c&0xff);
1658    }else{
1659      fputc(c, out);
1660    }
1661  }
1662  fputc('"', out);
1663}
1664
1665/*
1666** Output the given string as a quoted according to JSON quoting rules.
1667*/
1668static void output_json_string(FILE *out, const char *z, int n){
1669  unsigned int c;
1670  if( n<0 ) n = (int)strlen(z);
1671  fputc('"', out);
1672  while( n-- ){
1673    c = *(z++);
1674    if( c=='\\' || c=='"' ){
1675      fputc('\\', out);
1676      fputc(c, out);
1677    }else if( c<=0x1f ){
1678      fputc('\\', out);
1679      if( c=='\b' ){
1680        fputc('b', out);
1681      }else if( c=='\f' ){
1682        fputc('f', out);
1683      }else if( c=='\n' ){
1684        fputc('n', out);
1685      }else if( c=='\r' ){
1686        fputc('r', out);
1687      }else if( c=='\t' ){
1688        fputc('t', out);
1689      }else{
1690         raw_printf(out, "u%04x",c);
1691      }
1692    }else{
1693      fputc(c, out);
1694    }
1695  }
1696  fputc('"', out);
1697}
1698
1699/*
1700** Output the given string with characters that are special to
1701** HTML escaped.
1702*/
1703static void output_html_string(FILE *out, const char *z){
1704  int i;
1705  if( z==0 ) z = "";
1706  while( *z ){
1707    for(i=0;   z[i]
1708            && z[i]!='<'
1709            && z[i]!='&'
1710            && z[i]!='>'
1711            && z[i]!='\"'
1712            && z[i]!='\'';
1713        i++){}
1714    if( i>0 ){
1715      utf8_printf(out,"%.*s",i,z);
1716    }
1717    if( z[i]=='<' ){
1718      raw_printf(out,"&lt;");
1719    }else if( z[i]=='&' ){
1720      raw_printf(out,"&amp;");
1721    }else if( z[i]=='>' ){
1722      raw_printf(out,"&gt;");
1723    }else if( z[i]=='\"' ){
1724      raw_printf(out,"&quot;");
1725    }else if( z[i]=='\'' ){
1726      raw_printf(out,"&#39;");
1727    }else{
1728      break;
1729    }
1730    z += i + 1;
1731  }
1732}
1733
1734/*
1735** If a field contains any character identified by a 1 in the following
1736** array, then the string must be quoted for CSV.
1737*/
1738static const char needCsvQuote[] = {
1739  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1740  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1741  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1742  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1743  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1744  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1745  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1746  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1747  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1748  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1749  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1750  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1751  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1752  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1753  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1754  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1755};
1756
1757/*
1758** Output a single term of CSV.  Actually, p->colSeparator is used for
1759** the separator, which may or may not be a comma.  p->nullValue is
1760** the null value.  Strings are quoted if necessary.  The separator
1761** is only issued if bSep is true.
1762*/
1763static void output_csv(ShellState *p, const char *z, int bSep){
1764  FILE *out = p->out;
1765  if( z==0 ){
1766    utf8_printf(out,"%s",p->nullValue);
1767  }else{
1768    unsigned i;
1769    for(i=0; z[i]; i++){
1770      if( needCsvQuote[((unsigned char*)z)[i]] ){
1771        i = 0;
1772        break;
1773      }
1774    }
1775    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1776      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1777      shell_check_oom(zQuoted);
1778      utf8_printf(out, "%s", zQuoted);
1779      sqlite3_free(zQuoted);
1780    }else{
1781      utf8_printf(out, "%s", z);
1782    }
1783  }
1784  if( bSep ){
1785    utf8_printf(p->out, "%s", p->colSeparator);
1786  }
1787}
1788
1789/*
1790** This routine runs when the user presses Ctrl-C
1791*/
1792static void interrupt_handler(int NotUsed){
1793  UNUSED_PARAMETER(NotUsed);
1794  seenInterrupt++;
1795  if( seenInterrupt>2 ) exit(1);
1796  if( globalDb ) sqlite3_interrupt(globalDb);
1797}
1798
1799#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1800/*
1801** This routine runs for console events (e.g. Ctrl-C) on Win32
1802*/
1803static BOOL WINAPI ConsoleCtrlHandler(
1804  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1805){
1806  if( dwCtrlType==CTRL_C_EVENT ){
1807    interrupt_handler(0);
1808    return TRUE;
1809  }
1810  return FALSE;
1811}
1812#endif
1813
1814#ifndef SQLITE_OMIT_AUTHORIZATION
1815/*
1816** This authorizer runs in safe mode.
1817*/
1818static int safeModeAuth(
1819  void *pClientData,
1820  int op,
1821  const char *zA1,
1822  const char *zA2,
1823  const char *zA3,
1824  const char *zA4
1825){
1826  ShellState *p = (ShellState*)pClientData;
1827  static const char *azProhibitedFunctions[] = {
1828    "edit",
1829    "fts3_tokenizer",
1830    "load_extension",
1831    "readfile",
1832    "writefile",
1833    "zipfile",
1834    "zipfile_cds",
1835  };
1836  UNUSED_PARAMETER(zA2);
1837  UNUSED_PARAMETER(zA3);
1838  UNUSED_PARAMETER(zA4);
1839  switch( op ){
1840    case SQLITE_ATTACH: {
1841      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1842      break;
1843    }
1844    case SQLITE_FUNCTION: {
1845      int i;
1846      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1847        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1848          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1849                         azProhibitedFunctions[i]);
1850        }
1851      }
1852      break;
1853    }
1854  }
1855  return SQLITE_OK;
1856}
1857
1858/*
1859** When the ".auth ON" is set, the following authorizer callback is
1860** invoked.  It always returns SQLITE_OK.
1861*/
1862static int shellAuth(
1863  void *pClientData,
1864  int op,
1865  const char *zA1,
1866  const char *zA2,
1867  const char *zA3,
1868  const char *zA4
1869){
1870  ShellState *p = (ShellState*)pClientData;
1871  static const char *azAction[] = { 0,
1872     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1873     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1874     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1875     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1876     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1877     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1878     "PRAGMA",               "READ",                 "SELECT",
1879     "TRANSACTION",          "UPDATE",               "ATTACH",
1880     "DETACH",               "ALTER_TABLE",          "REINDEX",
1881     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1882     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1883  };
1884  int i;
1885  const char *az[4];
1886  az[0] = zA1;
1887  az[1] = zA2;
1888  az[2] = zA3;
1889  az[3] = zA4;
1890  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1891  for(i=0; i<4; i++){
1892    raw_printf(p->out, " ");
1893    if( az[i] ){
1894      output_c_string(p->out, az[i]);
1895    }else{
1896      raw_printf(p->out, "NULL");
1897    }
1898  }
1899  raw_printf(p->out, "\n");
1900  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1901  return SQLITE_OK;
1902}
1903#endif
1904
1905/*
1906** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1907**
1908** This routine converts some CREATE TABLE statements for shadow tables
1909** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1910*/
1911static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1912  if( z==0 ) return;
1913  if( zTail==0 ) return;
1914  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1915    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1916  }else{
1917    utf8_printf(out, "%s%s", z, zTail);
1918  }
1919}
1920static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1921  char c = z[n];
1922  z[n] = 0;
1923  printSchemaLine(out, z, zTail);
1924  z[n] = c;
1925}
1926
1927/*
1928** Return true if string z[] has nothing but whitespace and comments to the
1929** end of the first line.
1930*/
1931static int wsToEol(const char *z){
1932  int i;
1933  for(i=0; z[i]; i++){
1934    if( z[i]=='\n' ) return 1;
1935    if( IsSpace(z[i]) ) continue;
1936    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1937    return 0;
1938  }
1939  return 1;
1940}
1941
1942/*
1943** Add a new entry to the EXPLAIN QUERY PLAN data
1944*/
1945static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1946  EQPGraphRow *pNew;
1947  int nText = strlen30(zText);
1948  if( p->autoEQPtest ){
1949    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1950  }
1951  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1952  shell_check_oom(pNew);
1953  pNew->iEqpId = iEqpId;
1954  pNew->iParentId = p2;
1955  memcpy(pNew->zText, zText, nText+1);
1956  pNew->pNext = 0;
1957  if( p->sGraph.pLast ){
1958    p->sGraph.pLast->pNext = pNew;
1959  }else{
1960    p->sGraph.pRow = pNew;
1961  }
1962  p->sGraph.pLast = pNew;
1963}
1964
1965/*
1966** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1967** in p->sGraph.
1968*/
1969static void eqp_reset(ShellState *p){
1970  EQPGraphRow *pRow, *pNext;
1971  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1972    pNext = pRow->pNext;
1973    sqlite3_free(pRow);
1974  }
1975  memset(&p->sGraph, 0, sizeof(p->sGraph));
1976}
1977
1978/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1979** pOld, or return the first such line if pOld is NULL
1980*/
1981static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1982  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1983  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1984  return pRow;
1985}
1986
1987/* Render a single level of the graph that has iEqpId as its parent.  Called
1988** recursively to render sublevels.
1989*/
1990static void eqp_render_level(ShellState *p, int iEqpId){
1991  EQPGraphRow *pRow, *pNext;
1992  int n = strlen30(p->sGraph.zPrefix);
1993  char *z;
1994  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1995    pNext = eqp_next_row(p, iEqpId, pRow);
1996    z = pRow->zText;
1997    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1998                pNext ? "|--" : "`--", z);
1999    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2000      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2001      eqp_render_level(p, pRow->iEqpId);
2002      p->sGraph.zPrefix[n] = 0;
2003    }
2004  }
2005}
2006
2007/*
2008** Display and reset the EXPLAIN QUERY PLAN data
2009*/
2010static void eqp_render(ShellState *p){
2011  EQPGraphRow *pRow = p->sGraph.pRow;
2012  if( pRow ){
2013    if( pRow->zText[0]=='-' ){
2014      if( pRow->pNext==0 ){
2015        eqp_reset(p);
2016        return;
2017      }
2018      utf8_printf(p->out, "%s\n", pRow->zText+3);
2019      p->sGraph.pRow = pRow->pNext;
2020      sqlite3_free(pRow);
2021    }else{
2022      utf8_printf(p->out, "QUERY PLAN\n");
2023    }
2024    p->sGraph.zPrefix[0] = 0;
2025    eqp_render_level(p, 0);
2026    eqp_reset(p);
2027  }
2028}
2029
2030#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2031/*
2032** Progress handler callback.
2033*/
2034static int progress_handler(void *pClientData) {
2035  ShellState *p = (ShellState*)pClientData;
2036  p->nProgress++;
2037  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2038    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2039    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2040    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2041    return 1;
2042  }
2043  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2044    raw_printf(p->out, "Progress %u\n", p->nProgress);
2045  }
2046  return 0;
2047}
2048#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2049
2050/*
2051** Print N dashes
2052*/
2053static void print_dashes(FILE *out, int N){
2054  const char zDash[] = "--------------------------------------------------";
2055  const int nDash = sizeof(zDash) - 1;
2056  while( N>nDash ){
2057    fputs(zDash, out);
2058    N -= nDash;
2059  }
2060  raw_printf(out, "%.*s", N, zDash);
2061}
2062
2063/*
2064** Print a markdown or table-style row separator using ascii-art
2065*/
2066static void print_row_separator(
2067  ShellState *p,
2068  int nArg,
2069  const char *zSep
2070){
2071  int i;
2072  if( nArg>0 ){
2073    fputs(zSep, p->out);
2074    print_dashes(p->out, p->actualWidth[0]+2);
2075    for(i=1; i<nArg; i++){
2076      fputs(zSep, p->out);
2077      print_dashes(p->out, p->actualWidth[i]+2);
2078    }
2079    fputs(zSep, p->out);
2080  }
2081  fputs("\n", p->out);
2082}
2083
2084/*
2085** This is the callback routine that the shell
2086** invokes for each row of a query result.
2087*/
2088static int shell_callback(
2089  void *pArg,
2090  int nArg,        /* Number of result columns */
2091  char **azArg,    /* Text of each result column */
2092  char **azCol,    /* Column names */
2093  int *aiType      /* Column types.  Might be NULL */
2094){
2095  int i;
2096  ShellState *p = (ShellState*)pArg;
2097
2098  if( azArg==0 ) return 0;
2099  switch( p->cMode ){
2100    case MODE_Count:
2101    case MODE_Off: {
2102      break;
2103    }
2104    case MODE_Line: {
2105      int w = 5;
2106      if( azArg==0 ) break;
2107      for(i=0; i<nArg; i++){
2108        int len = strlen30(azCol[i] ? azCol[i] : "");
2109        if( len>w ) w = len;
2110      }
2111      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2112      for(i=0; i<nArg; i++){
2113        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2114                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2115      }
2116      break;
2117    }
2118    case MODE_Explain: {
2119      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2120      if( nArg>ArraySize(aExplainWidth) ){
2121        nArg = ArraySize(aExplainWidth);
2122      }
2123      if( p->cnt++==0 ){
2124        for(i=0; i<nArg; i++){
2125          int w = aExplainWidth[i];
2126          utf8_width_print(p->out, w, azCol[i]);
2127          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2128        }
2129        for(i=0; i<nArg; i++){
2130          int w = aExplainWidth[i];
2131          print_dashes(p->out, w);
2132          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2133        }
2134      }
2135      if( azArg==0 ) break;
2136      for(i=0; i<nArg; i++){
2137        int w = aExplainWidth[i];
2138        if( i==nArg-1 ) w = 0;
2139        if( azArg[i] && strlenChar(azArg[i])>w ){
2140          w = strlenChar(azArg[i]);
2141        }
2142        if( i==1 && p->aiIndent && p->pStmt ){
2143          if( p->iIndent<p->nIndent ){
2144            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2145          }
2146          p->iIndent++;
2147        }
2148        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2149        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2150      }
2151      break;
2152    }
2153    case MODE_Semi: {   /* .schema and .fullschema output */
2154      printSchemaLine(p->out, azArg[0], ";\n");
2155      break;
2156    }
2157    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2158      char *z;
2159      int j;
2160      int nParen = 0;
2161      char cEnd = 0;
2162      char c;
2163      int nLine = 0;
2164      assert( nArg==1 );
2165      if( azArg[0]==0 ) break;
2166      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2167       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2168      ){
2169        utf8_printf(p->out, "%s;\n", azArg[0]);
2170        break;
2171      }
2172      z = sqlite3_mprintf("%s", azArg[0]);
2173      shell_check_oom(z);
2174      j = 0;
2175      for(i=0; IsSpace(z[i]); i++){}
2176      for(; (c = z[i])!=0; i++){
2177        if( IsSpace(c) ){
2178          if( z[j-1]=='\r' ) z[j-1] = '\n';
2179          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2180        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2181          j--;
2182        }
2183        z[j++] = c;
2184      }
2185      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2186      z[j] = 0;
2187      if( strlen30(z)>=79 ){
2188        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2189          if( c==cEnd ){
2190            cEnd = 0;
2191          }else if( c=='"' || c=='\'' || c=='`' ){
2192            cEnd = c;
2193          }else if( c=='[' ){
2194            cEnd = ']';
2195          }else if( c=='-' && z[i+1]=='-' ){
2196            cEnd = '\n';
2197          }else if( c=='(' ){
2198            nParen++;
2199          }else if( c==')' ){
2200            nParen--;
2201            if( nLine>0 && nParen==0 && j>0 ){
2202              printSchemaLineN(p->out, z, j, "\n");
2203              j = 0;
2204            }
2205          }
2206          z[j++] = c;
2207          if( nParen==1 && cEnd==0
2208           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2209          ){
2210            if( c=='\n' ) j--;
2211            printSchemaLineN(p->out, z, j, "\n  ");
2212            j = 0;
2213            nLine++;
2214            while( IsSpace(z[i+1]) ){ i++; }
2215          }
2216        }
2217        z[j] = 0;
2218      }
2219      printSchemaLine(p->out, z, ";\n");
2220      sqlite3_free(z);
2221      break;
2222    }
2223    case MODE_List: {
2224      if( p->cnt++==0 && p->showHeader ){
2225        for(i=0; i<nArg; i++){
2226          utf8_printf(p->out,"%s%s",azCol[i],
2227                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2228        }
2229      }
2230      if( azArg==0 ) break;
2231      for(i=0; i<nArg; i++){
2232        char *z = azArg[i];
2233        if( z==0 ) z = p->nullValue;
2234        utf8_printf(p->out, "%s", z);
2235        if( i<nArg-1 ){
2236          utf8_printf(p->out, "%s", p->colSeparator);
2237        }else{
2238          utf8_printf(p->out, "%s", p->rowSeparator);
2239        }
2240      }
2241      break;
2242    }
2243    case MODE_Html: {
2244      if( p->cnt++==0 && p->showHeader ){
2245        raw_printf(p->out,"<TR>");
2246        for(i=0; i<nArg; i++){
2247          raw_printf(p->out,"<TH>");
2248          output_html_string(p->out, azCol[i]);
2249          raw_printf(p->out,"</TH>\n");
2250        }
2251        raw_printf(p->out,"</TR>\n");
2252      }
2253      if( azArg==0 ) break;
2254      raw_printf(p->out,"<TR>");
2255      for(i=0; i<nArg; i++){
2256        raw_printf(p->out,"<TD>");
2257        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2258        raw_printf(p->out,"</TD>\n");
2259      }
2260      raw_printf(p->out,"</TR>\n");
2261      break;
2262    }
2263    case MODE_Tcl: {
2264      if( p->cnt++==0 && p->showHeader ){
2265        for(i=0; i<nArg; i++){
2266          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2267          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2268        }
2269        utf8_printf(p->out, "%s", p->rowSeparator);
2270      }
2271      if( azArg==0 ) break;
2272      for(i=0; i<nArg; i++){
2273        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2274        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2275      }
2276      utf8_printf(p->out, "%s", p->rowSeparator);
2277      break;
2278    }
2279    case MODE_Csv: {
2280      setBinaryMode(p->out, 1);
2281      if( p->cnt++==0 && p->showHeader ){
2282        for(i=0; i<nArg; i++){
2283          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2284        }
2285        utf8_printf(p->out, "%s", p->rowSeparator);
2286      }
2287      if( nArg>0 ){
2288        for(i=0; i<nArg; i++){
2289          output_csv(p, azArg[i], i<nArg-1);
2290        }
2291        utf8_printf(p->out, "%s", p->rowSeparator);
2292      }
2293      setTextMode(p->out, 1);
2294      break;
2295    }
2296    case MODE_Insert: {
2297      if( azArg==0 ) break;
2298      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2299      if( p->showHeader ){
2300        raw_printf(p->out,"(");
2301        for(i=0; i<nArg; i++){
2302          if( i>0 ) raw_printf(p->out, ",");
2303          if( quoteChar(azCol[i]) ){
2304            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2305            shell_check_oom(z);
2306            utf8_printf(p->out, "%s", z);
2307            sqlite3_free(z);
2308          }else{
2309            raw_printf(p->out, "%s", azCol[i]);
2310          }
2311        }
2312        raw_printf(p->out,")");
2313      }
2314      p->cnt++;
2315      for(i=0; i<nArg; i++){
2316        raw_printf(p->out, i>0 ? "," : " VALUES(");
2317        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2318          utf8_printf(p->out,"NULL");
2319        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2320          if( ShellHasFlag(p, SHFLG_Newlines) ){
2321            output_quoted_string(p->out, azArg[i]);
2322          }else{
2323            output_quoted_escaped_string(p->out, azArg[i]);
2324          }
2325        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2326          utf8_printf(p->out,"%s", azArg[i]);
2327        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2328          char z[50];
2329          double r = sqlite3_column_double(p->pStmt, i);
2330          sqlite3_uint64 ur;
2331          memcpy(&ur,&r,sizeof(r));
2332          if( ur==0x7ff0000000000000LL ){
2333            raw_printf(p->out, "1e999");
2334          }else if( ur==0xfff0000000000000LL ){
2335            raw_printf(p->out, "-1e999");
2336          }else{
2337            sqlite3_int64 ir = (sqlite3_int64)r;
2338            if( r==(double)ir ){
2339              sqlite3_snprintf(50,z,"%lld.0", ir);
2340            }else{
2341              sqlite3_snprintf(50,z,"%!.20g", r);
2342            }
2343            raw_printf(p->out, "%s", z);
2344          }
2345        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2346          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2347          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2348          output_hex_blob(p->out, pBlob, nBlob);
2349        }else if( isNumber(azArg[i], 0) ){
2350          utf8_printf(p->out,"%s", azArg[i]);
2351        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2352          output_quoted_string(p->out, azArg[i]);
2353        }else{
2354          output_quoted_escaped_string(p->out, azArg[i]);
2355        }
2356      }
2357      raw_printf(p->out,");\n");
2358      break;
2359    }
2360    case MODE_Json: {
2361      if( azArg==0 ) break;
2362      if( p->cnt==0 ){
2363        fputs("[{", p->out);
2364      }else{
2365        fputs(",\n{", p->out);
2366      }
2367      p->cnt++;
2368      for(i=0; i<nArg; i++){
2369        output_json_string(p->out, azCol[i], -1);
2370        putc(':', p->out);
2371        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2372          fputs("null",p->out);
2373        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2374          char z[50];
2375          double r = sqlite3_column_double(p->pStmt, i);
2376          sqlite3_uint64 ur;
2377          memcpy(&ur,&r,sizeof(r));
2378          if( ur==0x7ff0000000000000LL ){
2379            raw_printf(p->out, "1e999");
2380          }else if( ur==0xfff0000000000000LL ){
2381            raw_printf(p->out, "-1e999");
2382          }else{
2383            sqlite3_snprintf(50,z,"%!.20g", r);
2384            raw_printf(p->out, "%s", z);
2385          }
2386        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2387          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2388          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2389          output_json_string(p->out, pBlob, nBlob);
2390        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2391          output_json_string(p->out, azArg[i], -1);
2392        }else{
2393          utf8_printf(p->out,"%s", azArg[i]);
2394        }
2395        if( i<nArg-1 ){
2396          putc(',', p->out);
2397        }
2398      }
2399      putc('}', p->out);
2400      break;
2401    }
2402    case MODE_Quote: {
2403      if( azArg==0 ) break;
2404      if( p->cnt==0 && p->showHeader ){
2405        for(i=0; i<nArg; i++){
2406          if( i>0 ) fputs(p->colSeparator, p->out);
2407          output_quoted_string(p->out, azCol[i]);
2408        }
2409        fputs(p->rowSeparator, p->out);
2410      }
2411      p->cnt++;
2412      for(i=0; i<nArg; i++){
2413        if( i>0 ) fputs(p->colSeparator, p->out);
2414        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2415          utf8_printf(p->out,"NULL");
2416        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2417          output_quoted_string(p->out, azArg[i]);
2418        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2419          utf8_printf(p->out,"%s", azArg[i]);
2420        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2421          char z[50];
2422          double r = sqlite3_column_double(p->pStmt, i);
2423          sqlite3_snprintf(50,z,"%!.20g", r);
2424          raw_printf(p->out, "%s", z);
2425        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2426          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2427          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2428          output_hex_blob(p->out, pBlob, nBlob);
2429        }else if( isNumber(azArg[i], 0) ){
2430          utf8_printf(p->out,"%s", azArg[i]);
2431        }else{
2432          output_quoted_string(p->out, azArg[i]);
2433        }
2434      }
2435      fputs(p->rowSeparator, p->out);
2436      break;
2437    }
2438    case MODE_Ascii: {
2439      if( p->cnt++==0 && p->showHeader ){
2440        for(i=0; i<nArg; i++){
2441          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2442          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2443        }
2444        utf8_printf(p->out, "%s", p->rowSeparator);
2445      }
2446      if( azArg==0 ) break;
2447      for(i=0; i<nArg; i++){
2448        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2449        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2450      }
2451      utf8_printf(p->out, "%s", p->rowSeparator);
2452      break;
2453    }
2454    case MODE_EQP: {
2455      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2456      break;
2457    }
2458  }
2459  return 0;
2460}
2461
2462/*
2463** This is the callback routine that the SQLite library
2464** invokes for each row of a query result.
2465*/
2466static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2467  /* since we don't have type info, call the shell_callback with a NULL value */
2468  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2469}
2470
2471/*
2472** This is the callback routine from sqlite3_exec() that appends all
2473** output onto the end of a ShellText object.
2474*/
2475static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2476  ShellText *p = (ShellText*)pArg;
2477  int i;
2478  UNUSED_PARAMETER(az);
2479  if( azArg==0 ) return 0;
2480  if( p->n ) appendText(p, "|", 0);
2481  for(i=0; i<nArg; i++){
2482    if( i ) appendText(p, ",", 0);
2483    if( azArg[i] ) appendText(p, azArg[i], 0);
2484  }
2485  return 0;
2486}
2487
2488/*
2489** Generate an appropriate SELFTEST table in the main database.
2490*/
2491static void createSelftestTable(ShellState *p){
2492  char *zErrMsg = 0;
2493  sqlite3_exec(p->db,
2494    "SAVEPOINT selftest_init;\n"
2495    "CREATE TABLE IF NOT EXISTS selftest(\n"
2496    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2497    "  op TEXT,\n"                   /* Operator:  memo run */
2498    "  cmd TEXT,\n"                  /* Command text */
2499    "  ans TEXT\n"                   /* Desired answer */
2500    ");"
2501    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2502    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2503    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2504    "         'memo','Tests generated by --init');\n"
2505    "INSERT INTO [_shell$self]\n"
2506    "  SELECT 'run',\n"
2507    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2508                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2509    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2510                          "FROM sqlite_schema ORDER BY 2',224));\n"
2511    "INSERT INTO [_shell$self]\n"
2512    "  SELECT 'run',"
2513    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2514    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2515    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2516    "  FROM (\n"
2517    "    SELECT name FROM sqlite_schema\n"
2518    "     WHERE type='table'\n"
2519    "       AND name<>'selftest'\n"
2520    "       AND coalesce(rootpage,0)>0\n"
2521    "  )\n"
2522    " ORDER BY name;\n"
2523    "INSERT INTO [_shell$self]\n"
2524    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2525    "INSERT INTO selftest(tno,op,cmd,ans)"
2526    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2527    "DROP TABLE [_shell$self];"
2528    ,0,0,&zErrMsg);
2529  if( zErrMsg ){
2530    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2531    sqlite3_free(zErrMsg);
2532  }
2533  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2534}
2535
2536
2537/*
2538** Set the destination table field of the ShellState structure to
2539** the name of the table given.  Escape any quote characters in the
2540** table name.
2541*/
2542static void set_table_name(ShellState *p, const char *zName){
2543  int i, n;
2544  char cQuote;
2545  char *z;
2546
2547  if( p->zDestTable ){
2548    free(p->zDestTable);
2549    p->zDestTable = 0;
2550  }
2551  if( zName==0 ) return;
2552  cQuote = quoteChar(zName);
2553  n = strlen30(zName);
2554  if( cQuote ) n += n+2;
2555  z = p->zDestTable = malloc( n+1 );
2556  shell_check_oom(z);
2557  n = 0;
2558  if( cQuote ) z[n++] = cQuote;
2559  for(i=0; zName[i]; i++){
2560    z[n++] = zName[i];
2561    if( zName[i]==cQuote ) z[n++] = cQuote;
2562  }
2563  if( cQuote ) z[n++] = cQuote;
2564  z[n] = 0;
2565}
2566
2567/*
2568** Maybe construct two lines of text that point out the position of a
2569** syntax error.  Return a pointer to the text, in memory obtained from
2570** sqlite3_malloc().  Or, if the most recent error does not involve a
2571** specific token that we can point to, return an empty string.
2572**
2573** In all cases, the memory returned is obtained from sqlite3_malloc64()
2574** and should be released by the caller invoking sqlite3_free().
2575*/
2576static char *shell_error_context(const char *zSql, sqlite3 *db){
2577  int iOffset;
2578  size_t len;
2579  char *zCode;
2580  char *zMsg;
2581  int i;
2582  if( db==0
2583   || zSql==0
2584   || (iOffset = sqlite3_error_offset(db))<0
2585  ){
2586    return sqlite3_mprintf("");
2587  }
2588  while( iOffset>50 ){
2589    iOffset--;
2590    zSql++;
2591    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2592  }
2593  len = strlen(zSql);
2594  if( len>78 ){
2595    len = 78;
2596    while( (zSql[len]&0xc0)==0x80 ) len--;
2597  }
2598  zCode = sqlite3_mprintf("%.*s", len, zSql);
2599  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2600  if( iOffset<25 ){
2601    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2602  }else{
2603    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2604  }
2605  return zMsg;
2606}
2607
2608
2609/*
2610** Execute a query statement that will generate SQL output.  Print
2611** the result columns, comma-separated, on a line and then add a
2612** semicolon terminator to the end of that line.
2613**
2614** If the number of columns is 1 and that column contains text "--"
2615** then write the semicolon on a separate line.  That way, if a
2616** "--" comment occurs at the end of the statement, the comment
2617** won't consume the semicolon terminator.
2618*/
2619static int run_table_dump_query(
2620  ShellState *p,           /* Query context */
2621  const char *zSelect      /* SELECT statement to extract content */
2622){
2623  sqlite3_stmt *pSelect;
2624  int rc;
2625  int nResult;
2626  int i;
2627  const char *z;
2628  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2629  if( rc!=SQLITE_OK || !pSelect ){
2630    char *zContext = shell_error_context(zSelect, p->db);
2631    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2632                sqlite3_errmsg(p->db), zContext);
2633    sqlite3_free(zContext);
2634    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2635    return rc;
2636  }
2637  rc = sqlite3_step(pSelect);
2638  nResult = sqlite3_column_count(pSelect);
2639  while( rc==SQLITE_ROW ){
2640    z = (const char*)sqlite3_column_text(pSelect, 0);
2641    utf8_printf(p->out, "%s", z);
2642    for(i=1; i<nResult; i++){
2643      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2644    }
2645    if( z==0 ) z = "";
2646    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2647    if( z[0] ){
2648      raw_printf(p->out, "\n;\n");
2649    }else{
2650      raw_printf(p->out, ";\n");
2651    }
2652    rc = sqlite3_step(pSelect);
2653  }
2654  rc = sqlite3_finalize(pSelect);
2655  if( rc!=SQLITE_OK ){
2656    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2657                sqlite3_errmsg(p->db));
2658    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2659  }
2660  return rc;
2661}
2662
2663/*
2664** Allocate space and save off string indicating current error.
2665*/
2666static char *save_err_msg(
2667  sqlite3 *db,           /* Database to query */
2668  const char *zPhase,    /* When the error occcurs */
2669  int rc,                /* Error code returned from API */
2670  const char *zSql       /* SQL string, or NULL */
2671){
2672  char *zErr;
2673  char *zContext;
2674  sqlite3_str *pStr = sqlite3_str_new(0);
2675  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2676  if( rc>1 ){
2677    sqlite3_str_appendf(pStr, " (%d)", rc);
2678  }
2679  zContext = shell_error_context(zSql, db);
2680  if( zContext ){
2681    sqlite3_str_appendall(pStr, zContext);
2682    sqlite3_free(zContext);
2683  }
2684  zErr = sqlite3_str_finish(pStr);
2685  shell_check_oom(zErr);
2686  return zErr;
2687}
2688
2689#ifdef __linux__
2690/*
2691** Attempt to display I/O stats on Linux using /proc/PID/io
2692*/
2693static void displayLinuxIoStats(FILE *out){
2694  FILE *in;
2695  char z[200];
2696  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2697  in = fopen(z, "rb");
2698  if( in==0 ) return;
2699  while( fgets(z, sizeof(z), in)!=0 ){
2700    static const struct {
2701      const char *zPattern;
2702      const char *zDesc;
2703    } aTrans[] = {
2704      { "rchar: ",                  "Bytes received by read():" },
2705      { "wchar: ",                  "Bytes sent to write():"    },
2706      { "syscr: ",                  "Read() system calls:"      },
2707      { "syscw: ",                  "Write() system calls:"     },
2708      { "read_bytes: ",             "Bytes read from storage:"  },
2709      { "write_bytes: ",            "Bytes written to storage:" },
2710      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2711    };
2712    int i;
2713    for(i=0; i<ArraySize(aTrans); i++){
2714      int n = strlen30(aTrans[i].zPattern);
2715      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2716        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2717        break;
2718      }
2719    }
2720  }
2721  fclose(in);
2722}
2723#endif
2724
2725/*
2726** Display a single line of status using 64-bit values.
2727*/
2728static void displayStatLine(
2729  ShellState *p,            /* The shell context */
2730  char *zLabel,             /* Label for this one line */
2731  char *zFormat,            /* Format for the result */
2732  int iStatusCtrl,          /* Which status to display */
2733  int bReset                /* True to reset the stats */
2734){
2735  sqlite3_int64 iCur = -1;
2736  sqlite3_int64 iHiwtr = -1;
2737  int i, nPercent;
2738  char zLine[200];
2739  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2740  for(i=0, nPercent=0; zFormat[i]; i++){
2741    if( zFormat[i]=='%' ) nPercent++;
2742  }
2743  if( nPercent>1 ){
2744    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2745  }else{
2746    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2747  }
2748  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2749}
2750
2751/*
2752** Display memory stats.
2753*/
2754static int display_stats(
2755  sqlite3 *db,                /* Database to query */
2756  ShellState *pArg,           /* Pointer to ShellState */
2757  int bReset                  /* True to reset the stats */
2758){
2759  int iCur;
2760  int iHiwtr;
2761  FILE *out;
2762  if( pArg==0 || pArg->out==0 ) return 0;
2763  out = pArg->out;
2764
2765  if( pArg->pStmt && pArg->statsOn==2 ){
2766    int nCol, i, x;
2767    sqlite3_stmt *pStmt = pArg->pStmt;
2768    char z[100];
2769    nCol = sqlite3_column_count(pStmt);
2770    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2771    for(i=0; i<nCol; i++){
2772      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2773      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2774#ifndef SQLITE_OMIT_DECLTYPE
2775      sqlite3_snprintf(30, z+x, "declared type:");
2776      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2777#endif
2778#ifdef SQLITE_ENABLE_COLUMN_METADATA
2779      sqlite3_snprintf(30, z+x, "database name:");
2780      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2781      sqlite3_snprintf(30, z+x, "table name:");
2782      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2783      sqlite3_snprintf(30, z+x, "origin name:");
2784      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2785#endif
2786    }
2787  }
2788
2789  if( pArg->statsOn==3 ){
2790    if( pArg->pStmt ){
2791      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2792      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2793    }
2794    return 0;
2795  }
2796
2797  displayStatLine(pArg, "Memory Used:",
2798     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2799  displayStatLine(pArg, "Number of Outstanding Allocations:",
2800     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2801  if( pArg->shellFlgs & SHFLG_Pagecache ){
2802    displayStatLine(pArg, "Number of Pcache Pages Used:",
2803       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2804  }
2805  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2806     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2807  displayStatLine(pArg, "Largest Allocation:",
2808     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2809  displayStatLine(pArg, "Largest Pcache Allocation:",
2810     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2811#ifdef YYTRACKMAXSTACKDEPTH
2812  displayStatLine(pArg, "Deepest Parser Stack:",
2813     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2814#endif
2815
2816  if( db ){
2817    if( pArg->shellFlgs & SHFLG_Lookaside ){
2818      iHiwtr = iCur = -1;
2819      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2820                        &iCur, &iHiwtr, bReset);
2821      raw_printf(pArg->out,
2822              "Lookaside Slots Used:                %d (max %d)\n",
2823              iCur, iHiwtr);
2824      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2825                        &iCur, &iHiwtr, bReset);
2826      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2827              iHiwtr);
2828      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2829                        &iCur, &iHiwtr, bReset);
2830      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2831              iHiwtr);
2832      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2833                        &iCur, &iHiwtr, bReset);
2834      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2835              iHiwtr);
2836    }
2837    iHiwtr = iCur = -1;
2838    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2839    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2840            iCur);
2841    iHiwtr = iCur = -1;
2842    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2843    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2844    iHiwtr = iCur = -1;
2845    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2846    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2847    iHiwtr = iCur = -1;
2848    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2849    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2850    iHiwtr = iCur = -1;
2851    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2852    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2853    iHiwtr = iCur = -1;
2854    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2855    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2856            iCur);
2857    iHiwtr = iCur = -1;
2858    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2859    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2860            iCur);
2861  }
2862
2863  if( pArg->pStmt ){
2864    int iHit, iMiss;
2865    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2866                               bReset);
2867    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2868    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2869    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2870    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2871    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2872    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2873    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2874    if( iHit || iMiss ){
2875      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2876            iHit, iHit+iMiss);
2877    }
2878    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2879    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2880    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2881    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2882    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2883    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2884    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2885    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2886  }
2887
2888#ifdef __linux__
2889  displayLinuxIoStats(pArg->out);
2890#endif
2891
2892  /* Do not remove this machine readable comment: extra-stats-output-here */
2893
2894  return 0;
2895}
2896
2897/*
2898** Display scan stats.
2899*/
2900static void display_scanstats(
2901  sqlite3 *db,                    /* Database to query */
2902  ShellState *pArg                /* Pointer to ShellState */
2903){
2904#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2905  UNUSED_PARAMETER(db);
2906  UNUSED_PARAMETER(pArg);
2907#else
2908  int i, k, n, mx;
2909  raw_printf(pArg->out, "-------- scanstats --------\n");
2910  mx = 0;
2911  for(k=0; k<=mx; k++){
2912    double rEstLoop = 1.0;
2913    for(i=n=0; 1; i++){
2914      sqlite3_stmt *p = pArg->pStmt;
2915      sqlite3_int64 nLoop, nVisit;
2916      double rEst;
2917      int iSid;
2918      const char *zExplain;
2919      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2920        break;
2921      }
2922      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2923      if( iSid>mx ) mx = iSid;
2924      if( iSid!=k ) continue;
2925      if( n==0 ){
2926        rEstLoop = (double)nLoop;
2927        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2928      }
2929      n++;
2930      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2931      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2932      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2933      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2934      rEstLoop *= rEst;
2935      raw_printf(pArg->out,
2936          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2937          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2938      );
2939    }
2940  }
2941  raw_printf(pArg->out, "---------------------------\n");
2942#endif
2943}
2944
2945/*
2946** Parameter azArray points to a zero-terminated array of strings. zStr
2947** points to a single nul-terminated string. Return non-zero if zStr
2948** is equal, according to strcmp(), to any of the strings in the array.
2949** Otherwise, return zero.
2950*/
2951static int str_in_array(const char *zStr, const char **azArray){
2952  int i;
2953  for(i=0; azArray[i]; i++){
2954    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2955  }
2956  return 0;
2957}
2958
2959/*
2960** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2961** and populate the ShellState.aiIndent[] array with the number of
2962** spaces each opcode should be indented before it is output.
2963**
2964** The indenting rules are:
2965**
2966**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2967**       all opcodes that occur between the p2 jump destination and the opcode
2968**       itself by 2 spaces.
2969**
2970**     * Do the previous for "Return" instructions for when P2 is positive.
2971**       See tag-20220407a in wherecode.c and vdbe.c.
2972**
2973**     * For each "Goto", if the jump destination is earlier in the program
2974**       and ends on one of:
2975**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2976**       or if the P1 parameter is one instead of zero,
2977**       then indent all opcodes between the earlier instruction
2978**       and "Goto" by 2 spaces.
2979*/
2980static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2981  const char *zSql;               /* The text of the SQL statement */
2982  const char *z;                  /* Used to check if this is an EXPLAIN */
2983  int *abYield = 0;               /* True if op is an OP_Yield */
2984  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2985  int iOp;                        /* Index of operation in p->aiIndent[] */
2986
2987  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2988                           "Return", 0 };
2989  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2990                            "Rewind", 0 };
2991  const char *azGoto[] = { "Goto", 0 };
2992
2993  /* Try to figure out if this is really an EXPLAIN statement. If this
2994  ** cannot be verified, return early.  */
2995  if( sqlite3_column_count(pSql)!=8 ){
2996    p->cMode = p->mode;
2997    return;
2998  }
2999  zSql = sqlite3_sql(pSql);
3000  if( zSql==0 ) return;
3001  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3002  if( sqlite3_strnicmp(z, "explain", 7) ){
3003    p->cMode = p->mode;
3004    return;
3005  }
3006
3007  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3008    int i;
3009    int iAddr = sqlite3_column_int(pSql, 0);
3010    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3011
3012    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3013    ** p2 is an instruction address, set variable p2op to the index of that
3014    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3015    ** the current instruction is part of a sub-program generated by an
3016    ** SQL trigger or foreign key.  */
3017    int p2 = sqlite3_column_int(pSql, 3);
3018    int p2op = (p2 + (iOp-iAddr));
3019
3020    /* Grow the p->aiIndent array as required */
3021    if( iOp>=nAlloc ){
3022      if( iOp==0 ){
3023        /* Do further verfication that this is explain output.  Abort if
3024        ** it is not */
3025        static const char *explainCols[] = {
3026           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3027        int jj;
3028        for(jj=0; jj<ArraySize(explainCols); jj++){
3029          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3030            p->cMode = p->mode;
3031            sqlite3_reset(pSql);
3032            return;
3033          }
3034        }
3035      }
3036      nAlloc += 100;
3037      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3038      shell_check_oom(p->aiIndent);
3039      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3040      shell_check_oom(abYield);
3041    }
3042    abYield[iOp] = str_in_array(zOp, azYield);
3043    p->aiIndent[iOp] = 0;
3044    p->nIndent = iOp+1;
3045
3046    if( str_in_array(zOp, azNext) && p2op>0 ){
3047      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3048    }
3049    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3050     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3051    ){
3052      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3053    }
3054  }
3055
3056  p->iIndent = 0;
3057  sqlite3_free(abYield);
3058  sqlite3_reset(pSql);
3059}
3060
3061/*
3062** Free the array allocated by explain_data_prepare().
3063*/
3064static void explain_data_delete(ShellState *p){
3065  sqlite3_free(p->aiIndent);
3066  p->aiIndent = 0;
3067  p->nIndent = 0;
3068  p->iIndent = 0;
3069}
3070
3071/*
3072** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3073*/
3074static unsigned int savedSelectTrace;
3075static unsigned int savedWhereTrace;
3076static void disable_debug_trace_modes(void){
3077  unsigned int zero = 0;
3078  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3079  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3080  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3081  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3082}
3083static void restore_debug_trace_modes(void){
3084  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3085  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3086}
3087
3088/* Create the TEMP table used to store parameter bindings */
3089static void bind_table_init(ShellState *p){
3090  int wrSchema = 0;
3091  int defensiveMode = 0;
3092  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3093  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3094  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3095  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3096  sqlite3_exec(p->db,
3097    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3098    "  key TEXT PRIMARY KEY,\n"
3099    "  value\n"
3100    ") WITHOUT ROWID;",
3101    0, 0, 0);
3102  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3103  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3104}
3105
3106/*
3107** Bind parameters on a prepared statement.
3108**
3109** Parameter bindings are taken from a TEMP table of the form:
3110**
3111**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3112**    WITHOUT ROWID;
3113**
3114** No bindings occur if this table does not exist.  The name of the table
3115** begins with "sqlite_" so that it will not collide with ordinary application
3116** tables.  The table must be in the TEMP schema.
3117*/
3118static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3119  int nVar;
3120  int i;
3121  int rc;
3122  sqlite3_stmt *pQ = 0;
3123
3124  nVar = sqlite3_bind_parameter_count(pStmt);
3125  if( nVar==0 ) return;  /* Nothing to do */
3126  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3127                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3128    return; /* Parameter table does not exist */
3129  }
3130  rc = sqlite3_prepare_v2(pArg->db,
3131          "SELECT value FROM temp.sqlite_parameters"
3132          " WHERE key=?1", -1, &pQ, 0);
3133  if( rc || pQ==0 ) return;
3134  for(i=1; i<=nVar; i++){
3135    char zNum[30];
3136    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3137    if( zVar==0 ){
3138      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3139      zVar = zNum;
3140    }
3141    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3142    if( sqlite3_step(pQ)==SQLITE_ROW ){
3143      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3144    }else{
3145      sqlite3_bind_null(pStmt, i);
3146    }
3147    sqlite3_reset(pQ);
3148  }
3149  sqlite3_finalize(pQ);
3150}
3151
3152/*
3153** UTF8 box-drawing characters.  Imagine box lines like this:
3154**
3155**           1
3156**           |
3157**       4 --+-- 2
3158**           |
3159**           3
3160**
3161** Each box characters has between 2 and 4 of the lines leading from
3162** the center.  The characters are here identified by the numbers of
3163** their corresponding lines.
3164*/
3165#define BOX_24   "\342\224\200"  /* U+2500 --- */
3166#define BOX_13   "\342\224\202"  /* U+2502  |  */
3167#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3168#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3169#define BOX_12   "\342\224\224"  /* U+2514  '- */
3170#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3171#define BOX_123  "\342\224\234"  /* U+251c  |- */
3172#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3173#define BOX_234  "\342\224\254"  /* U+252c -,- */
3174#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3175#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3176
3177/* Draw horizontal line N characters long using unicode box
3178** characters
3179*/
3180static void print_box_line(FILE *out, int N){
3181  const char zDash[] =
3182      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3183      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3184  const int nDash = sizeof(zDash) - 1;
3185  N *= 3;
3186  while( N>nDash ){
3187    utf8_printf(out, zDash);
3188    N -= nDash;
3189  }
3190  utf8_printf(out, "%.*s", N, zDash);
3191}
3192
3193/*
3194** Draw a horizontal separator for a MODE_Box table.
3195*/
3196static void print_box_row_separator(
3197  ShellState *p,
3198  int nArg,
3199  const char *zSep1,
3200  const char *zSep2,
3201  const char *zSep3
3202){
3203  int i;
3204  if( nArg>0 ){
3205    utf8_printf(p->out, "%s", zSep1);
3206    print_box_line(p->out, p->actualWidth[0]+2);
3207    for(i=1; i<nArg; i++){
3208      utf8_printf(p->out, "%s", zSep2);
3209      print_box_line(p->out, p->actualWidth[i]+2);
3210    }
3211    utf8_printf(p->out, "%s", zSep3);
3212  }
3213  fputs("\n", p->out);
3214}
3215
3216/*
3217** z[] is a line of text that is to be displayed the .mode box or table or
3218** similar tabular formats.  z[] might contain control characters such
3219** as \n, \t, \f, or \r.
3220**
3221** Compute characters to display on the first line of z[].  Stop at the
3222** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3223** from malloc()) of that first line, which caller should free sometime.
3224** Write anything to display on the next line into *pzTail.  If this is
3225** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3226*/
3227static char *translateForDisplayAndDup(
3228  const unsigned char *z,            /* Input text to be transformed */
3229  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3230  int mxWidth,                       /* Max width.  0 means no limit */
3231  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3232){
3233  int i;                 /* Input bytes consumed */
3234  int j;                 /* Output bytes generated */
3235  int k;                 /* Input bytes to be displayed */
3236  int n;                 /* Output column number */
3237  unsigned char *zOut;   /* Output text */
3238
3239  if( z==0 ){
3240    *pzTail = 0;
3241    return 0;
3242  }
3243  if( mxWidth<0 ) mxWidth = -mxWidth;
3244  if( mxWidth==0 ) mxWidth = 1000000;
3245  i = j = n = 0;
3246  while( n<mxWidth ){
3247    if( z[i]>=' ' ){
3248      n++;
3249      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3250      continue;
3251    }
3252    if( z[i]=='\t' ){
3253      do{
3254        n++;
3255        j++;
3256      }while( (n&7)!=0 && n<mxWidth );
3257      i++;
3258      continue;
3259    }
3260    break;
3261  }
3262  if( n>=mxWidth && bWordWrap  ){
3263    /* Perhaps try to back up to a better place to break the line */
3264    for(k=i; k>i/2; k--){
3265      if( isspace(z[k-1]) ) break;
3266    }
3267    if( k<=i/2 ){
3268      for(k=i; k>i/2; k--){
3269        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3270      }
3271    }
3272    if( k<=i/2 ){
3273      k = i;
3274    }else{
3275      i = k;
3276      while( z[i]==' ' ) i++;
3277    }
3278  }else{
3279    k = i;
3280  }
3281  if( n>=mxWidth && z[i]>=' ' ){
3282   *pzTail = &z[i];
3283  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3284    *pzTail = z[i+2] ? &z[i+2] : 0;
3285  }else if( z[i]==0 || z[i+1]==0 ){
3286    *pzTail = 0;
3287  }else{
3288    *pzTail = &z[i+1];
3289  }
3290  zOut = malloc( j+1 );
3291  shell_check_oom(zOut);
3292  i = j = n = 0;
3293  while( i<k ){
3294    if( z[i]>=' ' ){
3295      n++;
3296      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3297      continue;
3298    }
3299    if( z[i]=='\t' ){
3300      do{
3301        n++;
3302        zOut[j++] = ' ';
3303      }while( (n&7)!=0 && n<mxWidth );
3304      i++;
3305      continue;
3306    }
3307    break;
3308  }
3309  zOut[j] = 0;
3310  return (char*)zOut;
3311}
3312
3313/* Extract the value of the i-th current column for pStmt as an SQL literal
3314** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3315** the caller.
3316*/
3317static char *quoted_column(sqlite3_stmt *pStmt, int i){
3318  switch( sqlite3_column_type(pStmt, i) ){
3319    case SQLITE_NULL: {
3320      return sqlite3_mprintf("NULL");
3321    }
3322    case SQLITE_INTEGER:
3323    case SQLITE_FLOAT: {
3324      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3325    }
3326    case SQLITE_TEXT: {
3327      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3328    }
3329    case SQLITE_BLOB: {
3330      int j;
3331      sqlite3_str *pStr = sqlite3_str_new(0);
3332      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3333      int n = sqlite3_column_bytes(pStmt,i);
3334      sqlite3_str_append(pStr, "x'", 2);
3335      for(j=0; j<n; j++){
3336        sqlite3_str_appendf(pStr, "%02x", a[j]);
3337      }
3338      sqlite3_str_append(pStr, "'", 1);
3339      return sqlite3_str_finish(pStr);
3340    }
3341  }
3342  return 0; /* Not reached */
3343}
3344
3345/*
3346** Run a prepared statement and output the result in one of the
3347** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3348** or MODE_Box.
3349**
3350** This is different from ordinary exec_prepared_stmt() in that
3351** it has to run the entire query and gather the results into memory
3352** first, in order to determine column widths, before providing
3353** any output.
3354*/
3355static void exec_prepared_stmt_columnar(
3356  ShellState *p,                        /* Pointer to ShellState */
3357  sqlite3_stmt *pStmt                   /* Statment to run */
3358){
3359  sqlite3_int64 nRow = 0;
3360  int nColumn = 0;
3361  char **azData = 0;
3362  sqlite3_int64 nAlloc = 0;
3363  char *abRowDiv = 0;
3364  const unsigned char *uz;
3365  const char *z;
3366  char **azQuoted = 0;
3367  int rc;
3368  sqlite3_int64 i, nData;
3369  int j, nTotal, w, n;
3370  const char *colSep = 0;
3371  const char *rowSep = 0;
3372  const unsigned char **azNextLine = 0;
3373  int bNextLine = 0;
3374  int bMultiLineRowExists = 0;
3375  int bw = p->cmOpts.bWordWrap;
3376  const char *zEmpty = "";
3377  const char *zShowNull = p->nullValue;
3378
3379  rc = sqlite3_step(pStmt);
3380  if( rc!=SQLITE_ROW ) return;
3381  nColumn = sqlite3_column_count(pStmt);
3382  nAlloc = nColumn*4;
3383  if( nAlloc<=0 ) nAlloc = 1;
3384  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3385  shell_check_oom(azData);
3386  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3387  shell_check_oom((void*)azNextLine);
3388  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3389  if( p->cmOpts.bQuote ){
3390    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3391    shell_check_oom(azQuoted);
3392    memset(azQuoted, 0, nColumn*sizeof(char*) );
3393  }
3394  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3395  shell_check_oom(abRowDiv);
3396  if( nColumn>p->nWidth ){
3397    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3398    shell_check_oom(p->colWidth);
3399    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3400    p->nWidth = nColumn;
3401    p->actualWidth = &p->colWidth[nColumn];
3402  }
3403  memset(p->actualWidth, 0, nColumn*sizeof(int));
3404  for(i=0; i<nColumn; i++){
3405    w = p->colWidth[i];
3406    if( w<0 ) w = -w;
3407    p->actualWidth[i] = w;
3408  }
3409  for(i=0; i<nColumn; i++){
3410    const unsigned char *zNotUsed;
3411    int wx = p->colWidth[i];
3412    if( wx==0 ){
3413      wx = p->cmOpts.iWrap;
3414    }
3415    if( wx<0 ) wx = -wx;
3416    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3417    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3418  }
3419  do{
3420    int useNextLine = bNextLine;
3421    bNextLine = 0;
3422    if( (nRow+2)*nColumn >= nAlloc ){
3423      nAlloc *= 2;
3424      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3425      shell_check_oom(azData);
3426      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3427      shell_check_oom(abRowDiv);
3428    }
3429    abRowDiv[nRow] = 1;
3430    nRow++;
3431    for(i=0; i<nColumn; i++){
3432      int wx = p->colWidth[i];
3433      if( wx==0 ){
3434        wx = p->cmOpts.iWrap;
3435      }
3436      if( wx<0 ) wx = -wx;
3437      if( useNextLine ){
3438        uz = azNextLine[i];
3439        if( uz==0 ) uz = (u8*)zEmpty;
3440      }else if( p->cmOpts.bQuote ){
3441        sqlite3_free(azQuoted[i]);
3442        azQuoted[i] = quoted_column(pStmt,i);
3443        uz = (const unsigned char*)azQuoted[i];
3444      }else{
3445        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3446        if( uz==0 ) uz = (u8*)zShowNull;
3447      }
3448      azData[nRow*nColumn + i]
3449        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3450      if( azNextLine[i] ){
3451        bNextLine = 1;
3452        abRowDiv[nRow-1] = 0;
3453        bMultiLineRowExists = 1;
3454      }
3455    }
3456  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3457  nTotal = nColumn*(nRow+1);
3458  for(i=0; i<nTotal; i++){
3459    z = azData[i];
3460    if( z==0 ) z = (char*)zEmpty;
3461    n = strlenChar(z);
3462    j = i%nColumn;
3463    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3464  }
3465  if( seenInterrupt ) goto columnar_end;
3466  if( nColumn==0 ) goto columnar_end;
3467  switch( p->cMode ){
3468    case MODE_Column: {
3469      colSep = "  ";
3470      rowSep = "\n";
3471      if( p->showHeader ){
3472        for(i=0; i<nColumn; i++){
3473          w = p->actualWidth[i];
3474          if( p->colWidth[i]<0 ) w = -w;
3475          utf8_width_print(p->out, w, azData[i]);
3476          fputs(i==nColumn-1?"\n":"  ", p->out);
3477        }
3478        for(i=0; i<nColumn; i++){
3479          print_dashes(p->out, p->actualWidth[i]);
3480          fputs(i==nColumn-1?"\n":"  ", p->out);
3481        }
3482      }
3483      break;
3484    }
3485    case MODE_Table: {
3486      colSep = " | ";
3487      rowSep = " |\n";
3488      print_row_separator(p, nColumn, "+");
3489      fputs("| ", p->out);
3490      for(i=0; i<nColumn; i++){
3491        w = p->actualWidth[i];
3492        n = strlenChar(azData[i]);
3493        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3494        fputs(i==nColumn-1?" |\n":" | ", p->out);
3495      }
3496      print_row_separator(p, nColumn, "+");
3497      break;
3498    }
3499    case MODE_Markdown: {
3500      colSep = " | ";
3501      rowSep = " |\n";
3502      fputs("| ", p->out);
3503      for(i=0; i<nColumn; i++){
3504        w = p->actualWidth[i];
3505        n = strlenChar(azData[i]);
3506        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3507        fputs(i==nColumn-1?" |\n":" | ", p->out);
3508      }
3509      print_row_separator(p, nColumn, "|");
3510      break;
3511    }
3512    case MODE_Box: {
3513      colSep = " " BOX_13 " ";
3514      rowSep = " " BOX_13 "\n";
3515      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3516      utf8_printf(p->out, BOX_13 " ");
3517      for(i=0; i<nColumn; i++){
3518        w = p->actualWidth[i];
3519        n = strlenChar(azData[i]);
3520        utf8_printf(p->out, "%*s%s%*s%s",
3521            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3522            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3523      }
3524      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3525      break;
3526    }
3527  }
3528  for(i=nColumn, j=0; i<nTotal; i++, j++){
3529    if( j==0 && p->cMode!=MODE_Column ){
3530      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3531    }
3532    z = azData[i];
3533    if( z==0 ) z = p->nullValue;
3534    w = p->actualWidth[j];
3535    if( p->colWidth[j]<0 ) w = -w;
3536    utf8_width_print(p->out, w, z);
3537    if( j==nColumn-1 ){
3538      utf8_printf(p->out, "%s", rowSep);
3539      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3540        if( p->cMode==MODE_Table ){
3541          print_row_separator(p, nColumn, "+");
3542        }else if( p->cMode==MODE_Box ){
3543          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3544        }else if( p->cMode==MODE_Column ){
3545          raw_printf(p->out, "\n");
3546        }
3547      }
3548      j = -1;
3549      if( seenInterrupt ) goto columnar_end;
3550    }else{
3551      utf8_printf(p->out, "%s", colSep);
3552    }
3553  }
3554  if( p->cMode==MODE_Table ){
3555    print_row_separator(p, nColumn, "+");
3556  }else if( p->cMode==MODE_Box ){
3557    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3558  }
3559columnar_end:
3560  if( seenInterrupt ){
3561    utf8_printf(p->out, "Interrupt\n");
3562  }
3563  nData = (nRow+1)*nColumn;
3564  for(i=0; i<nData; i++){
3565    z = azData[i];
3566    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3567  }
3568  sqlite3_free(azData);
3569  sqlite3_free((void*)azNextLine);
3570  sqlite3_free(abRowDiv);
3571  if( azQuoted ){
3572    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3573    sqlite3_free(azQuoted);
3574  }
3575}
3576
3577/*
3578** Run a prepared statement
3579*/
3580static void exec_prepared_stmt(
3581  ShellState *pArg,                                /* Pointer to ShellState */
3582  sqlite3_stmt *pStmt                              /* Statment to run */
3583){
3584  int rc;
3585  sqlite3_uint64 nRow = 0;
3586
3587  if( pArg->cMode==MODE_Column
3588   || pArg->cMode==MODE_Table
3589   || pArg->cMode==MODE_Box
3590   || pArg->cMode==MODE_Markdown
3591  ){
3592    exec_prepared_stmt_columnar(pArg, pStmt);
3593    return;
3594  }
3595
3596  /* perform the first step.  this will tell us if we
3597  ** have a result set or not and how wide it is.
3598  */
3599  rc = sqlite3_step(pStmt);
3600  /* if we have a result set... */
3601  if( SQLITE_ROW == rc ){
3602    /* allocate space for col name ptr, value ptr, and type */
3603    int nCol = sqlite3_column_count(pStmt);
3604    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3605    if( !pData ){
3606      shell_out_of_memory();
3607    }else{
3608      char **azCols = (char **)pData;      /* Names of result columns */
3609      char **azVals = &azCols[nCol];       /* Results */
3610      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3611      int i, x;
3612      assert(sizeof(int) <= sizeof(char *));
3613      /* save off ptrs to column names */
3614      for(i=0; i<nCol; i++){
3615        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3616      }
3617      do{
3618        nRow++;
3619        /* extract the data and data types */
3620        for(i=0; i<nCol; i++){
3621          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3622          if( x==SQLITE_BLOB
3623           && pArg
3624           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3625          ){
3626            azVals[i] = "";
3627          }else{
3628            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3629          }
3630          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3631            rc = SQLITE_NOMEM;
3632            break; /* from for */
3633          }
3634        } /* end for */
3635
3636        /* if data and types extracted successfully... */
3637        if( SQLITE_ROW == rc ){
3638          /* call the supplied callback with the result row data */
3639          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3640            rc = SQLITE_ABORT;
3641          }else{
3642            rc = sqlite3_step(pStmt);
3643          }
3644        }
3645      } while( SQLITE_ROW == rc );
3646      sqlite3_free(pData);
3647      if( pArg->cMode==MODE_Json ){
3648        fputs("]\n", pArg->out);
3649      }else if( pArg->cMode==MODE_Count ){
3650        char zBuf[200];
3651        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3652                         nRow, nRow!=1 ? "s" : "");
3653        printf("%s", zBuf);
3654      }
3655    }
3656  }
3657}
3658
3659#ifndef SQLITE_OMIT_VIRTUALTABLE
3660/*
3661** This function is called to process SQL if the previous shell command
3662** was ".expert". It passes the SQL in the second argument directly to
3663** the sqlite3expert object.
3664**
3665** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3666** code. In this case, (*pzErr) may be set to point to a buffer containing
3667** an English language error message. It is the responsibility of the
3668** caller to eventually free this buffer using sqlite3_free().
3669*/
3670static int expertHandleSQL(
3671  ShellState *pState,
3672  const char *zSql,
3673  char **pzErr
3674){
3675  assert( pState->expert.pExpert );
3676  assert( pzErr==0 || *pzErr==0 );
3677  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3678}
3679
3680/*
3681** This function is called either to silently clean up the object
3682** created by the ".expert" command (if bCancel==1), or to generate a
3683** report from it and then clean it up (if bCancel==0).
3684**
3685** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3686** code. In this case, (*pzErr) may be set to point to a buffer containing
3687** an English language error message. It is the responsibility of the
3688** caller to eventually free this buffer using sqlite3_free().
3689*/
3690static int expertFinish(
3691  ShellState *pState,
3692  int bCancel,
3693  char **pzErr
3694){
3695  int rc = SQLITE_OK;
3696  sqlite3expert *p = pState->expert.pExpert;
3697  assert( p );
3698  assert( bCancel || pzErr==0 || *pzErr==0 );
3699  if( bCancel==0 ){
3700    FILE *out = pState->out;
3701    int bVerbose = pState->expert.bVerbose;
3702
3703    rc = sqlite3_expert_analyze(p, pzErr);
3704    if( rc==SQLITE_OK ){
3705      int nQuery = sqlite3_expert_count(p);
3706      int i;
3707
3708      if( bVerbose ){
3709        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3710        raw_printf(out, "-- Candidates -----------------------------\n");
3711        raw_printf(out, "%s\n", zCand);
3712      }
3713      for(i=0; i<nQuery; i++){
3714        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3715        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3716        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3717        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3718        if( bVerbose ){
3719          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3720          raw_printf(out, "%s\n\n", zSql);
3721        }
3722        raw_printf(out, "%s\n", zIdx);
3723        raw_printf(out, "%s\n", zEQP);
3724      }
3725    }
3726  }
3727  sqlite3_expert_destroy(p);
3728  pState->expert.pExpert = 0;
3729  return rc;
3730}
3731
3732/*
3733** Implementation of ".expert" dot command.
3734*/
3735static int expertDotCommand(
3736  ShellState *pState,             /* Current shell tool state */
3737  char **azArg,                   /* Array of arguments passed to dot command */
3738  int nArg                        /* Number of entries in azArg[] */
3739){
3740  int rc = SQLITE_OK;
3741  char *zErr = 0;
3742  int i;
3743  int iSample = 0;
3744
3745  assert( pState->expert.pExpert==0 );
3746  memset(&pState->expert, 0, sizeof(ExpertInfo));
3747
3748  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3749    char *z = azArg[i];
3750    int n;
3751    if( z[0]=='-' && z[1]=='-' ) z++;
3752    n = strlen30(z);
3753    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3754      pState->expert.bVerbose = 1;
3755    }
3756    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3757      if( i==(nArg-1) ){
3758        raw_printf(stderr, "option requires an argument: %s\n", z);
3759        rc = SQLITE_ERROR;
3760      }else{
3761        iSample = (int)integerValue(azArg[++i]);
3762        if( iSample<0 || iSample>100 ){
3763          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3764          rc = SQLITE_ERROR;
3765        }
3766      }
3767    }
3768    else{
3769      raw_printf(stderr, "unknown option: %s\n", z);
3770      rc = SQLITE_ERROR;
3771    }
3772  }
3773
3774  if( rc==SQLITE_OK ){
3775    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3776    if( pState->expert.pExpert==0 ){
3777      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3778      rc = SQLITE_ERROR;
3779    }else{
3780      sqlite3_expert_config(
3781          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3782      );
3783    }
3784  }
3785  sqlite3_free(zErr);
3786
3787  return rc;
3788}
3789#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3790
3791/*
3792** Execute a statement or set of statements.  Print
3793** any result rows/columns depending on the current mode
3794** set via the supplied callback.
3795**
3796** This is very similar to SQLite's built-in sqlite3_exec()
3797** function except it takes a slightly different callback
3798** and callback data argument.
3799*/
3800static int shell_exec(
3801  ShellState *pArg,                         /* Pointer to ShellState */
3802  const char *zSql,                         /* SQL to be evaluated */
3803  char **pzErrMsg                           /* Error msg written here */
3804){
3805  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3806  int rc = SQLITE_OK;             /* Return Code */
3807  int rc2;
3808  const char *zLeftover;          /* Tail of unprocessed SQL */
3809  sqlite3 *db = pArg->db;
3810
3811  if( pzErrMsg ){
3812    *pzErrMsg = NULL;
3813  }
3814
3815#ifndef SQLITE_OMIT_VIRTUALTABLE
3816  if( pArg->expert.pExpert ){
3817    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3818    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3819  }
3820#endif
3821
3822  while( zSql[0] && (SQLITE_OK == rc) ){
3823    static const char *zStmtSql;
3824    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3825    if( SQLITE_OK != rc ){
3826      if( pzErrMsg ){
3827        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3828      }
3829    }else{
3830      if( !pStmt ){
3831        /* this happens for a comment or white-space */
3832        zSql = zLeftover;
3833        while( IsSpace(zSql[0]) ) zSql++;
3834        continue;
3835      }
3836      zStmtSql = sqlite3_sql(pStmt);
3837      if( zStmtSql==0 ) zStmtSql = "";
3838      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3839
3840      /* save off the prepared statment handle and reset row count */
3841      if( pArg ){
3842        pArg->pStmt = pStmt;
3843        pArg->cnt = 0;
3844      }
3845
3846      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3847      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3848        sqlite3_stmt *pExplain;
3849        char *zEQP;
3850        int triggerEQP = 0;
3851        disable_debug_trace_modes();
3852        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3853        if( pArg->autoEQP>=AUTOEQP_trigger ){
3854          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3855        }
3856        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3857        shell_check_oom(zEQP);
3858        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3859        if( rc==SQLITE_OK ){
3860          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3861            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3862            int iEqpId = sqlite3_column_int(pExplain, 0);
3863            int iParentId = sqlite3_column_int(pExplain, 1);
3864            if( zEQPLine==0 ) zEQPLine = "";
3865            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3866            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3867          }
3868          eqp_render(pArg);
3869        }
3870        sqlite3_finalize(pExplain);
3871        sqlite3_free(zEQP);
3872        if( pArg->autoEQP>=AUTOEQP_full ){
3873          /* Also do an EXPLAIN for ".eqp full" mode */
3874          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3875          shell_check_oom(zEQP);
3876          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3877          if( rc==SQLITE_OK ){
3878            pArg->cMode = MODE_Explain;
3879            explain_data_prepare(pArg, pExplain);
3880            exec_prepared_stmt(pArg, pExplain);
3881            explain_data_delete(pArg);
3882          }
3883          sqlite3_finalize(pExplain);
3884          sqlite3_free(zEQP);
3885        }
3886        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3887          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3888          /* Reprepare pStmt before reactiving trace modes */
3889          sqlite3_finalize(pStmt);
3890          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3891          if( pArg ) pArg->pStmt = pStmt;
3892        }
3893        restore_debug_trace_modes();
3894      }
3895
3896      if( pArg ){
3897        pArg->cMode = pArg->mode;
3898        if( pArg->autoExplain ){
3899          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3900            pArg->cMode = MODE_Explain;
3901          }
3902          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3903            pArg->cMode = MODE_EQP;
3904          }
3905        }
3906
3907        /* If the shell is currently in ".explain" mode, gather the extra
3908        ** data required to add indents to the output.*/
3909        if( pArg->cMode==MODE_Explain ){
3910          explain_data_prepare(pArg, pStmt);
3911        }
3912      }
3913
3914      bind_prepared_stmt(pArg, pStmt);
3915      exec_prepared_stmt(pArg, pStmt);
3916      explain_data_delete(pArg);
3917      eqp_render(pArg);
3918
3919      /* print usage stats if stats on */
3920      if( pArg && pArg->statsOn ){
3921        display_stats(db, pArg, 0);
3922      }
3923
3924      /* print loop-counters if required */
3925      if( pArg && pArg->scanstatsOn ){
3926        display_scanstats(db, pArg);
3927      }
3928
3929      /* Finalize the statement just executed. If this fails, save a
3930      ** copy of the error message. Otherwise, set zSql to point to the
3931      ** next statement to execute. */
3932      rc2 = sqlite3_finalize(pStmt);
3933      if( rc!=SQLITE_NOMEM ) rc = rc2;
3934      if( rc==SQLITE_OK ){
3935        zSql = zLeftover;
3936        while( IsSpace(zSql[0]) ) zSql++;
3937      }else if( pzErrMsg ){
3938        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3939      }
3940
3941      /* clear saved stmt handle */
3942      if( pArg ){
3943        pArg->pStmt = NULL;
3944      }
3945    }
3946  } /* end while */
3947
3948  return rc;
3949}
3950
3951/*
3952** Release memory previously allocated by tableColumnList().
3953*/
3954static void freeColumnList(char **azCol){
3955  int i;
3956  for(i=1; azCol[i]; i++){
3957    sqlite3_free(azCol[i]);
3958  }
3959  /* azCol[0] is a static string */
3960  sqlite3_free(azCol);
3961}
3962
3963/*
3964** Return a list of pointers to strings which are the names of all
3965** columns in table zTab.   The memory to hold the names is dynamically
3966** allocated and must be released by the caller using a subsequent call
3967** to freeColumnList().
3968**
3969** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3970** value that needs to be preserved, then azCol[0] is filled in with the
3971** name of the rowid column.
3972**
3973** The first regular column in the table is azCol[1].  The list is terminated
3974** by an entry with azCol[i]==0.
3975*/
3976static char **tableColumnList(ShellState *p, const char *zTab){
3977  char **azCol = 0;
3978  sqlite3_stmt *pStmt;
3979  char *zSql;
3980  int nCol = 0;
3981  int nAlloc = 0;
3982  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3983  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3984  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3985  int rc;
3986
3987  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3988  shell_check_oom(zSql);
3989  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3990  sqlite3_free(zSql);
3991  if( rc ) return 0;
3992  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3993    if( nCol>=nAlloc-2 ){
3994      nAlloc = nAlloc*2 + nCol + 10;
3995      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3996      shell_check_oom(azCol);
3997    }
3998    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3999    shell_check_oom(azCol[nCol]);
4000    if( sqlite3_column_int(pStmt, 5) ){
4001      nPK++;
4002      if( nPK==1
4003       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4004                          "INTEGER")==0
4005      ){
4006        isIPK = 1;
4007      }else{
4008        isIPK = 0;
4009      }
4010    }
4011  }
4012  sqlite3_finalize(pStmt);
4013  if( azCol==0 ) return 0;
4014  azCol[0] = 0;
4015  azCol[nCol+1] = 0;
4016
4017  /* The decision of whether or not a rowid really needs to be preserved
4018  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4019  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4020  ** rowids on tables where the rowid is inaccessible because there are other
4021  ** columns in the table named "rowid", "_rowid_", and "oid".
4022  */
4023  if( preserveRowid && isIPK ){
4024    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4025    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4026    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4027    ** ROWID aliases.  To distinguish these cases, check to see if
4028    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4029    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4030    */
4031    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4032                           " WHERE origin='pk'", zTab);
4033    shell_check_oom(zSql);
4034    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4035    sqlite3_free(zSql);
4036    if( rc ){
4037      freeColumnList(azCol);
4038      return 0;
4039    }
4040    rc = sqlite3_step(pStmt);
4041    sqlite3_finalize(pStmt);
4042    preserveRowid = rc==SQLITE_ROW;
4043  }
4044  if( preserveRowid ){
4045    /* Only preserve the rowid if we can find a name to use for the
4046    ** rowid */
4047    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4048    int i, j;
4049    for(j=0; j<3; j++){
4050      for(i=1; i<=nCol; i++){
4051        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4052      }
4053      if( i>nCol ){
4054        /* At this point, we know that azRowid[j] is not the name of any
4055        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4056        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4057        ** tables will fail this last check */
4058        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4059        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4060        break;
4061      }
4062    }
4063  }
4064  return azCol;
4065}
4066
4067/*
4068** Toggle the reverse_unordered_selects setting.
4069*/
4070static void toggleSelectOrder(sqlite3 *db){
4071  sqlite3_stmt *pStmt = 0;
4072  int iSetting = 0;
4073  char zStmt[100];
4074  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4075  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4076    iSetting = sqlite3_column_int(pStmt, 0);
4077  }
4078  sqlite3_finalize(pStmt);
4079  sqlite3_snprintf(sizeof(zStmt), zStmt,
4080       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4081  sqlite3_exec(db, zStmt, 0, 0, 0);
4082}
4083
4084/*
4085** This is a different callback routine used for dumping the database.
4086** Each row received by this callback consists of a table name,
4087** the table type ("index" or "table") and SQL to create the table.
4088** This routine should print text sufficient to recreate the table.
4089*/
4090static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4091  int rc;
4092  const char *zTable;
4093  const char *zType;
4094  const char *zSql;
4095  ShellState *p = (ShellState *)pArg;
4096  int dataOnly;
4097  int noSys;
4098
4099  UNUSED_PARAMETER(azNotUsed);
4100  if( nArg!=3 || azArg==0 ) return 0;
4101  zTable = azArg[0];
4102  zType = azArg[1];
4103  zSql = azArg[2];
4104  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4105  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4106
4107  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4108    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4109  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4110    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4111  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4112    return 0;
4113  }else if( dataOnly ){
4114    /* no-op */
4115  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4116    char *zIns;
4117    if( !p->writableSchema ){
4118      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4119      p->writableSchema = 1;
4120    }
4121    zIns = sqlite3_mprintf(
4122       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4123       "VALUES('table','%q','%q',0,'%q');",
4124       zTable, zTable, zSql);
4125    shell_check_oom(zIns);
4126    utf8_printf(p->out, "%s\n", zIns);
4127    sqlite3_free(zIns);
4128    return 0;
4129  }else{
4130    printSchemaLine(p->out, zSql, ";\n");
4131  }
4132
4133  if( strcmp(zType, "table")==0 ){
4134    ShellText sSelect;
4135    ShellText sTable;
4136    char **azCol;
4137    int i;
4138    char *savedDestTable;
4139    int savedMode;
4140
4141    azCol = tableColumnList(p, zTable);
4142    if( azCol==0 ){
4143      p->nErr++;
4144      return 0;
4145    }
4146
4147    /* Always quote the table name, even if it appears to be pure ascii,
4148    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4149    initText(&sTable);
4150    appendText(&sTable, zTable, quoteChar(zTable));
4151    /* If preserving the rowid, add a column list after the table name.
4152    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4153    ** instead of the usual "INSERT INTO tab VALUES(...)".
4154    */
4155    if( azCol[0] ){
4156      appendText(&sTable, "(", 0);
4157      appendText(&sTable, azCol[0], 0);
4158      for(i=1; azCol[i]; i++){
4159        appendText(&sTable, ",", 0);
4160        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4161      }
4162      appendText(&sTable, ")", 0);
4163    }
4164
4165    /* Build an appropriate SELECT statement */
4166    initText(&sSelect);
4167    appendText(&sSelect, "SELECT ", 0);
4168    if( azCol[0] ){
4169      appendText(&sSelect, azCol[0], 0);
4170      appendText(&sSelect, ",", 0);
4171    }
4172    for(i=1; azCol[i]; i++){
4173      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4174      if( azCol[i+1] ){
4175        appendText(&sSelect, ",", 0);
4176      }
4177    }
4178    freeColumnList(azCol);
4179    appendText(&sSelect, " FROM ", 0);
4180    appendText(&sSelect, zTable, quoteChar(zTable));
4181
4182    savedDestTable = p->zDestTable;
4183    savedMode = p->mode;
4184    p->zDestTable = sTable.z;
4185    p->mode = p->cMode = MODE_Insert;
4186    rc = shell_exec(p, sSelect.z, 0);
4187    if( (rc&0xff)==SQLITE_CORRUPT ){
4188      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4189      toggleSelectOrder(p->db);
4190      shell_exec(p, sSelect.z, 0);
4191      toggleSelectOrder(p->db);
4192    }
4193    p->zDestTable = savedDestTable;
4194    p->mode = savedMode;
4195    freeText(&sTable);
4196    freeText(&sSelect);
4197    if( rc ) p->nErr++;
4198  }
4199  return 0;
4200}
4201
4202/*
4203** Run zQuery.  Use dump_callback() as the callback routine so that
4204** the contents of the query are output as SQL statements.
4205**
4206** If we get a SQLITE_CORRUPT error, rerun the query after appending
4207** "ORDER BY rowid DESC" to the end.
4208*/
4209static int run_schema_dump_query(
4210  ShellState *p,
4211  const char *zQuery
4212){
4213  int rc;
4214  char *zErr = 0;
4215  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4216  if( rc==SQLITE_CORRUPT ){
4217    char *zQ2;
4218    int len = strlen30(zQuery);
4219    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4220    if( zErr ){
4221      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4222      sqlite3_free(zErr);
4223      zErr = 0;
4224    }
4225    zQ2 = malloc( len+100 );
4226    if( zQ2==0 ) return rc;
4227    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4228    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4229    if( rc ){
4230      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4231    }else{
4232      rc = SQLITE_CORRUPT;
4233    }
4234    sqlite3_free(zErr);
4235    free(zQ2);
4236  }
4237  return rc;
4238}
4239
4240/*
4241** Text of help messages.
4242**
4243** The help text for each individual command begins with a line that starts
4244** with ".".  Subsequent lines are supplemental information.
4245**
4246** There must be two or more spaces between the end of the command and the
4247** start of the description of what that command does.
4248*/
4249static const char *(azHelp[]) = {
4250#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4251  && !defined(SQLITE_SHELL_WASM_MODE)
4252  ".archive ...             Manage SQL archives",
4253  "   Each command must have exactly one of the following options:",
4254  "     -c, --create               Create a new archive",
4255  "     -u, --update               Add or update files with changed mtime",
4256  "     -i, --insert               Like -u but always add even if unchanged",
4257  "     -r, --remove               Remove files from archive",
4258  "     -t, --list                 List contents of archive",
4259  "     -x, --extract              Extract files from archive",
4260  "   Optional arguments:",
4261  "     -v, --verbose              Print each filename as it is processed",
4262  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4263  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4264  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4265  "     -g, --glob                 Use glob matching for names in archive",
4266  "     -n, --dryrun               Show the SQL that would have occurred",
4267  "   Examples:",
4268  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4269  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4270  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4271  "   See also:",
4272  "      http://sqlite.org/cli.html#sqlite_archive_support",
4273#endif
4274#ifndef SQLITE_OMIT_AUTHORIZATION
4275  ".auth ON|OFF             Show authorizer callbacks",
4276#endif
4277#ifndef SQLITE_SHELL_WASM_MODE
4278  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4279  "   Options:",
4280  "       --append            Use the appendvfs",
4281  "       --async             Write to FILE without journal and fsync()",
4282#endif
4283  ".bail on|off             Stop after hitting an error.  Default OFF",
4284  ".binary on|off           Turn binary output on or off.  Default OFF",
4285#ifndef SQLITE_SHELL_WASM_MODE
4286  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4287#endif
4288  ".changes on|off          Show number of rows changed by SQL",
4289#ifndef SQLITE_SHELL_WASM_MODE
4290  ".check GLOB              Fail if output since .testcase does not match",
4291  ".clone NEWDB             Clone data into NEWDB from the existing database",
4292#endif
4293  ".connection [close] [#]  Open or close an auxiliary database connection",
4294  ".databases               List names and files of attached databases",
4295  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4296  ".dbinfo ?DB?             Show status information about the database",
4297  ".dump ?OBJECTS?          Render database content as SQL",
4298  "   Options:",
4299  "     --data-only            Output only INSERT statements",
4300  "     --newlines             Allow unescaped newline characters in output",
4301  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4302  "     --preserve-rowids      Include ROWID values in the output",
4303  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4304  "   Additional LIKE patterns can be given in subsequent arguments",
4305  ".echo on|off             Turn command echo on or off",
4306  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4307  "   Other Modes:",
4308#ifdef SQLITE_DEBUG
4309  "      test                  Show raw EXPLAIN QUERY PLAN output",
4310  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4311#endif
4312  "      trigger               Like \"full\" but also show trigger bytecode",
4313#ifndef SQLITE_SHELL_WASM_MODE
4314  ".excel                   Display the output of next command in spreadsheet",
4315  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4316#endif
4317#ifndef SQLITE_SHELL_WASM_MODE
4318  ".exit ?CODE?             Exit this program with return-code CODE",
4319#endif
4320  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4321  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4322  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4323  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4324  "   --help                  Show CMD details",
4325  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4326  ".headers on|off          Turn display of headers on or off",
4327  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4328#ifndef SQLITE_SHELL_WASM_MODE
4329  ".import FILE TABLE       Import data from FILE into TABLE",
4330  "   Options:",
4331  "     --ascii               Use \\037 and \\036 as column and row separators",
4332  "     --csv                 Use , and \\n as column and row separators",
4333  "     --skip N              Skip the first N rows of input",
4334  "     --schema S            Target table to be S.TABLE",
4335  "     -v                    \"Verbose\" - increase auxiliary output",
4336  "   Notes:",
4337  "     *  If TABLE does not exist, it is created.  The first row of input",
4338  "        determines the column names.",
4339  "     *  If neither --csv or --ascii are used, the input mode is derived",
4340  "        from the \".mode\" output mode",
4341  "     *  If FILE begins with \"|\" then it is a command that generates the",
4342  "        input text.",
4343#endif
4344#ifndef SQLITE_OMIT_TEST_CONTROL
4345  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4346#endif
4347  ".indexes ?TABLE?         Show names of indexes",
4348  "                           If TABLE is specified, only show indexes for",
4349  "                           tables matching TABLE using the LIKE operator.",
4350#ifdef SQLITE_ENABLE_IOTRACE
4351  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4352#endif
4353  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4354  ".lint OPTIONS            Report potential schema issues.",
4355  "     Options:",
4356  "        fkey-indexes     Find missing foreign key indexes",
4357#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
4358  ".load FILE ?ENTRY?       Load an extension library",
4359#endif
4360#ifndef SQLITE_SHELL_WASM_MODE
4361  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4362#endif
4363  ".mode MODE ?OPTIONS?     Set output mode",
4364  "   MODE is one of:",
4365  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4366  "     box         Tables using unicode box-drawing characters",
4367  "     csv         Comma-separated values",
4368  "     column      Output in columns.  (See .width)",
4369  "     html        HTML <table> code",
4370  "     insert      SQL insert statements for TABLE",
4371  "     json        Results in a JSON array",
4372  "     line        One value per line",
4373  "     list        Values delimited by \"|\"",
4374  "     markdown    Markdown table format",
4375  "     qbox        Shorthand for \"box --width 60 --quote\"",
4376  "     quote       Escape answers as for SQL",
4377  "     table       ASCII-art table",
4378  "     tabs        Tab-separated values",
4379  "     tcl         TCL list elements",
4380  "   OPTIONS: (for columnar modes or insert mode):",
4381  "     --wrap N       Wrap output lines to no longer than N characters",
4382  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4383  "     --ww           Shorthand for \"--wordwrap 1\"",
4384  "     --quote        Quote output text as SQL literals",
4385  "     --noquote      Do not quote output text",
4386  "     TABLE          The name of SQL table used for \"insert\" mode",
4387#ifndef SQLITE_SHELL_WASM_MODE
4388  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4389#endif
4390  ".nullvalue STRING        Use STRING in place of NULL values",
4391#ifndef SQLITE_SHELL_WASM_MODE
4392  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4393  "     If FILE begins with '|' then open as a pipe",
4394  "       --bom  Put a UTF8 byte-order mark at the beginning",
4395  "       -e     Send output to the system text editor",
4396  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4397  /* Note that .open is (partially) available in WASM builds but is
4398  ** currently only intended to be used by the fiddle tool, not
4399  ** end users, so is "undocumented." */
4400  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4401  "     Options:",
4402  "        --append        Use appendvfs to append database to the end of FILE",
4403#endif
4404#ifndef SQLITE_OMIT_DESERIALIZE
4405  "        --deserialize   Load into memory using sqlite3_deserialize()",
4406  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4407  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4408#endif
4409  "        --new           Initialize FILE to an empty database",
4410  "        --nofollow      Do not follow symbolic links",
4411  "        --readonly      Open FILE readonly",
4412  "        --zip           FILE is a ZIP archive",
4413#ifndef SQLITE_SHELL_WASM_MODE
4414  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4415  "   If FILE begins with '|' then open it as a pipe.",
4416  "   Options:",
4417  "     --bom                 Prefix output with a UTF8 byte-order mark",
4418  "     -e                    Send output to the system text editor",
4419  "     -x                    Send output as CSV to a spreadsheet",
4420#endif
4421  ".parameter CMD ...       Manage SQL parameter bindings",
4422  "   clear                   Erase all bindings",
4423  "   init                    Initialize the TEMP table that holds bindings",
4424  "   list                    List the current parameter bindings",
4425  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4426  "                           PARAMETER should start with one of: $ : @ ?",
4427  "   unset PARAMETER         Remove PARAMETER from the binding table",
4428  ".print STRING...         Print literal STRING",
4429#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4430  ".progress N              Invoke progress handler after every N opcodes",
4431  "   --limit N                 Interrupt after N progress callbacks",
4432  "   --once                    Do no more than one progress interrupt",
4433  "   --quiet|-q                No output except at interrupts",
4434  "   --reset                   Reset the count for each input and interrupt",
4435#endif
4436  ".prompt MAIN CONTINUE    Replace the standard prompts",
4437#ifndef SQLITE_SHELL_WASM_MODE
4438  ".quit                    Exit this program",
4439  ".read FILE               Read input from FILE or command output",
4440  "    If FILE begins with \"|\", it is a command that generates the input.",
4441#endif
4442#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4443  ".recover                 Recover as much data as possible from corrupt db.",
4444  "   --freelist-corrupt       Assume the freelist is corrupt",
4445  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4446  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4447  "   --no-rowids              Do not attempt to recover rowid values",
4448  "                            that are not also INTEGER PRIMARY KEYs",
4449#endif
4450#ifndef SQLITE_SHELL_WASM_MODE
4451  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4452  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4453#endif
4454  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4455  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4456  "   Options:",
4457  "      --indent             Try to pretty-print the schema",
4458  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4459  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4460  "    Options:",
4461  "       --init               Create a new SELFTEST table",
4462  "       -v                   Verbose output",
4463  ".separator COL ?ROW?     Change the column and row separators",
4464#if defined(SQLITE_ENABLE_SESSION)
4465  ".session ?NAME? CMD ...  Create or control sessions",
4466  "   Subcommands:",
4467  "     attach TABLE             Attach TABLE",
4468  "     changeset FILE           Write a changeset into FILE",
4469  "     close                    Close one session",
4470  "     enable ?BOOLEAN?         Set or query the enable bit",
4471  "     filter GLOB...           Reject tables matching GLOBs",
4472  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4473  "     isempty                  Query whether the session is empty",
4474  "     list                     List currently open session names",
4475  "     open DB NAME             Open a new session on DB",
4476  "     patchset FILE            Write a patchset into FILE",
4477  "   If ?NAME? is omitted, the first defined session is used.",
4478#endif
4479  ".sha3sum ...             Compute a SHA3 hash of database content",
4480  "    Options:",
4481  "      --schema              Also hash the sqlite_schema table",
4482  "      --sha3-224            Use the sha3-224 algorithm",
4483  "      --sha3-256            Use the sha3-256 algorithm (default)",
4484  "      --sha3-384            Use the sha3-384 algorithm",
4485  "      --sha3-512            Use the sha3-512 algorithm",
4486  "    Any other argument is a LIKE pattern for tables to hash",
4487#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4488  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4489#endif
4490  ".show                    Show the current values for various settings",
4491  ".stats ?ARG?             Show stats or turn stats on or off",
4492  "   off                      Turn off automatic stat display",
4493  "   on                       Turn on automatic stat display",
4494  "   stmt                     Show statement stats",
4495  "   vmstep                   Show the virtual machine step count only",
4496#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4497  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4498#endif
4499  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4500#ifndef SQLITE_SHELL_WASM_MODE
4501  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4502#endif
4503  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4504  "                           Run \".testctrl\" with no arguments for details",
4505  ".timeout MS              Try opening locked tables for MS milliseconds",
4506  ".timer on|off            Turn SQL timer on or off",
4507#ifndef SQLITE_OMIT_TRACE
4508  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4509  "    FILE                    Send output to FILE",
4510  "    stdout                  Send output to stdout",
4511  "    stderr                  Send output to stderr",
4512  "    off                     Disable tracing",
4513  "    --expanded              Expand query parameters",
4514#ifdef SQLITE_ENABLE_NORMALIZE
4515  "    --normalized            Normal the SQL statements",
4516#endif
4517  "    --plain                 Show SQL as it is input",
4518  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4519  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4520  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4521  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4522#endif /* SQLITE_OMIT_TRACE */
4523#ifdef SQLITE_DEBUG
4524  ".unmodule NAME ...       Unregister virtual table modules",
4525  "    --allexcept             Unregister everything except those named",
4526#endif
4527  ".vfsinfo ?AUX?           Information about the top-level VFS",
4528  ".vfslist                 List all available VFSes",
4529  ".vfsname ?AUX?           Print the name of the VFS stack",
4530  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4531  "     Negative values right-justify",
4532};
4533
4534/*
4535** Output help text.
4536**
4537** zPattern describes the set of commands for which help text is provided.
4538** If zPattern is NULL, then show all commands, but only give a one-line
4539** description of each.
4540**
4541** Return the number of matches.
4542*/
4543static int showHelp(FILE *out, const char *zPattern){
4544  int i = 0;
4545  int j = 0;
4546  int n = 0;
4547  char *zPat;
4548  if( zPattern==0
4549   || zPattern[0]=='0'
4550   || strcmp(zPattern,"-a")==0
4551   || strcmp(zPattern,"-all")==0
4552   || strcmp(zPattern,"--all")==0
4553  ){
4554    /* Show all commands, but only one line per command */
4555    if( zPattern==0 ) zPattern = "";
4556    for(i=0; i<ArraySize(azHelp); i++){
4557      if( azHelp[i][0]=='.' || zPattern[0] ){
4558        utf8_printf(out, "%s\n", azHelp[i]);
4559        n++;
4560      }
4561    }
4562  }else{
4563    /* Look for commands that for which zPattern is an exact prefix */
4564    zPat = sqlite3_mprintf(".%s*", zPattern);
4565    shell_check_oom(zPat);
4566    for(i=0; i<ArraySize(azHelp); i++){
4567      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4568        utf8_printf(out, "%s\n", azHelp[i]);
4569        j = i+1;
4570        n++;
4571      }
4572    }
4573    sqlite3_free(zPat);
4574    if( n ){
4575      if( n==1 ){
4576        /* when zPattern is a prefix of exactly one command, then include the
4577        ** details of that command, which should begin at offset j */
4578        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4579          utf8_printf(out, "%s\n", azHelp[j]);
4580          j++;
4581        }
4582      }
4583      return n;
4584    }
4585    /* Look for commands that contain zPattern anywhere.  Show the complete
4586    ** text of all commands that match. */
4587    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4588    shell_check_oom(zPat);
4589    for(i=0; i<ArraySize(azHelp); i++){
4590      if( azHelp[i][0]=='.' ) j = i;
4591      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4592        utf8_printf(out, "%s\n", azHelp[j]);
4593        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4594          j++;
4595          utf8_printf(out, "%s\n", azHelp[j]);
4596        }
4597        i = j;
4598        n++;
4599      }
4600    }
4601    sqlite3_free(zPat);
4602  }
4603  return n;
4604}
4605
4606/* Forward reference */
4607static int process_input(ShellState *p);
4608
4609/*
4610** Read the content of file zName into memory obtained from sqlite3_malloc64()
4611** and return a pointer to the buffer. The caller is responsible for freeing
4612** the memory.
4613**
4614** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4615** read.
4616**
4617** For convenience, a nul-terminator byte is always appended to the data read
4618** from the file before the buffer is returned. This byte is not included in
4619** the final value of (*pnByte), if applicable.
4620**
4621** NULL is returned if any error is encountered. The final value of *pnByte
4622** is undefined in this case.
4623*/
4624static char *readFile(const char *zName, int *pnByte){
4625  FILE *in = fopen(zName, "rb");
4626  long nIn;
4627  size_t nRead;
4628  char *pBuf;
4629  if( in==0 ) return 0;
4630  fseek(in, 0, SEEK_END);
4631  nIn = ftell(in);
4632  rewind(in);
4633  pBuf = sqlite3_malloc64( nIn+1 );
4634  if( pBuf==0 ){ fclose(in); return 0; }
4635  nRead = fread(pBuf, nIn, 1, in);
4636  fclose(in);
4637  if( nRead!=1 ){
4638    sqlite3_free(pBuf);
4639    return 0;
4640  }
4641  pBuf[nIn] = 0;
4642  if( pnByte ) *pnByte = nIn;
4643  return pBuf;
4644}
4645
4646#if defined(SQLITE_ENABLE_SESSION)
4647/*
4648** Close a single OpenSession object and release all of its associated
4649** resources.
4650*/
4651static void session_close(OpenSession *pSession){
4652  int i;
4653  sqlite3session_delete(pSession->p);
4654  sqlite3_free(pSession->zName);
4655  for(i=0; i<pSession->nFilter; i++){
4656    sqlite3_free(pSession->azFilter[i]);
4657  }
4658  sqlite3_free(pSession->azFilter);
4659  memset(pSession, 0, sizeof(OpenSession));
4660}
4661#endif
4662
4663/*
4664** Close all OpenSession objects and release all associated resources.
4665*/
4666#if defined(SQLITE_ENABLE_SESSION)
4667static void session_close_all(ShellState *p, int i){
4668  int j;
4669  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4670  for(j=0; j<pAuxDb->nSession; j++){
4671    session_close(&pAuxDb->aSession[j]);
4672  }
4673  pAuxDb->nSession = 0;
4674}
4675#else
4676# define session_close_all(X,Y)
4677#endif
4678
4679/*
4680** Implementation of the xFilter function for an open session.  Omit
4681** any tables named by ".session filter" but let all other table through.
4682*/
4683#if defined(SQLITE_ENABLE_SESSION)
4684static int session_filter(void *pCtx, const char *zTab){
4685  OpenSession *pSession = (OpenSession*)pCtx;
4686  int i;
4687  for(i=0; i<pSession->nFilter; i++){
4688    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4689  }
4690  return 1;
4691}
4692#endif
4693
4694/*
4695** Try to deduce the type of file for zName based on its content.  Return
4696** one of the SHELL_OPEN_* constants.
4697**
4698** If the file does not exist or is empty but its name looks like a ZIP
4699** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4700** Otherwise, assume an ordinary database regardless of the filename if
4701** the type cannot be determined from content.
4702*/
4703int deduceDatabaseType(const char *zName, int dfltZip){
4704  FILE *f = fopen(zName, "rb");
4705  size_t n;
4706  int rc = SHELL_OPEN_UNSPEC;
4707  char zBuf[100];
4708  if( f==0 ){
4709    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4710       return SHELL_OPEN_ZIPFILE;
4711    }else{
4712       return SHELL_OPEN_NORMAL;
4713    }
4714  }
4715  n = fread(zBuf, 16, 1, f);
4716  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4717    fclose(f);
4718    return SHELL_OPEN_NORMAL;
4719  }
4720  fseek(f, -25, SEEK_END);
4721  n = fread(zBuf, 25, 1, f);
4722  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4723    rc = SHELL_OPEN_APPENDVFS;
4724  }else{
4725    fseek(f, -22, SEEK_END);
4726    n = fread(zBuf, 22, 1, f);
4727    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4728       && zBuf[3]==0x06 ){
4729      rc = SHELL_OPEN_ZIPFILE;
4730    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4731      rc = SHELL_OPEN_ZIPFILE;
4732    }
4733  }
4734  fclose(f);
4735  return rc;
4736}
4737
4738#ifndef SQLITE_OMIT_DESERIALIZE
4739/*
4740** Reconstruct an in-memory database using the output from the "dbtotxt"
4741** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4742** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4743*/
4744static unsigned char *readHexDb(ShellState *p, int *pnData){
4745  unsigned char *a = 0;
4746  int nLine;
4747  int n = 0;
4748  int pgsz = 0;
4749  int iOffset = 0;
4750  int j, k;
4751  int rc;
4752  FILE *in;
4753  const char *zDbFilename = p->pAuxDb->zDbFilename;
4754  unsigned int x[16];
4755  char zLine[1000];
4756  if( zDbFilename ){
4757    in = fopen(zDbFilename, "r");
4758    if( in==0 ){
4759      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4760      return 0;
4761    }
4762    nLine = 0;
4763  }else{
4764    in = p->in;
4765    nLine = p->lineno;
4766    if( in==0 ) in = stdin;
4767  }
4768  *pnData = 0;
4769  nLine++;
4770  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4771  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4772  if( rc!=2 ) goto readHexDb_error;
4773  if( n<0 ) goto readHexDb_error;
4774  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4775  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4776  a = sqlite3_malloc( n ? n : 1 );
4777  shell_check_oom(a);
4778  memset(a, 0, n);
4779  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4780    utf8_printf(stderr, "invalid pagesize\n");
4781    goto readHexDb_error;
4782  }
4783  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4784    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4785    if( rc==2 ){
4786      iOffset = k;
4787      continue;
4788    }
4789    if( strncmp(zLine, "| end ", 6)==0 ){
4790      break;
4791    }
4792    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4793                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4794                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4795    if( rc==17 ){
4796      k = iOffset+j;
4797      if( k+16<=n && k>=0 ){
4798        int ii;
4799        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4800      }
4801    }
4802  }
4803  *pnData = n;
4804  if( in!=p->in ){
4805    fclose(in);
4806  }else{
4807    p->lineno = nLine;
4808  }
4809  return a;
4810
4811readHexDb_error:
4812  if( in!=p->in ){
4813    fclose(in);
4814  }else{
4815    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4816      nLine++;
4817      if(strncmp(zLine, "| end ", 6)==0 ) break;
4818    }
4819    p->lineno = nLine;
4820  }
4821  sqlite3_free(a);
4822  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4823  return 0;
4824}
4825#endif /* SQLITE_OMIT_DESERIALIZE */
4826
4827/*
4828** Scalar function "shell_int32". The first argument to this function
4829** must be a blob. The second a non-negative integer. This function
4830** reads and returns a 32-bit big-endian integer from byte
4831** offset (4*<arg2>) of the blob.
4832*/
4833static void shellInt32(
4834  sqlite3_context *context,
4835  int argc,
4836  sqlite3_value **argv
4837){
4838  const unsigned char *pBlob;
4839  int nBlob;
4840  int iInt;
4841
4842  UNUSED_PARAMETER(argc);
4843  nBlob = sqlite3_value_bytes(argv[0]);
4844  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4845  iInt = sqlite3_value_int(argv[1]);
4846
4847  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4848    const unsigned char *a = &pBlob[iInt*4];
4849    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4850                       + ((sqlite3_int64)a[1]<<16)
4851                       + ((sqlite3_int64)a[2]<< 8)
4852                       + ((sqlite3_int64)a[3]<< 0);
4853    sqlite3_result_int64(context, iVal);
4854  }
4855}
4856
4857/*
4858** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4859** using "..." with internal double-quote characters doubled.
4860*/
4861static void shellIdQuote(
4862  sqlite3_context *context,
4863  int argc,
4864  sqlite3_value **argv
4865){
4866  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4867  UNUSED_PARAMETER(argc);
4868  if( zName ){
4869    char *z = sqlite3_mprintf("\"%w\"", zName);
4870    sqlite3_result_text(context, z, -1, sqlite3_free);
4871  }
4872}
4873
4874/*
4875** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4876*/
4877static void shellUSleepFunc(
4878  sqlite3_context *context,
4879  int argcUnused,
4880  sqlite3_value **argv
4881){
4882  int sleep = sqlite3_value_int(argv[0]);
4883  (void)argcUnused;
4884  sqlite3_sleep(sleep/1000);
4885  sqlite3_result_int(context, sleep);
4886}
4887
4888/*
4889** Scalar function "shell_escape_crnl" used by the .recover command.
4890** The argument passed to this function is the output of built-in
4891** function quote(). If the first character of the input is "'",
4892** indicating that the value passed to quote() was a text value,
4893** then this function searches the input for "\n" and "\r" characters
4894** and adds a wrapper similar to the following:
4895**
4896**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4897**
4898** Or, if the first character of the input is not "'", then a copy
4899** of the input is returned.
4900*/
4901static void shellEscapeCrnl(
4902  sqlite3_context *context,
4903  int argc,
4904  sqlite3_value **argv
4905){
4906  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4907  UNUSED_PARAMETER(argc);
4908  if( zText && zText[0]=='\'' ){
4909    int nText = sqlite3_value_bytes(argv[0]);
4910    int i;
4911    char zBuf1[20];
4912    char zBuf2[20];
4913    const char *zNL = 0;
4914    const char *zCR = 0;
4915    int nCR = 0;
4916    int nNL = 0;
4917
4918    for(i=0; zText[i]; i++){
4919      if( zNL==0 && zText[i]=='\n' ){
4920        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4921        nNL = (int)strlen(zNL);
4922      }
4923      if( zCR==0 && zText[i]=='\r' ){
4924        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4925        nCR = (int)strlen(zCR);
4926      }
4927    }
4928
4929    if( zNL || zCR ){
4930      int iOut = 0;
4931      i64 nMax = (nNL > nCR) ? nNL : nCR;
4932      i64 nAlloc = nMax * nText + (nMax+64)*2;
4933      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4934      if( zOut==0 ){
4935        sqlite3_result_error_nomem(context);
4936        return;
4937      }
4938
4939      if( zNL && zCR ){
4940        memcpy(&zOut[iOut], "replace(replace(", 16);
4941        iOut += 16;
4942      }else{
4943        memcpy(&zOut[iOut], "replace(", 8);
4944        iOut += 8;
4945      }
4946      for(i=0; zText[i]; i++){
4947        if( zText[i]=='\n' ){
4948          memcpy(&zOut[iOut], zNL, nNL);
4949          iOut += nNL;
4950        }else if( zText[i]=='\r' ){
4951          memcpy(&zOut[iOut], zCR, nCR);
4952          iOut += nCR;
4953        }else{
4954          zOut[iOut] = zText[i];
4955          iOut++;
4956        }
4957      }
4958
4959      if( zNL ){
4960        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4961        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4962        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4963      }
4964      if( zCR ){
4965        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4966        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4967        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4968      }
4969
4970      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4971      sqlite3_free(zOut);
4972      return;
4973    }
4974  }
4975
4976  sqlite3_result_value(context, argv[0]);
4977}
4978
4979/* Flags for open_db().
4980**
4981** The default behavior of open_db() is to exit(1) if the database fails to
4982** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4983** but still returns without calling exit.
4984**
4985** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4986** ZIP archive if the file does not exist or is empty and its name matches
4987** the *.zip pattern.
4988*/
4989#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4990#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4991
4992/*
4993** Make sure the database is open.  If it is not, then open it.  If
4994** the database fails to open, print an error message and exit.
4995*/
4996static void open_db(ShellState *p, int openFlags){
4997  if( p->db==0 ){
4998    const char *zDbFilename = p->pAuxDb->zDbFilename;
4999    if( p->openMode==SHELL_OPEN_UNSPEC ){
5000      if( zDbFilename==0 || zDbFilename[0]==0 ){
5001        p->openMode = SHELL_OPEN_NORMAL;
5002      }else{
5003        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5004                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5005      }
5006    }
5007    switch( p->openMode ){
5008      case SHELL_OPEN_APPENDVFS: {
5009        sqlite3_open_v2(zDbFilename, &p->db,
5010           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5011        break;
5012      }
5013      case SHELL_OPEN_HEXDB:
5014      case SHELL_OPEN_DESERIALIZE: {
5015        sqlite3_open(0, &p->db);
5016        break;
5017      }
5018      case SHELL_OPEN_ZIPFILE: {
5019        sqlite3_open(":memory:", &p->db);
5020        break;
5021      }
5022      case SHELL_OPEN_READONLY: {
5023        sqlite3_open_v2(zDbFilename, &p->db,
5024            SQLITE_OPEN_READONLY|p->openFlags, 0);
5025        break;
5026      }
5027      case SHELL_OPEN_UNSPEC:
5028      case SHELL_OPEN_NORMAL: {
5029        sqlite3_open_v2(zDbFilename, &p->db,
5030           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5031        break;
5032      }
5033    }
5034    globalDb = p->db;
5035    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5036      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5037          zDbFilename, sqlite3_errmsg(p->db));
5038      if( openFlags & OPEN_DB_KEEPALIVE ){
5039        sqlite3_open(":memory:", &p->db);
5040        return;
5041      }
5042      exit(1);
5043    }
5044#ifndef SQLITE_OMIT_LOAD_EXTENSION
5045    sqlite3_enable_load_extension(p->db, 1);
5046#endif
5047    sqlite3_shathree_init(p->db, 0, 0);
5048    sqlite3_uint_init(p->db, 0, 0);
5049    sqlite3_decimal_init(p->db, 0, 0);
5050    sqlite3_regexp_init(p->db, 0, 0);
5051    sqlite3_ieee_init(p->db, 0, 0);
5052    sqlite3_series_init(p->db, 0, 0);
5053#ifndef SQLITE_SHELL_WASM_MODE
5054    sqlite3_fileio_init(p->db, 0, 0);
5055    sqlite3_completion_init(p->db, 0, 0);
5056#endif
5057#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5058    sqlite3_dbdata_init(p->db, 0, 0);
5059#endif
5060#ifdef SQLITE_HAVE_ZLIB
5061    if( !p->bSafeModePersist ){
5062      sqlite3_zipfile_init(p->db, 0, 0);
5063      sqlite3_sqlar_init(p->db, 0, 0);
5064    }
5065#endif
5066    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5067                            shellAddSchemaName, 0, 0);
5068    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5069                            shellModuleSchema, 0, 0);
5070    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5071                            shellPutsFunc, 0, 0);
5072    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5073                            shellEscapeCrnl, 0, 0);
5074    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5075                            shellInt32, 0, 0);
5076    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5077                            shellIdQuote, 0, 0);
5078    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5079                            shellUSleepFunc, 0, 0);
5080#ifndef SQLITE_NOHAVE_SYSTEM
5081    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5082                            editFunc, 0, 0);
5083    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5084                            editFunc, 0, 0);
5085#endif
5086    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5087      char *zSql = sqlite3_mprintf(
5088         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5089      shell_check_oom(zSql);
5090      sqlite3_exec(p->db, zSql, 0, 0, 0);
5091      sqlite3_free(zSql);
5092    }
5093#ifndef SQLITE_OMIT_DESERIALIZE
5094    else
5095    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5096      int rc;
5097      int nData = 0;
5098      unsigned char *aData;
5099      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5100        aData = (unsigned char*)readFile(zDbFilename, &nData);
5101      }else{
5102        aData = readHexDb(p, &nData);
5103        if( aData==0 ){
5104          return;
5105        }
5106      }
5107      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5108                   SQLITE_DESERIALIZE_RESIZEABLE |
5109                   SQLITE_DESERIALIZE_FREEONCLOSE);
5110      if( rc ){
5111        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5112      }
5113      if( p->szMax>0 ){
5114        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5115      }
5116    }
5117#endif
5118  }
5119  if( p->bSafeModePersist && p->db!=0 ){
5120    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5121  }
5122}
5123
5124/*
5125** Attempt to close the databaes connection.  Report errors.
5126*/
5127void close_db(sqlite3 *db){
5128  int rc = sqlite3_close(db);
5129  if( rc ){
5130    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5131        rc, sqlite3_errmsg(db));
5132  }
5133}
5134
5135#if HAVE_READLINE || HAVE_EDITLINE
5136/*
5137** Readline completion callbacks
5138*/
5139static char *readline_completion_generator(const char *text, int state){
5140  static sqlite3_stmt *pStmt = 0;
5141  char *zRet;
5142  if( state==0 ){
5143    char *zSql;
5144    sqlite3_finalize(pStmt);
5145    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5146                           "  FROM completion(%Q) ORDER BY 1", text);
5147    shell_check_oom(zSql);
5148    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5149    sqlite3_free(zSql);
5150  }
5151  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5152    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5153    zRet = z ? strdup(z) : 0;
5154  }else{
5155    sqlite3_finalize(pStmt);
5156    pStmt = 0;
5157    zRet = 0;
5158  }
5159  return zRet;
5160}
5161static char **readline_completion(const char *zText, int iStart, int iEnd){
5162  rl_attempted_completion_over = 1;
5163  return rl_completion_matches(zText, readline_completion_generator);
5164}
5165
5166#elif HAVE_LINENOISE
5167/*
5168** Linenoise completion callback
5169*/
5170static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5171  int nLine = strlen30(zLine);
5172  int i, iStart;
5173  sqlite3_stmt *pStmt = 0;
5174  char *zSql;
5175  char zBuf[1000];
5176
5177  if( nLine>sizeof(zBuf)-30 ) return;
5178  if( zLine[0]=='.' || zLine[0]=='#') return;
5179  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5180  if( i==nLine-1 ) return;
5181  iStart = i+1;
5182  memcpy(zBuf, zLine, iStart);
5183  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5184                         "  FROM completion(%Q,%Q) ORDER BY 1",
5185                         &zLine[iStart], zLine);
5186  shell_check_oom(zSql);
5187  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5188  sqlite3_free(zSql);
5189  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5190  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5191    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5192    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5193    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5194      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5195      linenoiseAddCompletion(lc, zBuf);
5196    }
5197  }
5198  sqlite3_finalize(pStmt);
5199}
5200#endif
5201
5202/*
5203** Do C-language style dequoting.
5204**
5205**    \a    -> alarm
5206**    \b    -> backspace
5207**    \t    -> tab
5208**    \n    -> newline
5209**    \v    -> vertical tab
5210**    \f    -> form feed
5211**    \r    -> carriage return
5212**    \s    -> space
5213**    \"    -> "
5214**    \'    -> '
5215**    \\    -> backslash
5216**    \NNN  -> ascii character NNN in octal
5217*/
5218static void resolve_backslashes(char *z){
5219  int i, j;
5220  char c;
5221  while( *z && *z!='\\' ) z++;
5222  for(i=j=0; (c = z[i])!=0; i++, j++){
5223    if( c=='\\' && z[i+1]!=0 ){
5224      c = z[++i];
5225      if( c=='a' ){
5226        c = '\a';
5227      }else if( c=='b' ){
5228        c = '\b';
5229      }else if( c=='t' ){
5230        c = '\t';
5231      }else if( c=='n' ){
5232        c = '\n';
5233      }else if( c=='v' ){
5234        c = '\v';
5235      }else if( c=='f' ){
5236        c = '\f';
5237      }else if( c=='r' ){
5238        c = '\r';
5239      }else if( c=='"' ){
5240        c = '"';
5241      }else if( c=='\'' ){
5242        c = '\'';
5243      }else if( c=='\\' ){
5244        c = '\\';
5245      }else if( c>='0' && c<='7' ){
5246        c -= '0';
5247        if( z[i+1]>='0' && z[i+1]<='7' ){
5248          i++;
5249          c = (c<<3) + z[i] - '0';
5250          if( z[i+1]>='0' && z[i+1]<='7' ){
5251            i++;
5252            c = (c<<3) + z[i] - '0';
5253          }
5254        }
5255      }
5256    }
5257    z[j] = c;
5258  }
5259  if( j<i ) z[j] = 0;
5260}
5261
5262/*
5263** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5264** for TRUE and FALSE.  Return the integer value if appropriate.
5265*/
5266static int booleanValue(const char *zArg){
5267  int i;
5268  if( zArg[0]=='0' && zArg[1]=='x' ){
5269    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5270  }else{
5271    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5272  }
5273  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5274  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5275    return 1;
5276  }
5277  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5278    return 0;
5279  }
5280  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5281          zArg);
5282  return 0;
5283}
5284
5285/*
5286** Set or clear a shell flag according to a boolean value.
5287*/
5288static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5289  if( booleanValue(zArg) ){
5290    ShellSetFlag(p, mFlag);
5291  }else{
5292    ShellClearFlag(p, mFlag);
5293  }
5294}
5295
5296/*
5297** Close an output file, assuming it is not stderr or stdout
5298*/
5299static void output_file_close(FILE *f){
5300  if( f && f!=stdout && f!=stderr ) fclose(f);
5301}
5302
5303/*
5304** Try to open an output file.   The names "stdout" and "stderr" are
5305** recognized and do the right thing.  NULL is returned if the output
5306** filename is "off".
5307*/
5308static FILE *output_file_open(const char *zFile, int bTextMode){
5309  FILE *f;
5310  if( strcmp(zFile,"stdout")==0 ){
5311    f = stdout;
5312  }else if( strcmp(zFile, "stderr")==0 ){
5313    f = stderr;
5314  }else if( strcmp(zFile, "off")==0 ){
5315    f = 0;
5316  }else{
5317    f = fopen(zFile, bTextMode ? "w" : "wb");
5318    if( f==0 ){
5319      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5320    }
5321  }
5322  return f;
5323}
5324
5325#ifndef SQLITE_OMIT_TRACE
5326/*
5327** A routine for handling output from sqlite3_trace().
5328*/
5329static int sql_trace_callback(
5330  unsigned mType,         /* The trace type */
5331  void *pArg,             /* The ShellState pointer */
5332  void *pP,               /* Usually a pointer to sqlite_stmt */
5333  void *pX                /* Auxiliary output */
5334){
5335  ShellState *p = (ShellState*)pArg;
5336  sqlite3_stmt *pStmt;
5337  const char *zSql;
5338  int nSql;
5339  if( p->traceOut==0 ) return 0;
5340  if( mType==SQLITE_TRACE_CLOSE ){
5341    utf8_printf(p->traceOut, "-- closing database connection\n");
5342    return 0;
5343  }
5344  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5345    zSql = (const char*)pX;
5346  }else{
5347    pStmt = (sqlite3_stmt*)pP;
5348    switch( p->eTraceType ){
5349      case SHELL_TRACE_EXPANDED: {
5350        zSql = sqlite3_expanded_sql(pStmt);
5351        break;
5352      }
5353#ifdef SQLITE_ENABLE_NORMALIZE
5354      case SHELL_TRACE_NORMALIZED: {
5355        zSql = sqlite3_normalized_sql(pStmt);
5356        break;
5357      }
5358#endif
5359      default: {
5360        zSql = sqlite3_sql(pStmt);
5361        break;
5362      }
5363    }
5364  }
5365  if( zSql==0 ) return 0;
5366  nSql = strlen30(zSql);
5367  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5368  switch( mType ){
5369    case SQLITE_TRACE_ROW:
5370    case SQLITE_TRACE_STMT: {
5371      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5372      break;
5373    }
5374    case SQLITE_TRACE_PROFILE: {
5375      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5376      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5377      break;
5378    }
5379  }
5380  return 0;
5381}
5382#endif
5383
5384/*
5385** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5386** a useful spot to set a debugger breakpoint.
5387*/
5388static void test_breakpoint(void){
5389  static int nCall = 0;
5390  nCall++;
5391}
5392
5393/*
5394** An object used to read a CSV and other files for import.
5395*/
5396typedef struct ImportCtx ImportCtx;
5397struct ImportCtx {
5398  const char *zFile;  /* Name of the input file */
5399  FILE *in;           /* Read the CSV text from this input stream */
5400  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5401  char *z;            /* Accumulated text for a field */
5402  int n;              /* Number of bytes in z */
5403  int nAlloc;         /* Space allocated for z[] */
5404  int nLine;          /* Current line number */
5405  int nRow;           /* Number of rows imported */
5406  int nErr;           /* Number of errors encountered */
5407  int bNotFirst;      /* True if one or more bytes already read */
5408  int cTerm;          /* Character that terminated the most recent field */
5409  int cColSep;        /* The column separator character.  (Usually ",") */
5410  int cRowSep;        /* The row separator character.  (Usually "\n") */
5411};
5412
5413/* Clean up resourced used by an ImportCtx */
5414static void import_cleanup(ImportCtx *p){
5415  if( p->in!=0 && p->xCloser!=0 ){
5416    p->xCloser(p->in);
5417    p->in = 0;
5418  }
5419  sqlite3_free(p->z);
5420  p->z = 0;
5421}
5422
5423/* Append a single byte to z[] */
5424static void import_append_char(ImportCtx *p, int c){
5425  if( p->n+1>=p->nAlloc ){
5426    p->nAlloc += p->nAlloc + 100;
5427    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5428    shell_check_oom(p->z);
5429  }
5430  p->z[p->n++] = (char)c;
5431}
5432
5433/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5434** with the option of having a separator other than ",".
5435**
5436**   +  Input comes from p->in.
5437**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5438**      from sqlite3_malloc64().
5439**   +  Use p->cSep as the column separator.  The default is ",".
5440**   +  Use p->rSep as the row separator.  The default is "\n".
5441**   +  Keep track of the line number in p->nLine.
5442**   +  Store the character that terminates the field in p->cTerm.  Store
5443**      EOF on end-of-file.
5444**   +  Report syntax errors on stderr
5445*/
5446static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5447  int c;
5448  int cSep = p->cColSep;
5449  int rSep = p->cRowSep;
5450  p->n = 0;
5451  c = fgetc(p->in);
5452  if( c==EOF || seenInterrupt ){
5453    p->cTerm = EOF;
5454    return 0;
5455  }
5456  if( c=='"' ){
5457    int pc, ppc;
5458    int startLine = p->nLine;
5459    int cQuote = c;
5460    pc = ppc = 0;
5461    while( 1 ){
5462      c = fgetc(p->in);
5463      if( c==rSep ) p->nLine++;
5464      if( c==cQuote ){
5465        if( pc==cQuote ){
5466          pc = 0;
5467          continue;
5468        }
5469      }
5470      if( (c==cSep && pc==cQuote)
5471       || (c==rSep && pc==cQuote)
5472       || (c==rSep && pc=='\r' && ppc==cQuote)
5473       || (c==EOF && pc==cQuote)
5474      ){
5475        do{ p->n--; }while( p->z[p->n]!=cQuote );
5476        p->cTerm = c;
5477        break;
5478      }
5479      if( pc==cQuote && c!='\r' ){
5480        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5481                p->zFile, p->nLine, cQuote);
5482      }
5483      if( c==EOF ){
5484        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5485                p->zFile, startLine, cQuote);
5486        p->cTerm = c;
5487        break;
5488      }
5489      import_append_char(p, c);
5490      ppc = pc;
5491      pc = c;
5492    }
5493  }else{
5494    /* If this is the first field being parsed and it begins with the
5495    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5496    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5497      import_append_char(p, c);
5498      c = fgetc(p->in);
5499      if( (c&0xff)==0xbb ){
5500        import_append_char(p, c);
5501        c = fgetc(p->in);
5502        if( (c&0xff)==0xbf ){
5503          p->bNotFirst = 1;
5504          p->n = 0;
5505          return csv_read_one_field(p);
5506        }
5507      }
5508    }
5509    while( c!=EOF && c!=cSep && c!=rSep ){
5510      import_append_char(p, c);
5511      c = fgetc(p->in);
5512    }
5513    if( c==rSep ){
5514      p->nLine++;
5515      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5516    }
5517    p->cTerm = c;
5518  }
5519  if( p->z ) p->z[p->n] = 0;
5520  p->bNotFirst = 1;
5521  return p->z;
5522}
5523
5524/* Read a single field of ASCII delimited text.
5525**
5526**   +  Input comes from p->in.
5527**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5528**      from sqlite3_malloc64().
5529**   +  Use p->cSep as the column separator.  The default is "\x1F".
5530**   +  Use p->rSep as the row separator.  The default is "\x1E".
5531**   +  Keep track of the row number in p->nLine.
5532**   +  Store the character that terminates the field in p->cTerm.  Store
5533**      EOF on end-of-file.
5534**   +  Report syntax errors on stderr
5535*/
5536static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5537  int c;
5538  int cSep = p->cColSep;
5539  int rSep = p->cRowSep;
5540  p->n = 0;
5541  c = fgetc(p->in);
5542  if( c==EOF || seenInterrupt ){
5543    p->cTerm = EOF;
5544    return 0;
5545  }
5546  while( c!=EOF && c!=cSep && c!=rSep ){
5547    import_append_char(p, c);
5548    c = fgetc(p->in);
5549  }
5550  if( c==rSep ){
5551    p->nLine++;
5552  }
5553  p->cTerm = c;
5554  if( p->z ) p->z[p->n] = 0;
5555  return p->z;
5556}
5557
5558/*
5559** Try to transfer data for table zTable.  If an error is seen while
5560** moving forward, try to go backwards.  The backwards movement won't
5561** work for WITHOUT ROWID tables.
5562*/
5563static void tryToCloneData(
5564  ShellState *p,
5565  sqlite3 *newDb,
5566  const char *zTable
5567){
5568  sqlite3_stmt *pQuery = 0;
5569  sqlite3_stmt *pInsert = 0;
5570  char *zQuery = 0;
5571  char *zInsert = 0;
5572  int rc;
5573  int i, j, n;
5574  int nTable = strlen30(zTable);
5575  int k = 0;
5576  int cnt = 0;
5577  const int spinRate = 10000;
5578
5579  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5580  shell_check_oom(zQuery);
5581  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5582  if( rc ){
5583    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5584            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5585            zQuery);
5586    goto end_data_xfer;
5587  }
5588  n = sqlite3_column_count(pQuery);
5589  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5590  shell_check_oom(zInsert);
5591  sqlite3_snprintf(200+nTable,zInsert,
5592                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5593  i = strlen30(zInsert);
5594  for(j=1; j<n; j++){
5595    memcpy(zInsert+i, ",?", 2);
5596    i += 2;
5597  }
5598  memcpy(zInsert+i, ");", 3);
5599  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5600  if( rc ){
5601    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5602            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5603            zQuery);
5604    goto end_data_xfer;
5605  }
5606  for(k=0; k<2; k++){
5607    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5608      for(i=0; i<n; i++){
5609        switch( sqlite3_column_type(pQuery, i) ){
5610          case SQLITE_NULL: {
5611            sqlite3_bind_null(pInsert, i+1);
5612            break;
5613          }
5614          case SQLITE_INTEGER: {
5615            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5616            break;
5617          }
5618          case SQLITE_FLOAT: {
5619            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5620            break;
5621          }
5622          case SQLITE_TEXT: {
5623            sqlite3_bind_text(pInsert, i+1,
5624                             (const char*)sqlite3_column_text(pQuery,i),
5625                             -1, SQLITE_STATIC);
5626            break;
5627          }
5628          case SQLITE_BLOB: {
5629            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5630                                            sqlite3_column_bytes(pQuery,i),
5631                                            SQLITE_STATIC);
5632            break;
5633          }
5634        }
5635      } /* End for */
5636      rc = sqlite3_step(pInsert);
5637      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5638        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5639                        sqlite3_errmsg(newDb));
5640      }
5641      sqlite3_reset(pInsert);
5642      cnt++;
5643      if( (cnt%spinRate)==0 ){
5644        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5645        fflush(stdout);
5646      }
5647    } /* End while */
5648    if( rc==SQLITE_DONE ) break;
5649    sqlite3_finalize(pQuery);
5650    sqlite3_free(zQuery);
5651    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5652                             zTable);
5653    shell_check_oom(zQuery);
5654    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5655    if( rc ){
5656      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5657      break;
5658    }
5659  } /* End for(k=0...) */
5660
5661end_data_xfer:
5662  sqlite3_finalize(pQuery);
5663  sqlite3_finalize(pInsert);
5664  sqlite3_free(zQuery);
5665  sqlite3_free(zInsert);
5666}
5667
5668
5669/*
5670** Try to transfer all rows of the schema that match zWhere.  For
5671** each row, invoke xForEach() on the object defined by that row.
5672** If an error is encountered while moving forward through the
5673** sqlite_schema table, try again moving backwards.
5674*/
5675static void tryToCloneSchema(
5676  ShellState *p,
5677  sqlite3 *newDb,
5678  const char *zWhere,
5679  void (*xForEach)(ShellState*,sqlite3*,const char*)
5680){
5681  sqlite3_stmt *pQuery = 0;
5682  char *zQuery = 0;
5683  int rc;
5684  const unsigned char *zName;
5685  const unsigned char *zSql;
5686  char *zErrMsg = 0;
5687
5688  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5689                           " WHERE %s", zWhere);
5690  shell_check_oom(zQuery);
5691  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5692  if( rc ){
5693    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5694                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5695                    zQuery);
5696    goto end_schema_xfer;
5697  }
5698  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5699    zName = sqlite3_column_text(pQuery, 0);
5700    zSql = sqlite3_column_text(pQuery, 1);
5701    if( zName==0 || zSql==0 ) continue;
5702    printf("%s... ", zName); fflush(stdout);
5703    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5704    if( zErrMsg ){
5705      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5706      sqlite3_free(zErrMsg);
5707      zErrMsg = 0;
5708    }
5709    if( xForEach ){
5710      xForEach(p, newDb, (const char*)zName);
5711    }
5712    printf("done\n");
5713  }
5714  if( rc!=SQLITE_DONE ){
5715    sqlite3_finalize(pQuery);
5716    sqlite3_free(zQuery);
5717    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5718                             " WHERE %s ORDER BY rowid DESC", zWhere);
5719    shell_check_oom(zQuery);
5720    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5721    if( rc ){
5722      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5723                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5724                      zQuery);
5725      goto end_schema_xfer;
5726    }
5727    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5728      zName = sqlite3_column_text(pQuery, 0);
5729      zSql = sqlite3_column_text(pQuery, 1);
5730      if( zName==0 || zSql==0 ) continue;
5731      printf("%s... ", zName); fflush(stdout);
5732      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5733      if( zErrMsg ){
5734        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5735        sqlite3_free(zErrMsg);
5736        zErrMsg = 0;
5737      }
5738      if( xForEach ){
5739        xForEach(p, newDb, (const char*)zName);
5740      }
5741      printf("done\n");
5742    }
5743  }
5744end_schema_xfer:
5745  sqlite3_finalize(pQuery);
5746  sqlite3_free(zQuery);
5747}
5748
5749/*
5750** Open a new database file named "zNewDb".  Try to recover as much information
5751** as possible out of the main database (which might be corrupt) and write it
5752** into zNewDb.
5753*/
5754static void tryToClone(ShellState *p, const char *zNewDb){
5755  int rc;
5756  sqlite3 *newDb = 0;
5757  if( access(zNewDb,0)==0 ){
5758    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5759    return;
5760  }
5761  rc = sqlite3_open(zNewDb, &newDb);
5762  if( rc ){
5763    utf8_printf(stderr, "Cannot create output database: %s\n",
5764            sqlite3_errmsg(newDb));
5765  }else{
5766    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5767    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5768    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5769    tryToCloneSchema(p, newDb, "type!='table'", 0);
5770    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5771    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5772  }
5773  close_db(newDb);
5774}
5775
5776/*
5777** Change the output file back to stdout.
5778**
5779** If the p->doXdgOpen flag is set, that means the output was being
5780** redirected to a temporary file named by p->zTempFile.  In that case,
5781** launch start/open/xdg-open on that temporary file.
5782*/
5783static void output_reset(ShellState *p){
5784  if( p->outfile[0]=='|' ){
5785#ifndef SQLITE_OMIT_POPEN
5786    pclose(p->out);
5787#endif
5788  }else{
5789    output_file_close(p->out);
5790#ifndef SQLITE_NOHAVE_SYSTEM
5791    if( p->doXdgOpen ){
5792      const char *zXdgOpenCmd =
5793#if defined(_WIN32)
5794      "start";
5795#elif defined(__APPLE__)
5796      "open";
5797#else
5798      "xdg-open";
5799#endif
5800      char *zCmd;
5801      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5802      if( system(zCmd) ){
5803        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5804      }else{
5805        /* Give the start/open/xdg-open command some time to get
5806        ** going before we continue, and potential delete the
5807        ** p->zTempFile data file out from under it */
5808        sqlite3_sleep(2000);
5809      }
5810      sqlite3_free(zCmd);
5811      outputModePop(p);
5812      p->doXdgOpen = 0;
5813    }
5814#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5815  }
5816  p->outfile[0] = 0;
5817  p->out = stdout;
5818}
5819
5820/*
5821** Run an SQL command and return the single integer result.
5822*/
5823static int db_int(sqlite3 *db, const char *zSql){
5824  sqlite3_stmt *pStmt;
5825  int res = 0;
5826  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5827  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5828    res = sqlite3_column_int(pStmt,0);
5829  }
5830  sqlite3_finalize(pStmt);
5831  return res;
5832}
5833
5834/*
5835** Convert a 2-byte or 4-byte big-endian integer into a native integer
5836*/
5837static unsigned int get2byteInt(unsigned char *a){
5838  return (a[0]<<8) + a[1];
5839}
5840static unsigned int get4byteInt(unsigned char *a){
5841  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5842}
5843
5844/*
5845** Implementation of the ".dbinfo" command.
5846**
5847** Return 1 on error, 2 to exit, and 0 otherwise.
5848*/
5849static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5850  static const struct { const char *zName; int ofst; } aField[] = {
5851     { "file change counter:",  24  },
5852     { "database page count:",  28  },
5853     { "freelist page count:",  36  },
5854     { "schema cookie:",        40  },
5855     { "schema format:",        44  },
5856     { "default cache size:",   48  },
5857     { "autovacuum top root:",  52  },
5858     { "incremental vacuum:",   64  },
5859     { "text encoding:",        56  },
5860     { "user version:",         60  },
5861     { "application id:",       68  },
5862     { "software version:",     96  },
5863  };
5864  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5865     { "number of tables:",
5866       "SELECT count(*) FROM %s WHERE type='table'" },
5867     { "number of indexes:",
5868       "SELECT count(*) FROM %s WHERE type='index'" },
5869     { "number of triggers:",
5870       "SELECT count(*) FROM %s WHERE type='trigger'" },
5871     { "number of views:",
5872       "SELECT count(*) FROM %s WHERE type='view'" },
5873     { "schema size:",
5874       "SELECT total(length(sql)) FROM %s" },
5875  };
5876  int i, rc;
5877  unsigned iDataVersion;
5878  char *zSchemaTab;
5879  char *zDb = nArg>=2 ? azArg[1] : "main";
5880  sqlite3_stmt *pStmt = 0;
5881  unsigned char aHdr[100];
5882  open_db(p, 0);
5883  if( p->db==0 ) return 1;
5884  rc = sqlite3_prepare_v2(p->db,
5885             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5886             -1, &pStmt, 0);
5887  if( rc ){
5888    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5889    sqlite3_finalize(pStmt);
5890    return 1;
5891  }
5892  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5893  if( sqlite3_step(pStmt)==SQLITE_ROW
5894   && sqlite3_column_bytes(pStmt,0)>100
5895  ){
5896    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5897    sqlite3_finalize(pStmt);
5898  }else{
5899    raw_printf(stderr, "unable to read database header\n");
5900    sqlite3_finalize(pStmt);
5901    return 1;
5902  }
5903  i = get2byteInt(aHdr+16);
5904  if( i==1 ) i = 65536;
5905  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5906  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5907  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5908  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5909  for(i=0; i<ArraySize(aField); i++){
5910    int ofst = aField[i].ofst;
5911    unsigned int val = get4byteInt(aHdr + ofst);
5912    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5913    switch( ofst ){
5914      case 56: {
5915        if( val==1 ) raw_printf(p->out, " (utf8)");
5916        if( val==2 ) raw_printf(p->out, " (utf16le)");
5917        if( val==3 ) raw_printf(p->out, " (utf16be)");
5918      }
5919    }
5920    raw_printf(p->out, "\n");
5921  }
5922  if( zDb==0 ){
5923    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5924  }else if( strcmp(zDb,"temp")==0 ){
5925    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5926  }else{
5927    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5928  }
5929  for(i=0; i<ArraySize(aQuery); i++){
5930    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5931    int val = db_int(p->db, zSql);
5932    sqlite3_free(zSql);
5933    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5934  }
5935  sqlite3_free(zSchemaTab);
5936  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5937  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5938  return 0;
5939}
5940
5941/*
5942** Print the current sqlite3_errmsg() value to stderr and return 1.
5943*/
5944static int shellDatabaseError(sqlite3 *db){
5945  const char *zErr = sqlite3_errmsg(db);
5946  utf8_printf(stderr, "Error: %s\n", zErr);
5947  return 1;
5948}
5949
5950/*
5951** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5952** if they match and FALSE (0) if they do not match.
5953**
5954** Globbing rules:
5955**
5956**      '*'       Matches any sequence of zero or more characters.
5957**
5958**      '?'       Matches exactly one character.
5959**
5960**     [...]      Matches one character from the enclosed list of
5961**                characters.
5962**
5963**     [^...]     Matches one character not in the enclosed list.
5964**
5965**      '#'       Matches any sequence of one or more digits with an
5966**                optional + or - sign in front
5967**
5968**      ' '       Any span of whitespace matches any other span of
5969**                whitespace.
5970**
5971** Extra whitespace at the end of z[] is ignored.
5972*/
5973static int testcase_glob(const char *zGlob, const char *z){
5974  int c, c2;
5975  int invert;
5976  int seen;
5977
5978  while( (c = (*(zGlob++)))!=0 ){
5979    if( IsSpace(c) ){
5980      if( !IsSpace(*z) ) return 0;
5981      while( IsSpace(*zGlob) ) zGlob++;
5982      while( IsSpace(*z) ) z++;
5983    }else if( c=='*' ){
5984      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5985        if( c=='?' && (*(z++))==0 ) return 0;
5986      }
5987      if( c==0 ){
5988        return 1;
5989      }else if( c=='[' ){
5990        while( *z && testcase_glob(zGlob-1,z)==0 ){
5991          z++;
5992        }
5993        return (*z)!=0;
5994      }
5995      while( (c2 = (*(z++)))!=0 ){
5996        while( c2!=c ){
5997          c2 = *(z++);
5998          if( c2==0 ) return 0;
5999        }
6000        if( testcase_glob(zGlob,z) ) return 1;
6001      }
6002      return 0;
6003    }else if( c=='?' ){
6004      if( (*(z++))==0 ) return 0;
6005    }else if( c=='[' ){
6006      int prior_c = 0;
6007      seen = 0;
6008      invert = 0;
6009      c = *(z++);
6010      if( c==0 ) return 0;
6011      c2 = *(zGlob++);
6012      if( c2=='^' ){
6013        invert = 1;
6014        c2 = *(zGlob++);
6015      }
6016      if( c2==']' ){
6017        if( c==']' ) seen = 1;
6018        c2 = *(zGlob++);
6019      }
6020      while( c2 && c2!=']' ){
6021        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6022          c2 = *(zGlob++);
6023          if( c>=prior_c && c<=c2 ) seen = 1;
6024          prior_c = 0;
6025        }else{
6026          if( c==c2 ){
6027            seen = 1;
6028          }
6029          prior_c = c2;
6030        }
6031        c2 = *(zGlob++);
6032      }
6033      if( c2==0 || (seen ^ invert)==0 ) return 0;
6034    }else if( c=='#' ){
6035      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6036      if( !IsDigit(z[0]) ) return 0;
6037      z++;
6038      while( IsDigit(z[0]) ){ z++; }
6039    }else{
6040      if( c!=(*(z++)) ) return 0;
6041    }
6042  }
6043  while( IsSpace(*z) ){ z++; }
6044  return *z==0;
6045}
6046
6047
6048/*
6049** Compare the string as a command-line option with either one or two
6050** initial "-" characters.
6051*/
6052static int optionMatch(const char *zStr, const char *zOpt){
6053  if( zStr[0]!='-' ) return 0;
6054  zStr++;
6055  if( zStr[0]=='-' ) zStr++;
6056  return strcmp(zStr, zOpt)==0;
6057}
6058
6059/*
6060** Delete a file.
6061*/
6062int shellDeleteFile(const char *zFilename){
6063  int rc;
6064#ifdef _WIN32
6065  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6066  rc = _wunlink(z);
6067  sqlite3_free(z);
6068#else
6069  rc = unlink(zFilename);
6070#endif
6071  return rc;
6072}
6073
6074/*
6075** Try to delete the temporary file (if there is one) and free the
6076** memory used to hold the name of the temp file.
6077*/
6078static void clearTempFile(ShellState *p){
6079  if( p->zTempFile==0 ) return;
6080  if( p->doXdgOpen ) return;
6081  if( shellDeleteFile(p->zTempFile) ) return;
6082  sqlite3_free(p->zTempFile);
6083  p->zTempFile = 0;
6084}
6085
6086/*
6087** Create a new temp file name with the given suffix.
6088*/
6089static void newTempFile(ShellState *p, const char *zSuffix){
6090  clearTempFile(p);
6091  sqlite3_free(p->zTempFile);
6092  p->zTempFile = 0;
6093  if( p->db ){
6094    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6095  }
6096  if( p->zTempFile==0 ){
6097    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6098    ** will not work and we will need to fallback to guessing */
6099    char *zTemp;
6100    sqlite3_uint64 r;
6101    sqlite3_randomness(sizeof(r), &r);
6102    zTemp = getenv("TEMP");
6103    if( zTemp==0 ) zTemp = getenv("TMP");
6104    if( zTemp==0 ){
6105#ifdef _WIN32
6106      zTemp = "\\tmp";
6107#else
6108      zTemp = "/tmp";
6109#endif
6110    }
6111    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6112  }else{
6113    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6114  }
6115  shell_check_oom(p->zTempFile);
6116}
6117
6118
6119/*
6120** The implementation of SQL scalar function fkey_collate_clause(), used
6121** by the ".lint fkey-indexes" command. This scalar function is always
6122** called with four arguments - the parent table name, the parent column name,
6123** the child table name and the child column name.
6124**
6125**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6126**
6127** If either of the named tables or columns do not exist, this function
6128** returns an empty string. An empty string is also returned if both tables
6129** and columns exist but have the same default collation sequence. Or,
6130** if both exist but the default collation sequences are different, this
6131** function returns the string " COLLATE <parent-collation>", where
6132** <parent-collation> is the default collation sequence of the parent column.
6133*/
6134static void shellFkeyCollateClause(
6135  sqlite3_context *pCtx,
6136  int nVal,
6137  sqlite3_value **apVal
6138){
6139  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6140  const char *zParent;
6141  const char *zParentCol;
6142  const char *zParentSeq;
6143  const char *zChild;
6144  const char *zChildCol;
6145  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6146  int rc;
6147
6148  assert( nVal==4 );
6149  zParent = (const char*)sqlite3_value_text(apVal[0]);
6150  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6151  zChild = (const char*)sqlite3_value_text(apVal[2]);
6152  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6153
6154  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6155  rc = sqlite3_table_column_metadata(
6156      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6157  );
6158  if( rc==SQLITE_OK ){
6159    rc = sqlite3_table_column_metadata(
6160        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6161    );
6162  }
6163
6164  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6165    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6166    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6167    sqlite3_free(z);
6168  }
6169}
6170
6171
6172/*
6173** The implementation of dot-command ".lint fkey-indexes".
6174*/
6175static int lintFkeyIndexes(
6176  ShellState *pState,             /* Current shell tool state */
6177  char **azArg,                   /* Array of arguments passed to dot command */
6178  int nArg                        /* Number of entries in azArg[] */
6179){
6180  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6181  FILE *out = pState->out;        /* Stream to write non-error output to */
6182  int bVerbose = 0;               /* If -verbose is present */
6183  int bGroupByParent = 0;         /* If -groupbyparent is present */
6184  int i;                          /* To iterate through azArg[] */
6185  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6186  int rc;                         /* Return code */
6187  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6188
6189  /*
6190  ** This SELECT statement returns one row for each foreign key constraint
6191  ** in the schema of the main database. The column values are:
6192  **
6193  ** 0. The text of an SQL statement similar to:
6194  **
6195  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6196  **
6197  **    This SELECT is similar to the one that the foreign keys implementation
6198  **    needs to run internally on child tables. If there is an index that can
6199  **    be used to optimize this query, then it can also be used by the FK
6200  **    implementation to optimize DELETE or UPDATE statements on the parent
6201  **    table.
6202  **
6203  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6204  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6205  **    contains an index that can be used to optimize the query.
6206  **
6207  ** 2. Human readable text that describes the child table and columns. e.g.
6208  **
6209  **       "child_table(child_key1, child_key2)"
6210  **
6211  ** 3. Human readable text that describes the parent table and columns. e.g.
6212  **
6213  **       "parent_table(parent_key1, parent_key2)"
6214  **
6215  ** 4. A full CREATE INDEX statement for an index that could be used to
6216  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6217  **
6218  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6219  **
6220  ** 5. The name of the parent table.
6221  **
6222  ** These six values are used by the C logic below to generate the report.
6223  */
6224  const char *zSql =
6225  "SELECT "
6226    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6227    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6228    "  || fkey_collate_clause("
6229    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6230    ", "
6231    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6232    "  || group_concat('*=?', ' AND ') || ')'"
6233    ", "
6234    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6235    ", "
6236    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6237    ", "
6238    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6239    "  || ' ON ' || quote(s.name) || '('"
6240    "  || group_concat(quote(f.[from]) ||"
6241    "        fkey_collate_clause("
6242    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6243    "  || ');'"
6244    ", "
6245    "     f.[table] "
6246    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6247    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6248    "GROUP BY s.name, f.id "
6249    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6250  ;
6251  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6252
6253  for(i=2; i<nArg; i++){
6254    int n = strlen30(azArg[i]);
6255    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6256      bVerbose = 1;
6257    }
6258    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6259      bGroupByParent = 1;
6260      zIndent = "    ";
6261    }
6262    else{
6263      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6264          azArg[0], azArg[1]
6265      );
6266      return SQLITE_ERROR;
6267    }
6268  }
6269
6270  /* Register the fkey_collate_clause() SQL function */
6271  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6272      0, shellFkeyCollateClause, 0, 0
6273  );
6274
6275
6276  if( rc==SQLITE_OK ){
6277    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6278  }
6279  if( rc==SQLITE_OK ){
6280    sqlite3_bind_int(pSql, 1, bGroupByParent);
6281  }
6282
6283  if( rc==SQLITE_OK ){
6284    int rc2;
6285    char *zPrev = 0;
6286    while( SQLITE_ROW==sqlite3_step(pSql) ){
6287      int res = -1;
6288      sqlite3_stmt *pExplain = 0;
6289      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6290      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6291      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6292      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6293      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6294      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6295
6296      if( zEQP==0 ) continue;
6297      if( zGlob==0 ) continue;
6298      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6299      if( rc!=SQLITE_OK ) break;
6300      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6301        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6302        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6303                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6304      }
6305      rc = sqlite3_finalize(pExplain);
6306      if( rc!=SQLITE_OK ) break;
6307
6308      if( res<0 ){
6309        raw_printf(stderr, "Error: internal error");
6310        break;
6311      }else{
6312        if( bGroupByParent
6313        && (bVerbose || res==0)
6314        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6315        ){
6316          raw_printf(out, "-- Parent table %s\n", zParent);
6317          sqlite3_free(zPrev);
6318          zPrev = sqlite3_mprintf("%s", zParent);
6319        }
6320
6321        if( res==0 ){
6322          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6323        }else if( bVerbose ){
6324          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6325              zIndent, zFrom, zTarget
6326          );
6327        }
6328      }
6329    }
6330    sqlite3_free(zPrev);
6331
6332    if( rc!=SQLITE_OK ){
6333      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6334    }
6335
6336    rc2 = sqlite3_finalize(pSql);
6337    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6338      rc = rc2;
6339      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6340    }
6341  }else{
6342    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6343  }
6344
6345  return rc;
6346}
6347
6348/*
6349** Implementation of ".lint" dot command.
6350*/
6351static int lintDotCommand(
6352  ShellState *pState,             /* Current shell tool state */
6353  char **azArg,                   /* Array of arguments passed to dot command */
6354  int nArg                        /* Number of entries in azArg[] */
6355){
6356  int n;
6357  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6358  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6359  return lintFkeyIndexes(pState, azArg, nArg);
6360
6361 usage:
6362  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6363  raw_printf(stderr, "Where sub-commands are:\n");
6364  raw_printf(stderr, "    fkey-indexes\n");
6365  return SQLITE_ERROR;
6366}
6367
6368#if !defined SQLITE_OMIT_VIRTUALTABLE
6369static void shellPrepare(
6370  sqlite3 *db,
6371  int *pRc,
6372  const char *zSql,
6373  sqlite3_stmt **ppStmt
6374){
6375  *ppStmt = 0;
6376  if( *pRc==SQLITE_OK ){
6377    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6378    if( rc!=SQLITE_OK ){
6379      raw_printf(stderr, "sql error: %s (%d)\n",
6380          sqlite3_errmsg(db), sqlite3_errcode(db)
6381      );
6382      *pRc = rc;
6383    }
6384  }
6385}
6386
6387/*
6388** Create a prepared statement using printf-style arguments for the SQL.
6389**
6390** This routine is could be marked "static".  But it is not always used,
6391** depending on compile-time options.  By omitting the "static", we avoid
6392** nuisance compiler warnings about "defined but not used".
6393*/
6394void shellPreparePrintf(
6395  sqlite3 *db,
6396  int *pRc,
6397  sqlite3_stmt **ppStmt,
6398  const char *zFmt,
6399  ...
6400){
6401  *ppStmt = 0;
6402  if( *pRc==SQLITE_OK ){
6403    va_list ap;
6404    char *z;
6405    va_start(ap, zFmt);
6406    z = sqlite3_vmprintf(zFmt, ap);
6407    va_end(ap);
6408    if( z==0 ){
6409      *pRc = SQLITE_NOMEM;
6410    }else{
6411      shellPrepare(db, pRc, z, ppStmt);
6412      sqlite3_free(z);
6413    }
6414  }
6415}
6416
6417/* Finalize the prepared statement created using shellPreparePrintf().
6418**
6419** This routine is could be marked "static".  But it is not always used,
6420** depending on compile-time options.  By omitting the "static", we avoid
6421** nuisance compiler warnings about "defined but not used".
6422*/
6423void shellFinalize(
6424  int *pRc,
6425  sqlite3_stmt *pStmt
6426){
6427  if( pStmt ){
6428    sqlite3 *db = sqlite3_db_handle(pStmt);
6429    int rc = sqlite3_finalize(pStmt);
6430    if( *pRc==SQLITE_OK ){
6431      if( rc!=SQLITE_OK ){
6432        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6433      }
6434      *pRc = rc;
6435    }
6436  }
6437}
6438
6439/* Reset the prepared statement created using shellPreparePrintf().
6440**
6441** This routine is could be marked "static".  But it is not always used,
6442** depending on compile-time options.  By omitting the "static", we avoid
6443** nuisance compiler warnings about "defined but not used".
6444*/
6445void shellReset(
6446  int *pRc,
6447  sqlite3_stmt *pStmt
6448){
6449  int rc = sqlite3_reset(pStmt);
6450  if( *pRc==SQLITE_OK ){
6451    if( rc!=SQLITE_OK ){
6452      sqlite3 *db = sqlite3_db_handle(pStmt);
6453      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6454    }
6455    *pRc = rc;
6456  }
6457}
6458#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6459
6460#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6461/******************************************************************************
6462** The ".archive" or ".ar" command.
6463*/
6464/*
6465** Structure representing a single ".ar" command.
6466*/
6467typedef struct ArCommand ArCommand;
6468struct ArCommand {
6469  u8 eCmd;                        /* An AR_CMD_* value */
6470  u8 bVerbose;                    /* True if --verbose */
6471  u8 bZip;                        /* True if the archive is a ZIP */
6472  u8 bDryRun;                     /* True if --dry-run */
6473  u8 bAppend;                     /* True if --append */
6474  u8 bGlob;                       /* True if --glob */
6475  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6476  int nArg;                       /* Number of command arguments */
6477  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6478  const char *zFile;              /* --file argument, or NULL */
6479  const char *zDir;               /* --directory argument, or NULL */
6480  char **azArg;                   /* Array of command arguments */
6481  ShellState *p;                  /* Shell state */
6482  sqlite3 *db;                    /* Database containing the archive */
6483};
6484
6485/*
6486** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6487*/
6488static int arUsage(FILE *f){
6489  showHelp(f,"archive");
6490  return SQLITE_ERROR;
6491}
6492
6493/*
6494** Print an error message for the .ar command to stderr and return
6495** SQLITE_ERROR.
6496*/
6497static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6498  va_list ap;
6499  char *z;
6500  va_start(ap, zFmt);
6501  z = sqlite3_vmprintf(zFmt, ap);
6502  va_end(ap);
6503  utf8_printf(stderr, "Error: %s\n", z);
6504  if( pAr->fromCmdLine ){
6505    utf8_printf(stderr, "Use \"-A\" for more help\n");
6506  }else{
6507    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6508  }
6509  sqlite3_free(z);
6510  return SQLITE_ERROR;
6511}
6512
6513/*
6514** Values for ArCommand.eCmd.
6515*/
6516#define AR_CMD_CREATE       1
6517#define AR_CMD_UPDATE       2
6518#define AR_CMD_INSERT       3
6519#define AR_CMD_EXTRACT      4
6520#define AR_CMD_LIST         5
6521#define AR_CMD_HELP         6
6522#define AR_CMD_REMOVE       7
6523
6524/*
6525** Other (non-command) switches.
6526*/
6527#define AR_SWITCH_VERBOSE     8
6528#define AR_SWITCH_FILE        9
6529#define AR_SWITCH_DIRECTORY  10
6530#define AR_SWITCH_APPEND     11
6531#define AR_SWITCH_DRYRUN     12
6532#define AR_SWITCH_GLOB       13
6533
6534static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6535  switch( eSwitch ){
6536    case AR_CMD_CREATE:
6537    case AR_CMD_EXTRACT:
6538    case AR_CMD_LIST:
6539    case AR_CMD_REMOVE:
6540    case AR_CMD_UPDATE:
6541    case AR_CMD_INSERT:
6542    case AR_CMD_HELP:
6543      if( pAr->eCmd ){
6544        return arErrorMsg(pAr, "multiple command options");
6545      }
6546      pAr->eCmd = eSwitch;
6547      break;
6548
6549    case AR_SWITCH_DRYRUN:
6550      pAr->bDryRun = 1;
6551      break;
6552    case AR_SWITCH_GLOB:
6553      pAr->bGlob = 1;
6554      break;
6555    case AR_SWITCH_VERBOSE:
6556      pAr->bVerbose = 1;
6557      break;
6558    case AR_SWITCH_APPEND:
6559      pAr->bAppend = 1;
6560      /* Fall thru into --file */
6561    case AR_SWITCH_FILE:
6562      pAr->zFile = zArg;
6563      break;
6564    case AR_SWITCH_DIRECTORY:
6565      pAr->zDir = zArg;
6566      break;
6567  }
6568
6569  return SQLITE_OK;
6570}
6571
6572/*
6573** Parse the command line for an ".ar" command. The results are written into
6574** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6575** successfully, otherwise an error message is written to stderr and
6576** SQLITE_ERROR returned.
6577*/
6578static int arParseCommand(
6579  char **azArg,                   /* Array of arguments passed to dot command */
6580  int nArg,                       /* Number of entries in azArg[] */
6581  ArCommand *pAr                  /* Populate this object */
6582){
6583  struct ArSwitch {
6584    const char *zLong;
6585    char cShort;
6586    u8 eSwitch;
6587    u8 bArg;
6588  } aSwitch[] = {
6589    { "create",    'c', AR_CMD_CREATE,       0 },
6590    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6591    { "insert",    'i', AR_CMD_INSERT,       0 },
6592    { "list",      't', AR_CMD_LIST,         0 },
6593    { "remove",    'r', AR_CMD_REMOVE,       0 },
6594    { "update",    'u', AR_CMD_UPDATE,       0 },
6595    { "help",      'h', AR_CMD_HELP,         0 },
6596    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6597    { "file",      'f', AR_SWITCH_FILE,      1 },
6598    { "append",    'a', AR_SWITCH_APPEND,    1 },
6599    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6600    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6601    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6602  };
6603  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6604  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6605
6606  if( nArg<=1 ){
6607    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6608    return arUsage(stderr);
6609  }else{
6610    char *z = azArg[1];
6611    if( z[0]!='-' ){
6612      /* Traditional style [tar] invocation */
6613      int i;
6614      int iArg = 2;
6615      for(i=0; z[i]; i++){
6616        const char *zArg = 0;
6617        struct ArSwitch *pOpt;
6618        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6619          if( z[i]==pOpt->cShort ) break;
6620        }
6621        if( pOpt==pEnd ){
6622          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6623        }
6624        if( pOpt->bArg ){
6625          if( iArg>=nArg ){
6626            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6627          }
6628          zArg = azArg[iArg++];
6629        }
6630        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6631      }
6632      pAr->nArg = nArg-iArg;
6633      if( pAr->nArg>0 ){
6634        pAr->azArg = &azArg[iArg];
6635      }
6636    }else{
6637      /* Non-traditional invocation */
6638      int iArg;
6639      for(iArg=1; iArg<nArg; iArg++){
6640        int n;
6641        z = azArg[iArg];
6642        if( z[0]!='-' ){
6643          /* All remaining command line words are command arguments. */
6644          pAr->azArg = &azArg[iArg];
6645          pAr->nArg = nArg-iArg;
6646          break;
6647        }
6648        n = strlen30(z);
6649
6650        if( z[1]!='-' ){
6651          int i;
6652          /* One or more short options */
6653          for(i=1; i<n; i++){
6654            const char *zArg = 0;
6655            struct ArSwitch *pOpt;
6656            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6657              if( z[i]==pOpt->cShort ) break;
6658            }
6659            if( pOpt==pEnd ){
6660              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6661            }
6662            if( pOpt->bArg ){
6663              if( i<(n-1) ){
6664                zArg = &z[i+1];
6665                i = n;
6666              }else{
6667                if( iArg>=(nArg-1) ){
6668                  return arErrorMsg(pAr, "option requires an argument: %c",
6669                                    z[i]);
6670                }
6671                zArg = azArg[++iArg];
6672              }
6673            }
6674            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6675          }
6676        }else if( z[2]=='\0' ){
6677          /* A -- option, indicating that all remaining command line words
6678          ** are command arguments.  */
6679          pAr->azArg = &azArg[iArg+1];
6680          pAr->nArg = nArg-iArg-1;
6681          break;
6682        }else{
6683          /* A long option */
6684          const char *zArg = 0;             /* Argument for option, if any */
6685          struct ArSwitch *pMatch = 0;      /* Matching option */
6686          struct ArSwitch *pOpt;            /* Iterator */
6687          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6688            const char *zLong = pOpt->zLong;
6689            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6690              if( pMatch ){
6691                return arErrorMsg(pAr, "ambiguous option: %s",z);
6692              }else{
6693                pMatch = pOpt;
6694              }
6695            }
6696          }
6697
6698          if( pMatch==0 ){
6699            return arErrorMsg(pAr, "unrecognized option: %s", z);
6700          }
6701          if( pMatch->bArg ){
6702            if( iArg>=(nArg-1) ){
6703              return arErrorMsg(pAr, "option requires an argument: %s", z);
6704            }
6705            zArg = azArg[++iArg];
6706          }
6707          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6708        }
6709      }
6710    }
6711  }
6712
6713  return SQLITE_OK;
6714}
6715
6716/*
6717** This function assumes that all arguments within the ArCommand.azArg[]
6718** array refer to archive members, as for the --extract, --list or --remove
6719** commands. It checks that each of them are "present". If any specified
6720** file is not present in the archive, an error is printed to stderr and an
6721** error code returned. Otherwise, if all specified arguments are present
6722** in the archive, SQLITE_OK is returned. Here, "present" means either an
6723** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6724** when pAr->bGlob is true.
6725**
6726** This function strips any trailing '/' characters from each argument.
6727** This is consistent with the way the [tar] command seems to work on
6728** Linux.
6729*/
6730static int arCheckEntries(ArCommand *pAr){
6731  int rc = SQLITE_OK;
6732  if( pAr->nArg ){
6733    int i, j;
6734    sqlite3_stmt *pTest = 0;
6735    const char *zSel = (pAr->bGlob)
6736      ? "SELECT name FROM %s WHERE glob($name,name)"
6737      : "SELECT name FROM %s WHERE name=$name";
6738
6739    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6740    j = sqlite3_bind_parameter_index(pTest, "$name");
6741    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6742      char *z = pAr->azArg[i];
6743      int n = strlen30(z);
6744      int bOk = 0;
6745      while( n>0 && z[n-1]=='/' ) n--;
6746      z[n] = '\0';
6747      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6748      if( SQLITE_ROW==sqlite3_step(pTest) ){
6749        bOk = 1;
6750      }
6751      shellReset(&rc, pTest);
6752      if( rc==SQLITE_OK && bOk==0 ){
6753        utf8_printf(stderr, "not found in archive: %s\n", z);
6754        rc = SQLITE_ERROR;
6755      }
6756    }
6757    shellFinalize(&rc, pTest);
6758  }
6759  return rc;
6760}
6761
6762/*
6763** Format a WHERE clause that can be used against the "sqlar" table to
6764** identify all archive members that match the command arguments held
6765** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6766** The caller is responsible for eventually calling sqlite3_free() on
6767** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6768** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6769*/
6770static void arWhereClause(
6771  int *pRc,
6772  ArCommand *pAr,
6773  char **pzWhere                  /* OUT: New WHERE clause */
6774){
6775  char *zWhere = 0;
6776  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6777  if( *pRc==SQLITE_OK ){
6778    if( pAr->nArg==0 ){
6779      zWhere = sqlite3_mprintf("1");
6780    }else{
6781      int i;
6782      const char *zSep = "";
6783      for(i=0; i<pAr->nArg; i++){
6784        const char *z = pAr->azArg[i];
6785        zWhere = sqlite3_mprintf(
6786          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6787          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6788        );
6789        if( zWhere==0 ){
6790          *pRc = SQLITE_NOMEM;
6791          break;
6792        }
6793        zSep = " OR ";
6794      }
6795    }
6796  }
6797  *pzWhere = zWhere;
6798}
6799
6800/*
6801** Implementation of .ar "lisT" command.
6802*/
6803static int arListCommand(ArCommand *pAr){
6804  const char *zSql = "SELECT %s FROM %s WHERE %s";
6805  const char *azCols[] = {
6806    "name",
6807    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6808  };
6809
6810  char *zWhere = 0;
6811  sqlite3_stmt *pSql = 0;
6812  int rc;
6813
6814  rc = arCheckEntries(pAr);
6815  arWhereClause(&rc, pAr, &zWhere);
6816
6817  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6818                     pAr->zSrcTable, zWhere);
6819  if( pAr->bDryRun ){
6820    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6821  }else{
6822    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6823      if( pAr->bVerbose ){
6824        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6825            sqlite3_column_text(pSql, 0),
6826            sqlite3_column_int(pSql, 1),
6827            sqlite3_column_text(pSql, 2),
6828            sqlite3_column_text(pSql, 3)
6829        );
6830      }else{
6831        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6832      }
6833    }
6834  }
6835  shellFinalize(&rc, pSql);
6836  sqlite3_free(zWhere);
6837  return rc;
6838}
6839
6840
6841/*
6842** Implementation of .ar "Remove" command.
6843*/
6844static int arRemoveCommand(ArCommand *pAr){
6845  int rc = 0;
6846  char *zSql = 0;
6847  char *zWhere = 0;
6848
6849  if( pAr->nArg ){
6850    /* Verify that args actually exist within the archive before proceeding.
6851    ** And formulate a WHERE clause to match them.  */
6852    rc = arCheckEntries(pAr);
6853    arWhereClause(&rc, pAr, &zWhere);
6854  }
6855  if( rc==SQLITE_OK ){
6856    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6857                           pAr->zSrcTable, zWhere);
6858    if( pAr->bDryRun ){
6859      utf8_printf(pAr->p->out, "%s\n", zSql);
6860    }else{
6861      char *zErr = 0;
6862      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6863      if( rc==SQLITE_OK ){
6864        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6865        if( rc!=SQLITE_OK ){
6866          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6867        }else{
6868          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6869        }
6870      }
6871      if( zErr ){
6872        utf8_printf(stdout, "ERROR: %s\n", zErr);
6873        sqlite3_free(zErr);
6874      }
6875    }
6876  }
6877  sqlite3_free(zWhere);
6878  sqlite3_free(zSql);
6879  return rc;
6880}
6881
6882/*
6883** Implementation of .ar "eXtract" command.
6884*/
6885static int arExtractCommand(ArCommand *pAr){
6886  const char *zSql1 =
6887    "SELECT "
6888    " ($dir || name),"
6889    " writefile(($dir || name), %s, mode, mtime) "
6890    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6891    " AND name NOT GLOB '*..[/\\]*'";
6892
6893  const char *azExtraArg[] = {
6894    "sqlar_uncompress(data, sz)",
6895    "data"
6896  };
6897
6898  sqlite3_stmt *pSql = 0;
6899  int rc = SQLITE_OK;
6900  char *zDir = 0;
6901  char *zWhere = 0;
6902  int i, j;
6903
6904  /* If arguments are specified, check that they actually exist within
6905  ** the archive before proceeding. And formulate a WHERE clause to
6906  ** match them.  */
6907  rc = arCheckEntries(pAr);
6908  arWhereClause(&rc, pAr, &zWhere);
6909
6910  if( rc==SQLITE_OK ){
6911    if( pAr->zDir ){
6912      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6913    }else{
6914      zDir = sqlite3_mprintf("");
6915    }
6916    if( zDir==0 ) rc = SQLITE_NOMEM;
6917  }
6918
6919  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6920      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6921  );
6922
6923  if( rc==SQLITE_OK ){
6924    j = sqlite3_bind_parameter_index(pSql, "$dir");
6925    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6926
6927    /* Run the SELECT statement twice. The first time, writefile() is called
6928    ** for all archive members that should be extracted. The second time,
6929    ** only for the directories. This is because the timestamps for
6930    ** extracted directories must be reset after they are populated (as
6931    ** populating them changes the timestamp).  */
6932    for(i=0; i<2; i++){
6933      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6934      sqlite3_bind_int(pSql, j, i);
6935      if( pAr->bDryRun ){
6936        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6937      }else{
6938        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6939          if( i==0 && pAr->bVerbose ){
6940            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6941          }
6942        }
6943      }
6944      shellReset(&rc, pSql);
6945    }
6946    shellFinalize(&rc, pSql);
6947  }
6948
6949  sqlite3_free(zDir);
6950  sqlite3_free(zWhere);
6951  return rc;
6952}
6953
6954/*
6955** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6956*/
6957static int arExecSql(ArCommand *pAr, const char *zSql){
6958  int rc;
6959  if( pAr->bDryRun ){
6960    utf8_printf(pAr->p->out, "%s\n", zSql);
6961    rc = SQLITE_OK;
6962  }else{
6963    char *zErr = 0;
6964    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6965    if( zErr ){
6966      utf8_printf(stdout, "ERROR: %s\n", zErr);
6967      sqlite3_free(zErr);
6968    }
6969  }
6970  return rc;
6971}
6972
6973
6974/*
6975** Implementation of .ar "create", "insert", and "update" commands.
6976**
6977**     create    ->     Create a new SQL archive
6978**     insert    ->     Insert or reinsert all files listed
6979**     update    ->     Insert files that have changed or that were not
6980**                      previously in the archive
6981**
6982** Create the "sqlar" table in the database if it does not already exist.
6983** Then add each file in the azFile[] array to the archive. Directories
6984** are added recursively. If argument bVerbose is non-zero, a message is
6985** printed on stdout for each file archived.
6986**
6987** The create command is the same as update, except that it drops
6988** any existing "sqlar" table before beginning.  The "insert" command
6989** always overwrites every file named on the command-line, where as
6990** "update" only overwrites if the size or mtime or mode has changed.
6991*/
6992static int arCreateOrUpdateCommand(
6993  ArCommand *pAr,                 /* Command arguments and options */
6994  int bUpdate,                    /* true for a --create. */
6995  int bOnlyIfChanged              /* Only update if file has changed */
6996){
6997  const char *zCreate =
6998      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6999      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7000      "  mode INT,               -- access permissions\n"
7001      "  mtime INT,              -- last modification time\n"
7002      "  sz INT,                 -- original file size\n"
7003      "  data BLOB               -- compressed content\n"
7004      ")";
7005  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7006  const char *zInsertFmt[2] = {
7007     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7008     "  SELECT\n"
7009     "    %s,\n"
7010     "    mode,\n"
7011     "    mtime,\n"
7012     "    CASE substr(lsmode(mode),1,1)\n"
7013     "      WHEN '-' THEN length(data)\n"
7014     "      WHEN 'd' THEN 0\n"
7015     "      ELSE -1 END,\n"
7016     "    sqlar_compress(data)\n"
7017     "  FROM fsdir(%Q,%Q) AS disk\n"
7018     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7019     ,
7020     "REPLACE INTO %s(name,mode,mtime,data)\n"
7021     "  SELECT\n"
7022     "    %s,\n"
7023     "    mode,\n"
7024     "    mtime,\n"
7025     "    data\n"
7026     "  FROM fsdir(%Q,%Q) AS disk\n"
7027     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7028  };
7029  int i;                          /* For iterating through azFile[] */
7030  int rc;                         /* Return code */
7031  const char *zTab = 0;           /* SQL table into which to insert */
7032  char *zSql;
7033  char zTemp[50];
7034  char *zExists = 0;
7035
7036  arExecSql(pAr, "PRAGMA page_size=512");
7037  rc = arExecSql(pAr, "SAVEPOINT ar;");
7038  if( rc!=SQLITE_OK ) return rc;
7039  zTemp[0] = 0;
7040  if( pAr->bZip ){
7041    /* Initialize the zipfile virtual table, if necessary */
7042    if( pAr->zFile ){
7043      sqlite3_uint64 r;
7044      sqlite3_randomness(sizeof(r),&r);
7045      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7046      zTab = zTemp;
7047      zSql = sqlite3_mprintf(
7048         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7049         zTab, pAr->zFile
7050      );
7051      rc = arExecSql(pAr, zSql);
7052      sqlite3_free(zSql);
7053    }else{
7054      zTab = "zip";
7055    }
7056  }else{
7057    /* Initialize the table for an SQLAR */
7058    zTab = "sqlar";
7059    if( bUpdate==0 ){
7060      rc = arExecSql(pAr, zDrop);
7061      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7062    }
7063    rc = arExecSql(pAr, zCreate);
7064  }
7065  if( bOnlyIfChanged ){
7066    zExists = sqlite3_mprintf(
7067      " AND NOT EXISTS("
7068          "SELECT 1 FROM %s AS mem"
7069          " WHERE mem.name=disk.name"
7070          " AND mem.mtime=disk.mtime"
7071          " AND mem.mode=disk.mode)", zTab);
7072  }else{
7073    zExists = sqlite3_mprintf("");
7074  }
7075  if( zExists==0 ) rc = SQLITE_NOMEM;
7076  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7077    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7078        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7079        pAr->azArg[i], pAr->zDir, zExists);
7080    rc = arExecSql(pAr, zSql2);
7081    sqlite3_free(zSql2);
7082  }
7083end_ar_transaction:
7084  if( rc!=SQLITE_OK ){
7085    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7086  }else{
7087    rc = arExecSql(pAr, "RELEASE ar;");
7088    if( pAr->bZip && pAr->zFile ){
7089      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7090      arExecSql(pAr, zSql);
7091      sqlite3_free(zSql);
7092    }
7093  }
7094  sqlite3_free(zExists);
7095  return rc;
7096}
7097
7098/*
7099** Implementation of ".ar" dot command.
7100*/
7101static int arDotCommand(
7102  ShellState *pState,          /* Current shell tool state */
7103  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7104  char **azArg,                /* Array of arguments passed to dot command */
7105  int nArg                     /* Number of entries in azArg[] */
7106){
7107  ArCommand cmd;
7108  int rc;
7109  memset(&cmd, 0, sizeof(cmd));
7110  cmd.fromCmdLine = fromCmdLine;
7111  rc = arParseCommand(azArg, nArg, &cmd);
7112  if( rc==SQLITE_OK ){
7113    int eDbType = SHELL_OPEN_UNSPEC;
7114    cmd.p = pState;
7115    cmd.db = pState->db;
7116    if( cmd.zFile ){
7117      eDbType = deduceDatabaseType(cmd.zFile, 1);
7118    }else{
7119      eDbType = pState->openMode;
7120    }
7121    if( eDbType==SHELL_OPEN_ZIPFILE ){
7122      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7123        if( cmd.zFile==0 ){
7124          cmd.zSrcTable = sqlite3_mprintf("zip");
7125        }else{
7126          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7127        }
7128      }
7129      cmd.bZip = 1;
7130    }else if( cmd.zFile ){
7131      int flags;
7132      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7133      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7134           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7135        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7136      }else{
7137        flags = SQLITE_OPEN_READONLY;
7138      }
7139      cmd.db = 0;
7140      if( cmd.bDryRun ){
7141        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7142             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7143      }
7144      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7145             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7146      if( rc!=SQLITE_OK ){
7147        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7148            cmd.zFile, sqlite3_errmsg(cmd.db)
7149        );
7150        goto end_ar_command;
7151      }
7152      sqlite3_fileio_init(cmd.db, 0, 0);
7153      sqlite3_sqlar_init(cmd.db, 0, 0);
7154      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7155                              shellPutsFunc, 0, 0);
7156
7157    }
7158    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7159      if( cmd.eCmd!=AR_CMD_CREATE
7160       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7161      ){
7162        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7163        rc = SQLITE_ERROR;
7164        goto end_ar_command;
7165      }
7166      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7167    }
7168
7169    switch( cmd.eCmd ){
7170      case AR_CMD_CREATE:
7171        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7172        break;
7173
7174      case AR_CMD_EXTRACT:
7175        rc = arExtractCommand(&cmd);
7176        break;
7177
7178      case AR_CMD_LIST:
7179        rc = arListCommand(&cmd);
7180        break;
7181
7182      case AR_CMD_HELP:
7183        arUsage(pState->out);
7184        break;
7185
7186      case AR_CMD_INSERT:
7187        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7188        break;
7189
7190      case AR_CMD_REMOVE:
7191        rc = arRemoveCommand(&cmd);
7192        break;
7193
7194      default:
7195        assert( cmd.eCmd==AR_CMD_UPDATE );
7196        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7197        break;
7198    }
7199  }
7200end_ar_command:
7201  if( cmd.db!=pState->db ){
7202    close_db(cmd.db);
7203  }
7204  sqlite3_free(cmd.zSrcTable);
7205
7206  return rc;
7207}
7208/* End of the ".archive" or ".ar" command logic
7209*******************************************************************************/
7210#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7211
7212#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7213/*
7214** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7215** Otherwise, the SQL statement or statements in zSql are executed using
7216** database connection db and the error code written to *pRc before
7217** this function returns.
7218*/
7219static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7220  int rc = *pRc;
7221  if( rc==SQLITE_OK ){
7222    char *zErr = 0;
7223    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7224    if( rc!=SQLITE_OK ){
7225      raw_printf(stderr, "SQL error: %s\n", zErr);
7226    }
7227    sqlite3_free(zErr);
7228    *pRc = rc;
7229  }
7230}
7231
7232/*
7233** Like shellExec(), except that zFmt is a printf() style format string.
7234*/
7235static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7236  char *z = 0;
7237  if( *pRc==SQLITE_OK ){
7238    va_list ap;
7239    va_start(ap, zFmt);
7240    z = sqlite3_vmprintf(zFmt, ap);
7241    va_end(ap);
7242    if( z==0 ){
7243      *pRc = SQLITE_NOMEM;
7244    }else{
7245      shellExec(db, pRc, z);
7246    }
7247    sqlite3_free(z);
7248  }
7249}
7250
7251/*
7252** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7253** Otherwise, an attempt is made to allocate, zero and return a pointer
7254** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7255** to SQLITE_NOMEM and NULL returned.
7256*/
7257static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7258  void *pRet = 0;
7259  if( *pRc==SQLITE_OK ){
7260    pRet = sqlite3_malloc64(nByte);
7261    if( pRet==0 ){
7262      *pRc = SQLITE_NOMEM;
7263    }else{
7264      memset(pRet, 0, nByte);
7265    }
7266  }
7267  return pRet;
7268}
7269
7270/*
7271** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7272** Otherwise, zFmt is treated as a printf() style string. The result of
7273** formatting it along with any trailing arguments is written into a
7274** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7275** It is the responsibility of the caller to eventually free this buffer
7276** using a call to sqlite3_free().
7277**
7278** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7279** pointer returned.
7280*/
7281static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7282  char *z = 0;
7283  if( *pRc==SQLITE_OK ){
7284    va_list ap;
7285    va_start(ap, zFmt);
7286    z = sqlite3_vmprintf(zFmt, ap);
7287    va_end(ap);
7288    if( z==0 ){
7289      *pRc = SQLITE_NOMEM;
7290    }
7291  }
7292  return z;
7293}
7294
7295
7296/*
7297** When running the ".recover" command, each output table, and the special
7298** orphaned row table if it is required, is represented by an instance
7299** of the following struct.
7300*/
7301typedef struct RecoverTable RecoverTable;
7302struct RecoverTable {
7303  char *zQuoted;                  /* Quoted version of table name */
7304  int nCol;                       /* Number of columns in table */
7305  char **azlCol;                  /* Array of column lists */
7306  int iPk;                        /* Index of IPK column */
7307};
7308
7309/*
7310** Free a RecoverTable object allocated by recoverFindTable() or
7311** recoverOrphanTable().
7312*/
7313static void recoverFreeTable(RecoverTable *pTab){
7314  if( pTab ){
7315    sqlite3_free(pTab->zQuoted);
7316    if( pTab->azlCol ){
7317      int i;
7318      for(i=0; i<=pTab->nCol; i++){
7319        sqlite3_free(pTab->azlCol[i]);
7320      }
7321      sqlite3_free(pTab->azlCol);
7322    }
7323    sqlite3_free(pTab);
7324  }
7325}
7326
7327/*
7328** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7329** Otherwise, it allocates and returns a RecoverTable object based on the
7330** final four arguments passed to this function. It is the responsibility
7331** of the caller to eventually free the returned object using
7332** recoverFreeTable().
7333*/
7334static RecoverTable *recoverNewTable(
7335  int *pRc,                       /* IN/OUT: Error code */
7336  const char *zName,              /* Name of table */
7337  const char *zSql,               /* CREATE TABLE statement */
7338  int bIntkey,
7339  int nCol
7340){
7341  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7342  int rc = *pRc;
7343  RecoverTable *pTab = 0;
7344
7345  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7346  if( rc==SQLITE_OK ){
7347    int nSqlCol = 0;
7348    int bSqlIntkey = 0;
7349    sqlite3_stmt *pStmt = 0;
7350
7351    rc = sqlite3_open("", &dbtmp);
7352    if( rc==SQLITE_OK ){
7353      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7354                              shellIdQuote, 0, 0);
7355    }
7356    if( rc==SQLITE_OK ){
7357      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7358    }
7359    if( rc==SQLITE_OK ){
7360      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7361      if( rc==SQLITE_ERROR ){
7362        rc = SQLITE_OK;
7363        goto finished;
7364      }
7365    }
7366    shellPreparePrintf(dbtmp, &rc, &pStmt,
7367        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7368    );
7369    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7370      nSqlCol = sqlite3_column_int(pStmt, 0);
7371    }
7372    shellFinalize(&rc, pStmt);
7373
7374    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7375      goto finished;
7376    }
7377
7378    shellPreparePrintf(dbtmp, &rc, &pStmt,
7379      "SELECT ("
7380      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7381      ") FROM sqlite_schema WHERE name = %Q", zName
7382    );
7383    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7384      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7385    }
7386    shellFinalize(&rc, pStmt);
7387
7388    if( bIntkey==bSqlIntkey ){
7389      int i;
7390      const char *zPk = "_rowid_";
7391      sqlite3_stmt *pPkFinder = 0;
7392
7393      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7394      ** set zPk to the name of the PK column, and pTab->iPk to the index
7395      ** of the column, where columns are 0-numbered from left to right.
7396      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7397      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7398      pTab->iPk = -2;
7399      if( bIntkey ){
7400        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7401          "SELECT cid, name FROM pragma_table_info(%Q) "
7402          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7403          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7404          , zName, zName
7405        );
7406        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7407          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7408          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7409          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7410        }
7411      }
7412
7413      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7414      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7415      pTab->nCol = nSqlCol;
7416
7417      if( bIntkey ){
7418        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7419      }else{
7420        pTab->azlCol[0] = shellMPrintf(&rc, "");
7421      }
7422      i = 1;
7423      shellPreparePrintf(dbtmp, &rc, &pStmt,
7424          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7425          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7426          "FROM pragma_table_info(%Q)",
7427          bIntkey ? ", " : "", pTab->iPk,
7428          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7429          zName
7430      );
7431      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7432        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7433        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7434        i++;
7435      }
7436      shellFinalize(&rc, pStmt);
7437
7438      shellFinalize(&rc, pPkFinder);
7439    }
7440  }
7441
7442 finished:
7443  sqlite3_close(dbtmp);
7444  *pRc = rc;
7445  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7446    recoverFreeTable(pTab);
7447    pTab = 0;
7448  }
7449  return pTab;
7450}
7451
7452/*
7453** This function is called to search the schema recovered from the
7454** sqlite_schema table of the (possibly) corrupt database as part
7455** of a ".recover" command. Specifically, for a table with root page
7456** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7457** table must be a WITHOUT ROWID table, or if non-zero, not one of
7458** those.
7459**
7460** If a table is found, a (RecoverTable*) object is returned. Or, if
7461** no such table is found, but bIntkey is false and iRoot is the
7462** root page of an index in the recovered schema, then (*pbNoop) is
7463** set to true and NULL returned. Or, if there is no such table or
7464** index, NULL is returned and (*pbNoop) set to 0, indicating that
7465** the caller should write data to the orphans table.
7466*/
7467static RecoverTable *recoverFindTable(
7468  ShellState *pState,             /* Shell state object */
7469  int *pRc,                       /* IN/OUT: Error code */
7470  int iRoot,                      /* Root page of table */
7471  int bIntkey,                    /* True for an intkey table */
7472  int nCol,                       /* Number of columns in table */
7473  int *pbNoop                     /* OUT: True if iRoot is root of index */
7474){
7475  sqlite3_stmt *pStmt = 0;
7476  RecoverTable *pRet = 0;
7477  int bNoop = 0;
7478  const char *zSql = 0;
7479  const char *zName = 0;
7480
7481  /* Search the recovered schema for an object with root page iRoot. */
7482  shellPreparePrintf(pState->db, pRc, &pStmt,
7483      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7484  );
7485  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7486    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7487    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7488      bNoop = 1;
7489      break;
7490    }
7491    if( sqlite3_stricmp(zType, "table")==0 ){
7492      zName = (const char*)sqlite3_column_text(pStmt, 1);
7493      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7494      if( zName!=0 && zSql!=0 ){
7495        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7496        break;
7497      }
7498    }
7499  }
7500
7501  shellFinalize(pRc, pStmt);
7502  *pbNoop = bNoop;
7503  return pRet;
7504}
7505
7506/*
7507** Return a RecoverTable object representing the orphans table.
7508*/
7509static RecoverTable *recoverOrphanTable(
7510  ShellState *pState,             /* Shell state object */
7511  int *pRc,                       /* IN/OUT: Error code */
7512  const char *zLostAndFound,      /* Base name for orphans table */
7513  int nCol                        /* Number of user data columns */
7514){
7515  RecoverTable *pTab = 0;
7516  if( nCol>=0 && *pRc==SQLITE_OK ){
7517    int i;
7518
7519    /* This block determines the name of the orphan table. The prefered
7520    ** name is zLostAndFound. But if that clashes with another name
7521    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7522    ** and so on until a non-clashing name is found.  */
7523    int iTab = 0;
7524    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7525    sqlite3_stmt *pTest = 0;
7526    shellPrepare(pState->db, pRc,
7527        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7528    );
7529    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7530    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7531      shellReset(pRc, pTest);
7532      sqlite3_free(zTab);
7533      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7534      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7535    }
7536    shellFinalize(pRc, pTest);
7537
7538    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7539    if( pTab ){
7540      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7541      pTab->nCol = nCol;
7542      pTab->iPk = -2;
7543      if( nCol>0 ){
7544        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7545        if( pTab->azlCol ){
7546          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7547          for(i=nCol-1; i>=0; i--){
7548            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7549          }
7550        }
7551      }
7552
7553      if( *pRc!=SQLITE_OK ){
7554        recoverFreeTable(pTab);
7555        pTab = 0;
7556      }else{
7557        raw_printf(pState->out,
7558            "CREATE TABLE %s(rootpgno INTEGER, "
7559            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7560        );
7561        for(i=0; i<nCol; i++){
7562          raw_printf(pState->out, ", c%d", i);
7563        }
7564        raw_printf(pState->out, ");\n");
7565      }
7566    }
7567    sqlite3_free(zTab);
7568  }
7569  return pTab;
7570}
7571
7572/*
7573** This function is called to recover data from the database. A script
7574** to construct a new database containing all recovered data is output
7575** on stream pState->out.
7576*/
7577static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7578  int rc = SQLITE_OK;
7579  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7580  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7581  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7582  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7583  const char *zLostAndFound = "lost_and_found";
7584  int i;
7585  int nOrphan = -1;
7586  RecoverTable *pOrphan = 0;
7587
7588  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7589  int bRowids = 1;                /* 0 if --no-rowids */
7590  for(i=1; i<nArg; i++){
7591    char *z = azArg[i];
7592    int n;
7593    if( z[0]=='-' && z[1]=='-' ) z++;
7594    n = strlen30(z);
7595    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7596      bFreelist = 0;
7597    }else
7598    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7599      i++;
7600      zRecoveryDb = azArg[i];
7601    }else
7602    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7603      i++;
7604      zLostAndFound = azArg[i];
7605    }else
7606    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7607      bRowids = 0;
7608    }
7609    else{
7610      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7611      showHelp(pState->out, azArg[0]);
7612      return 1;
7613    }
7614  }
7615
7616  shellExecPrintf(pState->db, &rc,
7617    /* Attach an in-memory database named 'recovery'. Create an indexed
7618    ** cache of the sqlite_dbptr virtual table. */
7619    "PRAGMA writable_schema = on;"
7620    "ATTACH %Q AS recovery;"
7621    "DROP TABLE IF EXISTS recovery.dbptr;"
7622    "DROP TABLE IF EXISTS recovery.freelist;"
7623    "DROP TABLE IF EXISTS recovery.map;"
7624    "DROP TABLE IF EXISTS recovery.schema;"
7625    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7626  );
7627
7628  if( bFreelist ){
7629    shellExec(pState->db, &rc,
7630      "WITH trunk(pgno) AS ("
7631      "  SELECT shell_int32("
7632      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7633      "      WHERE x>0"
7634      "    UNION"
7635      "  SELECT shell_int32("
7636      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7637      "      FROM trunk WHERE x>0"
7638      "),"
7639      "freelist(data, n, freepgno) AS ("
7640      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7641      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7642      "    UNION ALL"
7643      "  SELECT data, n-1, shell_int32(data, 2+n) "
7644      "      FROM freelist WHERE n>=0"
7645      ")"
7646      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7647    );
7648  }
7649
7650  /* If this is an auto-vacuum database, add all pointer-map pages to
7651  ** the freelist table. Do this regardless of whether or not
7652  ** --freelist-corrupt was specified.  */
7653  shellExec(pState->db, &rc,
7654    "WITH ptrmap(pgno) AS ("
7655    "  SELECT 2 WHERE shell_int32("
7656    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7657    "  )"
7658    "    UNION ALL "
7659    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7660    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7661    ")"
7662    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7663  );
7664
7665  shellExec(pState->db, &rc,
7666    "CREATE TABLE recovery.dbptr("
7667    "      pgno, child, PRIMARY KEY(child, pgno)"
7668    ") WITHOUT ROWID;"
7669    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7670    "    SELECT * FROM sqlite_dbptr"
7671    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7672
7673    /* Delete any pointer to page 1. This ensures that page 1 is considered
7674    ** a root page, regardless of how corrupt the db is. */
7675    "DELETE FROM recovery.dbptr WHERE child = 1;"
7676
7677    /* Delete all pointers to any pages that have more than one pointer
7678    ** to them. Such pages will be treated as root pages when recovering
7679    ** data.  */
7680    "DELETE FROM recovery.dbptr WHERE child IN ("
7681    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7682    ");"
7683
7684    /* Create the "map" table that will (eventually) contain instructions
7685    ** for dealing with each page in the db that contains one or more
7686    ** records. */
7687    "CREATE TABLE recovery.map("
7688      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7689    ");"
7690
7691    /* Populate table [map]. If there are circular loops of pages in the
7692    ** database, the following adds all pages in such a loop to the map
7693    ** as individual root pages. This could be handled better.  */
7694    "WITH pages(i, maxlen) AS ("
7695    "  SELECT page_count, ("
7696    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7697    "  ) FROM pragma_page_count WHERE page_count>0"
7698    "    UNION ALL"
7699    "  SELECT i-1, ("
7700    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7701    "  ) FROM pages WHERE i>=2"
7702    ")"
7703    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7704    "  SELECT i, maxlen, NULL, ("
7705    "    WITH p(orig, pgno, parent) AS ("
7706    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7707    "        UNION "
7708    "      SELECT i, p.parent, "
7709    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7710    "    )"
7711    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7712    ") "
7713    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7714    "UPDATE recovery.map AS o SET intkey = ("
7715    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7716    ");"
7717
7718    /* Extract data from page 1 and any linked pages into table
7719    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7720    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7721    "INSERT INTO recovery.schema SELECT "
7722    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7723    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7724    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7725    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7726    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7727    "FROM sqlite_dbdata WHERE pgno IN ("
7728    "  SELECT pgno FROM recovery.map WHERE root=1"
7729    ")"
7730    "GROUP BY pgno, cell;"
7731    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7732  );
7733
7734  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7735  ** CREATE TABLE statements that extracted from the existing schema.  */
7736  if( rc==SQLITE_OK ){
7737    sqlite3_stmt *pStmt = 0;
7738    /* ".recover" might output content in an order which causes immediate
7739    ** foreign key constraints to be violated. So disable foreign-key
7740    ** constraint enforcement to prevent problems when running the output
7741    ** script. */
7742    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7743    raw_printf(pState->out, "BEGIN;\n");
7744    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7745    shellPrepare(pState->db, &rc,
7746        "SELECT sql FROM recovery.schema "
7747        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7748    );
7749    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7750      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7751      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7752          &zCreateTable[12]
7753      );
7754    }
7755    shellFinalize(&rc, pStmt);
7756  }
7757
7758  /* Figure out if an orphan table will be required. And if so, how many
7759  ** user columns it should contain */
7760  shellPrepare(pState->db, &rc,
7761      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7762      , &pLoop
7763  );
7764  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7765    nOrphan = sqlite3_column_int(pLoop, 0);
7766  }
7767  shellFinalize(&rc, pLoop);
7768  pLoop = 0;
7769
7770  shellPrepare(pState->db, &rc,
7771      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7772  );
7773
7774  shellPrepare(pState->db, &rc,
7775      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7776      "(case when (? AND field<0) then NULL else value end)"
7777      "), ', ')"
7778      ", min(field) "
7779      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7780      "GROUP BY cell", &pCells
7781  );
7782
7783  /* Loop through each root page. */
7784  shellPrepare(pState->db, &rc,
7785      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7786      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7787      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7788      ")", &pLoop
7789  );
7790  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7791    int iRoot = sqlite3_column_int(pLoop, 0);
7792    int bIntkey = sqlite3_column_int(pLoop, 1);
7793    int nCol = sqlite3_column_int(pLoop, 2);
7794    int bNoop = 0;
7795    RecoverTable *pTab;
7796
7797    assert( bIntkey==0 || bIntkey==1 );
7798    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7799    if( bNoop || rc ) continue;
7800    if( pTab==0 ){
7801      if( pOrphan==0 ){
7802        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7803      }
7804      pTab = pOrphan;
7805      if( pTab==0 ) break;
7806    }
7807
7808    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7809      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7810    }
7811    sqlite3_bind_int(pPages, 1, iRoot);
7812    if( bRowids==0 && pTab->iPk<0 ){
7813      sqlite3_bind_int(pCells, 1, 1);
7814    }else{
7815      sqlite3_bind_int(pCells, 1, 0);
7816    }
7817    sqlite3_bind_int(pCells, 3, pTab->iPk);
7818
7819    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7820      int iPgno = sqlite3_column_int(pPages, 0);
7821      sqlite3_bind_int(pCells, 2, iPgno);
7822      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7823        int nField = sqlite3_column_int(pCells, 0);
7824        int iMin = sqlite3_column_int(pCells, 2);
7825        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7826
7827        RecoverTable *pTab2 = pTab;
7828        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7829          if( pOrphan==0 ){
7830            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7831          }
7832          pTab2 = pOrphan;
7833          if( pTab2==0 ) break;
7834        }
7835
7836        nField = nField+1;
7837        if( pTab2==pOrphan ){
7838          raw_printf(pState->out,
7839              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7840              pTab2->zQuoted, iRoot, iPgno, nField,
7841              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7842          );
7843        }else{
7844          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7845              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7846          );
7847        }
7848      }
7849      shellReset(&rc, pCells);
7850    }
7851    shellReset(&rc, pPages);
7852    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7853  }
7854  shellFinalize(&rc, pLoop);
7855  shellFinalize(&rc, pPages);
7856  shellFinalize(&rc, pCells);
7857  recoverFreeTable(pOrphan);
7858
7859  /* The rest of the schema */
7860  if( rc==SQLITE_OK ){
7861    sqlite3_stmt *pStmt = 0;
7862    shellPrepare(pState->db, &rc,
7863        "SELECT sql, name FROM recovery.schema "
7864        "WHERE sql NOT LIKE 'create table%'", &pStmt
7865    );
7866    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7867      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7868      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7869        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7870        char *zPrint = shellMPrintf(&rc,
7871          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7872          zName, zName, zSql
7873        );
7874        raw_printf(pState->out, "%s;\n", zPrint);
7875        sqlite3_free(zPrint);
7876      }else{
7877        raw_printf(pState->out, "%s;\n", zSql);
7878      }
7879    }
7880    shellFinalize(&rc, pStmt);
7881  }
7882
7883  if( rc==SQLITE_OK ){
7884    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7885    raw_printf(pState->out, "COMMIT;\n");
7886  }
7887  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7888  return rc;
7889}
7890#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7891
7892
7893/*
7894 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7895 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7896 *   close db and set it to 0, and return the columns spec, to later
7897 *   be sqlite3_free()'ed by the caller.
7898 * The return is 0 when either:
7899 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7900 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7901 * The 3rd argument, pRenamed, references an out parameter. If the
7902 * pointer is non-zero, its referent will be set to a summary of renames
7903 * done if renaming was necessary, or set to 0 if none was done. The out
7904 * string (if any) must be sqlite3_free()'ed by the caller.
7905 */
7906#ifdef SHELL_DEBUG
7907#define rc_err_oom_die(rc) \
7908  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7909  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7910    fprintf(stderr,"E:%d\n",rc), assert(0)
7911#else
7912static void rc_err_oom_die(int rc){
7913  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7914  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7915}
7916#endif
7917
7918#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7919static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7920#else  /* Otherwise, memory is faster/better for the transient DB. */
7921static const char *zCOL_DB = ":memory:";
7922#endif
7923
7924/* Define character (as C string) to separate generated column ordinal
7925 * from protected part of incoming column names. This defaults to "_"
7926 * so that incoming column identifiers that did not need not be quoted
7927 * remain usable without being quoted. It must be one character.
7928 */
7929#ifndef SHELL_AUTOCOLUMN_SEP
7930# define AUTOCOLUMN_SEP "_"
7931#else
7932# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7933#endif
7934
7935static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7936  /* Queries and D{D,M}L used here */
7937  static const char * const zTabMake = "\
7938CREATE TABLE ColNames(\
7939 cpos INTEGER PRIMARY KEY,\
7940 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7941CREATE VIEW RepeatedNames AS \
7942SELECT DISTINCT t.name FROM ColNames t \
7943WHERE t.name COLLATE NOCASE IN (\
7944 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7945);\
7946";
7947  static const char * const zTabFill = "\
7948INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7949 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7950";
7951  static const char * const zHasDupes = "\
7952SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7953 <count(name) FROM ColNames\
7954";
7955#ifdef SHELL_COLUMN_RENAME_CLEAN
7956  static const char * const zDedoctor = "\
7957UPDATE ColNames SET chop=iif(\
7958  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7959  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7960 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7961 0\
7962)\
7963";
7964#endif
7965  static const char * const zSetReps = "\
7966UPDATE ColNames AS t SET reps=\
7967(SELECT count(*) FROM ColNames d \
7968 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7969 COLLATE NOCASE\
7970)\
7971";
7972#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7973  static const char * const zColDigits = "\
7974SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7975";
7976#else
7977  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7978  static const char * const zColDigits = "\
7979SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7980 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7981 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7982";
7983#endif
7984  static const char * const zRenameRank =
7985#ifdef SHELL_COLUMN_RENAME_CLEAN
7986    "UPDATE ColNames AS t SET suff="
7987    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7988#else /* ...RENAME_MINIMAL_ONE_PASS */
7989"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7990"  SELECT 0 AS nlz"
7991"  UNION"
7992"  SELECT nlz+1 AS nlz FROM Lzn"
7993"  WHERE EXISTS("
7994"   SELECT 1"
7995"   FROM ColNames t, ColNames o"
7996"   WHERE"
7997"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7998"     printf('%s"AUTOCOLUMN_SEP"%s',"
7999"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8000"     t.name"
8001"    )"
8002"    ="
8003"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8004"     printf('%s"AUTOCOLUMN_SEP"%s',"
8005"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8006"     o.name"
8007"    )"
8008"    COLLATE NOCASE"
8009"    AND o.cpos<>t.cpos"
8010"   GROUP BY t.cpos"
8011"  )"
8012") UPDATE Colnames AS t SET"
8013" chop = 0," /* No chopping, never touch incoming names. */
8014" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8015"  printf('"AUTOCOLUMN_SEP"%s', substring("
8016"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8017"  ''"
8018" )"
8019#endif
8020    ;
8021  static const char * const zCollectVar = "\
8022SELECT\
8023 '('||x'0a'\
8024 || group_concat(\
8025  cname||' TEXT',\
8026  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8027 ||')' AS ColsSpec \
8028FROM (\
8029 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8030 FROM ColNames ORDER BY cpos\
8031)";
8032  static const char * const zRenamesDone =
8033    "SELECT group_concat("
8034    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8035    " ','||x'0a')"
8036    "FROM ColNames WHERE suff<>'' OR chop!=0"
8037    ;
8038  int rc;
8039  sqlite3_stmt *pStmt = 0;
8040  assert(pDb!=0);
8041  if( zColNew ){
8042    /* Add initial or additional column. Init db if necessary. */
8043    if( *pDb==0 ){
8044      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8045#ifdef SHELL_COLFIX_DB
8046      if(*zCOL_DB!=':')
8047        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8048                     "drop view if exists RepeatedNames;",0,0,0);
8049#endif
8050      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8051      rc_err_oom_die(rc);
8052    }
8053    assert(*pDb!=0);
8054    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8055    rc_err_oom_die(rc);
8056    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8057    rc_err_oom_die(rc);
8058    rc = sqlite3_step(pStmt);
8059    rc_err_oom_die(rc);
8060    sqlite3_finalize(pStmt);
8061    return 0;
8062  }else if( *pDb==0 ){
8063    return 0;
8064  }else{
8065    /* Formulate the columns spec, close the DB, zero *pDb. */
8066    char *zColsSpec = 0;
8067    int hasDupes = db_int(*pDb, zHasDupes);
8068    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8069    if( hasDupes ){
8070#ifdef SHELL_COLUMN_RENAME_CLEAN
8071      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8072      rc_err_oom_die(rc);
8073#endif
8074      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8075      rc_err_oom_die(rc);
8076      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8077      rc_err_oom_die(rc);
8078      sqlite3_bind_int(pStmt, 1, nDigits);
8079      rc = sqlite3_step(pStmt);
8080      sqlite3_finalize(pStmt);
8081      assert(rc==SQLITE_DONE);
8082    }
8083    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8084    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8085    rc_err_oom_die(rc);
8086    rc = sqlite3_step(pStmt);
8087    if( rc==SQLITE_ROW ){
8088      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8089    }else{
8090      zColsSpec = 0;
8091    }
8092    if( pzRenamed!=0 ){
8093      if( !hasDupes ) *pzRenamed = 0;
8094      else{
8095        sqlite3_finalize(pStmt);
8096        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8097            && SQLITE_ROW==sqlite3_step(pStmt) ){
8098          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8099        }else
8100          *pzRenamed = 0;
8101      }
8102    }
8103    sqlite3_finalize(pStmt);
8104    sqlite3_close(*pDb);
8105    *pDb = 0;
8106    return zColsSpec;
8107  }
8108}
8109
8110/*
8111** If an input line begins with "." then invoke this routine to
8112** process that line.
8113**
8114** Return 1 on error, 2 to exit, and 0 otherwise.
8115*/
8116static int do_meta_command(char *zLine, ShellState *p){
8117  int h = 1;
8118  int nArg = 0;
8119  int n, c;
8120  int rc = 0;
8121  char *azArg[52];
8122
8123#ifndef SQLITE_OMIT_VIRTUALTABLE
8124  if( p->expert.pExpert ){
8125    expertFinish(p, 1, 0);
8126  }
8127#endif
8128
8129  /* Parse the input line into tokens.
8130  */
8131  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8132    while( IsSpace(zLine[h]) ){ h++; }
8133    if( zLine[h]==0 ) break;
8134    if( zLine[h]=='\'' || zLine[h]=='"' ){
8135      int delim = zLine[h++];
8136      azArg[nArg++] = &zLine[h];
8137      while( zLine[h] && zLine[h]!=delim ){
8138        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8139        h++;
8140      }
8141      if( zLine[h]==delim ){
8142        zLine[h++] = 0;
8143      }
8144      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8145    }else{
8146      azArg[nArg++] = &zLine[h];
8147      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8148      if( zLine[h] ) zLine[h++] = 0;
8149      resolve_backslashes(azArg[nArg-1]);
8150    }
8151  }
8152  azArg[nArg] = 0;
8153
8154  /* Process the input line.
8155  */
8156  if( nArg==0 ) return 0; /* no tokens, no error */
8157  n = strlen30(azArg[0]);
8158  c = azArg[0][0];
8159  clearTempFile(p);
8160
8161#ifndef SQLITE_OMIT_AUTHORIZATION
8162  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8163    if( nArg!=2 ){
8164      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8165      rc = 1;
8166      goto meta_command_exit;
8167    }
8168    open_db(p, 0);
8169    if( booleanValue(azArg[1]) ){
8170      sqlite3_set_authorizer(p->db, shellAuth, p);
8171    }else if( p->bSafeModePersist ){
8172      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8173    }else{
8174      sqlite3_set_authorizer(p->db, 0, 0);
8175    }
8176  }else
8177#endif
8178
8179#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8180  && !defined(SQLITE_SHELL_WASM_MODE)
8181  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8182    open_db(p, 0);
8183    failIfSafeMode(p, "cannot run .archive in safe mode");
8184    rc = arDotCommand(p, 0, azArg, nArg);
8185  }else
8186#endif
8187
8188#ifndef SQLITE_SHELL_WASM_MODE
8189  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8190   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8191  ){
8192    const char *zDestFile = 0;
8193    const char *zDb = 0;
8194    sqlite3 *pDest;
8195    sqlite3_backup *pBackup;
8196    int j;
8197    int bAsync = 0;
8198    const char *zVfs = 0;
8199    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8200    for(j=1; j<nArg; j++){
8201      const char *z = azArg[j];
8202      if( z[0]=='-' ){
8203        if( z[1]=='-' ) z++;
8204        if( strcmp(z, "-append")==0 ){
8205          zVfs = "apndvfs";
8206        }else
8207        if( strcmp(z, "-async")==0 ){
8208          bAsync = 1;
8209        }else
8210        {
8211          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8212          return 1;
8213        }
8214      }else if( zDestFile==0 ){
8215        zDestFile = azArg[j];
8216      }else if( zDb==0 ){
8217        zDb = zDestFile;
8218        zDestFile = azArg[j];
8219      }else{
8220        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8221        return 1;
8222      }
8223    }
8224    if( zDestFile==0 ){
8225      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8226      return 1;
8227    }
8228    if( zDb==0 ) zDb = "main";
8229    rc = sqlite3_open_v2(zDestFile, &pDest,
8230                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8231    if( rc!=SQLITE_OK ){
8232      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8233      close_db(pDest);
8234      return 1;
8235    }
8236    if( bAsync ){
8237      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8238                   0, 0, 0);
8239    }
8240    open_db(p, 0);
8241    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8242    if( pBackup==0 ){
8243      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8244      close_db(pDest);
8245      return 1;
8246    }
8247    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8248    sqlite3_backup_finish(pBackup);
8249    if( rc==SQLITE_DONE ){
8250      rc = 0;
8251    }else{
8252      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8253      rc = 1;
8254    }
8255    close_db(pDest);
8256  }else
8257#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8258
8259  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8260    if( nArg==2 ){
8261      bail_on_error = booleanValue(azArg[1]);
8262    }else{
8263      raw_printf(stderr, "Usage: .bail on|off\n");
8264      rc = 1;
8265    }
8266  }else
8267
8268  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8269    if( nArg==2 ){
8270      if( booleanValue(azArg[1]) ){
8271        setBinaryMode(p->out, 1);
8272      }else{
8273        setTextMode(p->out, 1);
8274      }
8275    }else{
8276      raw_printf(stderr, "Usage: .binary on|off\n");
8277      rc = 1;
8278    }
8279  }else
8280
8281  /* The undocumented ".breakpoint" command causes a call to the no-op
8282  ** routine named test_breakpoint().
8283  */
8284  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8285    test_breakpoint();
8286  }else
8287
8288#ifndef SQLITE_SHELL_WASM_MODE
8289  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8290    failIfSafeMode(p, "cannot run .cd in safe mode");
8291    if( nArg==2 ){
8292#if defined(_WIN32) || defined(WIN32)
8293      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8294      rc = !SetCurrentDirectoryW(z);
8295      sqlite3_free(z);
8296#else
8297      rc = chdir(azArg[1]);
8298#endif
8299      if( rc ){
8300        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8301        rc = 1;
8302      }
8303    }else{
8304      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8305      rc = 1;
8306    }
8307  }else
8308#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8309
8310  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8311    if( nArg==2 ){
8312      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8313    }else{
8314      raw_printf(stderr, "Usage: .changes on|off\n");
8315      rc = 1;
8316    }
8317  }else
8318
8319#ifndef SQLITE_SHELL_WASM_MODE
8320  /* Cancel output redirection, if it is currently set (by .testcase)
8321  ** Then read the content of the testcase-out.txt file and compare against
8322  ** azArg[1].  If there are differences, report an error and exit.
8323  */
8324  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8325    char *zRes = 0;
8326    output_reset(p);
8327    if( nArg!=2 ){
8328      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8329      rc = 2;
8330    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8331      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8332      rc = 2;
8333    }else if( testcase_glob(azArg[1],zRes)==0 ){
8334      utf8_printf(stderr,
8335                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8336                 p->zTestcase, azArg[1], zRes);
8337      rc = 1;
8338    }else{
8339      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8340      p->nCheck++;
8341    }
8342    sqlite3_free(zRes);
8343  }else
8344#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8345
8346#ifndef SQLITE_SHELL_WASM_MODE
8347  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8348    failIfSafeMode(p, "cannot run .clone in safe mode");
8349    if( nArg==2 ){
8350      tryToClone(p, azArg[1]);
8351    }else{
8352      raw_printf(stderr, "Usage: .clone FILENAME\n");
8353      rc = 1;
8354    }
8355  }else
8356#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8357
8358  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8359    if( nArg==1 ){
8360      /* List available connections */
8361      int i;
8362      for(i=0; i<ArraySize(p->aAuxDb); i++){
8363        const char *zFile = p->aAuxDb[i].zDbFilename;
8364        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8365          zFile = "(not open)";
8366        }else if( zFile==0 ){
8367          zFile = "(memory)";
8368        }else if( zFile[0]==0 ){
8369          zFile = "(temporary-file)";
8370        }
8371        if( p->pAuxDb == &p->aAuxDb[i] ){
8372          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8373        }else if( p->aAuxDb[i].db!=0 ){
8374          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8375        }
8376      }
8377    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8378      int i = azArg[1][0] - '0';
8379      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8380        p->pAuxDb->db = p->db;
8381        p->pAuxDb = &p->aAuxDb[i];
8382        globalDb = p->db = p->pAuxDb->db;
8383        p->pAuxDb->db = 0;
8384      }
8385    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8386           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8387      int i = azArg[2][0] - '0';
8388      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8389        /* No-op */
8390      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8391        raw_printf(stderr, "cannot close the active database connection\n");
8392        rc = 1;
8393      }else if( p->aAuxDb[i].db ){
8394        session_close_all(p, i);
8395        close_db(p->aAuxDb[i].db);
8396        p->aAuxDb[i].db = 0;
8397      }
8398    }else{
8399      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8400      rc = 1;
8401    }
8402  }else
8403
8404  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8405    char **azName = 0;
8406    int nName = 0;
8407    sqlite3_stmt *pStmt;
8408    int i;
8409    open_db(p, 0);
8410    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8411    if( rc ){
8412      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8413      rc = 1;
8414    }else{
8415      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8416        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8417        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8418        if( zSchema==0 || zFile==0 ) continue;
8419        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8420        shell_check_oom(azName);
8421        azName[nName*2] = strdup(zSchema);
8422        azName[nName*2+1] = strdup(zFile);
8423        nName++;
8424      }
8425    }
8426    sqlite3_finalize(pStmt);
8427    for(i=0; i<nName; i++){
8428      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8429      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8430      const char *z = azName[i*2+1];
8431      utf8_printf(p->out, "%s: %s %s%s\n",
8432         azName[i*2],
8433         z && z[0] ? z : "\"\"",
8434         bRdonly ? "r/o" : "r/w",
8435         eTxn==SQLITE_TXN_NONE ? "" :
8436            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8437      free(azName[i*2]);
8438      free(azName[i*2+1]);
8439    }
8440    sqlite3_free(azName);
8441  }else
8442
8443  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8444    static const struct DbConfigChoices {
8445      const char *zName;
8446      int op;
8447    } aDbConfig[] = {
8448        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8449        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8450        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8451        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8452        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8453        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8454        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8455        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8456        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8457        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8458        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8459        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8460        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8461        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8462        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8463        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8464    };
8465    int ii, v;
8466    open_db(p, 0);
8467    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8468      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8469      if( nArg>=3 ){
8470        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8471      }
8472      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8473      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8474      if( nArg>1 ) break;
8475    }
8476    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8477      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8478      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8479    }
8480  }else
8481
8482  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8483    rc = shell_dbinfo_command(p, nArg, azArg);
8484  }else
8485
8486#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8487  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8488    open_db(p, 0);
8489    rc = recoverDatabaseCmd(p, nArg, azArg);
8490  }else
8491#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8492
8493  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8494    char *zLike = 0;
8495    char *zSql;
8496    int i;
8497    int savedShowHeader = p->showHeader;
8498    int savedShellFlags = p->shellFlgs;
8499    ShellClearFlag(p,
8500       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8501       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8502    for(i=1; i<nArg; i++){
8503      if( azArg[i][0]=='-' ){
8504        const char *z = azArg[i]+1;
8505        if( z[0]=='-' ) z++;
8506        if( strcmp(z,"preserve-rowids")==0 ){
8507#ifdef SQLITE_OMIT_VIRTUALTABLE
8508          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8509                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8510          rc = 1;
8511          sqlite3_free(zLike);
8512          goto meta_command_exit;
8513#else
8514          ShellSetFlag(p, SHFLG_PreserveRowid);
8515#endif
8516        }else
8517        if( strcmp(z,"newlines")==0 ){
8518          ShellSetFlag(p, SHFLG_Newlines);
8519        }else
8520        if( strcmp(z,"data-only")==0 ){
8521          ShellSetFlag(p, SHFLG_DumpDataOnly);
8522        }else
8523        if( strcmp(z,"nosys")==0 ){
8524          ShellSetFlag(p, SHFLG_DumpNoSys);
8525        }else
8526        {
8527          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8528          rc = 1;
8529          sqlite3_free(zLike);
8530          goto meta_command_exit;
8531        }
8532      }else{
8533        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8534        ** only dump data for tables for which either the table name matches
8535        ** the LIKE pattern, or the table appears to be a shadow table of
8536        ** a virtual table for which the name matches the LIKE pattern.
8537        */
8538        char *zExpr = sqlite3_mprintf(
8539            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8540            "  SELECT 1 FROM sqlite_schema WHERE "
8541            "    name LIKE %Q ESCAPE '\\' AND"
8542            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8543            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8544            ")", azArg[i], azArg[i]
8545        );
8546
8547        if( zLike ){
8548          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8549        }else{
8550          zLike = zExpr;
8551        }
8552      }
8553    }
8554
8555    open_db(p, 0);
8556
8557    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8558      /* When playing back a "dump", the content might appear in an order
8559      ** which causes immediate foreign key constraints to be violated.
8560      ** So disable foreign-key constraint enforcement to prevent problems. */
8561      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8562      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8563    }
8564    p->writableSchema = 0;
8565    p->showHeader = 0;
8566    /* Set writable_schema=ON since doing so forces SQLite to initialize
8567    ** as much of the schema as it can even if the sqlite_schema table is
8568    ** corrupt. */
8569    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8570    p->nErr = 0;
8571    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8572    zSql = sqlite3_mprintf(
8573      "SELECT name, type, sql FROM sqlite_schema AS o "
8574      "WHERE (%s) AND type=='table'"
8575      "  AND sql NOT NULL"
8576      " ORDER BY tbl_name='sqlite_sequence', rowid",
8577      zLike
8578    );
8579    run_schema_dump_query(p,zSql);
8580    sqlite3_free(zSql);
8581    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8582      zSql = sqlite3_mprintf(
8583        "SELECT sql FROM sqlite_schema AS o "
8584        "WHERE (%s) AND sql NOT NULL"
8585        "  AND type IN ('index','trigger','view')",
8586        zLike
8587      );
8588      run_table_dump_query(p, zSql);
8589      sqlite3_free(zSql);
8590    }
8591    sqlite3_free(zLike);
8592    if( p->writableSchema ){
8593      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8594      p->writableSchema = 0;
8595    }
8596    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8597    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8598    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8599      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8600    }
8601    p->showHeader = savedShowHeader;
8602    p->shellFlgs = savedShellFlags;
8603  }else
8604
8605  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8606    if( nArg==2 ){
8607      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8608    }else{
8609      raw_printf(stderr, "Usage: .echo on|off\n");
8610      rc = 1;
8611    }
8612  }else
8613
8614  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8615    if( nArg==2 ){
8616      p->autoEQPtest = 0;
8617      if( p->autoEQPtrace ){
8618        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8619        p->autoEQPtrace = 0;
8620      }
8621      if( strcmp(azArg[1],"full")==0 ){
8622        p->autoEQP = AUTOEQP_full;
8623      }else if( strcmp(azArg[1],"trigger")==0 ){
8624        p->autoEQP = AUTOEQP_trigger;
8625#ifdef SQLITE_DEBUG
8626      }else if( strcmp(azArg[1],"test")==0 ){
8627        p->autoEQP = AUTOEQP_on;
8628        p->autoEQPtest = 1;
8629      }else if( strcmp(azArg[1],"trace")==0 ){
8630        p->autoEQP = AUTOEQP_full;
8631        p->autoEQPtrace = 1;
8632        open_db(p, 0);
8633        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8634        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8635#endif
8636      }else{
8637        p->autoEQP = (u8)booleanValue(azArg[1]);
8638      }
8639    }else{
8640      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8641      rc = 1;
8642    }
8643  }else
8644
8645#ifndef SQLITE_SHELL_WASM_MODE
8646  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8647    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8648    rc = 2;
8649  }else
8650#endif
8651
8652  /* The ".explain" command is automatic now.  It is largely pointless.  It
8653  ** retained purely for backwards compatibility */
8654  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8655    int val = 1;
8656    if( nArg>=2 ){
8657      if( strcmp(azArg[1],"auto")==0 ){
8658        val = 99;
8659      }else{
8660        val =  booleanValue(azArg[1]);
8661      }
8662    }
8663    if( val==1 && p->mode!=MODE_Explain ){
8664      p->normalMode = p->mode;
8665      p->mode = MODE_Explain;
8666      p->autoExplain = 0;
8667    }else if( val==0 ){
8668      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8669      p->autoExplain = 0;
8670    }else if( val==99 ){
8671      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8672      p->autoExplain = 1;
8673    }
8674  }else
8675
8676#ifndef SQLITE_OMIT_VIRTUALTABLE
8677  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8678    if( p->bSafeMode ){
8679      raw_printf(stderr,
8680        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8681        azArg[0]);
8682      rc = 1;
8683    }else{
8684      open_db(p, 0);
8685      expertDotCommand(p, azArg, nArg);
8686    }
8687  }else
8688#endif
8689
8690  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8691    static const struct {
8692       const char *zCtrlName;   /* Name of a test-control option */
8693       int ctrlCode;            /* Integer code for that option */
8694       const char *zUsage;      /* Usage notes */
8695    } aCtrl[] = {
8696      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8697      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8698      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8699      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8700      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8701   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8702      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8703      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8704      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8705      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8706   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8707    };
8708    int filectrl = -1;
8709    int iCtrl = -1;
8710    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8711    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8712    int n2, i;
8713    const char *zCmd = 0;
8714    const char *zSchema = 0;
8715
8716    open_db(p, 0);
8717    zCmd = nArg>=2 ? azArg[1] : "help";
8718
8719    if( zCmd[0]=='-'
8720     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8721     && nArg>=4
8722    ){
8723      zSchema = azArg[2];
8724      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8725      nArg -= 2;
8726      zCmd = azArg[1];
8727    }
8728
8729    /* The argument can optionally begin with "-" or "--" */
8730    if( zCmd[0]=='-' && zCmd[1] ){
8731      zCmd++;
8732      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8733    }
8734
8735    /* --help lists all file-controls */
8736    if( strcmp(zCmd,"help")==0 ){
8737      utf8_printf(p->out, "Available file-controls:\n");
8738      for(i=0; i<ArraySize(aCtrl); i++){
8739        utf8_printf(p->out, "  .filectrl %s %s\n",
8740                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8741      }
8742      rc = 1;
8743      goto meta_command_exit;
8744    }
8745
8746    /* convert filectrl text option to value. allow any unique prefix
8747    ** of the option name, or a numerical value. */
8748    n2 = strlen30(zCmd);
8749    for(i=0; i<ArraySize(aCtrl); i++){
8750      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8751        if( filectrl<0 ){
8752          filectrl = aCtrl[i].ctrlCode;
8753          iCtrl = i;
8754        }else{
8755          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8756                              "Use \".filectrl --help\" for help\n", zCmd);
8757          rc = 1;
8758          goto meta_command_exit;
8759        }
8760      }
8761    }
8762    if( filectrl<0 ){
8763      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8764                         "Use \".filectrl --help\" for help\n", zCmd);
8765    }else{
8766      switch(filectrl){
8767        case SQLITE_FCNTL_SIZE_LIMIT: {
8768          if( nArg!=2 && nArg!=3 ) break;
8769          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8770          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8771          isOk = 1;
8772          break;
8773        }
8774        case SQLITE_FCNTL_LOCK_TIMEOUT:
8775        case SQLITE_FCNTL_CHUNK_SIZE: {
8776          int x;
8777          if( nArg!=3 ) break;
8778          x = (int)integerValue(azArg[2]);
8779          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8780          isOk = 2;
8781          break;
8782        }
8783        case SQLITE_FCNTL_PERSIST_WAL:
8784        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8785          int x;
8786          if( nArg!=2 && nArg!=3 ) break;
8787          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8788          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8789          iRes = x;
8790          isOk = 1;
8791          break;
8792        }
8793        case SQLITE_FCNTL_DATA_VERSION:
8794        case SQLITE_FCNTL_HAS_MOVED: {
8795          int x;
8796          if( nArg!=2 ) break;
8797          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8798          iRes = x;
8799          isOk = 1;
8800          break;
8801        }
8802        case SQLITE_FCNTL_TEMPFILENAME: {
8803          char *z = 0;
8804          if( nArg!=2 ) break;
8805          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8806          if( z ){
8807            utf8_printf(p->out, "%s\n", z);
8808            sqlite3_free(z);
8809          }
8810          isOk = 2;
8811          break;
8812        }
8813        case SQLITE_FCNTL_RESERVE_BYTES: {
8814          int x;
8815          if( nArg>=3 ){
8816            x = atoi(azArg[2]);
8817            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8818          }
8819          x = -1;
8820          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8821          utf8_printf(p->out,"%d\n", x);
8822          isOk = 2;
8823          break;
8824        }
8825      }
8826    }
8827    if( isOk==0 && iCtrl>=0 ){
8828      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8829      rc = 1;
8830    }else if( isOk==1 ){
8831      char zBuf[100];
8832      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8833      raw_printf(p->out, "%s\n", zBuf);
8834    }
8835  }else
8836
8837  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8838    ShellState data;
8839    int doStats = 0;
8840    memcpy(&data, p, sizeof(data));
8841    data.showHeader = 0;
8842    data.cMode = data.mode = MODE_Semi;
8843    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8844      data.cMode = data.mode = MODE_Pretty;
8845      nArg = 1;
8846    }
8847    if( nArg!=1 ){
8848      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8849      rc = 1;
8850      goto meta_command_exit;
8851    }
8852    open_db(p, 0);
8853    rc = sqlite3_exec(p->db,
8854       "SELECT sql FROM"
8855       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8856       "     FROM sqlite_schema UNION ALL"
8857       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8858       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8859       "ORDER BY x",
8860       callback, &data, 0
8861    );
8862    if( rc==SQLITE_OK ){
8863      sqlite3_stmt *pStmt;
8864      rc = sqlite3_prepare_v2(p->db,
8865               "SELECT rowid FROM sqlite_schema"
8866               " WHERE name GLOB 'sqlite_stat[134]'",
8867               -1, &pStmt, 0);
8868      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8869      sqlite3_finalize(pStmt);
8870    }
8871    if( doStats==0 ){
8872      raw_printf(p->out, "/* No STAT tables available */\n");
8873    }else{
8874      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8875      data.cMode = data.mode = MODE_Insert;
8876      data.zDestTable = "sqlite_stat1";
8877      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8878      data.zDestTable = "sqlite_stat4";
8879      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8880      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8881    }
8882  }else
8883
8884  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8885    if( nArg==2 ){
8886      p->showHeader = booleanValue(azArg[1]);
8887      p->shellFlgs |= SHFLG_HeaderSet;
8888    }else{
8889      raw_printf(stderr, "Usage: .headers on|off\n");
8890      rc = 1;
8891    }
8892  }else
8893
8894  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8895    if( nArg>=2 ){
8896      n = showHelp(p->out, azArg[1]);
8897      if( n==0 ){
8898        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8899      }
8900    }else{
8901      showHelp(p->out, 0);
8902    }
8903  }else
8904
8905#ifndef SQLITE_SHELL_WASM_MODE
8906  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8907    char *zTable = 0;           /* Insert data into this table */
8908    char *zSchema = 0;          /* within this schema (may default to "main") */
8909    char *zFile = 0;            /* Name of file to extra content from */
8910    sqlite3_stmt *pStmt = NULL; /* A statement */
8911    int nCol;                   /* Number of columns in the table */
8912    int nByte;                  /* Number of bytes in an SQL string */
8913    int i, j;                   /* Loop counters */
8914    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8915    int nSep;                   /* Number of bytes in p->colSeparator[] */
8916    char *zSql;                 /* An SQL statement */
8917    char *zFullTabName;         /* Table name with schema if applicable */
8918    ImportCtx sCtx;             /* Reader context */
8919    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8920    int eVerbose = 0;           /* Larger for more console output */
8921    int nSkip = 0;              /* Initial lines to skip */
8922    int useOutputMode = 1;      /* Use output mode to determine separators */
8923    char *zCreate = 0;          /* CREATE TABLE statement text */
8924
8925    failIfSafeMode(p, "cannot run .import in safe mode");
8926    memset(&sCtx, 0, sizeof(sCtx));
8927    if( p->mode==MODE_Ascii ){
8928      xRead = ascii_read_one_field;
8929    }else{
8930      xRead = csv_read_one_field;
8931    }
8932    rc = 1;
8933    for(i=1; i<nArg; i++){
8934      char *z = azArg[i];
8935      if( z[0]=='-' && z[1]=='-' ) z++;
8936      if( z[0]!='-' ){
8937        if( zFile==0 ){
8938          zFile = z;
8939        }else if( zTable==0 ){
8940          zTable = z;
8941        }else{
8942          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8943          showHelp(p->out, "import");
8944          goto meta_command_exit;
8945        }
8946      }else if( strcmp(z,"-v")==0 ){
8947        eVerbose++;
8948      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8949        zSchema = azArg[++i];
8950      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8951        nSkip = integerValue(azArg[++i]);
8952      }else if( strcmp(z,"-ascii")==0 ){
8953        sCtx.cColSep = SEP_Unit[0];
8954        sCtx.cRowSep = SEP_Record[0];
8955        xRead = ascii_read_one_field;
8956        useOutputMode = 0;
8957      }else if( strcmp(z,"-csv")==0 ){
8958        sCtx.cColSep = ',';
8959        sCtx.cRowSep = '\n';
8960        xRead = csv_read_one_field;
8961        useOutputMode = 0;
8962      }else{
8963        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8964        showHelp(p->out, "import");
8965        goto meta_command_exit;
8966      }
8967    }
8968    if( zTable==0 ){
8969      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8970                  zFile==0 ? "FILE" : "TABLE");
8971      showHelp(p->out, "import");
8972      goto meta_command_exit;
8973    }
8974    seenInterrupt = 0;
8975    open_db(p, 0);
8976    if( useOutputMode ){
8977      /* If neither the --csv or --ascii options are specified, then set
8978      ** the column and row separator characters from the output mode. */
8979      nSep = strlen30(p->colSeparator);
8980      if( nSep==0 ){
8981        raw_printf(stderr,
8982                   "Error: non-null column separator required for import\n");
8983        goto meta_command_exit;
8984      }
8985      if( nSep>1 ){
8986        raw_printf(stderr,
8987              "Error: multi-character column separators not allowed"
8988              " for import\n");
8989        goto meta_command_exit;
8990      }
8991      nSep = strlen30(p->rowSeparator);
8992      if( nSep==0 ){
8993        raw_printf(stderr,
8994            "Error: non-null row separator required for import\n");
8995        goto meta_command_exit;
8996      }
8997      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8998        /* When importing CSV (only), if the row separator is set to the
8999        ** default output row separator, change it to the default input
9000        ** row separator.  This avoids having to maintain different input
9001        ** and output row separators. */
9002        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9003        nSep = strlen30(p->rowSeparator);
9004      }
9005      if( nSep>1 ){
9006        raw_printf(stderr, "Error: multi-character row separators not allowed"
9007                           " for import\n");
9008        goto meta_command_exit;
9009      }
9010      sCtx.cColSep = p->colSeparator[0];
9011      sCtx.cRowSep = p->rowSeparator[0];
9012    }
9013    sCtx.zFile = zFile;
9014    sCtx.nLine = 1;
9015    if( sCtx.zFile[0]=='|' ){
9016#ifdef SQLITE_OMIT_POPEN
9017      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9018      goto meta_command_exit;
9019#else
9020      sCtx.in = popen(sCtx.zFile+1, "r");
9021      sCtx.zFile = "<pipe>";
9022      sCtx.xCloser = pclose;
9023#endif
9024    }else{
9025      sCtx.in = fopen(sCtx.zFile, "rb");
9026      sCtx.xCloser = fclose;
9027    }
9028    if( sCtx.in==0 ){
9029      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9030      goto meta_command_exit;
9031    }
9032    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9033      char zSep[2];
9034      zSep[1] = 0;
9035      zSep[0] = sCtx.cColSep;
9036      utf8_printf(p->out, "Column separator ");
9037      output_c_string(p->out, zSep);
9038      utf8_printf(p->out, ", row separator ");
9039      zSep[0] = sCtx.cRowSep;
9040      output_c_string(p->out, zSep);
9041      utf8_printf(p->out, "\n");
9042    }
9043    sCtx.z = sqlite3_malloc64(120);
9044    if( sCtx.z==0 ){
9045      import_cleanup(&sCtx);
9046      shell_out_of_memory();
9047    }
9048    /* Below, resources must be freed before exit. */
9049    while( (nSkip--)>0 ){
9050      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9051    }
9052    if( zSchema!=0 ){
9053      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9054    }else{
9055      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9056    }
9057    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9058    if( zSql==0 || zFullTabName==0 ){
9059      import_cleanup(&sCtx);
9060      shell_out_of_memory();
9061    }
9062    nByte = strlen30(zSql);
9063    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9064    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9065    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9066      sqlite3 *dbCols = 0;
9067      char *zRenames = 0;
9068      char *zColDefs;
9069      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9070      while( xRead(&sCtx) ){
9071        zAutoColumn(sCtx.z, &dbCols, 0);
9072        if( sCtx.cTerm!=sCtx.cColSep ) break;
9073      }
9074      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9075      if( zRenames!=0 ){
9076        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9077                    "Columns renamed during .import %s due to duplicates:\n"
9078                    "%s\n", sCtx.zFile, zRenames);
9079        sqlite3_free(zRenames);
9080      }
9081      assert(dbCols==0);
9082      if( zColDefs==0 ){
9083        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9084      import_fail:
9085        sqlite3_free(zCreate);
9086        sqlite3_free(zSql);
9087        sqlite3_free(zFullTabName);
9088        import_cleanup(&sCtx);
9089        rc = 1;
9090        goto meta_command_exit;
9091      }
9092      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9093      if( eVerbose>=1 ){
9094        utf8_printf(p->out, "%s\n", zCreate);
9095      }
9096      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9097      if( rc ){
9098        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9099        goto import_fail;
9100      }
9101      sqlite3_free(zCreate);
9102      zCreate = 0;
9103      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9104    }
9105    if( rc ){
9106      if (pStmt) sqlite3_finalize(pStmt);
9107      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9108      goto import_fail;
9109    }
9110    sqlite3_free(zSql);
9111    nCol = sqlite3_column_count(pStmt);
9112    sqlite3_finalize(pStmt);
9113    pStmt = 0;
9114    if( nCol==0 ) return 0; /* no columns, no error */
9115    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9116    if( zSql==0 ){
9117      import_cleanup(&sCtx);
9118      shell_out_of_memory();
9119    }
9120    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9121    j = strlen30(zSql);
9122    for(i=1; i<nCol; i++){
9123      zSql[j++] = ',';
9124      zSql[j++] = '?';
9125    }
9126    zSql[j++] = ')';
9127    zSql[j] = 0;
9128    if( eVerbose>=2 ){
9129      utf8_printf(p->out, "Insert using: %s\n", zSql);
9130    }
9131    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9132    if( rc ){
9133      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9134      if (pStmt) sqlite3_finalize(pStmt);
9135      goto import_fail;
9136    }
9137    sqlite3_free(zSql);
9138    sqlite3_free(zFullTabName);
9139    needCommit = sqlite3_get_autocommit(p->db);
9140    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9141    do{
9142      int startLine = sCtx.nLine;
9143      for(i=0; i<nCol; i++){
9144        char *z = xRead(&sCtx);
9145        /*
9146        ** Did we reach end-of-file before finding any columns?
9147        ** If so, stop instead of NULL filling the remaining columns.
9148        */
9149        if( z==0 && i==0 ) break;
9150        /*
9151        ** Did we reach end-of-file OR end-of-line before finding any
9152        ** columns in ASCII mode?  If so, stop instead of NULL filling
9153        ** the remaining columns.
9154        */
9155        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9156        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9157        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9158          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9159                          "filling the rest with NULL\n",
9160                          sCtx.zFile, startLine, nCol, i+1);
9161          i += 2;
9162          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9163        }
9164      }
9165      if( sCtx.cTerm==sCtx.cColSep ){
9166        do{
9167          xRead(&sCtx);
9168          i++;
9169        }while( sCtx.cTerm==sCtx.cColSep );
9170        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9171                        "extras ignored\n",
9172                        sCtx.zFile, startLine, nCol, i);
9173      }
9174      if( i>=nCol ){
9175        sqlite3_step(pStmt);
9176        rc = sqlite3_reset(pStmt);
9177        if( rc!=SQLITE_OK ){
9178          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9179                      startLine, sqlite3_errmsg(p->db));
9180          sCtx.nErr++;
9181        }else{
9182          sCtx.nRow++;
9183        }
9184      }
9185    }while( sCtx.cTerm!=EOF );
9186
9187    import_cleanup(&sCtx);
9188    sqlite3_finalize(pStmt);
9189    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9190    if( eVerbose>0 ){
9191      utf8_printf(p->out,
9192          "Added %d rows with %d errors using %d lines of input\n",
9193          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9194    }
9195  }else
9196#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9197
9198#ifndef SQLITE_UNTESTABLE
9199  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9200    char *zSql;
9201    char *zCollist = 0;
9202    sqlite3_stmt *pStmt;
9203    int tnum = 0;
9204    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9205    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9206    int i;
9207    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9208      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9209                          "       .imposter off\n");
9210      /* Also allowed, but not documented:
9211      **
9212      **    .imposter TABLE IMPOSTER
9213      **
9214      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9215      ** imposter is another WITHOUT ROWID table with the columns in
9216      ** storage order. */
9217      rc = 1;
9218      goto meta_command_exit;
9219    }
9220    open_db(p, 0);
9221    if( nArg==2 ){
9222      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9223      goto meta_command_exit;
9224    }
9225    zSql = sqlite3_mprintf(
9226      "SELECT rootpage, 0 FROM sqlite_schema"
9227      " WHERE name='%q' AND type='index'"
9228      "UNION ALL "
9229      "SELECT rootpage, 1 FROM sqlite_schema"
9230      " WHERE name='%q' AND type='table'"
9231      "   AND sql LIKE '%%without%%rowid%%'",
9232      azArg[1], azArg[1]
9233    );
9234    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9235    sqlite3_free(zSql);
9236    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9237      tnum = sqlite3_column_int(pStmt, 0);
9238      isWO = sqlite3_column_int(pStmt, 1);
9239    }
9240    sqlite3_finalize(pStmt);
9241    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9242    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9243    sqlite3_free(zSql);
9244    i = 0;
9245    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9246      char zLabel[20];
9247      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9248      i++;
9249      if( zCol==0 ){
9250        if( sqlite3_column_int(pStmt,1)==-1 ){
9251          zCol = "_ROWID_";
9252        }else{
9253          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9254          zCol = zLabel;
9255        }
9256      }
9257      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9258        lenPK = (int)strlen(zCollist);
9259      }
9260      if( zCollist==0 ){
9261        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9262      }else{
9263        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9264      }
9265    }
9266    sqlite3_finalize(pStmt);
9267    if( i==0 || tnum==0 ){
9268      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9269      rc = 1;
9270      sqlite3_free(zCollist);
9271      goto meta_command_exit;
9272    }
9273    if( lenPK==0 ) lenPK = 100000;
9274    zSql = sqlite3_mprintf(
9275          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9276          azArg[2], zCollist, lenPK, zCollist);
9277    sqlite3_free(zCollist);
9278    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9279    if( rc==SQLITE_OK ){
9280      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9281      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9282      if( rc ){
9283        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9284      }else{
9285        utf8_printf(stdout, "%s;\n", zSql);
9286        raw_printf(stdout,
9287          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9288          azArg[1], isWO ? "table" : "index"
9289        );
9290      }
9291    }else{
9292      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9293      rc = 1;
9294    }
9295    sqlite3_free(zSql);
9296  }else
9297#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9298
9299#ifdef SQLITE_ENABLE_IOTRACE
9300  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9301    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9302    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9303    iotrace = 0;
9304    if( nArg<2 ){
9305      sqlite3IoTrace = 0;
9306    }else if( strcmp(azArg[1], "-")==0 ){
9307      sqlite3IoTrace = iotracePrintf;
9308      iotrace = stdout;
9309    }else{
9310      iotrace = fopen(azArg[1], "w");
9311      if( iotrace==0 ){
9312        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9313        sqlite3IoTrace = 0;
9314        rc = 1;
9315      }else{
9316        sqlite3IoTrace = iotracePrintf;
9317      }
9318    }
9319  }else
9320#endif
9321
9322  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9323    static const struct {
9324       const char *zLimitName;   /* Name of a limit */
9325       int limitCode;            /* Integer code for that limit */
9326    } aLimit[] = {
9327      { "length",                SQLITE_LIMIT_LENGTH                    },
9328      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9329      { "column",                SQLITE_LIMIT_COLUMN                    },
9330      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9331      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9332      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9333      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9334      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9335      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9336      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9337      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9338      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9339    };
9340    int i, n2;
9341    open_db(p, 0);
9342    if( nArg==1 ){
9343      for(i=0; i<ArraySize(aLimit); i++){
9344        printf("%20s %d\n", aLimit[i].zLimitName,
9345               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9346      }
9347    }else if( nArg>3 ){
9348      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9349      rc = 1;
9350      goto meta_command_exit;
9351    }else{
9352      int iLimit = -1;
9353      n2 = strlen30(azArg[1]);
9354      for(i=0; i<ArraySize(aLimit); i++){
9355        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9356          if( iLimit<0 ){
9357            iLimit = i;
9358          }else{
9359            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9360            rc = 1;
9361            goto meta_command_exit;
9362          }
9363        }
9364      }
9365      if( iLimit<0 ){
9366        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9367                        "enter \".limits\" with no arguments for a list.\n",
9368                         azArg[1]);
9369        rc = 1;
9370        goto meta_command_exit;
9371      }
9372      if( nArg==3 ){
9373        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9374                      (int)integerValue(azArg[2]));
9375      }
9376      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9377             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9378    }
9379  }else
9380
9381  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9382    open_db(p, 0);
9383    lintDotCommand(p, azArg, nArg);
9384  }else
9385
9386#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
9387  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9388    const char *zFile, *zProc;
9389    char *zErrMsg = 0;
9390    failIfSafeMode(p, "cannot run .load in safe mode");
9391    if( nArg<2 ){
9392      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9393      rc = 1;
9394      goto meta_command_exit;
9395    }
9396    zFile = azArg[1];
9397    zProc = nArg>=3 ? azArg[2] : 0;
9398    open_db(p, 0);
9399    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9400    if( rc!=SQLITE_OK ){
9401      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9402      sqlite3_free(zErrMsg);
9403      rc = 1;
9404    }
9405  }else
9406#endif
9407
9408#ifndef SQLITE_SHELL_WASM_MODE
9409  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9410    failIfSafeMode(p, "cannot run .log in safe mode");
9411    if( nArg!=2 ){
9412      raw_printf(stderr, "Usage: .log FILENAME\n");
9413      rc = 1;
9414    }else{
9415      const char *zFile = azArg[1];
9416      output_file_close(p->pLog);
9417      p->pLog = output_file_open(zFile, 0);
9418    }
9419  }else
9420#endif
9421
9422  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9423    const char *zMode = 0;
9424    const char *zTabname = 0;
9425    int i, n2;
9426    ColModeOpts cmOpts = ColModeOpts_default;
9427    for(i=1; i<nArg; i++){
9428      const char *z = azArg[i];
9429      if( optionMatch(z,"wrap") && i+1<nArg ){
9430        cmOpts.iWrap = integerValue(azArg[++i]);
9431      }else if( optionMatch(z,"ww") ){
9432        cmOpts.bWordWrap = 1;
9433      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9434        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9435      }else if( optionMatch(z,"quote") ){
9436        cmOpts.bQuote = 1;
9437      }else if( optionMatch(z,"noquote") ){
9438        cmOpts.bQuote = 0;
9439      }else if( zMode==0 ){
9440        zMode = z;
9441        /* Apply defaults for qbox pseudo-mods. If that
9442         * overwrites already-set values, user was informed of this.
9443         */
9444        if( strcmp(z, "qbox")==0 ){
9445          ColModeOpts cmo = ColModeOpts_default_qbox;
9446          zMode = "box";
9447          cmOpts = cmo;
9448        }
9449      }else if( zTabname==0 ){
9450        zTabname = z;
9451      }else if( z[0]=='-' ){
9452        utf8_printf(stderr, "unknown option: %s\n", z);
9453        utf8_printf(stderr, "options:\n"
9454                            "  --noquote\n"
9455                            "  --quote\n"
9456                            "  --wordwrap on/off\n"
9457                            "  --wrap N\n"
9458                            "  --ww\n");
9459        rc = 1;
9460        goto meta_command_exit;
9461      }else{
9462        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9463        rc = 1;
9464        goto meta_command_exit;
9465      }
9466    }
9467    if( zMode==0 ){
9468      if( p->mode==MODE_Column
9469       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9470      ){
9471        raw_printf
9472          (p->out,
9473           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9474           modeDescr[p->mode], p->cmOpts.iWrap,
9475           p->cmOpts.bWordWrap ? "on" : "off",
9476           p->cmOpts.bQuote ? "" : "no");
9477      }else{
9478        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9479      }
9480      zMode = modeDescr[p->mode];
9481    }
9482    n2 = strlen30(zMode);
9483    if( strncmp(zMode,"lines",n2)==0 ){
9484      p->mode = MODE_Line;
9485      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9486    }else if( strncmp(zMode,"columns",n2)==0 ){
9487      p->mode = MODE_Column;
9488      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9489        p->showHeader = 1;
9490      }
9491      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9492      p->cmOpts = cmOpts;
9493    }else if( strncmp(zMode,"list",n2)==0 ){
9494      p->mode = MODE_List;
9495      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9496      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9497    }else if( strncmp(zMode,"html",n2)==0 ){
9498      p->mode = MODE_Html;
9499    }else if( strncmp(zMode,"tcl",n2)==0 ){
9500      p->mode = MODE_Tcl;
9501      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9502      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9503    }else if( strncmp(zMode,"csv",n2)==0 ){
9504      p->mode = MODE_Csv;
9505      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9506      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9507    }else if( strncmp(zMode,"tabs",n2)==0 ){
9508      p->mode = MODE_List;
9509      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9510    }else if( strncmp(zMode,"insert",n2)==0 ){
9511      p->mode = MODE_Insert;
9512      set_table_name(p, zTabname ? zTabname : "table");
9513    }else if( strncmp(zMode,"quote",n2)==0 ){
9514      p->mode = MODE_Quote;
9515      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9516      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9517    }else if( strncmp(zMode,"ascii",n2)==0 ){
9518      p->mode = MODE_Ascii;
9519      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9520      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9521    }else if( strncmp(zMode,"markdown",n2)==0 ){
9522      p->mode = MODE_Markdown;
9523      p->cmOpts = cmOpts;
9524    }else if( strncmp(zMode,"table",n2)==0 ){
9525      p->mode = MODE_Table;
9526      p->cmOpts = cmOpts;
9527    }else if( strncmp(zMode,"box",n2)==0 ){
9528      p->mode = MODE_Box;
9529      p->cmOpts = cmOpts;
9530    }else if( strncmp(zMode,"count",n2)==0 ){
9531      p->mode = MODE_Count;
9532    }else if( strncmp(zMode,"off",n2)==0 ){
9533      p->mode = MODE_Off;
9534    }else if( strncmp(zMode,"json",n2)==0 ){
9535      p->mode = MODE_Json;
9536    }else{
9537      raw_printf(stderr, "Error: mode should be one of: "
9538         "ascii box column csv html insert json line list markdown "
9539         "qbox quote table tabs tcl\n");
9540      rc = 1;
9541    }
9542    p->cMode = p->mode;
9543  }else
9544
9545#ifndef SQLITE_SHELL_WASM_MODE
9546  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9547    if( nArg!=2 ){
9548      raw_printf(stderr, "Usage: .nonce NONCE\n");
9549      rc = 1;
9550    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9551      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9552                 p->lineno, azArg[1]);
9553      exit(1);
9554    }else{
9555      p->bSafeMode = 0;
9556      return 0;  /* Return immediately to bypass the safe mode reset
9557                 ** at the end of this procedure */
9558    }
9559  }else
9560#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9561
9562  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9563    if( nArg==2 ){
9564      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9565                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9566    }else{
9567      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9568      rc = 1;
9569    }
9570  }else
9571
9572  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9573    const char *zFN = 0;     /* Pointer to constant filename */
9574    char *zNewFilename = 0;  /* Name of the database file to open */
9575    int iName = 1;           /* Index in azArg[] of the filename */
9576    int newFlag = 0;         /* True to delete file before opening */
9577    int openMode = SHELL_OPEN_UNSPEC;
9578
9579    /* Check for command-line arguments */
9580    for(iName=1; iName<nArg; iName++){
9581      const char *z = azArg[iName];
9582#ifndef SQLITE_SHELL_WASM_MODE
9583      if( optionMatch(z,"new") ){
9584        newFlag = 1;
9585#ifdef SQLITE_HAVE_ZLIB
9586      }else if( optionMatch(z, "zip") ){
9587        openMode = SHELL_OPEN_ZIPFILE;
9588#endif
9589      }else if( optionMatch(z, "append") ){
9590        openMode = SHELL_OPEN_APPENDVFS;
9591      }else if( optionMatch(z, "readonly") ){
9592        openMode = SHELL_OPEN_READONLY;
9593      }else if( optionMatch(z, "nofollow") ){
9594        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9595#ifndef SQLITE_OMIT_DESERIALIZE
9596      }else if( optionMatch(z, "deserialize") ){
9597        openMode = SHELL_OPEN_DESERIALIZE;
9598      }else if( optionMatch(z, "hexdb") ){
9599        openMode = SHELL_OPEN_HEXDB;
9600      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9601        p->szMax = integerValue(azArg[++iName]);
9602#endif /* SQLITE_OMIT_DESERIALIZE */
9603      }else
9604#endif /* !SQLITE_SHELL_WASM_MODE */
9605      if( z[0]=='-' ){
9606        utf8_printf(stderr, "unknown option: %s\n", z);
9607        rc = 1;
9608        goto meta_command_exit;
9609      }else if( zFN ){
9610        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9611        rc = 1;
9612        goto meta_command_exit;
9613      }else{
9614        zFN = z;
9615      }
9616    }
9617
9618    /* Close the existing database */
9619    session_close_all(p, -1);
9620    close_db(p->db);
9621    p->db = 0;
9622    p->pAuxDb->zDbFilename = 0;
9623    sqlite3_free(p->pAuxDb->zFreeOnClose);
9624    p->pAuxDb->zFreeOnClose = 0;
9625    p->openMode = openMode;
9626    p->openFlags = 0;
9627    p->szMax = 0;
9628
9629    /* If a filename is specified, try to open it first */
9630    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9631      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9632#ifndef SQLITE_SHELL_WASM_MODE
9633      if( p->bSafeMode
9634       && p->openMode!=SHELL_OPEN_HEXDB
9635       && zFN
9636       && strcmp(zFN,":memory:")!=0
9637      ){
9638        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9639      }
9640#else
9641      /* WASM mode has its own sandboxed pseudo-filesystem. */
9642#endif
9643      if( zFN ){
9644        zNewFilename = sqlite3_mprintf("%s", zFN);
9645        shell_check_oom(zNewFilename);
9646      }else{
9647        zNewFilename = 0;
9648      }
9649      p->pAuxDb->zDbFilename = zNewFilename;
9650      open_db(p, OPEN_DB_KEEPALIVE);
9651      if( p->db==0 ){
9652        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9653        sqlite3_free(zNewFilename);
9654      }else{
9655        p->pAuxDb->zFreeOnClose = zNewFilename;
9656      }
9657    }
9658    if( p->db==0 ){
9659      /* As a fall-back open a TEMP database */
9660      p->pAuxDb->zDbFilename = 0;
9661      open_db(p, 0);
9662    }
9663  }else
9664
9665#ifndef SQLITE_SHELL_WASM_MODE
9666  if( (c=='o'
9667        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9668   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9669  ){
9670    char *zFile = 0;
9671    int bTxtMode = 0;
9672    int i;
9673    int eMode = 0;
9674    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9675    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9676
9677    zBOM[0] = 0;
9678    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9679    if( c=='e' ){
9680      eMode = 'x';
9681      bOnce = 2;
9682    }else if( strncmp(azArg[0],"once",n)==0 ){
9683      bOnce = 1;
9684    }
9685    for(i=1; i<nArg; i++){
9686      char *z = azArg[i];
9687      if( z[0]=='-' ){
9688        if( z[1]=='-' ) z++;
9689        if( strcmp(z,"-bom")==0 ){
9690          zBOM[0] = 0xef;
9691          zBOM[1] = 0xbb;
9692          zBOM[2] = 0xbf;
9693          zBOM[3] = 0;
9694        }else if( c!='e' && strcmp(z,"-x")==0 ){
9695          eMode = 'x';  /* spreadsheet */
9696        }else if( c!='e' && strcmp(z,"-e")==0 ){
9697          eMode = 'e';  /* text editor */
9698        }else{
9699          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9700                      azArg[i]);
9701          showHelp(p->out, azArg[0]);
9702          rc = 1;
9703          goto meta_command_exit;
9704        }
9705      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9706        zFile = sqlite3_mprintf("%s", z);
9707        if( zFile && zFile[0]=='|' ){
9708          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9709          break;
9710        }
9711      }else{
9712        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9713                    azArg[i]);
9714        showHelp(p->out, azArg[0]);
9715        rc = 1;
9716        sqlite3_free(zFile);
9717        goto meta_command_exit;
9718      }
9719    }
9720    if( zFile==0 ){
9721      zFile = sqlite3_mprintf("stdout");
9722    }
9723    if( bOnce ){
9724      p->outCount = 2;
9725    }else{
9726      p->outCount = 0;
9727    }
9728    output_reset(p);
9729#ifndef SQLITE_NOHAVE_SYSTEM
9730    if( eMode=='e' || eMode=='x' ){
9731      p->doXdgOpen = 1;
9732      outputModePush(p);
9733      if( eMode=='x' ){
9734        /* spreadsheet mode.  Output as CSV. */
9735        newTempFile(p, "csv");
9736        ShellClearFlag(p, SHFLG_Echo);
9737        p->mode = MODE_Csv;
9738        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9739        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9740      }else{
9741        /* text editor mode */
9742        newTempFile(p, "txt");
9743        bTxtMode = 1;
9744      }
9745      sqlite3_free(zFile);
9746      zFile = sqlite3_mprintf("%s", p->zTempFile);
9747    }
9748#endif /* SQLITE_NOHAVE_SYSTEM */
9749    shell_check_oom(zFile);
9750    if( zFile[0]=='|' ){
9751#ifdef SQLITE_OMIT_POPEN
9752      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9753      rc = 1;
9754      p->out = stdout;
9755#else
9756      p->out = popen(zFile + 1, "w");
9757      if( p->out==0 ){
9758        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9759        p->out = stdout;
9760        rc = 1;
9761      }else{
9762        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9763        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9764      }
9765#endif
9766    }else{
9767      p->out = output_file_open(zFile, bTxtMode);
9768      if( p->out==0 ){
9769        if( strcmp(zFile,"off")!=0 ){
9770          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9771        }
9772        p->out = stdout;
9773        rc = 1;
9774      } else {
9775        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9776        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9777      }
9778    }
9779    sqlite3_free(zFile);
9780  }else
9781#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9782
9783  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9784    open_db(p,0);
9785    if( nArg<=1 ) goto parameter_syntax_error;
9786
9787    /* .parameter clear
9788    ** Clear all bind parameters by dropping the TEMP table that holds them.
9789    */
9790    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9791      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9792                   0, 0, 0);
9793    }else
9794
9795    /* .parameter list
9796    ** List all bind parameters.
9797    */
9798    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9799      sqlite3_stmt *pStmt = 0;
9800      int rx;
9801      int len = 0;
9802      rx = sqlite3_prepare_v2(p->db,
9803             "SELECT max(length(key)) "
9804             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9805      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9806        len = sqlite3_column_int(pStmt, 0);
9807        if( len>40 ) len = 40;
9808      }
9809      sqlite3_finalize(pStmt);
9810      pStmt = 0;
9811      if( len ){
9812        rx = sqlite3_prepare_v2(p->db,
9813             "SELECT key, quote(value) "
9814             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9815        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9816          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9817                      sqlite3_column_text(pStmt,1));
9818        }
9819        sqlite3_finalize(pStmt);
9820      }
9821    }else
9822
9823    /* .parameter init
9824    ** Make sure the TEMP table used to hold bind parameters exists.
9825    ** Create it if necessary.
9826    */
9827    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9828      bind_table_init(p);
9829    }else
9830
9831    /* .parameter set NAME VALUE
9832    ** Set or reset a bind parameter.  NAME should be the full parameter
9833    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9834    ** VALUE can be in either SQL literal notation, or if not it will be
9835    ** understood to be a text string.
9836    */
9837    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9838      int rx;
9839      char *zSql;
9840      sqlite3_stmt *pStmt;
9841      const char *zKey = azArg[2];
9842      const char *zValue = azArg[3];
9843      bind_table_init(p);
9844      zSql = sqlite3_mprintf(
9845                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9846                  "VALUES(%Q,%s);", zKey, zValue);
9847      shell_check_oom(zSql);
9848      pStmt = 0;
9849      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9850      sqlite3_free(zSql);
9851      if( rx!=SQLITE_OK ){
9852        sqlite3_finalize(pStmt);
9853        pStmt = 0;
9854        zSql = sqlite3_mprintf(
9855                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9856                   "VALUES(%Q,%Q);", zKey, zValue);
9857        shell_check_oom(zSql);
9858        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9859        sqlite3_free(zSql);
9860        if( rx!=SQLITE_OK ){
9861          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9862          sqlite3_finalize(pStmt);
9863          pStmt = 0;
9864          rc = 1;
9865        }
9866      }
9867      sqlite3_step(pStmt);
9868      sqlite3_finalize(pStmt);
9869    }else
9870
9871    /* .parameter unset NAME
9872    ** Remove the NAME binding from the parameter binding table, if it
9873    ** exists.
9874    */
9875    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9876      char *zSql = sqlite3_mprintf(
9877          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9878      shell_check_oom(zSql);
9879      sqlite3_exec(p->db, zSql, 0, 0, 0);
9880      sqlite3_free(zSql);
9881    }else
9882    /* If no command name matches, show a syntax error */
9883    parameter_syntax_error:
9884    showHelp(p->out, "parameter");
9885  }else
9886
9887  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9888    int i;
9889    for(i=1; i<nArg; i++){
9890      if( i>1 ) raw_printf(p->out, " ");
9891      utf8_printf(p->out, "%s", azArg[i]);
9892    }
9893    raw_printf(p->out, "\n");
9894  }else
9895
9896#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9897  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9898    int i;
9899    int nn = 0;
9900    p->flgProgress = 0;
9901    p->mxProgress = 0;
9902    p->nProgress = 0;
9903    for(i=1; i<nArg; i++){
9904      const char *z = azArg[i];
9905      if( z[0]=='-' ){
9906        z++;
9907        if( z[0]=='-' ) z++;
9908        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9909          p->flgProgress |= SHELL_PROGRESS_QUIET;
9910          continue;
9911        }
9912        if( strcmp(z,"reset")==0 ){
9913          p->flgProgress |= SHELL_PROGRESS_RESET;
9914          continue;
9915        }
9916        if( strcmp(z,"once")==0 ){
9917          p->flgProgress |= SHELL_PROGRESS_ONCE;
9918          continue;
9919        }
9920        if( strcmp(z,"limit")==0 ){
9921          if( i+1>=nArg ){
9922            utf8_printf(stderr, "Error: missing argument on --limit\n");
9923            rc = 1;
9924            goto meta_command_exit;
9925          }else{
9926            p->mxProgress = (int)integerValue(azArg[++i]);
9927          }
9928          continue;
9929        }
9930        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9931        rc = 1;
9932        goto meta_command_exit;
9933      }else{
9934        nn = (int)integerValue(z);
9935      }
9936    }
9937    open_db(p, 0);
9938    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9939  }else
9940#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9941
9942  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9943    if( nArg >= 2) {
9944      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9945    }
9946    if( nArg >= 3) {
9947      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9948    }
9949  }else
9950
9951#ifndef SQLITE_SHELL_WASM_MODE
9952  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9953    rc = 2;
9954  }else
9955#endif
9956
9957#ifndef SQLITE_SHELL_WASM_MODE
9958  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9959    FILE *inSaved = p->in;
9960    int savedLineno = p->lineno;
9961    failIfSafeMode(p, "cannot run .read in safe mode");
9962    if( nArg!=2 ){
9963      raw_printf(stderr, "Usage: .read FILE\n");
9964      rc = 1;
9965      goto meta_command_exit;
9966    }
9967    if( azArg[1][0]=='|' ){
9968#ifdef SQLITE_OMIT_POPEN
9969      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9970      rc = 1;
9971      p->out = stdout;
9972#else
9973      p->in = popen(azArg[1]+1, "r");
9974      if( p->in==0 ){
9975        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9976        rc = 1;
9977      }else{
9978        rc = process_input(p);
9979        pclose(p->in);
9980      }
9981#endif
9982    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9983      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9984      rc = 1;
9985    }else{
9986      rc = process_input(p);
9987      fclose(p->in);
9988    }
9989    p->in = inSaved;
9990    p->lineno = savedLineno;
9991  }else
9992#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9993
9994#ifndef SQLITE_SHELL_WASM_MODE
9995  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9996    const char *zSrcFile;
9997    const char *zDb;
9998    sqlite3 *pSrc;
9999    sqlite3_backup *pBackup;
10000    int nTimeout = 0;
10001
10002    failIfSafeMode(p, "cannot run .restore in safe mode");
10003    if( nArg==2 ){
10004      zSrcFile = azArg[1];
10005      zDb = "main";
10006    }else if( nArg==3 ){
10007      zSrcFile = azArg[2];
10008      zDb = azArg[1];
10009    }else{
10010      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10011      rc = 1;
10012      goto meta_command_exit;
10013    }
10014    rc = sqlite3_open(zSrcFile, &pSrc);
10015    if( rc!=SQLITE_OK ){
10016      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10017      close_db(pSrc);
10018      return 1;
10019    }
10020    open_db(p, 0);
10021    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10022    if( pBackup==0 ){
10023      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10024      close_db(pSrc);
10025      return 1;
10026    }
10027    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10028          || rc==SQLITE_BUSY  ){
10029      if( rc==SQLITE_BUSY ){
10030        if( nTimeout++ >= 3 ) break;
10031        sqlite3_sleep(100);
10032      }
10033    }
10034    sqlite3_backup_finish(pBackup);
10035    if( rc==SQLITE_DONE ){
10036      rc = 0;
10037    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10038      raw_printf(stderr, "Error: source database is busy\n");
10039      rc = 1;
10040    }else{
10041      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10042      rc = 1;
10043    }
10044    close_db(pSrc);
10045  }else
10046#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10047
10048  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10049    if( nArg==2 ){
10050      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10051#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10052      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10053#endif
10054    }else{
10055      raw_printf(stderr, "Usage: .scanstats on|off\n");
10056      rc = 1;
10057    }
10058  }else
10059
10060  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10061    ShellText sSelect;
10062    ShellState data;
10063    char *zErrMsg = 0;
10064    const char *zDiv = "(";
10065    const char *zName = 0;
10066    int iSchema = 0;
10067    int bDebug = 0;
10068    int bNoSystemTabs = 0;
10069    int ii;
10070
10071    open_db(p, 0);
10072    memcpy(&data, p, sizeof(data));
10073    data.showHeader = 0;
10074    data.cMode = data.mode = MODE_Semi;
10075    initText(&sSelect);
10076    for(ii=1; ii<nArg; ii++){
10077      if( optionMatch(azArg[ii],"indent") ){
10078        data.cMode = data.mode = MODE_Pretty;
10079      }else if( optionMatch(azArg[ii],"debug") ){
10080        bDebug = 1;
10081      }else if( optionMatch(azArg[ii],"nosys") ){
10082        bNoSystemTabs = 1;
10083      }else if( azArg[ii][0]=='-' ){
10084        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10085        rc = 1;
10086        goto meta_command_exit;
10087      }else if( zName==0 ){
10088        zName = azArg[ii];
10089      }else{
10090        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10091        rc = 1;
10092        goto meta_command_exit;
10093      }
10094    }
10095    if( zName!=0 ){
10096      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10097                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10098                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10099                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10100      if( isSchema ){
10101        char *new_argv[2], *new_colv[2];
10102        new_argv[0] = sqlite3_mprintf(
10103                      "CREATE TABLE %s (\n"
10104                      "  type text,\n"
10105                      "  name text,\n"
10106                      "  tbl_name text,\n"
10107                      "  rootpage integer,\n"
10108                      "  sql text\n"
10109                      ")", zName);
10110        shell_check_oom(new_argv[0]);
10111        new_argv[1] = 0;
10112        new_colv[0] = "sql";
10113        new_colv[1] = 0;
10114        callback(&data, 1, new_argv, new_colv);
10115        sqlite3_free(new_argv[0]);
10116      }
10117    }
10118    if( zDiv ){
10119      sqlite3_stmt *pStmt = 0;
10120      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10121                              -1, &pStmt, 0);
10122      if( rc ){
10123        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10124        sqlite3_finalize(pStmt);
10125        rc = 1;
10126        goto meta_command_exit;
10127      }
10128      appendText(&sSelect, "SELECT sql FROM", 0);
10129      iSchema = 0;
10130      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10131        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10132        char zScNum[30];
10133        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10134        appendText(&sSelect, zDiv, 0);
10135        zDiv = " UNION ALL ";
10136        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10137        if( sqlite3_stricmp(zDb, "main")!=0 ){
10138          appendText(&sSelect, zDb, '\'');
10139        }else{
10140          appendText(&sSelect, "NULL", 0);
10141        }
10142        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10143        appendText(&sSelect, zScNum, 0);
10144        appendText(&sSelect, " AS snum, ", 0);
10145        appendText(&sSelect, zDb, '\'');
10146        appendText(&sSelect, " AS sname FROM ", 0);
10147        appendText(&sSelect, zDb, quoteChar(zDb));
10148        appendText(&sSelect, ".sqlite_schema", 0);
10149      }
10150      sqlite3_finalize(pStmt);
10151#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10152      if( zName ){
10153        appendText(&sSelect,
10154           " UNION ALL SELECT shell_module_schema(name),"
10155           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10156        0);
10157      }
10158#endif
10159      appendText(&sSelect, ") WHERE ", 0);
10160      if( zName ){
10161        char *zQarg = sqlite3_mprintf("%Q", zName);
10162        int bGlob;
10163        shell_check_oom(zQarg);
10164        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10165                strchr(zName, '[') != 0;
10166        if( strchr(zName, '.') ){
10167          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10168        }else{
10169          appendText(&sSelect, "lower(tbl_name)", 0);
10170        }
10171        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10172        appendText(&sSelect, zQarg, 0);
10173        if( !bGlob ){
10174          appendText(&sSelect, " ESCAPE '\\' ", 0);
10175        }
10176        appendText(&sSelect, " AND ", 0);
10177        sqlite3_free(zQarg);
10178      }
10179      if( bNoSystemTabs ){
10180        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10181      }
10182      appendText(&sSelect, "sql IS NOT NULL"
10183                           " ORDER BY snum, rowid", 0);
10184      if( bDebug ){
10185        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10186      }else{
10187        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10188      }
10189      freeText(&sSelect);
10190    }
10191    if( zErrMsg ){
10192      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10193      sqlite3_free(zErrMsg);
10194      rc = 1;
10195    }else if( rc != SQLITE_OK ){
10196      raw_printf(stderr,"Error: querying schema information\n");
10197      rc = 1;
10198    }else{
10199      rc = 0;
10200    }
10201  }else
10202
10203  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10204   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10205  ){
10206    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10207    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10208  }else
10209
10210#if defined(SQLITE_ENABLE_SESSION)
10211  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10212    struct AuxDb *pAuxDb = p->pAuxDb;
10213    OpenSession *pSession = &pAuxDb->aSession[0];
10214    char **azCmd = &azArg[1];
10215    int iSes = 0;
10216    int nCmd = nArg - 1;
10217    int i;
10218    if( nArg<=1 ) goto session_syntax_error;
10219    open_db(p, 0);
10220    if( nArg>=3 ){
10221      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10222        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10223      }
10224      if( iSes<pAuxDb->nSession ){
10225        pSession = &pAuxDb->aSession[iSes];
10226        azCmd++;
10227        nCmd--;
10228      }else{
10229        pSession = &pAuxDb->aSession[0];
10230        iSes = 0;
10231      }
10232    }
10233
10234    /* .session attach TABLE
10235    ** Invoke the sqlite3session_attach() interface to attach a particular
10236    ** table so that it is never filtered.
10237    */
10238    if( strcmp(azCmd[0],"attach")==0 ){
10239      if( nCmd!=2 ) goto session_syntax_error;
10240      if( pSession->p==0 ){
10241        session_not_open:
10242        raw_printf(stderr, "ERROR: No sessions are open\n");
10243      }else{
10244        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10245        if( rc ){
10246          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10247          rc = 0;
10248        }
10249      }
10250    }else
10251
10252    /* .session changeset FILE
10253    ** .session patchset FILE
10254    ** Write a changeset or patchset into a file.  The file is overwritten.
10255    */
10256    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10257      FILE *out = 0;
10258      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10259      if( nCmd!=2 ) goto session_syntax_error;
10260      if( pSession->p==0 ) goto session_not_open;
10261      out = fopen(azCmd[1], "wb");
10262      if( out==0 ){
10263        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10264                    azCmd[1]);
10265      }else{
10266        int szChng;
10267        void *pChng;
10268        if( azCmd[0][0]=='c' ){
10269          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10270        }else{
10271          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10272        }
10273        if( rc ){
10274          printf("Error: error code %d\n", rc);
10275          rc = 0;
10276        }
10277        if( pChng
10278          && fwrite(pChng, szChng, 1, out)!=1 ){
10279          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10280                  szChng);
10281        }
10282        sqlite3_free(pChng);
10283        fclose(out);
10284      }
10285    }else
10286
10287    /* .session close
10288    ** Close the identified session
10289    */
10290    if( strcmp(azCmd[0], "close")==0 ){
10291      if( nCmd!=1 ) goto session_syntax_error;
10292      if( pAuxDb->nSession ){
10293        session_close(pSession);
10294        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10295      }
10296    }else
10297
10298    /* .session enable ?BOOLEAN?
10299    ** Query or set the enable flag
10300    */
10301    if( strcmp(azCmd[0], "enable")==0 ){
10302      int ii;
10303      if( nCmd>2 ) goto session_syntax_error;
10304      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10305      if( pAuxDb->nSession ){
10306        ii = sqlite3session_enable(pSession->p, ii);
10307        utf8_printf(p->out, "session %s enable flag = %d\n",
10308                    pSession->zName, ii);
10309      }
10310    }else
10311
10312    /* .session filter GLOB ....
10313    ** Set a list of GLOB patterns of table names to be excluded.
10314    */
10315    if( strcmp(azCmd[0], "filter")==0 ){
10316      int ii, nByte;
10317      if( nCmd<2 ) goto session_syntax_error;
10318      if( pAuxDb->nSession ){
10319        for(ii=0; ii<pSession->nFilter; ii++){
10320          sqlite3_free(pSession->azFilter[ii]);
10321        }
10322        sqlite3_free(pSession->azFilter);
10323        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10324        pSession->azFilter = sqlite3_malloc( nByte );
10325        if( pSession->azFilter==0 ){
10326          raw_printf(stderr, "Error: out or memory\n");
10327          exit(1);
10328        }
10329        for(ii=1; ii<nCmd; ii++){
10330          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10331          shell_check_oom(x);
10332        }
10333        pSession->nFilter = ii-1;
10334      }
10335    }else
10336
10337    /* .session indirect ?BOOLEAN?
10338    ** Query or set the indirect flag
10339    */
10340    if( strcmp(azCmd[0], "indirect")==0 ){
10341      int ii;
10342      if( nCmd>2 ) goto session_syntax_error;
10343      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10344      if( pAuxDb->nSession ){
10345        ii = sqlite3session_indirect(pSession->p, ii);
10346        utf8_printf(p->out, "session %s indirect flag = %d\n",
10347                    pSession->zName, ii);
10348      }
10349    }else
10350
10351    /* .session isempty
10352    ** Determine if the session is empty
10353    */
10354    if( strcmp(azCmd[0], "isempty")==0 ){
10355      int ii;
10356      if( nCmd!=1 ) goto session_syntax_error;
10357      if( pAuxDb->nSession ){
10358        ii = sqlite3session_isempty(pSession->p);
10359        utf8_printf(p->out, "session %s isempty flag = %d\n",
10360                    pSession->zName, ii);
10361      }
10362    }else
10363
10364    /* .session list
10365    ** List all currently open sessions
10366    */
10367    if( strcmp(azCmd[0],"list")==0 ){
10368      for(i=0; i<pAuxDb->nSession; i++){
10369        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10370      }
10371    }else
10372
10373    /* .session open DB NAME
10374    ** Open a new session called NAME on the attached database DB.
10375    ** DB is normally "main".
10376    */
10377    if( strcmp(azCmd[0],"open")==0 ){
10378      char *zName;
10379      if( nCmd!=3 ) goto session_syntax_error;
10380      zName = azCmd[2];
10381      if( zName[0]==0 ) goto session_syntax_error;
10382      for(i=0; i<pAuxDb->nSession; i++){
10383        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10384          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10385          goto meta_command_exit;
10386        }
10387      }
10388      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10389        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10390        goto meta_command_exit;
10391      }
10392      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10393      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10394      if( rc ){
10395        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10396        rc = 0;
10397        goto meta_command_exit;
10398      }
10399      pSession->nFilter = 0;
10400      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10401      pAuxDb->nSession++;
10402      pSession->zName = sqlite3_mprintf("%s", zName);
10403      shell_check_oom(pSession->zName);
10404    }else
10405    /* If no command name matches, show a syntax error */
10406    session_syntax_error:
10407    showHelp(p->out, "session");
10408  }else
10409#endif
10410
10411#ifdef SQLITE_DEBUG
10412  /* Undocumented commands for internal testing.  Subject to change
10413  ** without notice. */
10414  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10415    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10416      int i, v;
10417      for(i=1; i<nArg; i++){
10418        v = booleanValue(azArg[i]);
10419        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10420      }
10421    }
10422    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10423      int i; sqlite3_int64 v;
10424      for(i=1; i<nArg; i++){
10425        char zBuf[200];
10426        v = integerValue(azArg[i]);
10427        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10428        utf8_printf(p->out, "%s", zBuf);
10429      }
10430    }
10431  }else
10432#endif
10433
10434  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10435    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10436    int bVerbose = 0;        /* Verbose output */
10437    int bSelftestExists;     /* True if SELFTEST already exists */
10438    int i, k;                /* Loop counters */
10439    int nTest = 0;           /* Number of tests runs */
10440    int nErr = 0;            /* Number of errors seen */
10441    ShellText str;           /* Answer for a query */
10442    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10443
10444    open_db(p,0);
10445    for(i=1; i<nArg; i++){
10446      const char *z = azArg[i];
10447      if( z[0]=='-' && z[1]=='-' ) z++;
10448      if( strcmp(z,"-init")==0 ){
10449        bIsInit = 1;
10450      }else
10451      if( strcmp(z,"-v")==0 ){
10452        bVerbose++;
10453      }else
10454      {
10455        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10456                    azArg[i], azArg[0]);
10457        raw_printf(stderr, "Should be one of: --init -v\n");
10458        rc = 1;
10459        goto meta_command_exit;
10460      }
10461    }
10462    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10463           != SQLITE_OK ){
10464      bSelftestExists = 0;
10465    }else{
10466      bSelftestExists = 1;
10467    }
10468    if( bIsInit ){
10469      createSelftestTable(p);
10470      bSelftestExists = 1;
10471    }
10472    initText(&str);
10473    appendText(&str, "x", 0);
10474    for(k=bSelftestExists; k>=0; k--){
10475      if( k==1 ){
10476        rc = sqlite3_prepare_v2(p->db,
10477            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10478            -1, &pStmt, 0);
10479      }else{
10480        rc = sqlite3_prepare_v2(p->db,
10481          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10482          "      (1,'run','PRAGMA integrity_check','ok')",
10483          -1, &pStmt, 0);
10484      }
10485      if( rc ){
10486        raw_printf(stderr, "Error querying the selftest table\n");
10487        rc = 1;
10488        sqlite3_finalize(pStmt);
10489        goto meta_command_exit;
10490      }
10491      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10492        int tno = sqlite3_column_int(pStmt, 0);
10493        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10494        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10495        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10496
10497        if( zOp==0 ) continue;
10498        if( zSql==0 ) continue;
10499        if( zAns==0 ) continue;
10500        k = 0;
10501        if( bVerbose>0 ){
10502          printf("%d: %s %s\n", tno, zOp, zSql);
10503        }
10504        if( strcmp(zOp,"memo")==0 ){
10505          utf8_printf(p->out, "%s\n", zSql);
10506        }else
10507        if( strcmp(zOp,"run")==0 ){
10508          char *zErrMsg = 0;
10509          str.n = 0;
10510          str.z[0] = 0;
10511          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10512          nTest++;
10513          if( bVerbose ){
10514            utf8_printf(p->out, "Result: %s\n", str.z);
10515          }
10516          if( rc || zErrMsg ){
10517            nErr++;
10518            rc = 1;
10519            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10520            sqlite3_free(zErrMsg);
10521          }else if( strcmp(zAns,str.z)!=0 ){
10522            nErr++;
10523            rc = 1;
10524            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10525            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10526          }
10527        }else
10528        {
10529          utf8_printf(stderr,
10530            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10531          rc = 1;
10532          break;
10533        }
10534      } /* End loop over rows of content from SELFTEST */
10535      sqlite3_finalize(pStmt);
10536    } /* End loop over k */
10537    freeText(&str);
10538    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10539  }else
10540
10541  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10542    if( nArg<2 || nArg>3 ){
10543      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10544      rc = 1;
10545    }
10546    if( nArg>=2 ){
10547      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10548                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10549    }
10550    if( nArg>=3 ){
10551      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10552                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10553    }
10554  }else
10555
10556  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10557    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10558    int i;                   /* Loop counter */
10559    int bSchema = 0;         /* Also hash the schema */
10560    int bSeparate = 0;       /* Hash each table separately */
10561    int iSize = 224;         /* Hash algorithm to use */
10562    int bDebug = 0;          /* Only show the query that would have run */
10563    sqlite3_stmt *pStmt;     /* For querying tables names */
10564    char *zSql;              /* SQL to be run */
10565    char *zSep;              /* Separator */
10566    ShellText sSql;          /* Complete SQL for the query to run the hash */
10567    ShellText sQuery;        /* Set of queries used to read all content */
10568    open_db(p, 0);
10569    for(i=1; i<nArg; i++){
10570      const char *z = azArg[i];
10571      if( z[0]=='-' ){
10572        z++;
10573        if( z[0]=='-' ) z++;
10574        if( strcmp(z,"schema")==0 ){
10575          bSchema = 1;
10576        }else
10577        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10578         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10579        ){
10580          iSize = atoi(&z[5]);
10581        }else
10582        if( strcmp(z,"debug")==0 ){
10583          bDebug = 1;
10584        }else
10585        {
10586          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10587                      azArg[i], azArg[0]);
10588          showHelp(p->out, azArg[0]);
10589          rc = 1;
10590          goto meta_command_exit;
10591        }
10592      }else if( zLike ){
10593        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10594        rc = 1;
10595        goto meta_command_exit;
10596      }else{
10597        zLike = z;
10598        bSeparate = 1;
10599        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10600      }
10601    }
10602    if( bSchema ){
10603      zSql = "SELECT lower(name) FROM sqlite_schema"
10604             " WHERE type='table' AND coalesce(rootpage,0)>1"
10605             " UNION ALL SELECT 'sqlite_schema'"
10606             " ORDER BY 1 collate nocase";
10607    }else{
10608      zSql = "SELECT lower(name) FROM sqlite_schema"
10609             " WHERE type='table' AND coalesce(rootpage,0)>1"
10610             " AND name NOT LIKE 'sqlite_%'"
10611             " ORDER BY 1 collate nocase";
10612    }
10613    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10614    initText(&sQuery);
10615    initText(&sSql);
10616    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10617    zSep = "VALUES(";
10618    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10619      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10620      if( zTab==0 ) continue;
10621      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10622      if( strncmp(zTab, "sqlite_",7)!=0 ){
10623        appendText(&sQuery,"SELECT * FROM ", 0);
10624        appendText(&sQuery,zTab,'"');
10625        appendText(&sQuery," NOT INDEXED;", 0);
10626      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10627        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10628                           " ORDER BY name;", 0);
10629      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10630        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10631                           " ORDER BY name;", 0);
10632      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10633        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10634                           " ORDER BY tbl,idx;", 0);
10635      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10636        appendText(&sQuery, "SELECT * FROM ", 0);
10637        appendText(&sQuery, zTab, 0);
10638        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10639      }
10640      appendText(&sSql, zSep, 0);
10641      appendText(&sSql, sQuery.z, '\'');
10642      sQuery.n = 0;
10643      appendText(&sSql, ",", 0);
10644      appendText(&sSql, zTab, '\'');
10645      zSep = "),(";
10646    }
10647    sqlite3_finalize(pStmt);
10648    if( bSeparate ){
10649      zSql = sqlite3_mprintf(
10650          "%s))"
10651          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10652          "   FROM [sha3sum$query]",
10653          sSql.z, iSize);
10654    }else{
10655      zSql = sqlite3_mprintf(
10656          "%s))"
10657          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10658          "   FROM [sha3sum$query]",
10659          sSql.z, iSize);
10660    }
10661    shell_check_oom(zSql);
10662    freeText(&sQuery);
10663    freeText(&sSql);
10664    if( bDebug ){
10665      utf8_printf(p->out, "%s\n", zSql);
10666    }else{
10667      shell_exec(p, zSql, 0);
10668    }
10669    sqlite3_free(zSql);
10670  }else
10671
10672#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
10673  if( c=='s'
10674   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10675  ){
10676    char *zCmd;
10677    int i, x;
10678    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10679    if( nArg<2 ){
10680      raw_printf(stderr, "Usage: .system COMMAND\n");
10681      rc = 1;
10682      goto meta_command_exit;
10683    }
10684    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10685    for(i=2; i<nArg && zCmd!=0; i++){
10686      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10687                             zCmd, azArg[i]);
10688    }
10689    x = zCmd!=0 ? system(zCmd) : 1;
10690    sqlite3_free(zCmd);
10691    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10692  }else
10693#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE) */
10694
10695  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10696    static const char *azBool[] = { "off", "on", "trigger", "full"};
10697    const char *zOut;
10698    int i;
10699    if( nArg!=1 ){
10700      raw_printf(stderr, "Usage: .show\n");
10701      rc = 1;
10702      goto meta_command_exit;
10703    }
10704    utf8_printf(p->out, "%12.12s: %s\n","echo",
10705                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10706    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10707    utf8_printf(p->out, "%12.12s: %s\n","explain",
10708         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10709    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10710    if( p->mode==MODE_Column
10711     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10712    ){
10713      utf8_printf
10714        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10715         modeDescr[p->mode], p->cmOpts.iWrap,
10716         p->cmOpts.bWordWrap ? "on" : "off",
10717         p->cmOpts.bQuote ? "" : "no");
10718    }else{
10719      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10720    }
10721    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10722      output_c_string(p->out, p->nullValue);
10723      raw_printf(p->out, "\n");
10724    utf8_printf(p->out,"%12.12s: %s\n","output",
10725            strlen30(p->outfile) ? p->outfile : "stdout");
10726    utf8_printf(p->out,"%12.12s: ", "colseparator");
10727      output_c_string(p->out, p->colSeparator);
10728      raw_printf(p->out, "\n");
10729    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10730      output_c_string(p->out, p->rowSeparator);
10731      raw_printf(p->out, "\n");
10732    switch( p->statsOn ){
10733      case 0:  zOut = "off";     break;
10734      default: zOut = "on";      break;
10735      case 2:  zOut = "stmt";    break;
10736      case 3:  zOut = "vmstep";  break;
10737    }
10738    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10739    utf8_printf(p->out, "%12.12s: ", "width");
10740    for (i=0;i<p->nWidth;i++) {
10741      raw_printf(p->out, "%d ", p->colWidth[i]);
10742    }
10743    raw_printf(p->out, "\n");
10744    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10745                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10746  }else
10747
10748  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10749    if( nArg==2 ){
10750      if( strcmp(azArg[1],"stmt")==0 ){
10751        p->statsOn = 2;
10752      }else if( strcmp(azArg[1],"vmstep")==0 ){
10753        p->statsOn = 3;
10754      }else{
10755        p->statsOn = (u8)booleanValue(azArg[1]);
10756      }
10757    }else if( nArg==1 ){
10758      display_stats(p->db, p, 0);
10759    }else{
10760      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10761      rc = 1;
10762    }
10763  }else
10764
10765  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10766   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10767                 || strncmp(azArg[0], "indexes", n)==0) )
10768  ){
10769    sqlite3_stmt *pStmt;
10770    char **azResult;
10771    int nRow, nAlloc;
10772    int ii;
10773    ShellText s;
10774    initText(&s);
10775    open_db(p, 0);
10776    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10777    if( rc ){
10778      sqlite3_finalize(pStmt);
10779      return shellDatabaseError(p->db);
10780    }
10781
10782    if( nArg>2 && c=='i' ){
10783      /* It is an historical accident that the .indexes command shows an error
10784      ** when called with the wrong number of arguments whereas the .tables
10785      ** command does not. */
10786      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10787      rc = 1;
10788      sqlite3_finalize(pStmt);
10789      goto meta_command_exit;
10790    }
10791    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10792      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10793      if( zDbName==0 ) continue;
10794      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10795      if( sqlite3_stricmp(zDbName, "main")==0 ){
10796        appendText(&s, "SELECT name FROM ", 0);
10797      }else{
10798        appendText(&s, "SELECT ", 0);
10799        appendText(&s, zDbName, '\'');
10800        appendText(&s, "||'.'||name FROM ", 0);
10801      }
10802      appendText(&s, zDbName, '"');
10803      appendText(&s, ".sqlite_schema ", 0);
10804      if( c=='t' ){
10805        appendText(&s," WHERE type IN ('table','view')"
10806                      "   AND name NOT LIKE 'sqlite_%'"
10807                      "   AND name LIKE ?1", 0);
10808      }else{
10809        appendText(&s," WHERE type='index'"
10810                      "   AND tbl_name LIKE ?1", 0);
10811      }
10812    }
10813    rc = sqlite3_finalize(pStmt);
10814    if( rc==SQLITE_OK ){
10815      appendText(&s, " ORDER BY 1", 0);
10816      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10817    }
10818    freeText(&s);
10819    if( rc ) return shellDatabaseError(p->db);
10820
10821    /* Run the SQL statement prepared by the above block. Store the results
10822    ** as an array of nul-terminated strings in azResult[].  */
10823    nRow = nAlloc = 0;
10824    azResult = 0;
10825    if( nArg>1 ){
10826      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10827    }else{
10828      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10829    }
10830    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10831      if( nRow>=nAlloc ){
10832        char **azNew;
10833        int n2 = nAlloc*2 + 10;
10834        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10835        shell_check_oom(azNew);
10836        nAlloc = n2;
10837        azResult = azNew;
10838      }
10839      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10840      shell_check_oom(azResult[nRow]);
10841      nRow++;
10842    }
10843    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10844      rc = shellDatabaseError(p->db);
10845    }
10846
10847    /* Pretty-print the contents of array azResult[] to the output */
10848    if( rc==0 && nRow>0 ){
10849      int len, maxlen = 0;
10850      int i, j;
10851      int nPrintCol, nPrintRow;
10852      for(i=0; i<nRow; i++){
10853        len = strlen30(azResult[i]);
10854        if( len>maxlen ) maxlen = len;
10855      }
10856      nPrintCol = 80/(maxlen+2);
10857      if( nPrintCol<1 ) nPrintCol = 1;
10858      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10859      for(i=0; i<nPrintRow; i++){
10860        for(j=i; j<nRow; j+=nPrintRow){
10861          char *zSp = j<nPrintRow ? "" : "  ";
10862          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10863                      azResult[j] ? azResult[j]:"");
10864        }
10865        raw_printf(p->out, "\n");
10866      }
10867    }
10868
10869    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10870    sqlite3_free(azResult);
10871  }else
10872
10873#ifndef SQLITE_SHELL_WASM_MODE
10874  /* Begin redirecting output to the file "testcase-out.txt" */
10875  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10876    output_reset(p);
10877    p->out = output_file_open("testcase-out.txt", 0);
10878    if( p->out==0 ){
10879      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10880    }
10881    if( nArg>=2 ){
10882      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10883    }else{
10884      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10885    }
10886  }else
10887#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10888
10889#ifndef SQLITE_UNTESTABLE
10890  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10891    static const struct {
10892       const char *zCtrlName;   /* Name of a test-control option */
10893       int ctrlCode;            /* Integer code for that option */
10894       int unSafe;              /* Not valid for --safe mode */
10895       const char *zUsage;      /* Usage notes */
10896    } aCtrl[] = {
10897      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10898      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10899    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10900    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10901      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10902      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10903    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10904      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10905      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10906      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10907      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10908      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10909#ifdef YYCOVERAGE
10910      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10911#endif
10912      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10913      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10914      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10915      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10916      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10917      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10918      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10919    };
10920    int testctrl = -1;
10921    int iCtrl = -1;
10922    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10923    int isOk = 0;
10924    int i, n2;
10925    const char *zCmd = 0;
10926
10927    open_db(p, 0);
10928    zCmd = nArg>=2 ? azArg[1] : "help";
10929
10930    /* The argument can optionally begin with "-" or "--" */
10931    if( zCmd[0]=='-' && zCmd[1] ){
10932      zCmd++;
10933      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10934    }
10935
10936    /* --help lists all test-controls */
10937    if( strcmp(zCmd,"help")==0 ){
10938      utf8_printf(p->out, "Available test-controls:\n");
10939      for(i=0; i<ArraySize(aCtrl); i++){
10940        utf8_printf(p->out, "  .testctrl %s %s\n",
10941                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10942      }
10943      rc = 1;
10944      goto meta_command_exit;
10945    }
10946
10947    /* convert testctrl text option to value. allow any unique prefix
10948    ** of the option name, or a numerical value. */
10949    n2 = strlen30(zCmd);
10950    for(i=0; i<ArraySize(aCtrl); i++){
10951      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10952        if( testctrl<0 ){
10953          testctrl = aCtrl[i].ctrlCode;
10954          iCtrl = i;
10955        }else{
10956          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10957                              "Use \".testctrl --help\" for help\n", zCmd);
10958          rc = 1;
10959          goto meta_command_exit;
10960        }
10961      }
10962    }
10963    if( testctrl<0 ){
10964      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10965                         "Use \".testctrl --help\" for help\n", zCmd);
10966    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10967      utf8_printf(stderr,
10968         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10969         p->lineno, aCtrl[iCtrl].zCtrlName);
10970      exit(1);
10971    }else{
10972      switch(testctrl){
10973
10974        /* sqlite3_test_control(int, db, int) */
10975        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10976          if( nArg==3 ){
10977            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10978            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10979            isOk = 3;
10980          }
10981          break;
10982
10983        /* sqlite3_test_control(int) */
10984        case SQLITE_TESTCTRL_PRNG_SAVE:
10985        case SQLITE_TESTCTRL_PRNG_RESTORE:
10986        case SQLITE_TESTCTRL_BYTEORDER:
10987          if( nArg==2 ){
10988            rc2 = sqlite3_test_control(testctrl);
10989            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10990          }
10991          break;
10992
10993        /* sqlite3_test_control(int, uint) */
10994        case SQLITE_TESTCTRL_PENDING_BYTE:
10995          if( nArg==3 ){
10996            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10997            rc2 = sqlite3_test_control(testctrl, opt);
10998            isOk = 3;
10999          }
11000          break;
11001
11002        /* sqlite3_test_control(int, int, sqlite3*) */
11003        case SQLITE_TESTCTRL_PRNG_SEED:
11004          if( nArg==3 || nArg==4 ){
11005            int ii = (int)integerValue(azArg[2]);
11006            sqlite3 *db;
11007            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11008              sqlite3_randomness(sizeof(ii),&ii);
11009              printf("-- random seed: %d\n", ii);
11010            }
11011            if( nArg==3 ){
11012              db = 0;
11013            }else{
11014              db = p->db;
11015              /* Make sure the schema has been loaded */
11016              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11017            }
11018            rc2 = sqlite3_test_control(testctrl, ii, db);
11019            isOk = 3;
11020          }
11021          break;
11022
11023        /* sqlite3_test_control(int, int) */
11024        case SQLITE_TESTCTRL_ASSERT:
11025        case SQLITE_TESTCTRL_ALWAYS:
11026          if( nArg==3 ){
11027            int opt = booleanValue(azArg[2]);
11028            rc2 = sqlite3_test_control(testctrl, opt);
11029            isOk = 1;
11030          }
11031          break;
11032
11033        /* sqlite3_test_control(int, int) */
11034        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11035        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11036          if( nArg==3 ){
11037            int opt = booleanValue(azArg[2]);
11038            rc2 = sqlite3_test_control(testctrl, opt);
11039            isOk = 3;
11040          }
11041          break;
11042
11043        /* sqlite3_test_control(sqlite3*) */
11044        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11045          rc2 = sqlite3_test_control(testctrl, p->db);
11046          isOk = 3;
11047          break;
11048
11049        case SQLITE_TESTCTRL_IMPOSTER:
11050          if( nArg==5 ){
11051            rc2 = sqlite3_test_control(testctrl, p->db,
11052                          azArg[2],
11053                          integerValue(azArg[3]),
11054                          integerValue(azArg[4]));
11055            isOk = 3;
11056          }
11057          break;
11058
11059        case SQLITE_TESTCTRL_SEEK_COUNT: {
11060          u64 x = 0;
11061          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11062          utf8_printf(p->out, "%llu\n", x);
11063          isOk = 3;
11064          break;
11065        }
11066
11067#ifdef YYCOVERAGE
11068        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11069          if( nArg==2 ){
11070            sqlite3_test_control(testctrl, p->out);
11071            isOk = 3;
11072          }
11073          break;
11074        }
11075#endif
11076#ifdef SQLITE_DEBUG
11077        case SQLITE_TESTCTRL_TUNE: {
11078          if( nArg==4 ){
11079            int id = (int)integerValue(azArg[2]);
11080            int val = (int)integerValue(azArg[3]);
11081            sqlite3_test_control(testctrl, id, &val);
11082            isOk = 3;
11083          }else if( nArg==3 ){
11084            int id = (int)integerValue(azArg[2]);
11085            sqlite3_test_control(testctrl, -id, &rc2);
11086            isOk = 1;
11087          }else if( nArg==2 ){
11088            int id = 1;
11089            while(1){
11090              int val = 0;
11091              rc2 = sqlite3_test_control(testctrl, -id, &val);
11092              if( rc2!=SQLITE_OK ) break;
11093              if( id>1 ) utf8_printf(p->out, "  ");
11094              utf8_printf(p->out, "%d: %d", id, val);
11095              id++;
11096            }
11097            if( id>1 ) utf8_printf(p->out, "\n");
11098            isOk = 3;
11099          }
11100          break;
11101        }
11102#endif
11103        case SQLITE_TESTCTRL_SORTER_MMAP:
11104          if( nArg==3 ){
11105            int opt = (unsigned int)integerValue(azArg[2]);
11106            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11107            isOk = 3;
11108          }
11109          break;
11110      }
11111    }
11112    if( isOk==0 && iCtrl>=0 ){
11113      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11114      rc = 1;
11115    }else if( isOk==1 ){
11116      raw_printf(p->out, "%d\n", rc2);
11117    }else if( isOk==2 ){
11118      raw_printf(p->out, "0x%08x\n", rc2);
11119    }
11120  }else
11121#endif /* !defined(SQLITE_UNTESTABLE) */
11122
11123  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11124    open_db(p, 0);
11125    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11126  }else
11127
11128  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11129    if( nArg==2 ){
11130      enableTimer = booleanValue(azArg[1]);
11131      if( enableTimer && !HAS_TIMER ){
11132        raw_printf(stderr, "Error: timer not available on this system.\n");
11133        enableTimer = 0;
11134      }
11135    }else{
11136      raw_printf(stderr, "Usage: .timer on|off\n");
11137      rc = 1;
11138    }
11139  }else
11140
11141#ifndef SQLITE_OMIT_TRACE
11142  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11143    int mType = 0;
11144    int jj;
11145    open_db(p, 0);
11146    for(jj=1; jj<nArg; jj++){
11147      const char *z = azArg[jj];
11148      if( z[0]=='-' ){
11149        if( optionMatch(z, "expanded") ){
11150          p->eTraceType = SHELL_TRACE_EXPANDED;
11151        }
11152#ifdef SQLITE_ENABLE_NORMALIZE
11153        else if( optionMatch(z, "normalized") ){
11154          p->eTraceType = SHELL_TRACE_NORMALIZED;
11155        }
11156#endif
11157        else if( optionMatch(z, "plain") ){
11158          p->eTraceType = SHELL_TRACE_PLAIN;
11159        }
11160        else if( optionMatch(z, "profile") ){
11161          mType |= SQLITE_TRACE_PROFILE;
11162        }
11163        else if( optionMatch(z, "row") ){
11164          mType |= SQLITE_TRACE_ROW;
11165        }
11166        else if( optionMatch(z, "stmt") ){
11167          mType |= SQLITE_TRACE_STMT;
11168        }
11169        else if( optionMatch(z, "close") ){
11170          mType |= SQLITE_TRACE_CLOSE;
11171        }
11172        else {
11173          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11174          rc = 1;
11175          goto meta_command_exit;
11176        }
11177      }else{
11178        output_file_close(p->traceOut);
11179        p->traceOut = output_file_open(azArg[1], 0);
11180      }
11181    }
11182    if( p->traceOut==0 ){
11183      sqlite3_trace_v2(p->db, 0, 0, 0);
11184    }else{
11185      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11186      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11187    }
11188  }else
11189#endif /* !defined(SQLITE_OMIT_TRACE) */
11190
11191#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11192  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11193    int ii;
11194    int lenOpt;
11195    char *zOpt;
11196    if( nArg<2 ){
11197      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11198      rc = 1;
11199      goto meta_command_exit;
11200    }
11201    open_db(p, 0);
11202    zOpt = azArg[1];
11203    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11204    lenOpt = (int)strlen(zOpt);
11205    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11206      assert( azArg[nArg]==0 );
11207      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11208    }else{
11209      for(ii=1; ii<nArg; ii++){
11210        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11211      }
11212    }
11213  }else
11214#endif
11215
11216#if SQLITE_USER_AUTHENTICATION
11217  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11218    if( nArg<2 ){
11219      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11220      rc = 1;
11221      goto meta_command_exit;
11222    }
11223    open_db(p, 0);
11224    if( strcmp(azArg[1],"login")==0 ){
11225      if( nArg!=4 ){
11226        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11227        rc = 1;
11228        goto meta_command_exit;
11229      }
11230      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11231                                     strlen30(azArg[3]));
11232      if( rc ){
11233        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11234        rc = 1;
11235      }
11236    }else if( strcmp(azArg[1],"add")==0 ){
11237      if( nArg!=5 ){
11238        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11239        rc = 1;
11240        goto meta_command_exit;
11241      }
11242      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11243                            booleanValue(azArg[4]));
11244      if( rc ){
11245        raw_printf(stderr, "User-Add failed: %d\n", rc);
11246        rc = 1;
11247      }
11248    }else if( strcmp(azArg[1],"edit")==0 ){
11249      if( nArg!=5 ){
11250        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11251        rc = 1;
11252        goto meta_command_exit;
11253      }
11254      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11255                              booleanValue(azArg[4]));
11256      if( rc ){
11257        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11258        rc = 1;
11259      }
11260    }else if( strcmp(azArg[1],"delete")==0 ){
11261      if( nArg!=3 ){
11262        raw_printf(stderr, "Usage: .user delete USER\n");
11263        rc = 1;
11264        goto meta_command_exit;
11265      }
11266      rc = sqlite3_user_delete(p->db, azArg[2]);
11267      if( rc ){
11268        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11269        rc = 1;
11270      }
11271    }else{
11272      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11273      rc = 1;
11274      goto meta_command_exit;
11275    }
11276  }else
11277#endif /* SQLITE_USER_AUTHENTICATION */
11278
11279  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11280    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11281        sqlite3_libversion(), sqlite3_sourceid());
11282#if SQLITE_HAVE_ZLIB
11283    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11284#endif
11285#define CTIMEOPT_VAL_(opt) #opt
11286#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11287#if defined(__clang__) && defined(__clang_major__)
11288    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11289                    CTIMEOPT_VAL(__clang_minor__) "."
11290                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11291#elif defined(_MSC_VER)
11292    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11293#elif defined(__GNUC__) && defined(__VERSION__)
11294    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11295#endif
11296  }else
11297
11298  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11299    const char *zDbName = nArg==2 ? azArg[1] : "main";
11300    sqlite3_vfs *pVfs = 0;
11301    if( p->db ){
11302      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11303      if( pVfs ){
11304        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11305        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11306        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11307        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11308      }
11309    }
11310  }else
11311
11312  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11313    sqlite3_vfs *pVfs;
11314    sqlite3_vfs *pCurrent = 0;
11315    if( p->db ){
11316      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11317    }
11318    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11319      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11320           pVfs==pCurrent ? "  <--- CURRENT" : "");
11321      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11322      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11323      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11324      if( pVfs->pNext ){
11325        raw_printf(p->out, "-----------------------------------\n");
11326      }
11327    }
11328  }else
11329
11330  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11331    const char *zDbName = nArg==2 ? azArg[1] : "main";
11332    char *zVfsName = 0;
11333    if( p->db ){
11334      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11335      if( zVfsName ){
11336        utf8_printf(p->out, "%s\n", zVfsName);
11337        sqlite3_free(zVfsName);
11338      }
11339    }
11340  }else
11341
11342  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11343    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11344    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11345  }else
11346
11347  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11348    int j;
11349    assert( nArg<=ArraySize(azArg) );
11350    p->nWidth = nArg-1;
11351    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11352    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11353    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11354    for(j=1; j<nArg; j++){
11355      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11356    }
11357  }else
11358
11359  {
11360    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11361      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11362    rc = 1;
11363  }
11364
11365meta_command_exit:
11366  if( p->outCount ){
11367    p->outCount--;
11368    if( p->outCount==0 ) output_reset(p);
11369  }
11370  p->bSafeMode = p->bSafeModePersist;
11371  return rc;
11372}
11373
11374/* Line scan result and intermediate states (supporting scan resumption)
11375*/
11376#ifndef CHAR_BIT
11377# define CHAR_BIT 8
11378#endif
11379typedef enum {
11380  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11381  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11382  QSS_Start = 0
11383} QuickScanState;
11384#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11385#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11386#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11387#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11388#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11389
11390/*
11391** Scan line for classification to guide shell's handling.
11392** The scan is resumable for subsequent lines when prior
11393** return values are passed as the 2nd argument.
11394*/
11395static QuickScanState quickscan(char *zLine, QuickScanState qss){
11396  char cin;
11397  char cWait = (char)qss; /* intentional narrowing loss */
11398  if( cWait==0 ){
11399  PlainScan:
11400    assert( cWait==0 );
11401    while( (cin = *zLine++)!=0 ){
11402      if( IsSpace(cin) )
11403        continue;
11404      switch (cin){
11405      case '-':
11406        if( *zLine!='-' )
11407          break;
11408        while((cin = *++zLine)!=0 )
11409          if( cin=='\n')
11410            goto PlainScan;
11411        return qss;
11412      case ';':
11413        qss |= QSS_EndingSemi;
11414        continue;
11415      case '/':
11416        if( *zLine=='*' ){
11417          ++zLine;
11418          cWait = '*';
11419          qss = QSS_SETV(qss, cWait);
11420          goto TermScan;
11421        }
11422        break;
11423      case '[':
11424        cin = ']';
11425        /* fall thru */
11426      case '`': case '\'': case '"':
11427        cWait = cin;
11428        qss = QSS_HasDark | cWait;
11429        goto TermScan;
11430      default:
11431        break;
11432      }
11433      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11434    }
11435  }else{
11436  TermScan:
11437    while( (cin = *zLine++)!=0 ){
11438      if( cin==cWait ){
11439        switch( cWait ){
11440        case '*':
11441          if( *zLine != '/' )
11442            continue;
11443          ++zLine;
11444          cWait = 0;
11445          qss = QSS_SETV(qss, 0);
11446          goto PlainScan;
11447        case '`': case '\'': case '"':
11448          if(*zLine==cWait){
11449            ++zLine;
11450            continue;
11451          }
11452          /* fall thru */
11453        case ']':
11454          cWait = 0;
11455          qss = QSS_SETV(qss, 0);
11456          goto PlainScan;
11457        default: assert(0);
11458        }
11459      }
11460    }
11461  }
11462  return qss;
11463}
11464
11465/*
11466** Return TRUE if the line typed in is an SQL command terminator other
11467** than a semi-colon.  The SQL Server style "go" command is understood
11468** as is the Oracle "/".
11469*/
11470static int line_is_command_terminator(char *zLine){
11471  while( IsSpace(zLine[0]) ){ zLine++; };
11472  if( zLine[0]=='/' )
11473    zLine += 1; /* Oracle */
11474  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11475    zLine += 2; /* SQL Server */
11476  else
11477    return 0;
11478  return quickscan(zLine, QSS_Start)==QSS_Start;
11479}
11480
11481/*
11482** We need a default sqlite3_complete() implementation to use in case
11483** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11484** any arbitrary text is a complete SQL statement.  This is not very
11485** user-friendly, but it does seem to work.
11486*/
11487#ifdef SQLITE_OMIT_COMPLETE
11488#define sqlite3_complete(x) 1
11489#endif
11490
11491/*
11492** Return true if zSql is a complete SQL statement.  Return false if it
11493** ends in the middle of a string literal or C-style comment.
11494*/
11495static int line_is_complete(char *zSql, int nSql){
11496  int rc;
11497  if( zSql==0 ) return 1;
11498  zSql[nSql] = ';';
11499  zSql[nSql+1] = 0;
11500  rc = sqlite3_complete(zSql);
11501  zSql[nSql] = 0;
11502  return rc;
11503}
11504
11505/*
11506** Run a single line of SQL.  Return the number of errors.
11507*/
11508static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11509  int rc;
11510  char *zErrMsg = 0;
11511
11512  open_db(p, 0);
11513  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11514  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11515  BEGIN_TIMER;
11516  rc = shell_exec(p, zSql, &zErrMsg);
11517  END_TIMER;
11518  if( rc || zErrMsg ){
11519    char zPrefix[100];
11520    const char *zErrorTail;
11521    const char *zErrorType;
11522    if( zErrMsg==0 ){
11523      zErrorType = "Error";
11524      zErrorTail = sqlite3_errmsg(p->db);
11525    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11526      zErrorType = "Parse error";
11527      zErrorTail = &zErrMsg[12];
11528    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11529      zErrorType = "Runtime error";
11530      zErrorTail = &zErrMsg[10];
11531    }else{
11532      zErrorType = "Error";
11533      zErrorTail = zErrMsg;
11534    }
11535    if( in!=0 || !stdin_is_interactive ){
11536      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11537                       "%s near line %d:", zErrorType, startline);
11538    }else{
11539      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11540    }
11541    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11542    sqlite3_free(zErrMsg);
11543    zErrMsg = 0;
11544    return 1;
11545  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11546    char zLineBuf[2000];
11547    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11548            "changes: %lld   total_changes: %lld",
11549            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11550    raw_printf(p->out, "%s\n", zLineBuf);
11551  }
11552  return 0;
11553}
11554
11555static void echo_group_input(ShellState *p, const char *zDo){
11556  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11557}
11558
11559#ifdef SQLITE_SHELL_WASM_MODE
11560/*
11561** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11562** because we need the global shellState and cannot access it from that function
11563** without moving lots of code around (creating a larger/messier diff).
11564*/
11565static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11566  /* Parse the next line from shellState.wasm.zInput. */
11567  const char *zBegin = shellState.wasm.zPos;
11568  const char *z = zBegin;
11569  char *zLine = 0;
11570  int nZ = 0;
11571
11572  UNUSED_PARAMETER(in);
11573  UNUSED_PARAMETER(isContinuation);
11574  if(!z || !*z){
11575    return 0;
11576  }
11577  while(*z && isspace(*z)) ++z;
11578  zBegin = z;
11579  for(; *z && '\n'!=*z; ++nZ, ++z){}
11580  if(nZ>0 && '\r'==zBegin[nZ-1]){
11581    --nZ;
11582  }
11583  shellState.wasm.zPos = z;
11584  zLine = realloc(zPrior, nZ+1);
11585  shell_check_oom(zLine);
11586  memcpy(zLine, zBegin, (size_t)nZ);
11587  zLine[nZ] = 0;
11588  return zLine;
11589}
11590#endif /* SQLITE_SHELL_WASM_MODE */
11591
11592/*
11593** Read input from *in and process it.  If *in==0 then input
11594** is interactive - the user is typing it it.  Otherwise, input
11595** is coming from a file or device.  A prompt is issued and history
11596** is saved only if input is interactive.  An interrupt signal will
11597** cause this routine to exit immediately, unless input is interactive.
11598**
11599** Return the number of errors.
11600*/
11601static int process_input(ShellState *p){
11602  char *zLine = 0;          /* A single input line */
11603  char *zSql = 0;           /* Accumulated SQL text */
11604  int nLine;                /* Length of current line */
11605  int nSql = 0;             /* Bytes of zSql[] used */
11606  int nAlloc = 0;           /* Allocated zSql[] space */
11607  int rc;                   /* Error code */
11608  int errCnt = 0;           /* Number of errors seen */
11609  int startline = 0;        /* Line number for start of current input */
11610  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11611
11612  if( p->inputNesting==MAX_INPUT_NESTING ){
11613    /* This will be more informative in a later version. */
11614    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11615                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11616    return 1;
11617  }
11618  ++p->inputNesting;
11619  p->lineno = 0;
11620  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11621    fflush(p->out);
11622    zLine = one_input_line(p->in, zLine, nSql>0);
11623    if( zLine==0 ){
11624      /* End of input */
11625      if( p->in==0 && stdin_is_interactive ) printf("\n");
11626      break;
11627    }
11628    if( seenInterrupt ){
11629      if( p->in!=0 ) break;
11630      seenInterrupt = 0;
11631    }
11632    p->lineno++;
11633    if( QSS_INPLAIN(qss)
11634        && line_is_command_terminator(zLine)
11635        && line_is_complete(zSql, nSql) ){
11636      memcpy(zLine,";",2);
11637    }
11638    qss = quickscan(zLine, qss);
11639    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11640      /* Just swallow single-line whitespace */
11641      echo_group_input(p, zLine);
11642      qss = QSS_Start;
11643      continue;
11644    }
11645    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11646      echo_group_input(p, zLine);
11647      if( zLine[0]=='.' ){
11648        rc = do_meta_command(zLine, p);
11649        if( rc==2 ){ /* exit requested */
11650          break;
11651        }else if( rc ){
11652          errCnt++;
11653        }
11654      }
11655      qss = QSS_Start;
11656      continue;
11657    }
11658    /* No single-line dispositions remain; accumulate line(s). */
11659    nLine = strlen30(zLine);
11660    if( nSql+nLine+2>=nAlloc ){
11661      /* Grow buffer by half-again increments when big. */
11662      nAlloc = nSql+(nSql>>1)+nLine+100;
11663      zSql = realloc(zSql, nAlloc);
11664      shell_check_oom(zSql);
11665    }
11666    if( nSql==0 ){
11667      int i;
11668      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11669      assert( nAlloc>0 && zSql!=0 );
11670      memcpy(zSql, zLine+i, nLine+1-i);
11671      startline = p->lineno;
11672      nSql = nLine-i;
11673    }else{
11674      zSql[nSql++] = '\n';
11675      memcpy(zSql+nSql, zLine, nLine+1);
11676      nSql += nLine;
11677    }
11678    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11679      echo_group_input(p, zSql);
11680      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11681      nSql = 0;
11682      if( p->outCount ){
11683        output_reset(p);
11684        p->outCount = 0;
11685      }else{
11686        clearTempFile(p);
11687      }
11688      p->bSafeMode = p->bSafeModePersist;
11689      qss = QSS_Start;
11690    }else if( nSql && QSS_PLAINWHITE(qss) ){
11691      echo_group_input(p, zSql);
11692      nSql = 0;
11693      qss = QSS_Start;
11694    }
11695  }
11696  if( nSql ){
11697    /* This may be incomplete. Let the SQL parser deal with that. */
11698    echo_group_input(p, zSql);
11699    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11700  }
11701  free(zSql);
11702  free(zLine);
11703  --p->inputNesting;
11704  return errCnt>0;
11705}
11706
11707/*
11708** Return a pathname which is the user's home directory.  A
11709** 0 return indicates an error of some kind.
11710*/
11711static char *find_home_dir(int clearFlag){
11712  static char *home_dir = NULL;
11713  if( clearFlag ){
11714    free(home_dir);
11715    home_dir = 0;
11716    return 0;
11717  }
11718  if( home_dir ) return home_dir;
11719
11720#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11721     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11722  {
11723    struct passwd *pwent;
11724    uid_t uid = getuid();
11725    if( (pwent=getpwuid(uid)) != NULL) {
11726      home_dir = pwent->pw_dir;
11727    }
11728  }
11729#endif
11730
11731#if defined(_WIN32_WCE)
11732  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11733   */
11734  home_dir = "/";
11735#else
11736
11737#if defined(_WIN32) || defined(WIN32)
11738  if (!home_dir) {
11739    home_dir = getenv("USERPROFILE");
11740  }
11741#endif
11742
11743  if (!home_dir) {
11744    home_dir = getenv("HOME");
11745  }
11746
11747#if defined(_WIN32) || defined(WIN32)
11748  if (!home_dir) {
11749    char *zDrive, *zPath;
11750    int n;
11751    zDrive = getenv("HOMEDRIVE");
11752    zPath = getenv("HOMEPATH");
11753    if( zDrive && zPath ){
11754      n = strlen30(zDrive) + strlen30(zPath) + 1;
11755      home_dir = malloc( n );
11756      if( home_dir==0 ) return 0;
11757      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11758      return home_dir;
11759    }
11760    home_dir = "c:\\";
11761  }
11762#endif
11763
11764#endif /* !_WIN32_WCE */
11765
11766  if( home_dir ){
11767    int n = strlen30(home_dir) + 1;
11768    char *z = malloc( n );
11769    if( z ) memcpy(z, home_dir, n);
11770    home_dir = z;
11771  }
11772
11773  return home_dir;
11774}
11775
11776/*
11777** Read input from the file given by sqliterc_override.  Or if that
11778** parameter is NULL, take input from ~/.sqliterc
11779**
11780** Returns the number of errors.
11781*/
11782static void process_sqliterc(
11783  ShellState *p,                  /* Configuration data */
11784  const char *sqliterc_override   /* Name of config file. NULL to use default */
11785){
11786  char *home_dir = NULL;
11787  const char *sqliterc = sqliterc_override;
11788  char *zBuf = 0;
11789  FILE *inSaved = p->in;
11790  int savedLineno = p->lineno;
11791
11792  if (sqliterc == NULL) {
11793    home_dir = find_home_dir(0);
11794    if( home_dir==0 ){
11795      raw_printf(stderr, "-- warning: cannot find home directory;"
11796                      " cannot read ~/.sqliterc\n");
11797      return;
11798    }
11799    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11800    shell_check_oom(zBuf);
11801    sqliterc = zBuf;
11802  }
11803  p->in = fopen(sqliterc,"rb");
11804  if( p->in ){
11805    if( stdin_is_interactive ){
11806      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11807    }
11808    if( process_input(p) && bail_on_error ) exit(1);
11809    fclose(p->in);
11810  }else if( sqliterc_override!=0 ){
11811    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11812    if( bail_on_error ) exit(1);
11813  }
11814  p->in = inSaved;
11815  p->lineno = savedLineno;
11816  sqlite3_free(zBuf);
11817}
11818
11819/*
11820** Show available command line options
11821*/
11822static const char zOptions[] =
11823#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11824  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11825#endif
11826  "   -append              append the database to the end of the file\n"
11827  "   -ascii               set output mode to 'ascii'\n"
11828  "   -bail                stop after hitting an error\n"
11829  "   -batch               force batch I/O\n"
11830  "   -box                 set output mode to 'box'\n"
11831  "   -column              set output mode to 'column'\n"
11832  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11833  "   -csv                 set output mode to 'csv'\n"
11834#if !defined(SQLITE_OMIT_DESERIALIZE)
11835  "   -deserialize         open the database using sqlite3_deserialize()\n"
11836#endif
11837  "   -echo                print inputs before execution\n"
11838  "   -init FILENAME       read/process named file\n"
11839  "   -[no]header          turn headers on or off\n"
11840#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11841  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11842#endif
11843  "   -help                show this message\n"
11844  "   -html                set output mode to HTML\n"
11845  "   -interactive         force interactive I/O\n"
11846  "   -json                set output mode to 'json'\n"
11847  "   -line                set output mode to 'line'\n"
11848  "   -list                set output mode to 'list'\n"
11849  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11850  "   -markdown            set output mode to 'markdown'\n"
11851#if !defined(SQLITE_OMIT_DESERIALIZE)
11852  "   -maxsize N           maximum size for a --deserialize database\n"
11853#endif
11854  "   -memtrace            trace all memory allocations and deallocations\n"
11855  "   -mmap N              default mmap size set to N\n"
11856#ifdef SQLITE_ENABLE_MULTIPLEX
11857  "   -multiplex           enable the multiplexor VFS\n"
11858#endif
11859  "   -newline SEP         set output row separator. Default: '\\n'\n"
11860  "   -nofollow            refuse to open symbolic links to database files\n"
11861  "   -nonce STRING        set the safe-mode escape nonce\n"
11862  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11863  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11864  "   -quote               set output mode to 'quote'\n"
11865  "   -readonly            open the database read-only\n"
11866  "   -safe                enable safe-mode\n"
11867  "   -separator SEP       set output column separator. Default: '|'\n"
11868#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11869  "   -sorterref SIZE      sorter references threshold size\n"
11870#endif
11871  "   -stats               print memory stats before each finalize\n"
11872  "   -table               set output mode to 'table'\n"
11873  "   -tabs                set output mode to 'tabs'\n"
11874  "   -version             show SQLite version\n"
11875  "   -vfs NAME            use NAME as the default VFS\n"
11876#ifdef SQLITE_ENABLE_VFSTRACE
11877  "   -vfstrace            enable tracing of all VFS calls\n"
11878#endif
11879#ifdef SQLITE_HAVE_ZLIB
11880  "   -zip                 open the file as a ZIP Archive\n"
11881#endif
11882;
11883static void usage(int showDetail){
11884  utf8_printf(stderr,
11885      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11886      "FILENAME is the name of an SQLite database. A new database is created\n"
11887      "if the file does not previously exist.\n", Argv0);
11888  if( showDetail ){
11889    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11890  }else{
11891    raw_printf(stderr, "Use the -help option for additional information\n");
11892  }
11893  exit(1);
11894}
11895
11896/*
11897** Internal check:  Verify that the SQLite is uninitialized.  Print a
11898** error message if it is initialized.
11899*/
11900static void verify_uninitialized(void){
11901  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11902    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11903                        " initialization.\n");
11904  }
11905}
11906
11907/*
11908** Initialize the state information in data
11909*/
11910static void main_init(ShellState *data) {
11911  memset(data, 0, sizeof(*data));
11912  data->normalMode = data->cMode = data->mode = MODE_List;
11913  data->autoExplain = 1;
11914  data->pAuxDb = &data->aAuxDb[0];
11915  memcpy(data->colSeparator,SEP_Column, 2);
11916  memcpy(data->rowSeparator,SEP_Row, 2);
11917  data->showHeader = 0;
11918  data->shellFlgs = SHFLG_Lookaside;
11919  verify_uninitialized();
11920  sqlite3_config(SQLITE_CONFIG_URI, 1);
11921  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11922  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11923  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11924  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11925}
11926
11927/*
11928** Output text to the console in a font that attracts extra attention.
11929*/
11930#ifdef _WIN32
11931static void printBold(const char *zText){
11932#if !SQLITE_OS_WINRT
11933  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11934  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11935  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11936  SetConsoleTextAttribute(out,
11937         FOREGROUND_RED|FOREGROUND_INTENSITY
11938  );
11939#endif
11940  printf("%s", zText);
11941#if !SQLITE_OS_WINRT
11942  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11943#endif
11944}
11945#else
11946static void printBold(const char *zText){
11947  printf("\033[1m%s\033[0m", zText);
11948}
11949#endif
11950
11951/*
11952** Get the argument to an --option.  Throw an error and die if no argument
11953** is available.
11954*/
11955static char *cmdline_option_value(int argc, char **argv, int i){
11956  if( i==argc ){
11957    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11958            argv[0], argv[argc-1]);
11959    exit(1);
11960  }
11961  return argv[i];
11962}
11963
11964#ifndef SQLITE_SHELL_IS_UTF8
11965#  if (defined(_WIN32) || defined(WIN32)) \
11966   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11967#    define SQLITE_SHELL_IS_UTF8          (0)
11968#  else
11969#    define SQLITE_SHELL_IS_UTF8          (1)
11970#  endif
11971#endif
11972
11973#ifdef SQLITE_SHELL_WASM_MODE
11974#  define main fiddle_main
11975#endif
11976
11977#if SQLITE_SHELL_IS_UTF8
11978int SQLITE_CDECL main(int argc, char **argv){
11979#else
11980int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11981  char **argv;
11982#endif
11983#ifdef SQLITE_DEBUG
11984  sqlite3_uint64 mem_main_enter = sqlite3_memory_used();
11985#endif
11986  char *zErrMsg = 0;
11987#ifdef SQLITE_SHELL_WASM_MODE
11988#  define data shellState
11989#else
11990  ShellState data;
11991#endif
11992  const char *zInitFile = 0;
11993  int i;
11994  int rc = 0;
11995  int warnInmemoryDb = 0;
11996  int readStdin = 1;
11997  int nCmd = 0;
11998  char **azCmd = 0;
11999  const char *zVfs = 0;           /* Value of -vfs command-line option */
12000#if !SQLITE_SHELL_IS_UTF8
12001  char **argvToFree = 0;
12002  int argcToFree = 0;
12003#endif
12004
12005  setBinaryMode(stdin, 0);
12006  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12007#ifdef SQLITE_SHELL_WASM_MODE
12008  stdin_is_interactive = 0;
12009  stdout_is_console = 1;
12010#else
12011  stdin_is_interactive = isatty(0);
12012  stdout_is_console = isatty(1);
12013#endif
12014
12015#if !defined(_WIN32_WCE)
12016  if( getenv("SQLITE_DEBUG_BREAK") ){
12017    if( isatty(0) && isatty(2) ){
12018      fprintf(stderr,
12019          "attach debugger to process %d and press any key to continue.\n",
12020          GETPID());
12021      fgetc(stdin);
12022    }else{
12023#if defined(_WIN32) || defined(WIN32)
12024#if SQLITE_OS_WINRT
12025      __debugbreak();
12026#else
12027      DebugBreak();
12028#endif
12029#elif defined(SIGTRAP)
12030      raise(SIGTRAP);
12031#endif
12032    }
12033  }
12034#endif
12035
12036#if USE_SYSTEM_SQLITE+0!=1
12037  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12038    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12039            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12040    exit(1);
12041  }
12042#endif
12043  main_init(&data);
12044
12045  /* On Windows, we must translate command-line arguments into UTF-8.
12046  ** The SQLite memory allocator subsystem has to be enabled in order to
12047  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12048  ** subsequent sqlite3_config() calls will work.  So copy all results into
12049  ** memory that does not come from the SQLite memory allocator.
12050  */
12051#if !SQLITE_SHELL_IS_UTF8
12052  sqlite3_initialize();
12053  argvToFree = malloc(sizeof(argv[0])*argc*2);
12054  shell_check_oom(argvToFree);
12055  argcToFree = argc;
12056  argv = argvToFree + argc;
12057  for(i=0; i<argc; i++){
12058    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12059    int n;
12060    shell_check_oom(z);
12061    n = (int)strlen(z);
12062    argv[i] = malloc( n+1 );
12063    shell_check_oom(argv[i]);
12064    memcpy(argv[i], z, n+1);
12065    argvToFree[i] = argv[i];
12066    sqlite3_free(z);
12067  }
12068  sqlite3_shutdown();
12069#endif
12070
12071  assert( argc>=1 && argv && argv[0] );
12072  Argv0 = argv[0];
12073
12074  /* Make sure we have a valid signal handler early, before anything
12075  ** else is done.
12076  */
12077#ifdef SIGINT
12078  signal(SIGINT, interrupt_handler);
12079#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12080  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12081#endif
12082
12083#ifdef SQLITE_SHELL_DBNAME_PROC
12084  {
12085    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12086    ** of a C-function that will provide the name of the database file.  Use
12087    ** this compile-time option to embed this shell program in larger
12088    ** applications. */
12089    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12090    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12091    warnInmemoryDb = 0;
12092  }
12093#endif
12094
12095  /* Do an initial pass through the command-line argument to locate
12096  ** the name of the database file, the name of the initialization file,
12097  ** the size of the alternative malloc heap,
12098  ** and the first command to execute.
12099  */
12100  verify_uninitialized();
12101  for(i=1; i<argc; i++){
12102    char *z;
12103    z = argv[i];
12104    if( z[0]!='-' ){
12105      if( data.aAuxDb->zDbFilename==0 ){
12106        data.aAuxDb->zDbFilename = z;
12107      }else{
12108        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12109        ** mean that nothing is read from stdin */
12110        readStdin = 0;
12111        nCmd++;
12112        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12113        shell_check_oom(azCmd);
12114        azCmd[nCmd-1] = z;
12115      }
12116    }
12117    if( z[1]=='-' ) z++;
12118    if( strcmp(z,"-separator")==0
12119     || strcmp(z,"-nullvalue")==0
12120     || strcmp(z,"-newline")==0
12121     || strcmp(z,"-cmd")==0
12122    ){
12123      (void)cmdline_option_value(argc, argv, ++i);
12124    }else if( strcmp(z,"-init")==0 ){
12125      zInitFile = cmdline_option_value(argc, argv, ++i);
12126    }else if( strcmp(z,"-batch")==0 ){
12127      /* Need to check for batch mode here to so we can avoid printing
12128      ** informational messages (like from process_sqliterc) before
12129      ** we do the actual processing of arguments later in a second pass.
12130      */
12131      stdin_is_interactive = 0;
12132    }else if( strcmp(z,"-heap")==0 ){
12133#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12134      const char *zSize;
12135      sqlite3_int64 szHeap;
12136
12137      zSize = cmdline_option_value(argc, argv, ++i);
12138      szHeap = integerValue(zSize);
12139      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12140      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12141#else
12142      (void)cmdline_option_value(argc, argv, ++i);
12143#endif
12144    }else if( strcmp(z,"-pagecache")==0 ){
12145      sqlite3_int64 n, sz;
12146      sz = integerValue(cmdline_option_value(argc,argv,++i));
12147      if( sz>70000 ) sz = 70000;
12148      if( sz<0 ) sz = 0;
12149      n = integerValue(cmdline_option_value(argc,argv,++i));
12150      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12151        n = 0xffffffffffffLL/sz;
12152      }
12153      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12154                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12155      data.shellFlgs |= SHFLG_Pagecache;
12156    }else if( strcmp(z,"-lookaside")==0 ){
12157      int n, sz;
12158      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12159      if( sz<0 ) sz = 0;
12160      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12161      if( n<0 ) n = 0;
12162      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12163      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12164    }else if( strcmp(z,"-threadsafe")==0 ){
12165      int n;
12166      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12167      switch( n ){
12168         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12169         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12170         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12171      }
12172#ifdef SQLITE_ENABLE_VFSTRACE
12173    }else if( strcmp(z,"-vfstrace")==0 ){
12174      extern int vfstrace_register(
12175         const char *zTraceName,
12176         const char *zOldVfsName,
12177         int (*xOut)(const char*,void*),
12178         void *pOutArg,
12179         int makeDefault
12180      );
12181      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12182#endif
12183#ifdef SQLITE_ENABLE_MULTIPLEX
12184    }else if( strcmp(z,"-multiplex")==0 ){
12185      extern int sqlite3_multiple_initialize(const char*,int);
12186      sqlite3_multiplex_initialize(0, 1);
12187#endif
12188    }else if( strcmp(z,"-mmap")==0 ){
12189      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12190      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12191#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12192    }else if( strcmp(z,"-sorterref")==0 ){
12193      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12194      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12195#endif
12196    }else if( strcmp(z,"-vfs")==0 ){
12197      zVfs = cmdline_option_value(argc, argv, ++i);
12198#ifdef SQLITE_HAVE_ZLIB
12199    }else if( strcmp(z,"-zip")==0 ){
12200      data.openMode = SHELL_OPEN_ZIPFILE;
12201#endif
12202    }else if( strcmp(z,"-append")==0 ){
12203      data.openMode = SHELL_OPEN_APPENDVFS;
12204#ifndef SQLITE_OMIT_DESERIALIZE
12205    }else if( strcmp(z,"-deserialize")==0 ){
12206      data.openMode = SHELL_OPEN_DESERIALIZE;
12207    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12208      data.szMax = integerValue(argv[++i]);
12209#endif
12210    }else if( strcmp(z,"-readonly")==0 ){
12211      data.openMode = SHELL_OPEN_READONLY;
12212    }else if( strcmp(z,"-nofollow")==0 ){
12213      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12214#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12215    }else if( strncmp(z, "-A",2)==0 ){
12216      /* All remaining command-line arguments are passed to the ".archive"
12217      ** command, so ignore them */
12218      break;
12219#endif
12220    }else if( strcmp(z, "-memtrace")==0 ){
12221      sqlite3MemTraceActivate(stderr);
12222    }else if( strcmp(z,"-bail")==0 ){
12223      bail_on_error = 1;
12224    }else if( strcmp(z,"-nonce")==0 ){
12225      free(data.zNonce);
12226      data.zNonce = strdup(argv[++i]);
12227    }else if( strcmp(z,"-safe")==0 ){
12228      /* no-op - catch this on the second pass */
12229    }
12230  }
12231  verify_uninitialized();
12232
12233
12234#ifdef SQLITE_SHELL_INIT_PROC
12235  {
12236    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12237    ** of a C-function that will perform initialization actions on SQLite that
12238    ** occur just before or after sqlite3_initialize(). Use this compile-time
12239    ** option to embed this shell program in larger applications. */
12240    extern void SQLITE_SHELL_INIT_PROC(void);
12241    SQLITE_SHELL_INIT_PROC();
12242  }
12243#else
12244  /* All the sqlite3_config() calls have now been made. So it is safe
12245  ** to call sqlite3_initialize() and process any command line -vfs option. */
12246  sqlite3_initialize();
12247#endif
12248
12249  if( zVfs ){
12250    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12251    if( pVfs ){
12252      sqlite3_vfs_register(pVfs, 1);
12253    }else{
12254      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12255      exit(1);
12256    }
12257  }
12258
12259  if( data.pAuxDb->zDbFilename==0 ){
12260#ifndef SQLITE_OMIT_MEMORYDB
12261    data.pAuxDb->zDbFilename = ":memory:";
12262    warnInmemoryDb = argc==1;
12263#else
12264    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12265    return 1;
12266#endif
12267  }
12268  data.out = stdout;
12269#ifndef SQLITE_SHELL_WASM_MODE
12270  sqlite3_appendvfs_init(0,0,0);
12271#endif
12272
12273  /* Go ahead and open the database file if it already exists.  If the
12274  ** file does not exist, delay opening it.  This prevents empty database
12275  ** files from being created if a user mistypes the database name argument
12276  ** to the sqlite command-line tool.
12277  */
12278  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12279    open_db(&data, 0);
12280  }
12281
12282  /* Process the initialization file if there is one.  If no -init option
12283  ** is given on the command line, look for a file named ~/.sqliterc and
12284  ** try to process it.
12285  */
12286  process_sqliterc(&data,zInitFile);
12287
12288  /* Make a second pass through the command-line argument and set
12289  ** options.  This second pass is delayed until after the initialization
12290  ** file is processed so that the command-line arguments will override
12291  ** settings in the initialization file.
12292  */
12293  for(i=1; i<argc; i++){
12294    char *z = argv[i];
12295    if( z[0]!='-' ) continue;
12296    if( z[1]=='-' ){ z++; }
12297    if( strcmp(z,"-init")==0 ){
12298      i++;
12299    }else if( strcmp(z,"-html")==0 ){
12300      data.mode = MODE_Html;
12301    }else if( strcmp(z,"-list")==0 ){
12302      data.mode = MODE_List;
12303    }else if( strcmp(z,"-quote")==0 ){
12304      data.mode = MODE_Quote;
12305      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12306      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12307    }else if( strcmp(z,"-line")==0 ){
12308      data.mode = MODE_Line;
12309    }else if( strcmp(z,"-column")==0 ){
12310      data.mode = MODE_Column;
12311    }else if( strcmp(z,"-json")==0 ){
12312      data.mode = MODE_Json;
12313    }else if( strcmp(z,"-markdown")==0 ){
12314      data.mode = MODE_Markdown;
12315    }else if( strcmp(z,"-table")==0 ){
12316      data.mode = MODE_Table;
12317    }else if( strcmp(z,"-box")==0 ){
12318      data.mode = MODE_Box;
12319    }else if( strcmp(z,"-csv")==0 ){
12320      data.mode = MODE_Csv;
12321      memcpy(data.colSeparator,",",2);
12322#ifdef SQLITE_HAVE_ZLIB
12323    }else if( strcmp(z,"-zip")==0 ){
12324      data.openMode = SHELL_OPEN_ZIPFILE;
12325#endif
12326    }else if( strcmp(z,"-append")==0 ){
12327      data.openMode = SHELL_OPEN_APPENDVFS;
12328#ifndef SQLITE_OMIT_DESERIALIZE
12329    }else if( strcmp(z,"-deserialize")==0 ){
12330      data.openMode = SHELL_OPEN_DESERIALIZE;
12331    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12332      data.szMax = integerValue(argv[++i]);
12333#endif
12334    }else if( strcmp(z,"-readonly")==0 ){
12335      data.openMode = SHELL_OPEN_READONLY;
12336    }else if( strcmp(z,"-nofollow")==0 ){
12337      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12338    }else if( strcmp(z,"-ascii")==0 ){
12339      data.mode = MODE_Ascii;
12340      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12341      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12342    }else if( strcmp(z,"-tabs")==0 ){
12343      data.mode = MODE_List;
12344      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12345      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12346    }else if( strcmp(z,"-separator")==0 ){
12347      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12348                       "%s",cmdline_option_value(argc,argv,++i));
12349    }else if( strcmp(z,"-newline")==0 ){
12350      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12351                       "%s",cmdline_option_value(argc,argv,++i));
12352    }else if( strcmp(z,"-nullvalue")==0 ){
12353      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12354                       "%s",cmdline_option_value(argc,argv,++i));
12355    }else if( strcmp(z,"-header")==0 ){
12356      data.showHeader = 1;
12357      ShellSetFlag(&data, SHFLG_HeaderSet);
12358     }else if( strcmp(z,"-noheader")==0 ){
12359      data.showHeader = 0;
12360      ShellSetFlag(&data, SHFLG_HeaderSet);
12361    }else if( strcmp(z,"-echo")==0 ){
12362      ShellSetFlag(&data, SHFLG_Echo);
12363    }else if( strcmp(z,"-eqp")==0 ){
12364      data.autoEQP = AUTOEQP_on;
12365    }else if( strcmp(z,"-eqpfull")==0 ){
12366      data.autoEQP = AUTOEQP_full;
12367    }else if( strcmp(z,"-stats")==0 ){
12368      data.statsOn = 1;
12369    }else if( strcmp(z,"-scanstats")==0 ){
12370      data.scanstatsOn = 1;
12371    }else if( strcmp(z,"-backslash")==0 ){
12372      /* Undocumented command-line option: -backslash
12373      ** Causes C-style backslash escapes to be evaluated in SQL statements
12374      ** prior to sending the SQL into SQLite.  Useful for injecting
12375      ** crazy bytes in the middle of SQL statements for testing and debugging.
12376      */
12377      ShellSetFlag(&data, SHFLG_Backslash);
12378    }else if( strcmp(z,"-bail")==0 ){
12379      /* No-op.  The bail_on_error flag should already be set. */
12380    }else if( strcmp(z,"-version")==0 ){
12381      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12382      return 0;
12383    }else if( strcmp(z,"-interactive")==0 ){
12384      stdin_is_interactive = 1;
12385    }else if( strcmp(z,"-batch")==0 ){
12386      stdin_is_interactive = 0;
12387    }else if( strcmp(z,"-heap")==0 ){
12388      i++;
12389    }else if( strcmp(z,"-pagecache")==0 ){
12390      i+=2;
12391    }else if( strcmp(z,"-lookaside")==0 ){
12392      i+=2;
12393    }else if( strcmp(z,"-threadsafe")==0 ){
12394      i+=2;
12395    }else if( strcmp(z,"-nonce")==0 ){
12396      i += 2;
12397    }else if( strcmp(z,"-mmap")==0 ){
12398      i++;
12399    }else if( strcmp(z,"-memtrace")==0 ){
12400      i++;
12401#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12402    }else if( strcmp(z,"-sorterref")==0 ){
12403      i++;
12404#endif
12405    }else if( strcmp(z,"-vfs")==0 ){
12406      i++;
12407#ifdef SQLITE_ENABLE_VFSTRACE
12408    }else if( strcmp(z,"-vfstrace")==0 ){
12409      i++;
12410#endif
12411#ifdef SQLITE_ENABLE_MULTIPLEX
12412    }else if( strcmp(z,"-multiplex")==0 ){
12413      i++;
12414#endif
12415    }else if( strcmp(z,"-help")==0 ){
12416      usage(1);
12417    }else if( strcmp(z,"-cmd")==0 ){
12418      /* Run commands that follow -cmd first and separately from commands
12419      ** that simply appear on the command-line.  This seems goofy.  It would
12420      ** be better if all commands ran in the order that they appear.  But
12421      ** we retain the goofy behavior for historical compatibility. */
12422      if( i==argc-1 ) break;
12423      z = cmdline_option_value(argc,argv,++i);
12424      if( z[0]=='.' ){
12425        rc = do_meta_command(z, &data);
12426        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12427      }else{
12428        open_db(&data, 0);
12429        rc = shell_exec(&data, z, &zErrMsg);
12430        if( zErrMsg!=0 ){
12431          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12432          if( bail_on_error ) return rc!=0 ? rc : 1;
12433        }else if( rc!=0 ){
12434          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12435          if( bail_on_error ) return rc;
12436        }
12437      }
12438#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12439    }else if( strncmp(z, "-A", 2)==0 ){
12440      if( nCmd>0 ){
12441        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12442                            " with \"%s\"\n", z);
12443        return 1;
12444      }
12445      open_db(&data, OPEN_DB_ZIPFILE);
12446      if( z[2] ){
12447        argv[i] = &z[2];
12448        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12449      }else{
12450        arDotCommand(&data, 1, argv+i, argc-i);
12451      }
12452      readStdin = 0;
12453      break;
12454#endif
12455    }else if( strcmp(z,"-safe")==0 ){
12456      data.bSafeMode = data.bSafeModePersist = 1;
12457    }else{
12458      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12459      raw_printf(stderr,"Use -help for a list of options.\n");
12460      return 1;
12461    }
12462    data.cMode = data.mode;
12463  }
12464
12465  if( !readStdin ){
12466    /* Run all arguments that do not begin with '-' as if they were separate
12467    ** command-line inputs, except for the argToSkip argument which contains
12468    ** the database filename.
12469    */
12470    for(i=0; i<nCmd; i++){
12471      if( azCmd[i][0]=='.' ){
12472        rc = do_meta_command(azCmd[i], &data);
12473        if( rc ){
12474          free(azCmd);
12475          return rc==2 ? 0 : rc;
12476        }
12477      }else{
12478        open_db(&data, 0);
12479        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12480        if( zErrMsg || rc ){
12481          if( zErrMsg!=0 ){
12482            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12483          }else{
12484            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12485          }
12486          sqlite3_free(zErrMsg);
12487          free(azCmd);
12488          return rc!=0 ? rc : 1;
12489        }
12490      }
12491    }
12492  }else{
12493    /* Run commands received from standard input
12494    */
12495    if( stdin_is_interactive ){
12496      char *zHome;
12497      char *zHistory;
12498      int nHistory;
12499      printf(
12500        "SQLite version %s %.19s\n" /*extra-version-info*/
12501        "Enter \".help\" for usage hints.\n",
12502        sqlite3_libversion(), sqlite3_sourceid()
12503      );
12504      if( warnInmemoryDb ){
12505        printf("Connected to a ");
12506        printBold("transient in-memory database");
12507        printf(".\nUse \".open FILENAME\" to reopen on a "
12508               "persistent database.\n");
12509      }
12510      zHistory = getenv("SQLITE_HISTORY");
12511      if( zHistory ){
12512        zHistory = strdup(zHistory);
12513      }else if( (zHome = find_home_dir(0))!=0 ){
12514        nHistory = strlen30(zHome) + 20;
12515        if( (zHistory = malloc(nHistory))!=0 ){
12516          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12517        }
12518      }
12519      if( zHistory ){ shell_read_history(zHistory); }
12520#if HAVE_READLINE || HAVE_EDITLINE
12521      rl_attempted_completion_function = readline_completion;
12522#elif HAVE_LINENOISE
12523      linenoiseSetCompletionCallback(linenoise_completion);
12524#endif
12525      data.in = 0;
12526      rc = process_input(&data);
12527      if( zHistory ){
12528        shell_stifle_history(2000);
12529        shell_write_history(zHistory);
12530        free(zHistory);
12531      }
12532    }else{
12533      data.in = stdin;
12534      rc = process_input(&data);
12535    }
12536  }
12537#ifndef SQLITE_SHELL_WASM_MODE
12538  /* In WASM mode we have to leave the db state in place so that
12539  ** client code can "push" SQL into it after this call returns. */
12540  free(azCmd);
12541  set_table_name(&data, 0);
12542  if( data.db ){
12543    session_close_all(&data, -1);
12544    close_db(data.db);
12545  }
12546  for(i=0; i<ArraySize(data.aAuxDb); i++){
12547    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12548    if( data.aAuxDb[i].db ){
12549      session_close_all(&data, i);
12550      close_db(data.aAuxDb[i].db);
12551    }
12552  }
12553  find_home_dir(1);
12554  output_reset(&data);
12555  data.doXdgOpen = 0;
12556  clearTempFile(&data);
12557#if !SQLITE_SHELL_IS_UTF8
12558  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12559  free(argvToFree);
12560#endif
12561  free(data.colWidth);
12562  free(data.zNonce);
12563  /* Clear the global data structure so that valgrind will detect memory
12564  ** leaks */
12565  memset(&data, 0, sizeof(data));
12566#ifdef SQLITE_DEBUG
12567  if( sqlite3_memory_used()>mem_main_enter ){
12568    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12569                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12570  }
12571#endif
12572#endif /* !SQLITE_SHELL_WASM_MODE */
12573  return rc;
12574}
12575
12576
12577#ifdef SQLITE_SHELL_WASM_MODE
12578/* Only for emcc experimentation purposes. */
12579int fiddle_experiment(int a,int b){
12580   return a + b;
12581}
12582
12583/* Only for emcc experimentation purposes.
12584
12585  Define this function in JS using:
12586
12587  emcc ... --js-library somefile.js
12588
12589  containing:
12590
12591mergeInto(LibraryManager.library, {
12592    my_foo: function(){
12593        console.debug("my_foo()",arguments);
12594    }
12595});
12596*/
12597/*extern void my_foo(sqlite3 *);*/
12598/* Only for emcc experimentation purposes. */
12599sqlite3 * fiddle_the_db(){
12600    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12601    /*my_foo(globalDb);*/
12602    return globalDb;
12603}
12604/* Only for emcc experimentation purposes. */
12605sqlite3 * fiddle_db_arg(sqlite3 *arg){
12606    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12607    return arg;
12608}
12609
12610/*
12611** Intended to be called via a SharedWorker() while a separate
12612** SharedWorker() (which manages the wasm module) is performing work
12613** which should be interrupted. Unfortunately, SharedWorker is not
12614** portable enough to make real use of.
12615*/
12616void fiddle_interrupt(void){
12617  if(globalDb) sqlite3_interrupt(globalDb);
12618}
12619
12620/*
12621** Returns the filename of the given db name, assuming "main" if
12622** zDbName is NULL. Returns NULL if globalDb is not opened.
12623*/
12624const char * fiddle_db_filename(const char * zDbName){
12625    return globalDb
12626      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12627      : NULL;
12628}
12629
12630/*
12631** Closes, unlinks, and reopens the db using its current filename (or
12632** the default if the db is currently closed). It is assumed, for
12633** purposes of the fiddle build, that the file is in a transient
12634** virtual filesystem within the browser.
12635*/
12636void fiddle_reset_db(void){
12637  char *zFilename = 0;
12638  if(0==globalDb){
12639    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12640  }else{
12641    zFilename =
12642      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12643    shell_check_oom(zFilename);
12644    close_db(globalDb);
12645    shellDeleteFile(zFilename);
12646    shellState.db = 0;
12647    shellState.pAuxDb->zDbFilename = zFilename;
12648  }
12649  open_db(&shellState, 0);
12650  sqlite3_free(zFilename);
12651}
12652
12653/*
12654** Trivial exportable function for emscripten. Needs to be exported using:
12655**
12656** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12657**
12658** (Note the underscore before the function name.) It processes zSql
12659** as if it were input to the sqlite3 shell and redirects all output
12660** to the wasm binding.
12661*/
12662void fiddle_exec(const char * zSql){
12663  static int once = 0;
12664  int rc = 0;
12665  if(!once){
12666    /* Simulate an argv array for main() */
12667    static char * argv[] = {"fiddle",
12668                            "-bail",
12669                            "-safe"};
12670    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12671    once = rc ? -1 : 1;
12672    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12673    printf(
12674        "SQLite version %s %.19s\n" /*extra-version-info*/,
12675        sqlite3_libversion(), sqlite3_sourceid()
12676    );
12677    puts("WASM shell");
12678    puts("Enter \".help\" for usage hints.");
12679    if(once>0){
12680      fiddle_reset_db();
12681    }
12682    if(shellState.db){
12683      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12684    }else{
12685      fprintf(stderr,"ERROR initializing db!\n");
12686      return;
12687    }
12688  }
12689  if(once<0){
12690    puts("DB init failed. Not executing SQL.");
12691  }else if(zSql && *zSql){
12692    shellState.wasm.zInput = zSql;
12693    shellState.wasm.zPos = zSql;
12694    process_input(&shellState);
12695    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12696  }
12697}
12698#endif /* SQLITE_SHELL_WASM_MODE */
12699