xref: /sqlite-3.40.0/src/shell.c.in (revision c583719b)
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/* True if the timer is enabled */
234static int enableTimer = 0;
235
236/* Return the current wall-clock time */
237static sqlite3_int64 timeOfDay(void){
238  static sqlite3_vfs *clockVfs = 0;
239  sqlite3_int64 t;
240  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
241  if( clockVfs==0 ) return 0;  /* Never actually happens */
242  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
243    clockVfs->xCurrentTimeInt64(clockVfs, &t);
244  }else{
245    double r;
246    clockVfs->xCurrentTime(clockVfs, &r);
247    t = (sqlite3_int64)(r*86400000.0);
248  }
249  return t;
250}
251
252#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
253#include <sys/time.h>
254#include <sys/resource.h>
255
256/* VxWorks does not support getrusage() as far as we can determine */
257#if defined(_WRS_KERNEL) || defined(__RTP__)
258struct rusage {
259  struct timeval ru_utime; /* user CPU time used */
260  struct timeval ru_stime; /* system CPU time used */
261};
262#define getrusage(A,B) memset(B,0,sizeof(*B))
263#endif
264
265/* Saved resource information for the beginning of an operation */
266static struct rusage sBegin;  /* CPU time at start */
267static sqlite3_int64 iBegin;  /* Wall-clock time at start */
268
269/*
270** Begin timing an operation
271*/
272static void beginTimer(void){
273  if( enableTimer ){
274    getrusage(RUSAGE_SELF, &sBegin);
275    iBegin = timeOfDay();
276  }
277}
278
279/* Return the difference of two time_structs in seconds */
280static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
281  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
282         (double)(pEnd->tv_sec - pStart->tv_sec);
283}
284
285/*
286** Print the timing results.
287*/
288static void endTimer(void){
289  if( enableTimer ){
290    sqlite3_int64 iEnd = timeOfDay();
291    struct rusage sEnd;
292    getrusage(RUSAGE_SELF, &sEnd);
293    printf("Run Time: real %.3f user %f sys %f\n",
294       (iEnd - iBegin)*0.001,
295       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
296       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
297  }
298}
299
300#define BEGIN_TIMER beginTimer()
301#define END_TIMER endTimer()
302#define HAS_TIMER 1
303
304#elif (defined(_WIN32) || defined(WIN32))
305
306/* Saved resource information for the beginning of an operation */
307static HANDLE hProcess;
308static FILETIME ftKernelBegin;
309static FILETIME ftUserBegin;
310static sqlite3_int64 ftWallBegin;
311typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
312                                    LPFILETIME, LPFILETIME);
313static GETPROCTIMES getProcessTimesAddr = NULL;
314
315/*
316** Check to see if we have timer support.  Return 1 if necessary
317** support found (or found previously).
318*/
319static int hasTimer(void){
320  if( getProcessTimesAddr ){
321    return 1;
322  } else {
323#if !SQLITE_OS_WINRT
324    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
325    ** versions. See if the version we are running on has it, and if it
326    ** does, save off a pointer to it and the current process handle.
327    */
328    hProcess = GetCurrentProcess();
329    if( hProcess ){
330      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
331      if( NULL != hinstLib ){
332        getProcessTimesAddr =
333            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
334        if( NULL != getProcessTimesAddr ){
335          return 1;
336        }
337        FreeLibrary(hinstLib);
338      }
339    }
340#endif
341  }
342  return 0;
343}
344
345/*
346** Begin timing an operation
347*/
348static void beginTimer(void){
349  if( enableTimer && getProcessTimesAddr ){
350    FILETIME ftCreation, ftExit;
351    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
352                        &ftKernelBegin,&ftUserBegin);
353    ftWallBegin = timeOfDay();
354  }
355}
356
357/* Return the difference of two FILETIME structs in seconds */
358static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
359  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
360  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
361  return (double) ((i64End - i64Start) / 10000000.0);
362}
363
364/*
365** Print the timing results.
366*/
367static void endTimer(void){
368  if( enableTimer && getProcessTimesAddr){
369    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
370    sqlite3_int64 ftWallEnd = timeOfDay();
371    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
372    printf("Run Time: real %.3f user %f sys %f\n",
373       (ftWallEnd - ftWallBegin)*0.001,
374       timeDiff(&ftUserBegin, &ftUserEnd),
375       timeDiff(&ftKernelBegin, &ftKernelEnd));
376  }
377}
378
379#define BEGIN_TIMER beginTimer()
380#define END_TIMER endTimer()
381#define HAS_TIMER hasTimer()
382
383#else
384#define BEGIN_TIMER
385#define END_TIMER
386#define HAS_TIMER 0
387#endif
388
389/*
390** Used to prevent warnings about unused parameters
391*/
392#define UNUSED_PARAMETER(x) (void)(x)
393
394/*
395** Number of elements in an array
396*/
397#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
398
399/*
400** If the following flag is set, then command execution stops
401** at an error if we are not interactive.
402*/
403static int bail_on_error = 0;
404
405/*
406** Threat stdin as an interactive input if the following variable
407** is true.  Otherwise, assume stdin is connected to a file or pipe.
408*/
409static int stdin_is_interactive = 1;
410
411/*
412** On Windows systems we have to know if standard output is a console
413** in order to translate UTF-8 into MBCS.  The following variable is
414** true if translation is required.
415*/
416static int stdout_is_console = 1;
417
418/*
419** The following is the open SQLite database.  We make a pointer
420** to this database a static variable so that it can be accessed
421** by the SIGINT handler to interrupt database processing.
422*/
423static sqlite3 *globalDb = 0;
424
425/*
426** True if an interrupt (Control-C) has been received.
427*/
428static volatile int seenInterrupt = 0;
429
430/*
431** This is the name of our program. It is set in main(), used
432** in a number of other places, mostly for error messages.
433*/
434static char *Argv0;
435
436/*
437** Prompt strings. Initialized in main. Settable with
438**   .prompt main continue
439*/
440static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
441static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
442
443/*
444** Render output like fprintf().  Except, if the output is going to the
445** console and if this is running on a Windows machine, translate the
446** output from UTF-8 into MBCS.
447*/
448#if defined(_WIN32) || defined(WIN32)
449void utf8_printf(FILE *out, const char *zFormat, ...){
450  va_list ap;
451  va_start(ap, zFormat);
452  if( stdout_is_console && (out==stdout || out==stderr) ){
453    char *z1 = sqlite3_vmprintf(zFormat, ap);
454    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
455    sqlite3_free(z1);
456    fputs(z2, out);
457    sqlite3_free(z2);
458  }else{
459    vfprintf(out, zFormat, ap);
460  }
461  va_end(ap);
462}
463#elif !defined(utf8_printf)
464# define utf8_printf fprintf
465#endif
466
467/*
468** Render output like fprintf().  This should not be used on anything that
469** includes string formatting (e.g. "%s").
470*/
471#if !defined(raw_printf)
472# define raw_printf fprintf
473#endif
474
475/* Indicate out-of-memory and exit. */
476static void shell_out_of_memory(void){
477  raw_printf(stderr,"Error: out of memory\n");
478  exit(1);
479}
480
481/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
482** out-of-memory error.
483*/
484static void shell_check_oom(void *p){
485  if( p==0 ) shell_out_of_memory();
486}
487
488/*
489** Write I/O traces to the following stream.
490*/
491#ifdef SQLITE_ENABLE_IOTRACE
492static FILE *iotrace = 0;
493#endif
494
495/*
496** This routine works like printf in that its first argument is a
497** format string and subsequent arguments are values to be substituted
498** in place of % fields.  The result of formatting this string
499** is written to iotrace.
500*/
501#ifdef SQLITE_ENABLE_IOTRACE
502static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
503  va_list ap;
504  char *z;
505  if( iotrace==0 ) return;
506  va_start(ap, zFormat);
507  z = sqlite3_vmprintf(zFormat, ap);
508  va_end(ap);
509  utf8_printf(iotrace, "%s", z);
510  sqlite3_free(z);
511}
512#endif
513
514/*
515** Output string zUtf to stream pOut as w characters.  If w is negative,
516** then right-justify the text.  W is the width in UTF-8 characters, not
517** in bytes.  This is different from the %*.*s specification in printf
518** since with %*.*s the width is measured in bytes, not characters.
519*/
520static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
521  int i;
522  int n;
523  int aw = w<0 ? -w : w;
524  for(i=n=0; zUtf[i]; i++){
525    if( (zUtf[i]&0xc0)!=0x80 ){
526      n++;
527      if( n==aw ){
528        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
529        break;
530      }
531    }
532  }
533  if( n>=aw ){
534    utf8_printf(pOut, "%.*s", i, zUtf);
535  }else if( w<0 ){
536    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
537  }else{
538    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
539  }
540}
541
542
543/*
544** Determines if a string is a number of not.
545*/
546static int isNumber(const char *z, int *realnum){
547  if( *z=='-' || *z=='+' ) z++;
548  if( !IsDigit(*z) ){
549    return 0;
550  }
551  z++;
552  if( realnum ) *realnum = 0;
553  while( IsDigit(*z) ){ z++; }
554  if( *z=='.' ){
555    z++;
556    if( !IsDigit(*z) ) return 0;
557    while( IsDigit(*z) ){ z++; }
558    if( realnum ) *realnum = 1;
559  }
560  if( *z=='e' || *z=='E' ){
561    z++;
562    if( *z=='+' || *z=='-' ) z++;
563    if( !IsDigit(*z) ) return 0;
564    while( IsDigit(*z) ){ z++; }
565    if( realnum ) *realnum = 1;
566  }
567  return *z==0;
568}
569
570/*
571** Compute a string length that is limited to what can be stored in
572** lower 30 bits of a 32-bit signed integer.
573*/
574static int strlen30(const char *z){
575  const char *z2 = z;
576  while( *z2 ){ z2++; }
577  return 0x3fffffff & (int)(z2 - z);
578}
579
580/*
581** Return the length of a string in characters.  Multibyte UTF8 characters
582** count as a single character.
583*/
584static int strlenChar(const char *z){
585  int n = 0;
586  while( *z ){
587    if( (0xc0&*(z++))!=0x80 ) n++;
588  }
589  return n;
590}
591
592/*
593** Return open FILE * if zFile exists, can be opened for read
594** and is an ordinary file or a character stream source.
595** Otherwise return 0.
596*/
597static FILE * openChrSource(const char *zFile){
598#ifdef _WIN32
599  struct _stat x = {0};
600# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
601  /* On Windows, open first, then check the stream nature. This order
602  ** is necessary because _stat() and sibs, when checking a named pipe,
603  ** effectively break the pipe as its supplier sees it. */
604  FILE *rv = fopen(zFile, "rb");
605  if( rv==0 ) return 0;
606  if( _fstat(_fileno(rv), &x) != 0
607      || !STAT_CHR_SRC(x.st_mode)){
608    fclose(rv);
609    rv = 0;
610  }
611  return rv;
612#else
613  struct stat x = {0};
614  int rc = stat(zFile, &x);
615# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
616  if( rc!=0 ) return 0;
617  if( STAT_CHR_SRC(x.st_mode) ){
618    return fopen(zFile, "rb");
619  }else{
620    return 0;
621  }
622#endif
623#undef STAT_CHR_SRC
624}
625
626/*
627** This routine reads a line of text from FILE in, stores
628** the text in memory obtained from malloc() and returns a pointer
629** to the text.  NULL is returned at end of file, or if malloc()
630** fails.
631**
632** If zLine is not NULL then it is a malloced buffer returned from
633** a previous call to this routine that may be reused.
634*/
635static char *local_getline(char *zLine, FILE *in){
636  int nLine = zLine==0 ? 0 : 100;
637  int n = 0;
638
639  while( 1 ){
640    if( n+100>nLine ){
641      nLine = nLine*2 + 100;
642      zLine = realloc(zLine, nLine);
643      shell_check_oom(zLine);
644    }
645    if( fgets(&zLine[n], nLine - n, in)==0 ){
646      if( n==0 ){
647        free(zLine);
648        return 0;
649      }
650      zLine[n] = 0;
651      break;
652    }
653    while( zLine[n] ) n++;
654    if( n>0 && zLine[n-1]=='\n' ){
655      n--;
656      if( n>0 && zLine[n-1]=='\r' ) n--;
657      zLine[n] = 0;
658      break;
659    }
660  }
661#if defined(_WIN32) || defined(WIN32)
662  /* For interactive input on Windows systems, translate the
663  ** multi-byte characterset characters into UTF-8. */
664  if( stdin_is_interactive && in==stdin ){
665    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
666    if( zTrans ){
667      int nTrans = strlen30(zTrans)+1;
668      if( nTrans>nLine ){
669        zLine = realloc(zLine, nTrans);
670        shell_check_oom(zLine);
671      }
672      memcpy(zLine, zTrans, nTrans);
673      sqlite3_free(zTrans);
674    }
675  }
676#endif /* defined(_WIN32) || defined(WIN32) */
677  return zLine;
678}
679
680/*
681** Retrieve a single line of input text.
682**
683** If in==0 then read from standard input and prompt before each line.
684** If isContinuation is true, then a continuation prompt is appropriate.
685** If isContinuation is zero, then the main prompt should be used.
686**
687** If zPrior is not NULL then it is a buffer from a prior call to this
688** routine that can be reused.
689**
690** The result is stored in space obtained from malloc() and must either
691** be freed by the caller or else passed back into this routine via the
692** zPrior argument for reuse.
693*/
694static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
695  char *zPrompt;
696  char *zResult;
697  if( in!=0 ){
698    zResult = local_getline(zPrior, in);
699  }else{
700    zPrompt = isContinuation ? continuePrompt : mainPrompt;
701#if SHELL_USE_LOCAL_GETLINE
702    printf("%s", zPrompt);
703    fflush(stdout);
704    zResult = local_getline(zPrior, stdin);
705#else
706    free(zPrior);
707    zResult = shell_readline(zPrompt);
708    if( zResult && *zResult ) shell_add_history(zResult);
709#endif
710  }
711  return zResult;
712}
713
714
715/*
716** Return the value of a hexadecimal digit.  Return -1 if the input
717** is not a hex digit.
718*/
719static int hexDigitValue(char c){
720  if( c>='0' && c<='9' ) return c - '0';
721  if( c>='a' && c<='f' ) return c - 'a' + 10;
722  if( c>='A' && c<='F' ) return c - 'A' + 10;
723  return -1;
724}
725
726/*
727** Interpret zArg as an integer value, possibly with suffixes.
728*/
729static sqlite3_int64 integerValue(const char *zArg){
730  sqlite3_int64 v = 0;
731  static const struct { char *zSuffix; int iMult; } aMult[] = {
732    { "KiB", 1024 },
733    { "MiB", 1024*1024 },
734    { "GiB", 1024*1024*1024 },
735    { "KB",  1000 },
736    { "MB",  1000000 },
737    { "GB",  1000000000 },
738    { "K",   1000 },
739    { "M",   1000000 },
740    { "G",   1000000000 },
741  };
742  int i;
743  int isNeg = 0;
744  if( zArg[0]=='-' ){
745    isNeg = 1;
746    zArg++;
747  }else if( zArg[0]=='+' ){
748    zArg++;
749  }
750  if( zArg[0]=='0' && zArg[1]=='x' ){
751    int x;
752    zArg += 2;
753    while( (x = hexDigitValue(zArg[0]))>=0 ){
754      v = (v<<4) + x;
755      zArg++;
756    }
757  }else{
758    while( IsDigit(zArg[0]) ){
759      v = v*10 + zArg[0] - '0';
760      zArg++;
761    }
762  }
763  for(i=0; i<ArraySize(aMult); i++){
764    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
765      v *= aMult[i].iMult;
766      break;
767    }
768  }
769  return isNeg? -v : v;
770}
771
772/*
773** A variable length string to which one can append text.
774*/
775typedef struct ShellText ShellText;
776struct ShellText {
777  char *z;
778  int n;
779  int nAlloc;
780};
781
782/*
783** Initialize and destroy a ShellText object
784*/
785static void initText(ShellText *p){
786  memset(p, 0, sizeof(*p));
787}
788static void freeText(ShellText *p){
789  free(p->z);
790  initText(p);
791}
792
793/* zIn is either a pointer to a NULL-terminated string in memory obtained
794** from malloc(), or a NULL pointer. The string pointed to by zAppend is
795** added to zIn, and the result returned in memory obtained from malloc().
796** zIn, if it was not NULL, is freed.
797**
798** If the third argument, quote, is not '\0', then it is used as a
799** quote character for zAppend.
800*/
801static void appendText(ShellText *p, char const *zAppend, char quote){
802  int len;
803  int i;
804  int nAppend = strlen30(zAppend);
805
806  len = nAppend+p->n+1;
807  if( quote ){
808    len += 2;
809    for(i=0; i<nAppend; i++){
810      if( zAppend[i]==quote ) len++;
811    }
812  }
813
814  if( p->z==0 || p->n+len>=p->nAlloc ){
815    p->nAlloc = p->nAlloc*2 + len + 20;
816    p->z = realloc(p->z, p->nAlloc);
817    shell_check_oom(p->z);
818  }
819
820  if( quote ){
821    char *zCsr = p->z+p->n;
822    *zCsr++ = quote;
823    for(i=0; i<nAppend; i++){
824      *zCsr++ = zAppend[i];
825      if( zAppend[i]==quote ) *zCsr++ = quote;
826    }
827    *zCsr++ = quote;
828    p->n = (int)(zCsr - p->z);
829    *zCsr = '\0';
830  }else{
831    memcpy(p->z+p->n, zAppend, nAppend);
832    p->n += nAppend;
833    p->z[p->n] = '\0';
834  }
835}
836
837/*
838** Attempt to determine if identifier zName needs to be quoted, either
839** because it contains non-alphanumeric characters, or because it is an
840** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
841** that quoting is required.
842**
843** Return '"' if quoting is required.  Return 0 if no quoting is required.
844*/
845static char quoteChar(const char *zName){
846  int i;
847  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
848  for(i=0; zName[i]; i++){
849    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
850  }
851  return sqlite3_keyword_check(zName, i) ? '"' : 0;
852}
853
854/*
855** Construct a fake object name and column list to describe the structure
856** of the view, virtual table, or table valued function zSchema.zName.
857*/
858static char *shellFakeSchema(
859  sqlite3 *db,            /* The database connection containing the vtab */
860  const char *zSchema,    /* Schema of the database holding the vtab */
861  const char *zName       /* The name of the virtual table */
862){
863  sqlite3_stmt *pStmt = 0;
864  char *zSql;
865  ShellText s;
866  char cQuote;
867  char *zDiv = "(";
868  int nRow = 0;
869
870  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
871                         zSchema ? zSchema : "main", zName);
872  shell_check_oom(zSql);
873  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
874  sqlite3_free(zSql);
875  initText(&s);
876  if( zSchema ){
877    cQuote = quoteChar(zSchema);
878    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
879    appendText(&s, zSchema, cQuote);
880    appendText(&s, ".", 0);
881  }
882  cQuote = quoteChar(zName);
883  appendText(&s, zName, cQuote);
884  while( sqlite3_step(pStmt)==SQLITE_ROW ){
885    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
886    nRow++;
887    appendText(&s, zDiv, 0);
888    zDiv = ",";
889    if( zCol==0 ) zCol = "";
890    cQuote = quoteChar(zCol);
891    appendText(&s, zCol, cQuote);
892  }
893  appendText(&s, ")", 0);
894  sqlite3_finalize(pStmt);
895  if( nRow==0 ){
896    freeText(&s);
897    s.z = 0;
898  }
899  return s.z;
900}
901
902/*
903** SQL function:  shell_module_schema(X)
904**
905** Return a fake schema for the table-valued function or eponymous virtual
906** table X.
907*/
908static void shellModuleSchema(
909  sqlite3_context *pCtx,
910  int nVal,
911  sqlite3_value **apVal
912){
913  const char *zName;
914  char *zFake;
915  UNUSED_PARAMETER(nVal);
916  zName = (const char*)sqlite3_value_text(apVal[0]);
917  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
918  if( zFake ){
919    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
920                        -1, sqlite3_free);
921    free(zFake);
922  }
923}
924
925/*
926** SQL function:  shell_add_schema(S,X)
927**
928** Add the schema name X to the CREATE statement in S and return the result.
929** Examples:
930**
931**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
932**
933** Also works on
934**
935**    CREATE INDEX
936**    CREATE UNIQUE INDEX
937**    CREATE VIEW
938**    CREATE TRIGGER
939**    CREATE VIRTUAL TABLE
940**
941** This UDF is used by the .schema command to insert the schema name of
942** attached databases into the middle of the sqlite_schema.sql field.
943*/
944static void shellAddSchemaName(
945  sqlite3_context *pCtx,
946  int nVal,
947  sqlite3_value **apVal
948){
949  static const char *aPrefix[] = {
950     "TABLE",
951     "INDEX",
952     "UNIQUE INDEX",
953     "VIEW",
954     "TRIGGER",
955     "VIRTUAL TABLE"
956  };
957  int i = 0;
958  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
959  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
960  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
961  sqlite3 *db = sqlite3_context_db_handle(pCtx);
962  UNUSED_PARAMETER(nVal);
963  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
964    for(i=0; i<ArraySize(aPrefix); i++){
965      int n = strlen30(aPrefix[i]);
966      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
967        char *z = 0;
968        char *zFake = 0;
969        if( zSchema ){
970          char cQuote = quoteChar(zSchema);
971          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
972            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
973          }else{
974            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
975          }
976        }
977        if( zName
978         && aPrefix[i][0]=='V'
979         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
980        ){
981          if( z==0 ){
982            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
983          }else{
984            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
985          }
986          free(zFake);
987        }
988        if( z ){
989          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
990          return;
991        }
992      }
993    }
994  }
995  sqlite3_result_value(pCtx, apVal[0]);
996}
997
998/*
999** The source code for several run-time loadable extensions is inserted
1000** below by the ../tool/mkshellc.tcl script.  Before processing that included
1001** code, we need to override some macros to make the included program code
1002** work here in the middle of this regular program.
1003*/
1004#define SQLITE_EXTENSION_INIT1
1005#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1006
1007#if defined(_WIN32) && defined(_MSC_VER)
1008INCLUDE test_windirent.h
1009INCLUDE test_windirent.c
1010#define dirent DIRENT
1011#endif
1012INCLUDE ../ext/misc/shathree.c
1013INCLUDE ../ext/misc/fileio.c
1014INCLUDE ../ext/misc/completion.c
1015INCLUDE ../ext/misc/appendvfs.c
1016INCLUDE ../ext/misc/memtrace.c
1017INCLUDE ../ext/misc/uint.c
1018INCLUDE ../ext/misc/decimal.c
1019INCLUDE ../ext/misc/ieee754.c
1020INCLUDE ../ext/misc/series.c
1021INCLUDE ../ext/misc/regexp.c
1022#ifdef SQLITE_HAVE_ZLIB
1023INCLUDE ../ext/misc/zipfile.c
1024INCLUDE ../ext/misc/sqlar.c
1025#endif
1026INCLUDE ../ext/expert/sqlite3expert.h
1027INCLUDE ../ext/expert/sqlite3expert.c
1028
1029#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1030INCLUDE ../ext/misc/dbdata.c
1031#endif
1032
1033#if defined(SQLITE_ENABLE_SESSION)
1034/*
1035** State information for a single open session
1036*/
1037typedef struct OpenSession OpenSession;
1038struct OpenSession {
1039  char *zName;             /* Symbolic name for this session */
1040  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1041  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1042  sqlite3_session *p;      /* The open session */
1043};
1044#endif
1045
1046typedef struct ExpertInfo ExpertInfo;
1047struct ExpertInfo {
1048  sqlite3expert *pExpert;
1049  int bVerbose;
1050};
1051
1052/* A single line in the EQP output */
1053typedef struct EQPGraphRow EQPGraphRow;
1054struct EQPGraphRow {
1055  int iEqpId;           /* ID for this row */
1056  int iParentId;        /* ID of the parent row */
1057  EQPGraphRow *pNext;   /* Next row in sequence */
1058  char zText[1];        /* Text to display for this row */
1059};
1060
1061/* All EQP output is collected into an instance of the following */
1062typedef struct EQPGraph EQPGraph;
1063struct EQPGraph {
1064  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1065  EQPGraphRow *pLast;   /* Last element of the pRow list */
1066  char zPrefix[100];    /* Graph prefix */
1067};
1068
1069/* Parameters affecting columnar mode result display (defaulting together) */
1070typedef struct ColModeOpts {
1071  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1072  u8 bQuote;            /* Quote results for .mode box and table */
1073  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1074} ColModeOpts;
1075#define ColModeOpts_default { 60, 0, 0 }
1076#define ColModeOpts_default_qbox { 60, 1, 0 }
1077
1078/*
1079** State information about the database connection is contained in an
1080** instance of the following structure.
1081*/
1082typedef struct ShellState ShellState;
1083struct ShellState {
1084  sqlite3 *db;           /* The database */
1085  u8 autoExplain;        /* Automatically turn on .explain mode */
1086  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1087  u8 autoEQPtest;        /* autoEQP is in test mode */
1088  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1089  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1090  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1091  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1092  u8 nEqpLevel;          /* Depth of the EQP output graph */
1093  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1094  u8 bSafeMode;          /* True to prohibit unsafe operations */
1095  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1096  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1097  unsigned statsOn;      /* True to display memory stats before each finalize */
1098  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1099  int inputNesting;      /* Track nesting level of .read and other redirects */
1100  int outCount;          /* Revert to stdout when reaching zero */
1101  int cnt;               /* Number of records displayed so far */
1102  int lineno;            /* Line number of last line read from in */
1103  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1104  FILE *in;              /* Read commands from this stream */
1105  FILE *out;             /* Write results here */
1106  FILE *traceOut;        /* Output for sqlite3_trace() */
1107  int nErr;              /* Number of errors seen */
1108  int mode;              /* An output mode setting */
1109  int modePrior;         /* Saved mode */
1110  int cMode;             /* temporary output mode for the current query */
1111  int normalMode;        /* Output mode before ".explain on" */
1112  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1113  int showHeader;        /* True to show column names in List or Column mode */
1114  int nCheck;            /* Number of ".check" commands run */
1115  unsigned nProgress;    /* Number of progress callbacks encountered */
1116  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1117  unsigned flgProgress;  /* Flags for the progress callback */
1118  unsigned shellFlgs;    /* Various flags */
1119  unsigned priorShFlgs;  /* Saved copy of flags */
1120  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1121  char *zDestTable;      /* Name of destination table when MODE_Insert */
1122  char *zTempFile;       /* Temporary file that might need deleting */
1123  char zTestcase[30];    /* Name of current test case */
1124  char colSeparator[20]; /* Column separator character for several modes */
1125  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1126  char colSepPrior[20];  /* Saved column separator */
1127  char rowSepPrior[20];  /* Saved row separator */
1128  int *colWidth;         /* Requested width of each column in columnar modes */
1129  int *actualWidth;      /* Actual width of each column */
1130  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1131  char nullValue[20];    /* The text to print when a NULL comes back from
1132                         ** the database */
1133  char outfile[FILENAME_MAX]; /* Filename for *out */
1134  sqlite3_stmt *pStmt;   /* Current statement if any. */
1135  FILE *pLog;            /* Write log output here */
1136  struct AuxDb {         /* Storage space for auxiliary database connections */
1137    sqlite3 *db;               /* Connection pointer */
1138    const char *zDbFilename;   /* Filename used to open the connection */
1139    char *zFreeOnClose;        /* Free this memory allocation on close */
1140#if defined(SQLITE_ENABLE_SESSION)
1141    int nSession;              /* Number of active sessions */
1142    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1143#endif
1144  } aAuxDb[5],           /* Array of all database connections */
1145    *pAuxDb;             /* Currently active database connection */
1146  int *aiIndent;         /* Array of indents used in MODE_Explain */
1147  int nIndent;           /* Size of array aiIndent[] */
1148  int iIndent;           /* Index of current op in aiIndent[] */
1149  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1150  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1151  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1152};
1153
1154
1155/* Allowed values for ShellState.autoEQP
1156*/
1157#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1158#define AUTOEQP_on       1           /* Automatic EQP is on */
1159#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1160#define AUTOEQP_full     3           /* Show full EXPLAIN */
1161
1162/* Allowed values for ShellState.openMode
1163*/
1164#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1165#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1166#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1167#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1168#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1169#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1170#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1171
1172/* Allowed values for ShellState.eTraceType
1173*/
1174#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1175#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1176#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1177
1178/* Bits in the ShellState.flgProgress variable */
1179#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1180#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1181                                   ** callback limit is reached, and for each
1182                                   ** top-level SQL statement */
1183#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1184
1185/*
1186** These are the allowed shellFlgs values
1187*/
1188#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1189#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1190#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1191#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1192#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1193#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1194#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1195#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1196#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1197#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1198
1199/*
1200** Macros for testing and setting shellFlgs
1201*/
1202#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1203#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1204#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1205
1206/*
1207** These are the allowed modes.
1208*/
1209#define MODE_Line     0  /* One column per line.  Blank line between records */
1210#define MODE_Column   1  /* One record per line in neat columns */
1211#define MODE_List     2  /* One record per line with a separator */
1212#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1213#define MODE_Html     4  /* Generate an XHTML table */
1214#define MODE_Insert   5  /* Generate SQL "insert" statements */
1215#define MODE_Quote    6  /* Quote values as for SQL */
1216#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1217#define MODE_Csv      8  /* Quote strings, numbers are plain */
1218#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1219#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1220#define MODE_Pretty  11  /* Pretty-print schemas */
1221#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1222#define MODE_Json    13  /* Output JSON */
1223#define MODE_Markdown 14 /* Markdown formatting */
1224#define MODE_Table   15  /* MySQL-style table formatting */
1225#define MODE_Box     16  /* Unicode box-drawing characters */
1226#define MODE_Count   17  /* Output only a count of the rows of output */
1227#define MODE_Off     18  /* No query output shown */
1228
1229static const char *modeDescr[] = {
1230  "line",
1231  "column",
1232  "list",
1233  "semi",
1234  "html",
1235  "insert",
1236  "quote",
1237  "tcl",
1238  "csv",
1239  "explain",
1240  "ascii",
1241  "prettyprint",
1242  "eqp",
1243  "json",
1244  "markdown",
1245  "table",
1246  "box",
1247  "count",
1248  "off"
1249};
1250
1251/*
1252** These are the column/row/line separators used by the various
1253** import/export modes.
1254*/
1255#define SEP_Column    "|"
1256#define SEP_Row       "\n"
1257#define SEP_Tab       "\t"
1258#define SEP_Space     " "
1259#define SEP_Comma     ","
1260#define SEP_CrLf      "\r\n"
1261#define SEP_Unit      "\x1F"
1262#define SEP_Record    "\x1E"
1263
1264/*
1265** Limit input nesting via .read or any other input redirect.
1266** It's not too expensive, so a generous allowance can be made.
1267*/
1268#define MAX_INPUT_NESTING 25
1269
1270/*
1271** A callback for the sqlite3_log() interface.
1272*/
1273static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1274  ShellState *p = (ShellState*)pArg;
1275  if( p->pLog==0 ) return;
1276  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1277  fflush(p->pLog);
1278}
1279
1280/*
1281** SQL function:  shell_putsnl(X)
1282**
1283** Write the text X to the screen (or whatever output is being directed)
1284** adding a newline at the end, and then return X.
1285*/
1286static void shellPutsFunc(
1287  sqlite3_context *pCtx,
1288  int nVal,
1289  sqlite3_value **apVal
1290){
1291  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1292  (void)nVal;
1293  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1294  sqlite3_result_value(pCtx, apVal[0]);
1295}
1296
1297/*
1298** If in safe mode, print an error message described by the arguments
1299** and exit immediately.
1300*/
1301static void failIfSafeMode(
1302  ShellState *p,
1303  const char *zErrMsg,
1304  ...
1305){
1306  if( p->bSafeMode ){
1307    va_list ap;
1308    char *zMsg;
1309    va_start(ap, zErrMsg);
1310    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1311    va_end(ap);
1312    raw_printf(stderr, "line %d: ", p->lineno);
1313    utf8_printf(stderr, "%s\n", zMsg);
1314    exit(1);
1315  }
1316}
1317
1318/*
1319** SQL function:   edit(VALUE)
1320**                 edit(VALUE,EDITOR)
1321**
1322** These steps:
1323**
1324**     (1) Write VALUE into a temporary file.
1325**     (2) Run program EDITOR on that temporary file.
1326**     (3) Read the temporary file back and return its content as the result.
1327**     (4) Delete the temporary file
1328**
1329** If the EDITOR argument is omitted, use the value in the VISUAL
1330** environment variable.  If still there is no EDITOR, through an error.
1331**
1332** Also throw an error if the EDITOR program returns a non-zero exit code.
1333*/
1334#ifndef SQLITE_NOHAVE_SYSTEM
1335static void editFunc(
1336  sqlite3_context *context,
1337  int argc,
1338  sqlite3_value **argv
1339){
1340  const char *zEditor;
1341  char *zTempFile = 0;
1342  sqlite3 *db;
1343  char *zCmd = 0;
1344  int bBin;
1345  int rc;
1346  int hasCRNL = 0;
1347  FILE *f = 0;
1348  sqlite3_int64 sz;
1349  sqlite3_int64 x;
1350  unsigned char *p = 0;
1351
1352  if( argc==2 ){
1353    zEditor = (const char*)sqlite3_value_text(argv[1]);
1354  }else{
1355    zEditor = getenv("VISUAL");
1356  }
1357  if( zEditor==0 ){
1358    sqlite3_result_error(context, "no editor for edit()", -1);
1359    return;
1360  }
1361  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1362    sqlite3_result_error(context, "NULL input to edit()", -1);
1363    return;
1364  }
1365  db = sqlite3_context_db_handle(context);
1366  zTempFile = 0;
1367  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1368  if( zTempFile==0 ){
1369    sqlite3_uint64 r = 0;
1370    sqlite3_randomness(sizeof(r), &r);
1371    zTempFile = sqlite3_mprintf("temp%llx", r);
1372    if( zTempFile==0 ){
1373      sqlite3_result_error_nomem(context);
1374      return;
1375    }
1376  }
1377  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1378  /* When writing the file to be edited, do \n to \r\n conversions on systems
1379  ** that want \r\n line endings */
1380  f = fopen(zTempFile, bBin ? "wb" : "w");
1381  if( f==0 ){
1382    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1383    goto edit_func_end;
1384  }
1385  sz = sqlite3_value_bytes(argv[0]);
1386  if( bBin ){
1387    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1388  }else{
1389    const char *z = (const char*)sqlite3_value_text(argv[0]);
1390    /* Remember whether or not the value originally contained \r\n */
1391    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1392    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1393  }
1394  fclose(f);
1395  f = 0;
1396  if( x!=sz ){
1397    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1398    goto edit_func_end;
1399  }
1400  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1401  if( zCmd==0 ){
1402    sqlite3_result_error_nomem(context);
1403    goto edit_func_end;
1404  }
1405  rc = system(zCmd);
1406  sqlite3_free(zCmd);
1407  if( rc ){
1408    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1409    goto edit_func_end;
1410  }
1411  f = fopen(zTempFile, "rb");
1412  if( f==0 ){
1413    sqlite3_result_error(context,
1414      "edit() cannot reopen temp file after edit", -1);
1415    goto edit_func_end;
1416  }
1417  fseek(f, 0, SEEK_END);
1418  sz = ftell(f);
1419  rewind(f);
1420  p = sqlite3_malloc64( sz+1 );
1421  if( p==0 ){
1422    sqlite3_result_error_nomem(context);
1423    goto edit_func_end;
1424  }
1425  x = fread(p, 1, (size_t)sz, f);
1426  fclose(f);
1427  f = 0;
1428  if( x!=sz ){
1429    sqlite3_result_error(context, "could not read back the whole file", -1);
1430    goto edit_func_end;
1431  }
1432  if( bBin ){
1433    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1434  }else{
1435    sqlite3_int64 i, j;
1436    if( hasCRNL ){
1437      /* If the original contains \r\n then do no conversions back to \n */
1438    }else{
1439      /* If the file did not originally contain \r\n then convert any new
1440      ** \r\n back into \n */
1441      for(i=j=0; i<sz; i++){
1442        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1443        p[j++] = p[i];
1444      }
1445      sz = j;
1446      p[sz] = 0;
1447    }
1448    sqlite3_result_text64(context, (const char*)p, sz,
1449                          sqlite3_free, SQLITE_UTF8);
1450  }
1451  p = 0;
1452
1453edit_func_end:
1454  if( f ) fclose(f);
1455  unlink(zTempFile);
1456  sqlite3_free(zTempFile);
1457  sqlite3_free(p);
1458}
1459#endif /* SQLITE_NOHAVE_SYSTEM */
1460
1461/*
1462** Save or restore the current output mode
1463*/
1464static void outputModePush(ShellState *p){
1465  p->modePrior = p->mode;
1466  p->priorShFlgs = p->shellFlgs;
1467  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1468  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1469}
1470static void outputModePop(ShellState *p){
1471  p->mode = p->modePrior;
1472  p->shellFlgs = p->priorShFlgs;
1473  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1474  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1475}
1476
1477/*
1478** Output the given string as a hex-encoded blob (eg. X'1234' )
1479*/
1480static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1481  int i;
1482  char *zBlob = (char *)pBlob;
1483  raw_printf(out,"X'");
1484  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1485  raw_printf(out,"'");
1486}
1487
1488/*
1489** Find a string that is not found anywhere in z[].  Return a pointer
1490** to that string.
1491**
1492** Try to use zA and zB first.  If both of those are already found in z[]
1493** then make up some string and store it in the buffer zBuf.
1494*/
1495static const char *unused_string(
1496  const char *z,                    /* Result must not appear anywhere in z */
1497  const char *zA, const char *zB,   /* Try these first */
1498  char *zBuf                        /* Space to store a generated string */
1499){
1500  unsigned i = 0;
1501  if( strstr(z, zA)==0 ) return zA;
1502  if( strstr(z, zB)==0 ) return zB;
1503  do{
1504    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1505  }while( strstr(z,zBuf)!=0 );
1506  return zBuf;
1507}
1508
1509/*
1510** Output the given string as a quoted string using SQL quoting conventions.
1511**
1512** See also: output_quoted_escaped_string()
1513*/
1514static void output_quoted_string(FILE *out, const char *z){
1515  int i;
1516  char c;
1517  setBinaryMode(out, 1);
1518  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1519  if( c==0 ){
1520    utf8_printf(out,"'%s'",z);
1521  }else{
1522    raw_printf(out, "'");
1523    while( *z ){
1524      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1525      if( c=='\'' ) i++;
1526      if( i ){
1527        utf8_printf(out, "%.*s", i, z);
1528        z += i;
1529      }
1530      if( c=='\'' ){
1531        raw_printf(out, "'");
1532        continue;
1533      }
1534      if( c==0 ){
1535        break;
1536      }
1537      z++;
1538    }
1539    raw_printf(out, "'");
1540  }
1541  setTextMode(out, 1);
1542}
1543
1544/*
1545** Output the given string as a quoted string using SQL quoting conventions.
1546** Additionallly , escape the "\n" and "\r" characters so that they do not
1547** get corrupted by end-of-line translation facilities in some operating
1548** systems.
1549**
1550** This is like output_quoted_string() but with the addition of the \r\n
1551** escape mechanism.
1552*/
1553static void output_quoted_escaped_string(FILE *out, const char *z){
1554  int i;
1555  char c;
1556  setBinaryMode(out, 1);
1557  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1558  if( c==0 ){
1559    utf8_printf(out,"'%s'",z);
1560  }else{
1561    const char *zNL = 0;
1562    const char *zCR = 0;
1563    int nNL = 0;
1564    int nCR = 0;
1565    char zBuf1[20], zBuf2[20];
1566    for(i=0; z[i]; i++){
1567      if( z[i]=='\n' ) nNL++;
1568      if( z[i]=='\r' ) nCR++;
1569    }
1570    if( nNL ){
1571      raw_printf(out, "replace(");
1572      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1573    }
1574    if( nCR ){
1575      raw_printf(out, "replace(");
1576      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1577    }
1578    raw_printf(out, "'");
1579    while( *z ){
1580      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1581      if( c=='\'' ) i++;
1582      if( i ){
1583        utf8_printf(out, "%.*s", i, z);
1584        z += i;
1585      }
1586      if( c=='\'' ){
1587        raw_printf(out, "'");
1588        continue;
1589      }
1590      if( c==0 ){
1591        break;
1592      }
1593      z++;
1594      if( c=='\n' ){
1595        raw_printf(out, "%s", zNL);
1596        continue;
1597      }
1598      raw_printf(out, "%s", zCR);
1599    }
1600    raw_printf(out, "'");
1601    if( nCR ){
1602      raw_printf(out, ",'%s',char(13))", zCR);
1603    }
1604    if( nNL ){
1605      raw_printf(out, ",'%s',char(10))", zNL);
1606    }
1607  }
1608  setTextMode(out, 1);
1609}
1610
1611/*
1612** Output the given string as a quoted according to C or TCL quoting rules.
1613*/
1614static void output_c_string(FILE *out, const char *z){
1615  unsigned int c;
1616  fputc('"', out);
1617  while( (c = *(z++))!=0 ){
1618    if( c=='\\' ){
1619      fputc(c, out);
1620      fputc(c, out);
1621    }else if( c=='"' ){
1622      fputc('\\', out);
1623      fputc('"', out);
1624    }else if( c=='\t' ){
1625      fputc('\\', out);
1626      fputc('t', out);
1627    }else if( c=='\n' ){
1628      fputc('\\', out);
1629      fputc('n', out);
1630    }else if( c=='\r' ){
1631      fputc('\\', out);
1632      fputc('r', out);
1633    }else if( !isprint(c&0xff) ){
1634      raw_printf(out, "\\%03o", c&0xff);
1635    }else{
1636      fputc(c, out);
1637    }
1638  }
1639  fputc('"', out);
1640}
1641
1642/*
1643** Output the given string as a quoted according to JSON quoting rules.
1644*/
1645static void output_json_string(FILE *out, const char *z, int n){
1646  unsigned int c;
1647  if( n<0 ) n = (int)strlen(z);
1648  fputc('"', out);
1649  while( n-- ){
1650    c = *(z++);
1651    if( c=='\\' || c=='"' ){
1652      fputc('\\', out);
1653      fputc(c, out);
1654    }else if( c<=0x1f ){
1655      fputc('\\', out);
1656      if( c=='\b' ){
1657        fputc('b', out);
1658      }else if( c=='\f' ){
1659        fputc('f', out);
1660      }else if( c=='\n' ){
1661        fputc('n', out);
1662      }else if( c=='\r' ){
1663        fputc('r', out);
1664      }else if( c=='\t' ){
1665        fputc('t', out);
1666      }else{
1667         raw_printf(out, "u%04x",c);
1668      }
1669    }else{
1670      fputc(c, out);
1671    }
1672  }
1673  fputc('"', out);
1674}
1675
1676/*
1677** Output the given string with characters that are special to
1678** HTML escaped.
1679*/
1680static void output_html_string(FILE *out, const char *z){
1681  int i;
1682  if( z==0 ) z = "";
1683  while( *z ){
1684    for(i=0;   z[i]
1685            && z[i]!='<'
1686            && z[i]!='&'
1687            && z[i]!='>'
1688            && z[i]!='\"'
1689            && z[i]!='\'';
1690        i++){}
1691    if( i>0 ){
1692      utf8_printf(out,"%.*s",i,z);
1693    }
1694    if( z[i]=='<' ){
1695      raw_printf(out,"&lt;");
1696    }else if( z[i]=='&' ){
1697      raw_printf(out,"&amp;");
1698    }else if( z[i]=='>' ){
1699      raw_printf(out,"&gt;");
1700    }else if( z[i]=='\"' ){
1701      raw_printf(out,"&quot;");
1702    }else if( z[i]=='\'' ){
1703      raw_printf(out,"&#39;");
1704    }else{
1705      break;
1706    }
1707    z += i + 1;
1708  }
1709}
1710
1711/*
1712** If a field contains any character identified by a 1 in the following
1713** array, then the string must be quoted for CSV.
1714*/
1715static const char needCsvQuote[] = {
1716  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1717  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1718  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1719  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1720  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1721  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1722  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1723  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1724  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1725  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1726  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1727  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1728  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1729  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1730  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1731  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1732};
1733
1734/*
1735** Output a single term of CSV.  Actually, p->colSeparator is used for
1736** the separator, which may or may not be a comma.  p->nullValue is
1737** the null value.  Strings are quoted if necessary.  The separator
1738** is only issued if bSep is true.
1739*/
1740static void output_csv(ShellState *p, const char *z, int bSep){
1741  FILE *out = p->out;
1742  if( z==0 ){
1743    utf8_printf(out,"%s",p->nullValue);
1744  }else{
1745    unsigned i;
1746    for(i=0; z[i]; i++){
1747      if( needCsvQuote[((unsigned char*)z)[i]] ){
1748        i = 0;
1749        break;
1750      }
1751    }
1752    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1753      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1754      shell_check_oom(zQuoted);
1755      utf8_printf(out, "%s", zQuoted);
1756      sqlite3_free(zQuoted);
1757    }else{
1758      utf8_printf(out, "%s", z);
1759    }
1760  }
1761  if( bSep ){
1762    utf8_printf(p->out, "%s", p->colSeparator);
1763  }
1764}
1765
1766/*
1767** This routine runs when the user presses Ctrl-C
1768*/
1769static void interrupt_handler(int NotUsed){
1770  UNUSED_PARAMETER(NotUsed);
1771  seenInterrupt++;
1772  if( seenInterrupt>2 ) exit(1);
1773  if( globalDb ) sqlite3_interrupt(globalDb);
1774}
1775
1776#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1777/*
1778** This routine runs for console events (e.g. Ctrl-C) on Win32
1779*/
1780static BOOL WINAPI ConsoleCtrlHandler(
1781  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1782){
1783  if( dwCtrlType==CTRL_C_EVENT ){
1784    interrupt_handler(0);
1785    return TRUE;
1786  }
1787  return FALSE;
1788}
1789#endif
1790
1791#ifndef SQLITE_OMIT_AUTHORIZATION
1792/*
1793** This authorizer runs in safe mode.
1794*/
1795static int safeModeAuth(
1796  void *pClientData,
1797  int op,
1798  const char *zA1,
1799  const char *zA2,
1800  const char *zA3,
1801  const char *zA4
1802){
1803  ShellState *p = (ShellState*)pClientData;
1804  static const char *azProhibitedFunctions[] = {
1805    "edit",
1806    "fts3_tokenizer",
1807    "load_extension",
1808    "readfile",
1809    "writefile",
1810    "zipfile",
1811    "zipfile_cds",
1812  };
1813  UNUSED_PARAMETER(zA2);
1814  UNUSED_PARAMETER(zA3);
1815  UNUSED_PARAMETER(zA4);
1816  switch( op ){
1817    case SQLITE_ATTACH: {
1818      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1819      break;
1820    }
1821    case SQLITE_FUNCTION: {
1822      int i;
1823      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1824        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1825          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1826                         azProhibitedFunctions[i]);
1827        }
1828      }
1829      break;
1830    }
1831  }
1832  return SQLITE_OK;
1833}
1834
1835/*
1836** When the ".auth ON" is set, the following authorizer callback is
1837** invoked.  It always returns SQLITE_OK.
1838*/
1839static int shellAuth(
1840  void *pClientData,
1841  int op,
1842  const char *zA1,
1843  const char *zA2,
1844  const char *zA3,
1845  const char *zA4
1846){
1847  ShellState *p = (ShellState*)pClientData;
1848  static const char *azAction[] = { 0,
1849     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1850     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1851     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1852     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1853     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1854     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1855     "PRAGMA",               "READ",                 "SELECT",
1856     "TRANSACTION",          "UPDATE",               "ATTACH",
1857     "DETACH",               "ALTER_TABLE",          "REINDEX",
1858     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1859     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1860  };
1861  int i;
1862  const char *az[4];
1863  az[0] = zA1;
1864  az[1] = zA2;
1865  az[2] = zA3;
1866  az[3] = zA4;
1867  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1868  for(i=0; i<4; i++){
1869    raw_printf(p->out, " ");
1870    if( az[i] ){
1871      output_c_string(p->out, az[i]);
1872    }else{
1873      raw_printf(p->out, "NULL");
1874    }
1875  }
1876  raw_printf(p->out, "\n");
1877  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1878  return SQLITE_OK;
1879}
1880#endif
1881
1882/*
1883** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1884**
1885** This routine converts some CREATE TABLE statements for shadow tables
1886** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1887*/
1888static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1889  if( z==0 ) return;
1890  if( zTail==0 ) return;
1891  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1892    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1893  }else{
1894    utf8_printf(out, "%s%s", z, zTail);
1895  }
1896}
1897static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1898  char c = z[n];
1899  z[n] = 0;
1900  printSchemaLine(out, z, zTail);
1901  z[n] = c;
1902}
1903
1904/*
1905** Return true if string z[] has nothing but whitespace and comments to the
1906** end of the first line.
1907*/
1908static int wsToEol(const char *z){
1909  int i;
1910  for(i=0; z[i]; i++){
1911    if( z[i]=='\n' ) return 1;
1912    if( IsSpace(z[i]) ) continue;
1913    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1914    return 0;
1915  }
1916  return 1;
1917}
1918
1919/*
1920** Add a new entry to the EXPLAIN QUERY PLAN data
1921*/
1922static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1923  EQPGraphRow *pNew;
1924  int nText = strlen30(zText);
1925  if( p->autoEQPtest ){
1926    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1927  }
1928  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1929  shell_check_oom(pNew);
1930  pNew->iEqpId = iEqpId;
1931  pNew->iParentId = p2;
1932  memcpy(pNew->zText, zText, nText+1);
1933  pNew->pNext = 0;
1934  if( p->sGraph.pLast ){
1935    p->sGraph.pLast->pNext = pNew;
1936  }else{
1937    p->sGraph.pRow = pNew;
1938  }
1939  p->sGraph.pLast = pNew;
1940}
1941
1942/*
1943** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1944** in p->sGraph.
1945*/
1946static void eqp_reset(ShellState *p){
1947  EQPGraphRow *pRow, *pNext;
1948  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1949    pNext = pRow->pNext;
1950    sqlite3_free(pRow);
1951  }
1952  memset(&p->sGraph, 0, sizeof(p->sGraph));
1953}
1954
1955/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1956** pOld, or return the first such line if pOld is NULL
1957*/
1958static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1959  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1960  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1961  return pRow;
1962}
1963
1964/* Render a single level of the graph that has iEqpId as its parent.  Called
1965** recursively to render sublevels.
1966*/
1967static void eqp_render_level(ShellState *p, int iEqpId){
1968  EQPGraphRow *pRow, *pNext;
1969  int n = strlen30(p->sGraph.zPrefix);
1970  char *z;
1971  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1972    pNext = eqp_next_row(p, iEqpId, pRow);
1973    z = pRow->zText;
1974    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1975                pNext ? "|--" : "`--", z);
1976    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1977      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1978      eqp_render_level(p, pRow->iEqpId);
1979      p->sGraph.zPrefix[n] = 0;
1980    }
1981  }
1982}
1983
1984/*
1985** Display and reset the EXPLAIN QUERY PLAN data
1986*/
1987static void eqp_render(ShellState *p){
1988  EQPGraphRow *pRow = p->sGraph.pRow;
1989  if( pRow ){
1990    if( pRow->zText[0]=='-' ){
1991      if( pRow->pNext==0 ){
1992        eqp_reset(p);
1993        return;
1994      }
1995      utf8_printf(p->out, "%s\n", pRow->zText+3);
1996      p->sGraph.pRow = pRow->pNext;
1997      sqlite3_free(pRow);
1998    }else{
1999      utf8_printf(p->out, "QUERY PLAN\n");
2000    }
2001    p->sGraph.zPrefix[0] = 0;
2002    eqp_render_level(p, 0);
2003    eqp_reset(p);
2004  }
2005}
2006
2007#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2008/*
2009** Progress handler callback.
2010*/
2011static int progress_handler(void *pClientData) {
2012  ShellState *p = (ShellState*)pClientData;
2013  p->nProgress++;
2014  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2015    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2016    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2017    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2018    return 1;
2019  }
2020  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2021    raw_printf(p->out, "Progress %u\n", p->nProgress);
2022  }
2023  return 0;
2024}
2025#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2026
2027/*
2028** Print N dashes
2029*/
2030static void print_dashes(FILE *out, int N){
2031  const char zDash[] = "--------------------------------------------------";
2032  const int nDash = sizeof(zDash) - 1;
2033  while( N>nDash ){
2034    fputs(zDash, out);
2035    N -= nDash;
2036  }
2037  raw_printf(out, "%.*s", N, zDash);
2038}
2039
2040/*
2041** Print a markdown or table-style row separator using ascii-art
2042*/
2043static void print_row_separator(
2044  ShellState *p,
2045  int nArg,
2046  const char *zSep
2047){
2048  int i;
2049  if( nArg>0 ){
2050    fputs(zSep, p->out);
2051    print_dashes(p->out, p->actualWidth[0]+2);
2052    for(i=1; i<nArg; i++){
2053      fputs(zSep, p->out);
2054      print_dashes(p->out, p->actualWidth[i]+2);
2055    }
2056    fputs(zSep, p->out);
2057  }
2058  fputs("\n", p->out);
2059}
2060
2061/*
2062** This is the callback routine that the shell
2063** invokes for each row of a query result.
2064*/
2065static int shell_callback(
2066  void *pArg,
2067  int nArg,        /* Number of result columns */
2068  char **azArg,    /* Text of each result column */
2069  char **azCol,    /* Column names */
2070  int *aiType      /* Column types.  Might be NULL */
2071){
2072  int i;
2073  ShellState *p = (ShellState*)pArg;
2074
2075  if( azArg==0 ) return 0;
2076  switch( p->cMode ){
2077    case MODE_Count:
2078    case MODE_Off: {
2079      break;
2080    }
2081    case MODE_Line: {
2082      int w = 5;
2083      if( azArg==0 ) break;
2084      for(i=0; i<nArg; i++){
2085        int len = strlen30(azCol[i] ? azCol[i] : "");
2086        if( len>w ) w = len;
2087      }
2088      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2089      for(i=0; i<nArg; i++){
2090        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2091                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2092      }
2093      break;
2094    }
2095    case MODE_Explain: {
2096      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2097      if( nArg>ArraySize(aExplainWidth) ){
2098        nArg = ArraySize(aExplainWidth);
2099      }
2100      if( p->cnt++==0 ){
2101        for(i=0; i<nArg; i++){
2102          int w = aExplainWidth[i];
2103          utf8_width_print(p->out, w, azCol[i]);
2104          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2105        }
2106        for(i=0; i<nArg; i++){
2107          int w = aExplainWidth[i];
2108          print_dashes(p->out, w);
2109          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2110        }
2111      }
2112      if( azArg==0 ) break;
2113      for(i=0; i<nArg; i++){
2114        int w = aExplainWidth[i];
2115        if( i==nArg-1 ) w = 0;
2116        if( azArg[i] && strlenChar(azArg[i])>w ){
2117          w = strlenChar(azArg[i]);
2118        }
2119        if( i==1 && p->aiIndent && p->pStmt ){
2120          if( p->iIndent<p->nIndent ){
2121            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2122          }
2123          p->iIndent++;
2124        }
2125        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2126        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2127      }
2128      break;
2129    }
2130    case MODE_Semi: {   /* .schema and .fullschema output */
2131      printSchemaLine(p->out, azArg[0], ";\n");
2132      break;
2133    }
2134    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2135      char *z;
2136      int j;
2137      int nParen = 0;
2138      char cEnd = 0;
2139      char c;
2140      int nLine = 0;
2141      assert( nArg==1 );
2142      if( azArg[0]==0 ) break;
2143      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2144       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2145      ){
2146        utf8_printf(p->out, "%s;\n", azArg[0]);
2147        break;
2148      }
2149      z = sqlite3_mprintf("%s", azArg[0]);
2150      shell_check_oom(z);
2151      j = 0;
2152      for(i=0; IsSpace(z[i]); i++){}
2153      for(; (c = z[i])!=0; i++){
2154        if( IsSpace(c) ){
2155          if( z[j-1]=='\r' ) z[j-1] = '\n';
2156          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2157        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2158          j--;
2159        }
2160        z[j++] = c;
2161      }
2162      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2163      z[j] = 0;
2164      if( strlen30(z)>=79 ){
2165        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2166          if( c==cEnd ){
2167            cEnd = 0;
2168          }else if( c=='"' || c=='\'' || c=='`' ){
2169            cEnd = c;
2170          }else if( c=='[' ){
2171            cEnd = ']';
2172          }else if( c=='-' && z[i+1]=='-' ){
2173            cEnd = '\n';
2174          }else if( c=='(' ){
2175            nParen++;
2176          }else if( c==')' ){
2177            nParen--;
2178            if( nLine>0 && nParen==0 && j>0 ){
2179              printSchemaLineN(p->out, z, j, "\n");
2180              j = 0;
2181            }
2182          }
2183          z[j++] = c;
2184          if( nParen==1 && cEnd==0
2185           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2186          ){
2187            if( c=='\n' ) j--;
2188            printSchemaLineN(p->out, z, j, "\n  ");
2189            j = 0;
2190            nLine++;
2191            while( IsSpace(z[i+1]) ){ i++; }
2192          }
2193        }
2194        z[j] = 0;
2195      }
2196      printSchemaLine(p->out, z, ";\n");
2197      sqlite3_free(z);
2198      break;
2199    }
2200    case MODE_List: {
2201      if( p->cnt++==0 && p->showHeader ){
2202        for(i=0; i<nArg; i++){
2203          utf8_printf(p->out,"%s%s",azCol[i],
2204                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2205        }
2206      }
2207      if( azArg==0 ) break;
2208      for(i=0; i<nArg; i++){
2209        char *z = azArg[i];
2210        if( z==0 ) z = p->nullValue;
2211        utf8_printf(p->out, "%s", z);
2212        if( i<nArg-1 ){
2213          utf8_printf(p->out, "%s", p->colSeparator);
2214        }else{
2215          utf8_printf(p->out, "%s", p->rowSeparator);
2216        }
2217      }
2218      break;
2219    }
2220    case MODE_Html: {
2221      if( p->cnt++==0 && p->showHeader ){
2222        raw_printf(p->out,"<TR>");
2223        for(i=0; i<nArg; i++){
2224          raw_printf(p->out,"<TH>");
2225          output_html_string(p->out, azCol[i]);
2226          raw_printf(p->out,"</TH>\n");
2227        }
2228        raw_printf(p->out,"</TR>\n");
2229      }
2230      if( azArg==0 ) break;
2231      raw_printf(p->out,"<TR>");
2232      for(i=0; i<nArg; i++){
2233        raw_printf(p->out,"<TD>");
2234        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2235        raw_printf(p->out,"</TD>\n");
2236      }
2237      raw_printf(p->out,"</TR>\n");
2238      break;
2239    }
2240    case MODE_Tcl: {
2241      if( p->cnt++==0 && p->showHeader ){
2242        for(i=0; i<nArg; i++){
2243          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2244          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2245        }
2246        utf8_printf(p->out, "%s", p->rowSeparator);
2247      }
2248      if( azArg==0 ) break;
2249      for(i=0; i<nArg; i++){
2250        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2251        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2252      }
2253      utf8_printf(p->out, "%s", p->rowSeparator);
2254      break;
2255    }
2256    case MODE_Csv: {
2257      setBinaryMode(p->out, 1);
2258      if( p->cnt++==0 && p->showHeader ){
2259        for(i=0; i<nArg; i++){
2260          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2261        }
2262        utf8_printf(p->out, "%s", p->rowSeparator);
2263      }
2264      if( nArg>0 ){
2265        for(i=0; i<nArg; i++){
2266          output_csv(p, azArg[i], i<nArg-1);
2267        }
2268        utf8_printf(p->out, "%s", p->rowSeparator);
2269      }
2270      setTextMode(p->out, 1);
2271      break;
2272    }
2273    case MODE_Insert: {
2274      if( azArg==0 ) break;
2275      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2276      if( p->showHeader ){
2277        raw_printf(p->out,"(");
2278        for(i=0; i<nArg; i++){
2279          if( i>0 ) raw_printf(p->out, ",");
2280          if( quoteChar(azCol[i]) ){
2281            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2282            shell_check_oom(z);
2283            utf8_printf(p->out, "%s", z);
2284            sqlite3_free(z);
2285          }else{
2286            raw_printf(p->out, "%s", azCol[i]);
2287          }
2288        }
2289        raw_printf(p->out,")");
2290      }
2291      p->cnt++;
2292      for(i=0; i<nArg; i++){
2293        raw_printf(p->out, i>0 ? "," : " VALUES(");
2294        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2295          utf8_printf(p->out,"NULL");
2296        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2297          if( ShellHasFlag(p, SHFLG_Newlines) ){
2298            output_quoted_string(p->out, azArg[i]);
2299          }else{
2300            output_quoted_escaped_string(p->out, azArg[i]);
2301          }
2302        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2303          utf8_printf(p->out,"%s", azArg[i]);
2304        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2305          char z[50];
2306          double r = sqlite3_column_double(p->pStmt, i);
2307          sqlite3_uint64 ur;
2308          memcpy(&ur,&r,sizeof(r));
2309          if( ur==0x7ff0000000000000LL ){
2310            raw_printf(p->out, "1e999");
2311          }else if( ur==0xfff0000000000000LL ){
2312            raw_printf(p->out, "-1e999");
2313          }else{
2314            sqlite3_int64 ir = (sqlite3_int64)r;
2315            if( r==(double)ir ){
2316              sqlite3_snprintf(50,z,"%lld.0", ir);
2317            }else{
2318              sqlite3_snprintf(50,z,"%!.20g", r);
2319            }
2320            raw_printf(p->out, "%s", z);
2321          }
2322        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2323          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2324          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2325          output_hex_blob(p->out, pBlob, nBlob);
2326        }else if( isNumber(azArg[i], 0) ){
2327          utf8_printf(p->out,"%s", azArg[i]);
2328        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2329          output_quoted_string(p->out, azArg[i]);
2330        }else{
2331          output_quoted_escaped_string(p->out, azArg[i]);
2332        }
2333      }
2334      raw_printf(p->out,");\n");
2335      break;
2336    }
2337    case MODE_Json: {
2338      if( azArg==0 ) break;
2339      if( p->cnt==0 ){
2340        fputs("[{", p->out);
2341      }else{
2342        fputs(",\n{", p->out);
2343      }
2344      p->cnt++;
2345      for(i=0; i<nArg; i++){
2346        output_json_string(p->out, azCol[i], -1);
2347        putc(':', p->out);
2348        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2349          fputs("null",p->out);
2350        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2351          char z[50];
2352          double r = sqlite3_column_double(p->pStmt, i);
2353          sqlite3_uint64 ur;
2354          memcpy(&ur,&r,sizeof(r));
2355          if( ur==0x7ff0000000000000LL ){
2356            raw_printf(p->out, "1e999");
2357          }else if( ur==0xfff0000000000000LL ){
2358            raw_printf(p->out, "-1e999");
2359          }else{
2360            sqlite3_snprintf(50,z,"%!.20g", r);
2361            raw_printf(p->out, "%s", z);
2362          }
2363        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2364          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2365          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2366          output_json_string(p->out, pBlob, nBlob);
2367        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2368          output_json_string(p->out, azArg[i], -1);
2369        }else{
2370          utf8_printf(p->out,"%s", azArg[i]);
2371        }
2372        if( i<nArg-1 ){
2373          putc(',', p->out);
2374        }
2375      }
2376      putc('}', p->out);
2377      break;
2378    }
2379    case MODE_Quote: {
2380      if( azArg==0 ) break;
2381      if( p->cnt==0 && p->showHeader ){
2382        for(i=0; i<nArg; i++){
2383          if( i>0 ) fputs(p->colSeparator, p->out);
2384          output_quoted_string(p->out, azCol[i]);
2385        }
2386        fputs(p->rowSeparator, p->out);
2387      }
2388      p->cnt++;
2389      for(i=0; i<nArg; i++){
2390        if( i>0 ) fputs(p->colSeparator, p->out);
2391        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2392          utf8_printf(p->out,"NULL");
2393        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2394          output_quoted_string(p->out, azArg[i]);
2395        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2396          utf8_printf(p->out,"%s", azArg[i]);
2397        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2398          char z[50];
2399          double r = sqlite3_column_double(p->pStmt, i);
2400          sqlite3_snprintf(50,z,"%!.20g", r);
2401          raw_printf(p->out, "%s", z);
2402        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2403          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2404          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2405          output_hex_blob(p->out, pBlob, nBlob);
2406        }else if( isNumber(azArg[i], 0) ){
2407          utf8_printf(p->out,"%s", azArg[i]);
2408        }else{
2409          output_quoted_string(p->out, azArg[i]);
2410        }
2411      }
2412      fputs(p->rowSeparator, p->out);
2413      break;
2414    }
2415    case MODE_Ascii: {
2416      if( p->cnt++==0 && p->showHeader ){
2417        for(i=0; i<nArg; i++){
2418          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2419          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2420        }
2421        utf8_printf(p->out, "%s", p->rowSeparator);
2422      }
2423      if( azArg==0 ) break;
2424      for(i=0; i<nArg; i++){
2425        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2426        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2427      }
2428      utf8_printf(p->out, "%s", p->rowSeparator);
2429      break;
2430    }
2431    case MODE_EQP: {
2432      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2433      break;
2434    }
2435  }
2436  return 0;
2437}
2438
2439/*
2440** This is the callback routine that the SQLite library
2441** invokes for each row of a query result.
2442*/
2443static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2444  /* since we don't have type info, call the shell_callback with a NULL value */
2445  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2446}
2447
2448/*
2449** This is the callback routine from sqlite3_exec() that appends all
2450** output onto the end of a ShellText object.
2451*/
2452static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2453  ShellText *p = (ShellText*)pArg;
2454  int i;
2455  UNUSED_PARAMETER(az);
2456  if( azArg==0 ) return 0;
2457  if( p->n ) appendText(p, "|", 0);
2458  for(i=0; i<nArg; i++){
2459    if( i ) appendText(p, ",", 0);
2460    if( azArg[i] ) appendText(p, azArg[i], 0);
2461  }
2462  return 0;
2463}
2464
2465/*
2466** Generate an appropriate SELFTEST table in the main database.
2467*/
2468static void createSelftestTable(ShellState *p){
2469  char *zErrMsg = 0;
2470  sqlite3_exec(p->db,
2471    "SAVEPOINT selftest_init;\n"
2472    "CREATE TABLE IF NOT EXISTS selftest(\n"
2473    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2474    "  op TEXT,\n"                   /* Operator:  memo run */
2475    "  cmd TEXT,\n"                  /* Command text */
2476    "  ans TEXT\n"                   /* Desired answer */
2477    ");"
2478    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2479    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2480    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2481    "         'memo','Tests generated by --init');\n"
2482    "INSERT INTO [_shell$self]\n"
2483    "  SELECT 'run',\n"
2484    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2485                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2486    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2487                          "FROM sqlite_schema ORDER BY 2',224));\n"
2488    "INSERT INTO [_shell$self]\n"
2489    "  SELECT 'run',"
2490    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2491    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2492    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2493    "  FROM (\n"
2494    "    SELECT name FROM sqlite_schema\n"
2495    "     WHERE type='table'\n"
2496    "       AND name<>'selftest'\n"
2497    "       AND coalesce(rootpage,0)>0\n"
2498    "  )\n"
2499    " ORDER BY name;\n"
2500    "INSERT INTO [_shell$self]\n"
2501    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2502    "INSERT INTO selftest(tno,op,cmd,ans)"
2503    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2504    "DROP TABLE [_shell$self];"
2505    ,0,0,&zErrMsg);
2506  if( zErrMsg ){
2507    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2508    sqlite3_free(zErrMsg);
2509  }
2510  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2511}
2512
2513
2514/*
2515** Set the destination table field of the ShellState structure to
2516** the name of the table given.  Escape any quote characters in the
2517** table name.
2518*/
2519static void set_table_name(ShellState *p, const char *zName){
2520  int i, n;
2521  char cQuote;
2522  char *z;
2523
2524  if( p->zDestTable ){
2525    free(p->zDestTable);
2526    p->zDestTable = 0;
2527  }
2528  if( zName==0 ) return;
2529  cQuote = quoteChar(zName);
2530  n = strlen30(zName);
2531  if( cQuote ) n += n+2;
2532  z = p->zDestTable = malloc( n+1 );
2533  shell_check_oom(z);
2534  n = 0;
2535  if( cQuote ) z[n++] = cQuote;
2536  for(i=0; zName[i]; i++){
2537    z[n++] = zName[i];
2538    if( zName[i]==cQuote ) z[n++] = cQuote;
2539  }
2540  if( cQuote ) z[n++] = cQuote;
2541  z[n] = 0;
2542}
2543
2544/*
2545** Maybe construct two lines of text that point out the position of a
2546** syntax error.  Return a pointer to the text, in memory obtained from
2547** sqlite3_malloc().  Or, if the most recent error does not involve a
2548** specific token that we can point to, return an empty string.
2549**
2550** In all cases, the memory returned is obtained from sqlite3_malloc64()
2551** and should be released by the caller invoking sqlite3_free().
2552*/
2553static char *shell_error_context(const char *zSql, sqlite3 *db){
2554  int iOffset;
2555  size_t len;
2556  char *zCode;
2557  char *zMsg;
2558  int i;
2559  if( db==0
2560   || zSql==0
2561   || (iOffset = sqlite3_error_offset(db))<0
2562  ){
2563    return sqlite3_mprintf("");
2564  }
2565  while( iOffset>50 ){
2566    iOffset--;
2567    zSql++;
2568    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2569  }
2570  len = strlen(zSql);
2571  if( len>78 ){
2572    len = 78;
2573    while( (zSql[len]&0xc0)==0x80 ) len--;
2574  }
2575  zCode = sqlite3_mprintf("%.*s", len, zSql);
2576  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2577  if( iOffset<25 ){
2578    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2579  }else{
2580    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2581  }
2582  return zMsg;
2583}
2584
2585
2586/*
2587** Execute a query statement that will generate SQL output.  Print
2588** the result columns, comma-separated, on a line and then add a
2589** semicolon terminator to the end of that line.
2590**
2591** If the number of columns is 1 and that column contains text "--"
2592** then write the semicolon on a separate line.  That way, if a
2593** "--" comment occurs at the end of the statement, the comment
2594** won't consume the semicolon terminator.
2595*/
2596static int run_table_dump_query(
2597  ShellState *p,           /* Query context */
2598  const char *zSelect      /* SELECT statement to extract content */
2599){
2600  sqlite3_stmt *pSelect;
2601  int rc;
2602  int nResult;
2603  int i;
2604  const char *z;
2605  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2606  if( rc!=SQLITE_OK || !pSelect ){
2607    char *zContext = shell_error_context(zSelect, p->db);
2608    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2609                sqlite3_errmsg(p->db), zContext);
2610    sqlite3_free(zContext);
2611    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2612    return rc;
2613  }
2614  rc = sqlite3_step(pSelect);
2615  nResult = sqlite3_column_count(pSelect);
2616  while( rc==SQLITE_ROW ){
2617    z = (const char*)sqlite3_column_text(pSelect, 0);
2618    utf8_printf(p->out, "%s", z);
2619    for(i=1; i<nResult; i++){
2620      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2621    }
2622    if( z==0 ) z = "";
2623    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2624    if( z[0] ){
2625      raw_printf(p->out, "\n;\n");
2626    }else{
2627      raw_printf(p->out, ";\n");
2628    }
2629    rc = sqlite3_step(pSelect);
2630  }
2631  rc = sqlite3_finalize(pSelect);
2632  if( rc!=SQLITE_OK ){
2633    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2634                sqlite3_errmsg(p->db));
2635    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2636  }
2637  return rc;
2638}
2639
2640/*
2641** Allocate space and save off string indicating current error.
2642*/
2643static char *save_err_msg(
2644  sqlite3 *db,           /* Database to query */
2645  const char *zPhase,    /* When the error occcurs */
2646  int rc,                /* Error code returned from API */
2647  const char *zSql       /* SQL string, or NULL */
2648){
2649  char *zErr;
2650  char *zContext;
2651  sqlite3_str *pStr = sqlite3_str_new(0);
2652  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2653  if( rc>1 ){
2654    sqlite3_str_appendf(pStr, " (%d)", rc);
2655  }
2656  zContext = shell_error_context(zSql, db);
2657  if( zContext ){
2658    sqlite3_str_appendall(pStr, zContext);
2659    sqlite3_free(zContext);
2660  }
2661  zErr = sqlite3_str_finish(pStr);
2662  shell_check_oom(zErr);
2663  return zErr;
2664}
2665
2666#ifdef __linux__
2667/*
2668** Attempt to display I/O stats on Linux using /proc/PID/io
2669*/
2670static void displayLinuxIoStats(FILE *out){
2671  FILE *in;
2672  char z[200];
2673  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2674  in = fopen(z, "rb");
2675  if( in==0 ) return;
2676  while( fgets(z, sizeof(z), in)!=0 ){
2677    static const struct {
2678      const char *zPattern;
2679      const char *zDesc;
2680    } aTrans[] = {
2681      { "rchar: ",                  "Bytes received by read():" },
2682      { "wchar: ",                  "Bytes sent to write():"    },
2683      { "syscr: ",                  "Read() system calls:"      },
2684      { "syscw: ",                  "Write() system calls:"     },
2685      { "read_bytes: ",             "Bytes read from storage:"  },
2686      { "write_bytes: ",            "Bytes written to storage:" },
2687      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2688    };
2689    int i;
2690    for(i=0; i<ArraySize(aTrans); i++){
2691      int n = strlen30(aTrans[i].zPattern);
2692      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2693        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2694        break;
2695      }
2696    }
2697  }
2698  fclose(in);
2699}
2700#endif
2701
2702/*
2703** Display a single line of status using 64-bit values.
2704*/
2705static void displayStatLine(
2706  ShellState *p,            /* The shell context */
2707  char *zLabel,             /* Label for this one line */
2708  char *zFormat,            /* Format for the result */
2709  int iStatusCtrl,          /* Which status to display */
2710  int bReset                /* True to reset the stats */
2711){
2712  sqlite3_int64 iCur = -1;
2713  sqlite3_int64 iHiwtr = -1;
2714  int i, nPercent;
2715  char zLine[200];
2716  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2717  for(i=0, nPercent=0; zFormat[i]; i++){
2718    if( zFormat[i]=='%' ) nPercent++;
2719  }
2720  if( nPercent>1 ){
2721    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2722  }else{
2723    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2724  }
2725  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2726}
2727
2728/*
2729** Display memory stats.
2730*/
2731static int display_stats(
2732  sqlite3 *db,                /* Database to query */
2733  ShellState *pArg,           /* Pointer to ShellState */
2734  int bReset                  /* True to reset the stats */
2735){
2736  int iCur;
2737  int iHiwtr;
2738  FILE *out;
2739  if( pArg==0 || pArg->out==0 ) return 0;
2740  out = pArg->out;
2741
2742  if( pArg->pStmt && pArg->statsOn==2 ){
2743    int nCol, i, x;
2744    sqlite3_stmt *pStmt = pArg->pStmt;
2745    char z[100];
2746    nCol = sqlite3_column_count(pStmt);
2747    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2748    for(i=0; i<nCol; i++){
2749      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2750      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2751#ifndef SQLITE_OMIT_DECLTYPE
2752      sqlite3_snprintf(30, z+x, "declared type:");
2753      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2754#endif
2755#ifdef SQLITE_ENABLE_COLUMN_METADATA
2756      sqlite3_snprintf(30, z+x, "database name:");
2757      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2758      sqlite3_snprintf(30, z+x, "table name:");
2759      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2760      sqlite3_snprintf(30, z+x, "origin name:");
2761      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2762#endif
2763    }
2764  }
2765
2766  if( pArg->statsOn==3 ){
2767    if( pArg->pStmt ){
2768      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2769      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2770    }
2771    return 0;
2772  }
2773
2774  displayStatLine(pArg, "Memory Used:",
2775     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2776  displayStatLine(pArg, "Number of Outstanding Allocations:",
2777     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2778  if( pArg->shellFlgs & SHFLG_Pagecache ){
2779    displayStatLine(pArg, "Number of Pcache Pages Used:",
2780       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2781  }
2782  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2783     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2784  displayStatLine(pArg, "Largest Allocation:",
2785     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2786  displayStatLine(pArg, "Largest Pcache Allocation:",
2787     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2788#ifdef YYTRACKMAXSTACKDEPTH
2789  displayStatLine(pArg, "Deepest Parser Stack:",
2790     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2791#endif
2792
2793  if( db ){
2794    if( pArg->shellFlgs & SHFLG_Lookaside ){
2795      iHiwtr = iCur = -1;
2796      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2797                        &iCur, &iHiwtr, bReset);
2798      raw_printf(pArg->out,
2799              "Lookaside Slots Used:                %d (max %d)\n",
2800              iCur, iHiwtr);
2801      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2802                        &iCur, &iHiwtr, bReset);
2803      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2804              iHiwtr);
2805      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2806                        &iCur, &iHiwtr, bReset);
2807      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2808              iHiwtr);
2809      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2810                        &iCur, &iHiwtr, bReset);
2811      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2812              iHiwtr);
2813    }
2814    iHiwtr = iCur = -1;
2815    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2816    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2817            iCur);
2818    iHiwtr = iCur = -1;
2819    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2820    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2821    iHiwtr = iCur = -1;
2822    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2823    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2824    iHiwtr = iCur = -1;
2825    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2826    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2827    iHiwtr = iCur = -1;
2828    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2829    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2830    iHiwtr = iCur = -1;
2831    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2832    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2833            iCur);
2834    iHiwtr = iCur = -1;
2835    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2836    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2837            iCur);
2838  }
2839
2840  if( pArg->pStmt ){
2841    int iHit, iMiss;
2842    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2843                               bReset);
2844    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2845    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2846    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2847    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2848    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2849    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2850    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2851    if( iHit || iMiss ){
2852      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2853            iHit, iHit+iMiss);
2854    }
2855    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2856    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2857    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2858    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2859    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2860    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2861    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2862    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2863  }
2864
2865#ifdef __linux__
2866  displayLinuxIoStats(pArg->out);
2867#endif
2868
2869  /* Do not remove this machine readable comment: extra-stats-output-here */
2870
2871  return 0;
2872}
2873
2874/*
2875** Display scan stats.
2876*/
2877static void display_scanstats(
2878  sqlite3 *db,                    /* Database to query */
2879  ShellState *pArg                /* Pointer to ShellState */
2880){
2881#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2882  UNUSED_PARAMETER(db);
2883  UNUSED_PARAMETER(pArg);
2884#else
2885  int i, k, n, mx;
2886  raw_printf(pArg->out, "-------- scanstats --------\n");
2887  mx = 0;
2888  for(k=0; k<=mx; k++){
2889    double rEstLoop = 1.0;
2890    for(i=n=0; 1; i++){
2891      sqlite3_stmt *p = pArg->pStmt;
2892      sqlite3_int64 nLoop, nVisit;
2893      double rEst;
2894      int iSid;
2895      const char *zExplain;
2896      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2897        break;
2898      }
2899      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2900      if( iSid>mx ) mx = iSid;
2901      if( iSid!=k ) continue;
2902      if( n==0 ){
2903        rEstLoop = (double)nLoop;
2904        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2905      }
2906      n++;
2907      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2908      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2909      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2910      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2911      rEstLoop *= rEst;
2912      raw_printf(pArg->out,
2913          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2914          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2915      );
2916    }
2917  }
2918  raw_printf(pArg->out, "---------------------------\n");
2919#endif
2920}
2921
2922/*
2923** Parameter azArray points to a zero-terminated array of strings. zStr
2924** points to a single nul-terminated string. Return non-zero if zStr
2925** is equal, according to strcmp(), to any of the strings in the array.
2926** Otherwise, return zero.
2927*/
2928static int str_in_array(const char *zStr, const char **azArray){
2929  int i;
2930  for(i=0; azArray[i]; i++){
2931    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2932  }
2933  return 0;
2934}
2935
2936/*
2937** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2938** and populate the ShellState.aiIndent[] array with the number of
2939** spaces each opcode should be indented before it is output.
2940**
2941** The indenting rules are:
2942**
2943**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2944**       all opcodes that occur between the p2 jump destination and the opcode
2945**       itself by 2 spaces.
2946**
2947**     * Do the previous for "Return" instructions for when P2 is positive.
2948**       See tag-20220407a in wherecode.c and vdbe.c.
2949**
2950**     * For each "Goto", if the jump destination is earlier in the program
2951**       and ends on one of:
2952**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2953**       or if the P1 parameter is one instead of zero,
2954**       then indent all opcodes between the earlier instruction
2955**       and "Goto" by 2 spaces.
2956*/
2957static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2958  const char *zSql;               /* The text of the SQL statement */
2959  const char *z;                  /* Used to check if this is an EXPLAIN */
2960  int *abYield = 0;               /* True if op is an OP_Yield */
2961  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2962  int iOp;                        /* Index of operation in p->aiIndent[] */
2963
2964  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2965                           "Return", 0 };
2966  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2967                            "Rewind", 0 };
2968  const char *azGoto[] = { "Goto", 0 };
2969
2970  /* Try to figure out if this is really an EXPLAIN statement. If this
2971  ** cannot be verified, return early.  */
2972  if( sqlite3_column_count(pSql)!=8 ){
2973    p->cMode = p->mode;
2974    return;
2975  }
2976  zSql = sqlite3_sql(pSql);
2977  if( zSql==0 ) return;
2978  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2979  if( sqlite3_strnicmp(z, "explain", 7) ){
2980    p->cMode = p->mode;
2981    return;
2982  }
2983
2984  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2985    int i;
2986    int iAddr = sqlite3_column_int(pSql, 0);
2987    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2988
2989    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2990    ** p2 is an instruction address, set variable p2op to the index of that
2991    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2992    ** the current instruction is part of a sub-program generated by an
2993    ** SQL trigger or foreign key.  */
2994    int p2 = sqlite3_column_int(pSql, 3);
2995    int p2op = (p2 + (iOp-iAddr));
2996
2997    /* Grow the p->aiIndent array as required */
2998    if( iOp>=nAlloc ){
2999      if( iOp==0 ){
3000        /* Do further verfication that this is explain output.  Abort if
3001        ** it is not */
3002        static const char *explainCols[] = {
3003           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3004        int jj;
3005        for(jj=0; jj<ArraySize(explainCols); jj++){
3006          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3007            p->cMode = p->mode;
3008            sqlite3_reset(pSql);
3009            return;
3010          }
3011        }
3012      }
3013      nAlloc += 100;
3014      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3015      shell_check_oom(p->aiIndent);
3016      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3017      shell_check_oom(abYield);
3018    }
3019    abYield[iOp] = str_in_array(zOp, azYield);
3020    p->aiIndent[iOp] = 0;
3021    p->nIndent = iOp+1;
3022
3023    if( str_in_array(zOp, azNext) && p2op>0 ){
3024      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3025    }
3026    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3027     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3028    ){
3029      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3030    }
3031  }
3032
3033  p->iIndent = 0;
3034  sqlite3_free(abYield);
3035  sqlite3_reset(pSql);
3036}
3037
3038/*
3039** Free the array allocated by explain_data_prepare().
3040*/
3041static void explain_data_delete(ShellState *p){
3042  sqlite3_free(p->aiIndent);
3043  p->aiIndent = 0;
3044  p->nIndent = 0;
3045  p->iIndent = 0;
3046}
3047
3048/*
3049** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3050*/
3051static unsigned int savedSelectTrace;
3052static unsigned int savedWhereTrace;
3053static void disable_debug_trace_modes(void){
3054  unsigned int zero = 0;
3055  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3056  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3057  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3058  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3059}
3060static void restore_debug_trace_modes(void){
3061  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3062  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3063}
3064
3065/* Create the TEMP table used to store parameter bindings */
3066static void bind_table_init(ShellState *p){
3067  int wrSchema = 0;
3068  int defensiveMode = 0;
3069  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3070  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3071  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3072  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3073  sqlite3_exec(p->db,
3074    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3075    "  key TEXT PRIMARY KEY,\n"
3076    "  value\n"
3077    ") WITHOUT ROWID;",
3078    0, 0, 0);
3079  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3080  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3081}
3082
3083/*
3084** Bind parameters on a prepared statement.
3085**
3086** Parameter bindings are taken from a TEMP table of the form:
3087**
3088**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3089**    WITHOUT ROWID;
3090**
3091** No bindings occur if this table does not exist.  The name of the table
3092** begins with "sqlite_" so that it will not collide with ordinary application
3093** tables.  The table must be in the TEMP schema.
3094*/
3095static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3096  int nVar;
3097  int i;
3098  int rc;
3099  sqlite3_stmt *pQ = 0;
3100
3101  nVar = sqlite3_bind_parameter_count(pStmt);
3102  if( nVar==0 ) return;  /* Nothing to do */
3103  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3104                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3105    return; /* Parameter table does not exist */
3106  }
3107  rc = sqlite3_prepare_v2(pArg->db,
3108          "SELECT value FROM temp.sqlite_parameters"
3109          " WHERE key=?1", -1, &pQ, 0);
3110  if( rc || pQ==0 ) return;
3111  for(i=1; i<=nVar; i++){
3112    char zNum[30];
3113    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3114    if( zVar==0 ){
3115      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3116      zVar = zNum;
3117    }
3118    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3119    if( sqlite3_step(pQ)==SQLITE_ROW ){
3120      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3121    }else{
3122      sqlite3_bind_null(pStmt, i);
3123    }
3124    sqlite3_reset(pQ);
3125  }
3126  sqlite3_finalize(pQ);
3127}
3128
3129/*
3130** UTF8 box-drawing characters.  Imagine box lines like this:
3131**
3132**           1
3133**           |
3134**       4 --+-- 2
3135**           |
3136**           3
3137**
3138** Each box characters has between 2 and 4 of the lines leading from
3139** the center.  The characters are here identified by the numbers of
3140** their corresponding lines.
3141*/
3142#define BOX_24   "\342\224\200"  /* U+2500 --- */
3143#define BOX_13   "\342\224\202"  /* U+2502  |  */
3144#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3145#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3146#define BOX_12   "\342\224\224"  /* U+2514  '- */
3147#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3148#define BOX_123  "\342\224\234"  /* U+251c  |- */
3149#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3150#define BOX_234  "\342\224\254"  /* U+252c -,- */
3151#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3152#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3153
3154/* Draw horizontal line N characters long using unicode box
3155** characters
3156*/
3157static void print_box_line(FILE *out, int N){
3158  const char zDash[] =
3159      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3160      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3161  const int nDash = sizeof(zDash) - 1;
3162  N *= 3;
3163  while( N>nDash ){
3164    utf8_printf(out, zDash);
3165    N -= nDash;
3166  }
3167  utf8_printf(out, "%.*s", N, zDash);
3168}
3169
3170/*
3171** Draw a horizontal separator for a MODE_Box table.
3172*/
3173static void print_box_row_separator(
3174  ShellState *p,
3175  int nArg,
3176  const char *zSep1,
3177  const char *zSep2,
3178  const char *zSep3
3179){
3180  int i;
3181  if( nArg>0 ){
3182    utf8_printf(p->out, "%s", zSep1);
3183    print_box_line(p->out, p->actualWidth[0]+2);
3184    for(i=1; i<nArg; i++){
3185      utf8_printf(p->out, "%s", zSep2);
3186      print_box_line(p->out, p->actualWidth[i]+2);
3187    }
3188    utf8_printf(p->out, "%s", zSep3);
3189  }
3190  fputs("\n", p->out);
3191}
3192
3193/*
3194** z[] is a line of text that is to be displayed the .mode box or table or
3195** similar tabular formats.  z[] might contain control characters such
3196** as \n, \t, \f, or \r.
3197**
3198** Compute characters to display on the first line of z[].  Stop at the
3199** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3200** from malloc()) of that first line, which caller should free sometime.
3201** Write anything to display on the next line into *pzTail.  If this is
3202** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3203*/
3204static char *translateForDisplayAndDup(
3205  const unsigned char *z,            /* Input text to be transformed */
3206  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3207  int mxWidth,                       /* Max width.  0 means no limit */
3208  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3209){
3210  int i;                 /* Input bytes consumed */
3211  int j;                 /* Output bytes generated */
3212  int k;                 /* Input bytes to be displayed */
3213  int n;                 /* Output column number */
3214  unsigned char *zOut;   /* Output text */
3215
3216  if( z==0 ){
3217    *pzTail = 0;
3218    return 0;
3219  }
3220  if( mxWidth<0 ) mxWidth = -mxWidth;
3221  if( mxWidth==0 ) mxWidth = 1000000;
3222  i = j = n = 0;
3223  while( n<mxWidth ){
3224    if( z[i]>=' ' ){
3225      n++;
3226      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3227      continue;
3228    }
3229    if( z[i]=='\t' ){
3230      do{
3231        n++;
3232        j++;
3233      }while( (n&7)!=0 && n<mxWidth );
3234      i++;
3235      continue;
3236    }
3237    break;
3238  }
3239  if( n>=mxWidth && bWordWrap  ){
3240    /* Perhaps try to back up to a better place to break the line */
3241    for(k=i; k>i/2; k--){
3242      if( isspace(z[k-1]) ) break;
3243    }
3244    if( k<=i/2 ){
3245      for(k=i; k>i/2; k--){
3246        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3247      }
3248    }
3249    if( k<=i/2 ){
3250      k = i;
3251    }else{
3252      i = k;
3253      while( z[i]==' ' ) i++;
3254    }
3255  }else{
3256    k = i;
3257  }
3258  if( n>=mxWidth && z[i]>=' ' ){
3259   *pzTail = &z[i];
3260  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3261    *pzTail = z[i+2] ? &z[i+2] : 0;
3262  }else if( z[i]==0 || z[i+1]==0 ){
3263    *pzTail = 0;
3264  }else{
3265    *pzTail = &z[i+1];
3266  }
3267  zOut = malloc( j+1 );
3268  shell_check_oom(zOut);
3269  i = j = n = 0;
3270  while( i<k ){
3271    if( z[i]>=' ' ){
3272      n++;
3273      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3274      continue;
3275    }
3276    if( z[i]=='\t' ){
3277      do{
3278        n++;
3279        zOut[j++] = ' ';
3280      }while( (n&7)!=0 && n<mxWidth );
3281      i++;
3282      continue;
3283    }
3284    break;
3285  }
3286  zOut[j] = 0;
3287  return (char*)zOut;
3288}
3289
3290/* Extract the value of the i-th current column for pStmt as an SQL literal
3291** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3292** the caller.
3293*/
3294static char *quoted_column(sqlite3_stmt *pStmt, int i){
3295  switch( sqlite3_column_type(pStmt, i) ){
3296    case SQLITE_NULL: {
3297      return sqlite3_mprintf("NULL");
3298    }
3299    case SQLITE_INTEGER:
3300    case SQLITE_FLOAT: {
3301      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3302    }
3303    case SQLITE_TEXT: {
3304      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3305    }
3306    case SQLITE_BLOB: {
3307      int j;
3308      sqlite3_str *pStr = sqlite3_str_new(0);
3309      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3310      int n = sqlite3_column_bytes(pStmt,i);
3311      sqlite3_str_append(pStr, "x'", 2);
3312      for(j=0; j<n; j++){
3313        sqlite3_str_appendf(pStr, "%02x", a[j]);
3314      }
3315      sqlite3_str_append(pStr, "'", 1);
3316      return sqlite3_str_finish(pStr);
3317    }
3318  }
3319  return 0; /* Not reached */
3320}
3321
3322/*
3323** Run a prepared statement and output the result in one of the
3324** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3325** or MODE_Box.
3326**
3327** This is different from ordinary exec_prepared_stmt() in that
3328** it has to run the entire query and gather the results into memory
3329** first, in order to determine column widths, before providing
3330** any output.
3331*/
3332static void exec_prepared_stmt_columnar(
3333  ShellState *p,                        /* Pointer to ShellState */
3334  sqlite3_stmt *pStmt                   /* Statment to run */
3335){
3336  sqlite3_int64 nRow = 0;
3337  int nColumn = 0;
3338  char **azData = 0;
3339  sqlite3_int64 nAlloc = 0;
3340  char *abRowDiv = 0;
3341  const unsigned char *uz;
3342  const char *z;
3343  char **azQuoted = 0;
3344  int rc;
3345  sqlite3_int64 i, nData;
3346  int j, nTotal, w, n;
3347  const char *colSep = 0;
3348  const char *rowSep = 0;
3349  const unsigned char **azNextLine = 0;
3350  int bNextLine = 0;
3351  int bMultiLineRowExists = 0;
3352  int bw = p->cmOpts.bWordWrap;
3353
3354  rc = sqlite3_step(pStmt);
3355  if( rc!=SQLITE_ROW ) return;
3356  nColumn = sqlite3_column_count(pStmt);
3357  nAlloc = nColumn*4;
3358  if( nAlloc<=0 ) nAlloc = 1;
3359  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3360  shell_check_oom(azData);
3361  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3362  shell_check_oom((void*)azNextLine);
3363  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3364  if( p->cmOpts.bQuote ){
3365    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3366    shell_check_oom(azQuoted);
3367    memset(azQuoted, 0, nColumn*sizeof(char*) );
3368  }
3369  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3370  shell_check_oom(abRowDiv);
3371  if( nColumn>p->nWidth ){
3372    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3373    shell_check_oom(p->colWidth);
3374    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3375    p->nWidth = nColumn;
3376    p->actualWidth = &p->colWidth[nColumn];
3377  }
3378  memset(p->actualWidth, 0, nColumn*sizeof(int));
3379  for(i=0; i<nColumn; i++){
3380    w = p->colWidth[i];
3381    if( w<0 ) w = -w;
3382    p->actualWidth[i] = w;
3383  }
3384  for(i=0; i<nColumn; i++){
3385    const unsigned char *zNotUsed;
3386    int wx = p->colWidth[i];
3387    if( wx==0 ){
3388      wx = p->cmOpts.iWrap;
3389    }
3390    if( wx<0 ) wx = -wx;
3391    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3392    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3393  }
3394  do{
3395    int useNextLine = bNextLine;
3396    bNextLine = 0;
3397    if( (nRow+2)*nColumn >= nAlloc ){
3398      nAlloc *= 2;
3399      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3400      shell_check_oom(azData);
3401      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3402      shell_check_oom(abRowDiv);
3403    }
3404    abRowDiv[nRow] = 1;
3405    nRow++;
3406    for(i=0; i<nColumn; i++){
3407      int wx = p->colWidth[i];
3408      if( wx==0 ){
3409        wx = p->cmOpts.iWrap;
3410      }
3411      if( wx<0 ) wx = -wx;
3412      if( useNextLine ){
3413        uz = azNextLine[i];
3414      }else if( p->cmOpts.bQuote ){
3415        sqlite3_free(azQuoted[i]);
3416        azQuoted[i] = quoted_column(pStmt,i);
3417        uz = (const unsigned char*)azQuoted[i];
3418      }else{
3419        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3420      }
3421      azData[nRow*nColumn + i]
3422        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3423      if( azNextLine[i] ){
3424        bNextLine = 1;
3425        abRowDiv[nRow-1] = 0;
3426        bMultiLineRowExists = 1;
3427      }
3428    }
3429  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3430  nTotal = nColumn*(nRow+1);
3431  for(i=0; i<nTotal; i++){
3432    z = azData[i];
3433    if( z==0 ) z = p->nullValue;
3434    n = strlenChar(z);
3435    j = i%nColumn;
3436    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3437  }
3438  if( seenInterrupt ) goto columnar_end;
3439  if( nColumn==0 ) goto columnar_end;
3440  switch( p->cMode ){
3441    case MODE_Column: {
3442      colSep = "  ";
3443      rowSep = "\n";
3444      if( p->showHeader ){
3445        for(i=0; i<nColumn; i++){
3446          w = p->actualWidth[i];
3447          if( p->colWidth[i]<0 ) w = -w;
3448          utf8_width_print(p->out, w, azData[i]);
3449          fputs(i==nColumn-1?"\n":"  ", p->out);
3450        }
3451        for(i=0; i<nColumn; i++){
3452          print_dashes(p->out, p->actualWidth[i]);
3453          fputs(i==nColumn-1?"\n":"  ", p->out);
3454        }
3455      }
3456      break;
3457    }
3458    case MODE_Table: {
3459      colSep = " | ";
3460      rowSep = " |\n";
3461      print_row_separator(p, nColumn, "+");
3462      fputs("| ", p->out);
3463      for(i=0; i<nColumn; i++){
3464        w = p->actualWidth[i];
3465        n = strlenChar(azData[i]);
3466        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3467        fputs(i==nColumn-1?" |\n":" | ", p->out);
3468      }
3469      print_row_separator(p, nColumn, "+");
3470      break;
3471    }
3472    case MODE_Markdown: {
3473      colSep = " | ";
3474      rowSep = " |\n";
3475      fputs("| ", p->out);
3476      for(i=0; i<nColumn; i++){
3477        w = p->actualWidth[i];
3478        n = strlenChar(azData[i]);
3479        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3480        fputs(i==nColumn-1?" |\n":" | ", p->out);
3481      }
3482      print_row_separator(p, nColumn, "|");
3483      break;
3484    }
3485    case MODE_Box: {
3486      colSep = " " BOX_13 " ";
3487      rowSep = " " BOX_13 "\n";
3488      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3489      utf8_printf(p->out, BOX_13 " ");
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%s",
3494            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3495            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3496      }
3497      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3498      break;
3499    }
3500  }
3501  for(i=nColumn, j=0; i<nTotal; i++, j++){
3502    if( j==0 && p->cMode!=MODE_Column ){
3503      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3504    }
3505    z = azData[i];
3506    if( z==0 ) z = p->nullValue;
3507    w = p->actualWidth[j];
3508    if( p->colWidth[j]<0 ) w = -w;
3509    utf8_width_print(p->out, w, z);
3510    if( j==nColumn-1 ){
3511      utf8_printf(p->out, "%s", rowSep);
3512      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3513        if( p->cMode==MODE_Table ){
3514          print_row_separator(p, nColumn, "+");
3515        }else if( p->cMode==MODE_Box ){
3516          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3517        }else if( p->cMode==MODE_Column ){
3518          raw_printf(p->out, "\n");
3519        }
3520      }
3521      j = -1;
3522      if( seenInterrupt ) goto columnar_end;
3523    }else{
3524      utf8_printf(p->out, "%s", colSep);
3525    }
3526  }
3527  if( p->cMode==MODE_Table ){
3528    print_row_separator(p, nColumn, "+");
3529  }else if( p->cMode==MODE_Box ){
3530    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3531  }
3532columnar_end:
3533  if( seenInterrupt ){
3534    utf8_printf(p->out, "Interrupt\n");
3535  }
3536  nData = (nRow+1)*nColumn;
3537  for(i=0; i<nData; i++) free(azData[i]);
3538  sqlite3_free(azData);
3539  sqlite3_free((void*)azNextLine);
3540  sqlite3_free(abRowDiv);
3541  if( azQuoted ){
3542    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3543    sqlite3_free(azQuoted);
3544  }
3545}
3546
3547/*
3548** Run a prepared statement
3549*/
3550static void exec_prepared_stmt(
3551  ShellState *pArg,                                /* Pointer to ShellState */
3552  sqlite3_stmt *pStmt                              /* Statment to run */
3553){
3554  int rc;
3555  sqlite3_uint64 nRow = 0;
3556
3557  if( pArg->cMode==MODE_Column
3558   || pArg->cMode==MODE_Table
3559   || pArg->cMode==MODE_Box
3560   || pArg->cMode==MODE_Markdown
3561  ){
3562    exec_prepared_stmt_columnar(pArg, pStmt);
3563    return;
3564  }
3565
3566  /* perform the first step.  this will tell us if we
3567  ** have a result set or not and how wide it is.
3568  */
3569  rc = sqlite3_step(pStmt);
3570  /* if we have a result set... */
3571  if( SQLITE_ROW == rc ){
3572    /* allocate space for col name ptr, value ptr, and type */
3573    int nCol = sqlite3_column_count(pStmt);
3574    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3575    if( !pData ){
3576      shell_out_of_memory();
3577    }else{
3578      char **azCols = (char **)pData;      /* Names of result columns */
3579      char **azVals = &azCols[nCol];       /* Results */
3580      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3581      int i, x;
3582      assert(sizeof(int) <= sizeof(char *));
3583      /* save off ptrs to column names */
3584      for(i=0; i<nCol; i++){
3585        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3586      }
3587      do{
3588        nRow++;
3589        /* extract the data and data types */
3590        for(i=0; i<nCol; i++){
3591          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3592          if( x==SQLITE_BLOB
3593           && pArg
3594           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3595          ){
3596            azVals[i] = "";
3597          }else{
3598            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3599          }
3600          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3601            rc = SQLITE_NOMEM;
3602            break; /* from for */
3603          }
3604        } /* end for */
3605
3606        /* if data and types extracted successfully... */
3607        if( SQLITE_ROW == rc ){
3608          /* call the supplied callback with the result row data */
3609          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3610            rc = SQLITE_ABORT;
3611          }else{
3612            rc = sqlite3_step(pStmt);
3613          }
3614        }
3615      } while( SQLITE_ROW == rc );
3616      sqlite3_free(pData);
3617      if( pArg->cMode==MODE_Json ){
3618        fputs("]\n", pArg->out);
3619      }else if( pArg->cMode==MODE_Count ){
3620        char zBuf[200];
3621        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3622                         nRow, nRow!=1 ? "s" : "");
3623        printf("%s", zBuf);
3624      }
3625    }
3626  }
3627}
3628
3629#ifndef SQLITE_OMIT_VIRTUALTABLE
3630/*
3631** This function is called to process SQL if the previous shell command
3632** was ".expert". It passes the SQL in the second argument directly to
3633** the sqlite3expert object.
3634**
3635** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3636** code. In this case, (*pzErr) may be set to point to a buffer containing
3637** an English language error message. It is the responsibility of the
3638** caller to eventually free this buffer using sqlite3_free().
3639*/
3640static int expertHandleSQL(
3641  ShellState *pState,
3642  const char *zSql,
3643  char **pzErr
3644){
3645  assert( pState->expert.pExpert );
3646  assert( pzErr==0 || *pzErr==0 );
3647  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3648}
3649
3650/*
3651** This function is called either to silently clean up the object
3652** created by the ".expert" command (if bCancel==1), or to generate a
3653** report from it and then clean it up (if bCancel==0).
3654**
3655** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3656** code. In this case, (*pzErr) may be set to point to a buffer containing
3657** an English language error message. It is the responsibility of the
3658** caller to eventually free this buffer using sqlite3_free().
3659*/
3660static int expertFinish(
3661  ShellState *pState,
3662  int bCancel,
3663  char **pzErr
3664){
3665  int rc = SQLITE_OK;
3666  sqlite3expert *p = pState->expert.pExpert;
3667  assert( p );
3668  assert( bCancel || pzErr==0 || *pzErr==0 );
3669  if( bCancel==0 ){
3670    FILE *out = pState->out;
3671    int bVerbose = pState->expert.bVerbose;
3672
3673    rc = sqlite3_expert_analyze(p, pzErr);
3674    if( rc==SQLITE_OK ){
3675      int nQuery = sqlite3_expert_count(p);
3676      int i;
3677
3678      if( bVerbose ){
3679        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3680        raw_printf(out, "-- Candidates -----------------------------\n");
3681        raw_printf(out, "%s\n", zCand);
3682      }
3683      for(i=0; i<nQuery; i++){
3684        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3685        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3686        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3687        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3688        if( bVerbose ){
3689          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3690          raw_printf(out, "%s\n\n", zSql);
3691        }
3692        raw_printf(out, "%s\n", zIdx);
3693        raw_printf(out, "%s\n", zEQP);
3694      }
3695    }
3696  }
3697  sqlite3_expert_destroy(p);
3698  pState->expert.pExpert = 0;
3699  return rc;
3700}
3701
3702/*
3703** Implementation of ".expert" dot command.
3704*/
3705static int expertDotCommand(
3706  ShellState *pState,             /* Current shell tool state */
3707  char **azArg,                   /* Array of arguments passed to dot command */
3708  int nArg                        /* Number of entries in azArg[] */
3709){
3710  int rc = SQLITE_OK;
3711  char *zErr = 0;
3712  int i;
3713  int iSample = 0;
3714
3715  assert( pState->expert.pExpert==0 );
3716  memset(&pState->expert, 0, sizeof(ExpertInfo));
3717
3718  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3719    char *z = azArg[i];
3720    int n;
3721    if( z[0]=='-' && z[1]=='-' ) z++;
3722    n = strlen30(z);
3723    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3724      pState->expert.bVerbose = 1;
3725    }
3726    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3727      if( i==(nArg-1) ){
3728        raw_printf(stderr, "option requires an argument: %s\n", z);
3729        rc = SQLITE_ERROR;
3730      }else{
3731        iSample = (int)integerValue(azArg[++i]);
3732        if( iSample<0 || iSample>100 ){
3733          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3734          rc = SQLITE_ERROR;
3735        }
3736      }
3737    }
3738    else{
3739      raw_printf(stderr, "unknown option: %s\n", z);
3740      rc = SQLITE_ERROR;
3741    }
3742  }
3743
3744  if( rc==SQLITE_OK ){
3745    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3746    if( pState->expert.pExpert==0 ){
3747      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3748      rc = SQLITE_ERROR;
3749    }else{
3750      sqlite3_expert_config(
3751          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3752      );
3753    }
3754  }
3755  sqlite3_free(zErr);
3756
3757  return rc;
3758}
3759#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3760
3761/*
3762** Execute a statement or set of statements.  Print
3763** any result rows/columns depending on the current mode
3764** set via the supplied callback.
3765**
3766** This is very similar to SQLite's built-in sqlite3_exec()
3767** function except it takes a slightly different callback
3768** and callback data argument.
3769*/
3770static int shell_exec(
3771  ShellState *pArg,                         /* Pointer to ShellState */
3772  const char *zSql,                         /* SQL to be evaluated */
3773  char **pzErrMsg                           /* Error msg written here */
3774){
3775  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3776  int rc = SQLITE_OK;             /* Return Code */
3777  int rc2;
3778  const char *zLeftover;          /* Tail of unprocessed SQL */
3779  sqlite3 *db = pArg->db;
3780
3781  if( pzErrMsg ){
3782    *pzErrMsg = NULL;
3783  }
3784
3785#ifndef SQLITE_OMIT_VIRTUALTABLE
3786  if( pArg->expert.pExpert ){
3787    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3788    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3789  }
3790#endif
3791
3792  while( zSql[0] && (SQLITE_OK == rc) ){
3793    static const char *zStmtSql;
3794    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3795    if( SQLITE_OK != rc ){
3796      if( pzErrMsg ){
3797        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3798      }
3799    }else{
3800      if( !pStmt ){
3801        /* this happens for a comment or white-space */
3802        zSql = zLeftover;
3803        while( IsSpace(zSql[0]) ) zSql++;
3804        continue;
3805      }
3806      zStmtSql = sqlite3_sql(pStmt);
3807      if( zStmtSql==0 ) zStmtSql = "";
3808      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3809
3810      /* save off the prepared statment handle and reset row count */
3811      if( pArg ){
3812        pArg->pStmt = pStmt;
3813        pArg->cnt = 0;
3814      }
3815
3816      /* echo the sql statement if echo on */
3817      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3818        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3819      }
3820
3821      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3822      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3823        sqlite3_stmt *pExplain;
3824        char *zEQP;
3825        int triggerEQP = 0;
3826        disable_debug_trace_modes();
3827        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3828        if( pArg->autoEQP>=AUTOEQP_trigger ){
3829          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3830        }
3831        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3832        shell_check_oom(zEQP);
3833        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3834        if( rc==SQLITE_OK ){
3835          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3836            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3837            int iEqpId = sqlite3_column_int(pExplain, 0);
3838            int iParentId = sqlite3_column_int(pExplain, 1);
3839            if( zEQPLine==0 ) zEQPLine = "";
3840            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3841            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3842          }
3843          eqp_render(pArg);
3844        }
3845        sqlite3_finalize(pExplain);
3846        sqlite3_free(zEQP);
3847        if( pArg->autoEQP>=AUTOEQP_full ){
3848          /* Also do an EXPLAIN for ".eqp full" mode */
3849          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3850          shell_check_oom(zEQP);
3851          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3852          if( rc==SQLITE_OK ){
3853            pArg->cMode = MODE_Explain;
3854            explain_data_prepare(pArg, pExplain);
3855            exec_prepared_stmt(pArg, pExplain);
3856            explain_data_delete(pArg);
3857          }
3858          sqlite3_finalize(pExplain);
3859          sqlite3_free(zEQP);
3860        }
3861        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3862          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3863          /* Reprepare pStmt before reactiving trace modes */
3864          sqlite3_finalize(pStmt);
3865          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3866          if( pArg ) pArg->pStmt = pStmt;
3867        }
3868        restore_debug_trace_modes();
3869      }
3870
3871      if( pArg ){
3872        pArg->cMode = pArg->mode;
3873        if( pArg->autoExplain ){
3874          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3875            pArg->cMode = MODE_Explain;
3876          }
3877          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3878            pArg->cMode = MODE_EQP;
3879          }
3880        }
3881
3882        /* If the shell is currently in ".explain" mode, gather the extra
3883        ** data required to add indents to the output.*/
3884        if( pArg->cMode==MODE_Explain ){
3885          explain_data_prepare(pArg, pStmt);
3886        }
3887      }
3888
3889      bind_prepared_stmt(pArg, pStmt);
3890      exec_prepared_stmt(pArg, pStmt);
3891      explain_data_delete(pArg);
3892      eqp_render(pArg);
3893
3894      /* print usage stats if stats on */
3895      if( pArg && pArg->statsOn ){
3896        display_stats(db, pArg, 0);
3897      }
3898
3899      /* print loop-counters if required */
3900      if( pArg && pArg->scanstatsOn ){
3901        display_scanstats(db, pArg);
3902      }
3903
3904      /* Finalize the statement just executed. If this fails, save a
3905      ** copy of the error message. Otherwise, set zSql to point to the
3906      ** next statement to execute. */
3907      rc2 = sqlite3_finalize(pStmt);
3908      if( rc!=SQLITE_NOMEM ) rc = rc2;
3909      if( rc==SQLITE_OK ){
3910        zSql = zLeftover;
3911        while( IsSpace(zSql[0]) ) zSql++;
3912      }else if( pzErrMsg ){
3913        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3914      }
3915
3916      /* clear saved stmt handle */
3917      if( pArg ){
3918        pArg->pStmt = NULL;
3919      }
3920    }
3921  } /* end while */
3922
3923  return rc;
3924}
3925
3926/*
3927** Release memory previously allocated by tableColumnList().
3928*/
3929static void freeColumnList(char **azCol){
3930  int i;
3931  for(i=1; azCol[i]; i++){
3932    sqlite3_free(azCol[i]);
3933  }
3934  /* azCol[0] is a static string */
3935  sqlite3_free(azCol);
3936}
3937
3938/*
3939** Return a list of pointers to strings which are the names of all
3940** columns in table zTab.   The memory to hold the names is dynamically
3941** allocated and must be released by the caller using a subsequent call
3942** to freeColumnList().
3943**
3944** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3945** value that needs to be preserved, then azCol[0] is filled in with the
3946** name of the rowid column.
3947**
3948** The first regular column in the table is azCol[1].  The list is terminated
3949** by an entry with azCol[i]==0.
3950*/
3951static char **tableColumnList(ShellState *p, const char *zTab){
3952  char **azCol = 0;
3953  sqlite3_stmt *pStmt;
3954  char *zSql;
3955  int nCol = 0;
3956  int nAlloc = 0;
3957  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3958  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3959  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3960  int rc;
3961
3962  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3963  shell_check_oom(zSql);
3964  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3965  sqlite3_free(zSql);
3966  if( rc ) return 0;
3967  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3968    if( nCol>=nAlloc-2 ){
3969      nAlloc = nAlloc*2 + nCol + 10;
3970      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3971      shell_check_oom(azCol);
3972    }
3973    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3974    shell_check_oom(azCol[nCol]);
3975    if( sqlite3_column_int(pStmt, 5) ){
3976      nPK++;
3977      if( nPK==1
3978       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3979                          "INTEGER")==0
3980      ){
3981        isIPK = 1;
3982      }else{
3983        isIPK = 0;
3984      }
3985    }
3986  }
3987  sqlite3_finalize(pStmt);
3988  if( azCol==0 ) return 0;
3989  azCol[0] = 0;
3990  azCol[nCol+1] = 0;
3991
3992  /* The decision of whether or not a rowid really needs to be preserved
3993  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3994  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3995  ** rowids on tables where the rowid is inaccessible because there are other
3996  ** columns in the table named "rowid", "_rowid_", and "oid".
3997  */
3998  if( preserveRowid && isIPK ){
3999    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4000    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4001    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4002    ** ROWID aliases.  To distinguish these cases, check to see if
4003    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4004    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4005    */
4006    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4007                           " WHERE origin='pk'", zTab);
4008    shell_check_oom(zSql);
4009    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4010    sqlite3_free(zSql);
4011    if( rc ){
4012      freeColumnList(azCol);
4013      return 0;
4014    }
4015    rc = sqlite3_step(pStmt);
4016    sqlite3_finalize(pStmt);
4017    preserveRowid = rc==SQLITE_ROW;
4018  }
4019  if( preserveRowid ){
4020    /* Only preserve the rowid if we can find a name to use for the
4021    ** rowid */
4022    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4023    int i, j;
4024    for(j=0; j<3; j++){
4025      for(i=1; i<=nCol; i++){
4026        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4027      }
4028      if( i>nCol ){
4029        /* At this point, we know that azRowid[j] is not the name of any
4030        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4031        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4032        ** tables will fail this last check */
4033        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4034        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4035        break;
4036      }
4037    }
4038  }
4039  return azCol;
4040}
4041
4042/*
4043** Toggle the reverse_unordered_selects setting.
4044*/
4045static void toggleSelectOrder(sqlite3 *db){
4046  sqlite3_stmt *pStmt = 0;
4047  int iSetting = 0;
4048  char zStmt[100];
4049  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4050  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4051    iSetting = sqlite3_column_int(pStmt, 0);
4052  }
4053  sqlite3_finalize(pStmt);
4054  sqlite3_snprintf(sizeof(zStmt), zStmt,
4055       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4056  sqlite3_exec(db, zStmt, 0, 0, 0);
4057}
4058
4059/*
4060** This is a different callback routine used for dumping the database.
4061** Each row received by this callback consists of a table name,
4062** the table type ("index" or "table") and SQL to create the table.
4063** This routine should print text sufficient to recreate the table.
4064*/
4065static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4066  int rc;
4067  const char *zTable;
4068  const char *zType;
4069  const char *zSql;
4070  ShellState *p = (ShellState *)pArg;
4071  int dataOnly;
4072  int noSys;
4073
4074  UNUSED_PARAMETER(azNotUsed);
4075  if( nArg!=3 || azArg==0 ) return 0;
4076  zTable = azArg[0];
4077  zType = azArg[1];
4078  zSql = azArg[2];
4079  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4080  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4081
4082  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4083    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4084  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4085    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4086  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4087    return 0;
4088  }else if( dataOnly ){
4089    /* no-op */
4090  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4091    char *zIns;
4092    if( !p->writableSchema ){
4093      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4094      p->writableSchema = 1;
4095    }
4096    zIns = sqlite3_mprintf(
4097       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4098       "VALUES('table','%q','%q',0,'%q');",
4099       zTable, zTable, zSql);
4100    shell_check_oom(zIns);
4101    utf8_printf(p->out, "%s\n", zIns);
4102    sqlite3_free(zIns);
4103    return 0;
4104  }else{
4105    printSchemaLine(p->out, zSql, ";\n");
4106  }
4107
4108  if( strcmp(zType, "table")==0 ){
4109    ShellText sSelect;
4110    ShellText sTable;
4111    char **azCol;
4112    int i;
4113    char *savedDestTable;
4114    int savedMode;
4115
4116    azCol = tableColumnList(p, zTable);
4117    if( azCol==0 ){
4118      p->nErr++;
4119      return 0;
4120    }
4121
4122    /* Always quote the table name, even if it appears to be pure ascii,
4123    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4124    initText(&sTable);
4125    appendText(&sTable, zTable, quoteChar(zTable));
4126    /* If preserving the rowid, add a column list after the table name.
4127    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4128    ** instead of the usual "INSERT INTO tab VALUES(...)".
4129    */
4130    if( azCol[0] ){
4131      appendText(&sTable, "(", 0);
4132      appendText(&sTable, azCol[0], 0);
4133      for(i=1; azCol[i]; i++){
4134        appendText(&sTable, ",", 0);
4135        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4136      }
4137      appendText(&sTable, ")", 0);
4138    }
4139
4140    /* Build an appropriate SELECT statement */
4141    initText(&sSelect);
4142    appendText(&sSelect, "SELECT ", 0);
4143    if( azCol[0] ){
4144      appendText(&sSelect, azCol[0], 0);
4145      appendText(&sSelect, ",", 0);
4146    }
4147    for(i=1; azCol[i]; i++){
4148      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4149      if( azCol[i+1] ){
4150        appendText(&sSelect, ",", 0);
4151      }
4152    }
4153    freeColumnList(azCol);
4154    appendText(&sSelect, " FROM ", 0);
4155    appendText(&sSelect, zTable, quoteChar(zTable));
4156
4157    savedDestTable = p->zDestTable;
4158    savedMode = p->mode;
4159    p->zDestTable = sTable.z;
4160    p->mode = p->cMode = MODE_Insert;
4161    rc = shell_exec(p, sSelect.z, 0);
4162    if( (rc&0xff)==SQLITE_CORRUPT ){
4163      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4164      toggleSelectOrder(p->db);
4165      shell_exec(p, sSelect.z, 0);
4166      toggleSelectOrder(p->db);
4167    }
4168    p->zDestTable = savedDestTable;
4169    p->mode = savedMode;
4170    freeText(&sTable);
4171    freeText(&sSelect);
4172    if( rc ) p->nErr++;
4173  }
4174  return 0;
4175}
4176
4177/*
4178** Run zQuery.  Use dump_callback() as the callback routine so that
4179** the contents of the query are output as SQL statements.
4180**
4181** If we get a SQLITE_CORRUPT error, rerun the query after appending
4182** "ORDER BY rowid DESC" to the end.
4183*/
4184static int run_schema_dump_query(
4185  ShellState *p,
4186  const char *zQuery
4187){
4188  int rc;
4189  char *zErr = 0;
4190  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4191  if( rc==SQLITE_CORRUPT ){
4192    char *zQ2;
4193    int len = strlen30(zQuery);
4194    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4195    if( zErr ){
4196      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4197      sqlite3_free(zErr);
4198      zErr = 0;
4199    }
4200    zQ2 = malloc( len+100 );
4201    if( zQ2==0 ) return rc;
4202    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4203    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4204    if( rc ){
4205      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4206    }else{
4207      rc = SQLITE_CORRUPT;
4208    }
4209    sqlite3_free(zErr);
4210    free(zQ2);
4211  }
4212  return rc;
4213}
4214
4215/*
4216** Text of help messages.
4217**
4218** The help text for each individual command begins with a line that starts
4219** with ".".  Subsequent lines are supplimental information.
4220**
4221** There must be two or more spaces between the end of the command and the
4222** start of the description of what that command does.
4223*/
4224static const char *(azHelp[]) = {
4225#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
4226  ".archive ...             Manage SQL archives",
4227  "   Each command must have exactly one of the following options:",
4228  "     -c, --create               Create a new archive",
4229  "     -u, --update               Add or update files with changed mtime",
4230  "     -i, --insert               Like -u but always add even if unchanged",
4231  "     -r, --remove               Remove files from archive",
4232  "     -t, --list                 List contents of archive",
4233  "     -x, --extract              Extract files from archive",
4234  "   Optional arguments:",
4235  "     -v, --verbose              Print each filename as it is processed",
4236  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4237  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4238  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4239  "     -g, --glob                 Use glob matching for names in archive",
4240  "     -n, --dryrun               Show the SQL that would have occurred",
4241  "   Examples:",
4242  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4243  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4244  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4245  "   See also:",
4246  "      http://sqlite.org/cli.html#sqlite_archive_support",
4247#endif
4248#ifndef SQLITE_OMIT_AUTHORIZATION
4249  ".auth ON|OFF             Show authorizer callbacks",
4250#endif
4251  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4252  "   Options:",
4253  "       --append            Use the appendvfs",
4254  "       --async             Write to FILE without journal and fsync()",
4255  ".bail on|off             Stop after hitting an error.  Default OFF",
4256  ".binary on|off           Turn binary output on or off.  Default OFF",
4257  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4258  ".changes on|off          Show number of rows changed by SQL",
4259  ".check GLOB              Fail if output since .testcase does not match",
4260  ".clone NEWDB             Clone data into NEWDB from the existing database",
4261  ".connection [close] [#]  Open or close an auxiliary database connection",
4262  ".databases               List names and files of attached databases",
4263  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4264  ".dbinfo ?DB?             Show status information about the database",
4265  ".dump ?OBJECTS?          Render database content as SQL",
4266  "   Options:",
4267  "     --data-only            Output only INSERT statements",
4268  "     --newlines             Allow unescaped newline characters in output",
4269  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4270  "     --preserve-rowids      Include ROWID values in the output",
4271  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4272  "   Additional LIKE patterns can be given in subsequent arguments",
4273  ".echo on|off             Turn command echo on or off",
4274  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4275  "   Other Modes:",
4276#ifdef SQLITE_DEBUG
4277  "      test                  Show raw EXPLAIN QUERY PLAN output",
4278  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4279#endif
4280  "      trigger               Like \"full\" but also show trigger bytecode",
4281  ".excel                   Display the output of next command in spreadsheet",
4282  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4283  ".exit ?CODE?             Exit this program with return-code CODE",
4284  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4285  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4286  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4287  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4288  "   --help                  Show CMD details",
4289  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4290  ".headers on|off          Turn display of headers on or off",
4291  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4292  ".import FILE TABLE       Import data from FILE into TABLE",
4293  "   Options:",
4294  "     --ascii               Use \\037 and \\036 as column and row separators",
4295  "     --csv                 Use , and \\n as column and row separators",
4296  "     --skip N              Skip the first N rows of input",
4297  "     --schema S            Target table to be S.TABLE",
4298  "     -v                    \"Verbose\" - increase auxiliary output",
4299  "   Notes:",
4300  "     *  If TABLE does not exist, it is created.  The first row of input",
4301  "        determines the column names.",
4302  "     *  If neither --csv or --ascii are used, the input mode is derived",
4303  "        from the \".mode\" output mode",
4304  "     *  If FILE begins with \"|\" then it is a command that generates the",
4305  "        input text.",
4306#ifndef SQLITE_OMIT_TEST_CONTROL
4307  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4308#endif
4309  ".indexes ?TABLE?         Show names of indexes",
4310  "                           If TABLE is specified, only show indexes for",
4311  "                           tables matching TABLE using the LIKE operator.",
4312#ifdef SQLITE_ENABLE_IOTRACE
4313  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4314#endif
4315  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4316  ".lint OPTIONS            Report potential schema issues.",
4317  "     Options:",
4318  "        fkey-indexes     Find missing foreign key indexes",
4319#ifndef SQLITE_OMIT_LOAD_EXTENSION
4320  ".load FILE ?ENTRY?       Load an extension library",
4321#endif
4322  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4323  ".mode MODE ?OPTIONS?     Set output mode",
4324  "   MODE is one of:",
4325  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4326  "     box         Tables using unicode box-drawing characters",
4327  "     csv         Comma-separated values",
4328  "     column      Output in columns.  (See .width)",
4329  "     html        HTML <table> code",
4330  "     insert      SQL insert statements for TABLE",
4331  "     json        Results in a JSON array",
4332  "     line        One value per line",
4333  "     list        Values delimited by \"|\"",
4334  "     markdown    Markdown table format",
4335  "     qbox        Shorthand for \"box --width 60 --quote\"",
4336  "     quote       Escape answers as for SQL",
4337  "     table       ASCII-art table",
4338  "     tabs        Tab-separated values",
4339  "     tcl         TCL list elements",
4340  "   OPTIONS: (for columnar modes or insert mode):",
4341  "     --wrap N       Wrap output lines to no longer than N characters",
4342  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4343  "     --ww           Shorthand for \"--wordwrap 1\"",
4344  "     --quote        Quote output text as SQL literals",
4345  "     --noquote      Do not quote output text",
4346  "     TABLE          The name of SQL table used for \"insert\" mode",
4347  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4348  ".nullvalue STRING        Use STRING in place of NULL values",
4349  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4350  "     If FILE begins with '|' then open as a pipe",
4351  "       --bom  Put a UTF8 byte-order mark at the beginning",
4352  "       -e     Send output to the system text editor",
4353  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4354  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4355  "     Options:",
4356  "        --append        Use appendvfs to append database to the end of FILE",
4357#ifndef SQLITE_OMIT_DESERIALIZE
4358  "        --deserialize   Load into memory using sqlite3_deserialize()",
4359  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4360  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4361#endif
4362  "        --new           Initialize FILE to an empty database",
4363  "        --nofollow      Do not follow symbolic links",
4364  "        --readonly      Open FILE readonly",
4365  "        --zip           FILE is a ZIP archive",
4366  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4367  "   If FILE begins with '|' then open it as a pipe.",
4368  "   Options:",
4369  "     --bom                 Prefix output with a UTF8 byte-order mark",
4370  "     -e                    Send output to the system text editor",
4371  "     -x                    Send output as CSV to a spreadsheet",
4372  ".parameter CMD ...       Manage SQL parameter bindings",
4373  "   clear                   Erase all bindings",
4374  "   init                    Initialize the TEMP table that holds bindings",
4375  "   list                    List the current parameter bindings",
4376  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4377  "                           PARAMETER should start with one of: $ : @ ?",
4378  "   unset PARAMETER         Remove PARAMETER from the binding table",
4379  ".print STRING...         Print literal STRING",
4380#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4381  ".progress N              Invoke progress handler after every N opcodes",
4382  "   --limit N                 Interrupt after N progress callbacks",
4383  "   --once                    Do no more than one progress interrupt",
4384  "   --quiet|-q                No output except at interrupts",
4385  "   --reset                   Reset the count for each input and interrupt",
4386#endif
4387  ".prompt MAIN CONTINUE    Replace the standard prompts",
4388  ".quit                    Exit this program",
4389  ".read FILE               Read input from FILE or command output",
4390  "    If FILE begins with \"|\", it is a command that generates the input.",
4391#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4392  ".recover                 Recover as much data as possible from corrupt db.",
4393  "   --freelist-corrupt       Assume the freelist is corrupt",
4394  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4395  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4396  "   --no-rowids              Do not attempt to recover rowid values",
4397  "                            that are not also INTEGER PRIMARY KEYs",
4398#endif
4399  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4400  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4401  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4402  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4403  "   Options:",
4404  "      --indent             Try to pretty-print the schema",
4405  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4406  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4407  "    Options:",
4408  "       --init               Create a new SELFTEST table",
4409  "       -v                   Verbose output",
4410  ".separator COL ?ROW?     Change the column and row separators",
4411#if defined(SQLITE_ENABLE_SESSION)
4412  ".session ?NAME? CMD ...  Create or control sessions",
4413  "   Subcommands:",
4414  "     attach TABLE             Attach TABLE",
4415  "     changeset FILE           Write a changeset into FILE",
4416  "     close                    Close one session",
4417  "     enable ?BOOLEAN?         Set or query the enable bit",
4418  "     filter GLOB...           Reject tables matching GLOBs",
4419  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4420  "     isempty                  Query whether the session is empty",
4421  "     list                     List currently open session names",
4422  "     open DB NAME             Open a new session on DB",
4423  "     patchset FILE            Write a patchset into FILE",
4424  "   If ?NAME? is omitted, the first defined session is used.",
4425#endif
4426  ".sha3sum ...             Compute a SHA3 hash of database content",
4427  "    Options:",
4428  "      --schema              Also hash the sqlite_schema table",
4429  "      --sha3-224            Use the sha3-224 algorithm",
4430  "      --sha3-256            Use the sha3-256 algorithm (default)",
4431  "      --sha3-384            Use the sha3-384 algorithm",
4432  "      --sha3-512            Use the sha3-512 algorithm",
4433  "    Any other argument is a LIKE pattern for tables to hash",
4434#ifndef SQLITE_NOHAVE_SYSTEM
4435  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4436#endif
4437  ".show                    Show the current values for various settings",
4438  ".stats ?ARG?             Show stats or turn stats on or off",
4439  "   off                      Turn off automatic stat display",
4440  "   on                       Turn on automatic stat display",
4441  "   stmt                     Show statement stats",
4442  "   vmstep                   Show the virtual machine step count only",
4443#ifndef SQLITE_NOHAVE_SYSTEM
4444  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4445#endif
4446  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4447  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4448  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4449  "                           Run \".testctrl\" with no arguments for details",
4450  ".timeout MS              Try opening locked tables for MS milliseconds",
4451  ".timer on|off            Turn SQL timer on or off",
4452#ifndef SQLITE_OMIT_TRACE
4453  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4454  "    FILE                    Send output to FILE",
4455  "    stdout                  Send output to stdout",
4456  "    stderr                  Send output to stderr",
4457  "    off                     Disable tracing",
4458  "    --expanded              Expand query parameters",
4459#ifdef SQLITE_ENABLE_NORMALIZE
4460  "    --normalized            Normal the SQL statements",
4461#endif
4462  "    --plain                 Show SQL as it is input",
4463  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4464  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4465  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4466  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4467#endif /* SQLITE_OMIT_TRACE */
4468#ifdef SQLITE_DEBUG
4469  ".unmodule NAME ...       Unregister virtual table modules",
4470  "    --allexcept             Unregister everything except those named",
4471#endif
4472  ".vfsinfo ?AUX?           Information about the top-level VFS",
4473  ".vfslist                 List all available VFSes",
4474  ".vfsname ?AUX?           Print the name of the VFS stack",
4475  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4476  "     Negative values right-justify",
4477};
4478
4479/*
4480** Output help text.
4481**
4482** zPattern describes the set of commands for which help text is provided.
4483** If zPattern is NULL, then show all commands, but only give a one-line
4484** description of each.
4485**
4486** Return the number of matches.
4487*/
4488static int showHelp(FILE *out, const char *zPattern){
4489  int i = 0;
4490  int j = 0;
4491  int n = 0;
4492  char *zPat;
4493  if( zPattern==0
4494   || zPattern[0]=='0'
4495   || strcmp(zPattern,"-a")==0
4496   || strcmp(zPattern,"-all")==0
4497   || strcmp(zPattern,"--all")==0
4498  ){
4499    /* Show all commands, but only one line per command */
4500    if( zPattern==0 ) zPattern = "";
4501    for(i=0; i<ArraySize(azHelp); i++){
4502      if( azHelp[i][0]=='.' || zPattern[0] ){
4503        utf8_printf(out, "%s\n", azHelp[i]);
4504        n++;
4505      }
4506    }
4507  }else{
4508    /* Look for commands that for which zPattern is an exact prefix */
4509    zPat = sqlite3_mprintf(".%s*", zPattern);
4510    shell_check_oom(zPat);
4511    for(i=0; i<ArraySize(azHelp); i++){
4512      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4513        utf8_printf(out, "%s\n", azHelp[i]);
4514        j = i+1;
4515        n++;
4516      }
4517    }
4518    sqlite3_free(zPat);
4519    if( n ){
4520      if( n==1 ){
4521        /* when zPattern is a prefix of exactly one command, then include the
4522        ** details of that command, which should begin at offset j */
4523        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4524          utf8_printf(out, "%s\n", azHelp[j]);
4525          j++;
4526        }
4527      }
4528      return n;
4529    }
4530    /* Look for commands that contain zPattern anywhere.  Show the complete
4531    ** text of all commands that match. */
4532    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4533    shell_check_oom(zPat);
4534    for(i=0; i<ArraySize(azHelp); i++){
4535      if( azHelp[i][0]=='.' ) j = i;
4536      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4537        utf8_printf(out, "%s\n", azHelp[j]);
4538        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4539          j++;
4540          utf8_printf(out, "%s\n", azHelp[j]);
4541        }
4542        i = j;
4543        n++;
4544      }
4545    }
4546    sqlite3_free(zPat);
4547  }
4548  return n;
4549}
4550
4551/* Forward reference */
4552static int process_input(ShellState *p);
4553
4554/*
4555** Read the content of file zName into memory obtained from sqlite3_malloc64()
4556** and return a pointer to the buffer. The caller is responsible for freeing
4557** the memory.
4558**
4559** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4560** read.
4561**
4562** For convenience, a nul-terminator byte is always appended to the data read
4563** from the file before the buffer is returned. This byte is not included in
4564** the final value of (*pnByte), if applicable.
4565**
4566** NULL is returned if any error is encountered. The final value of *pnByte
4567** is undefined in this case.
4568*/
4569static char *readFile(const char *zName, int *pnByte){
4570  FILE *in = fopen(zName, "rb");
4571  long nIn;
4572  size_t nRead;
4573  char *pBuf;
4574  if( in==0 ) return 0;
4575  fseek(in, 0, SEEK_END);
4576  nIn = ftell(in);
4577  rewind(in);
4578  pBuf = sqlite3_malloc64( nIn+1 );
4579  if( pBuf==0 ){ fclose(in); return 0; }
4580  nRead = fread(pBuf, nIn, 1, in);
4581  fclose(in);
4582  if( nRead!=1 ){
4583    sqlite3_free(pBuf);
4584    return 0;
4585  }
4586  pBuf[nIn] = 0;
4587  if( pnByte ) *pnByte = nIn;
4588  return pBuf;
4589}
4590
4591#if defined(SQLITE_ENABLE_SESSION)
4592/*
4593** Close a single OpenSession object and release all of its associated
4594** resources.
4595*/
4596static void session_close(OpenSession *pSession){
4597  int i;
4598  sqlite3session_delete(pSession->p);
4599  sqlite3_free(pSession->zName);
4600  for(i=0; i<pSession->nFilter; i++){
4601    sqlite3_free(pSession->azFilter[i]);
4602  }
4603  sqlite3_free(pSession->azFilter);
4604  memset(pSession, 0, sizeof(OpenSession));
4605}
4606#endif
4607
4608/*
4609** Close all OpenSession objects and release all associated resources.
4610*/
4611#if defined(SQLITE_ENABLE_SESSION)
4612static void session_close_all(ShellState *p, int i){
4613  int j;
4614  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4615  for(j=0; j<pAuxDb->nSession; j++){
4616    session_close(&pAuxDb->aSession[j]);
4617  }
4618  pAuxDb->nSession = 0;
4619}
4620#else
4621# define session_close_all(X,Y)
4622#endif
4623
4624/*
4625** Implementation of the xFilter function for an open session.  Omit
4626** any tables named by ".session filter" but let all other table through.
4627*/
4628#if defined(SQLITE_ENABLE_SESSION)
4629static int session_filter(void *pCtx, const char *zTab){
4630  OpenSession *pSession = (OpenSession*)pCtx;
4631  int i;
4632  for(i=0; i<pSession->nFilter; i++){
4633    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4634  }
4635  return 1;
4636}
4637#endif
4638
4639/*
4640** Try to deduce the type of file for zName based on its content.  Return
4641** one of the SHELL_OPEN_* constants.
4642**
4643** If the file does not exist or is empty but its name looks like a ZIP
4644** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4645** Otherwise, assume an ordinary database regardless of the filename if
4646** the type cannot be determined from content.
4647*/
4648int deduceDatabaseType(const char *zName, int dfltZip){
4649  FILE *f = fopen(zName, "rb");
4650  size_t n;
4651  int rc = SHELL_OPEN_UNSPEC;
4652  char zBuf[100];
4653  if( f==0 ){
4654    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4655       return SHELL_OPEN_ZIPFILE;
4656    }else{
4657       return SHELL_OPEN_NORMAL;
4658    }
4659  }
4660  n = fread(zBuf, 16, 1, f);
4661  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4662    fclose(f);
4663    return SHELL_OPEN_NORMAL;
4664  }
4665  fseek(f, -25, SEEK_END);
4666  n = fread(zBuf, 25, 1, f);
4667  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4668    rc = SHELL_OPEN_APPENDVFS;
4669  }else{
4670    fseek(f, -22, SEEK_END);
4671    n = fread(zBuf, 22, 1, f);
4672    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4673       && zBuf[3]==0x06 ){
4674      rc = SHELL_OPEN_ZIPFILE;
4675    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4676      rc = SHELL_OPEN_ZIPFILE;
4677    }
4678  }
4679  fclose(f);
4680  return rc;
4681}
4682
4683#ifndef SQLITE_OMIT_DESERIALIZE
4684/*
4685** Reconstruct an in-memory database using the output from the "dbtotxt"
4686** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4687** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4688*/
4689static unsigned char *readHexDb(ShellState *p, int *pnData){
4690  unsigned char *a = 0;
4691  int nLine;
4692  int n = 0;
4693  int pgsz = 0;
4694  int iOffset = 0;
4695  int j, k;
4696  int rc;
4697  FILE *in;
4698  const char *zDbFilename = p->pAuxDb->zDbFilename;
4699  unsigned int x[16];
4700  char zLine[1000];
4701  if( zDbFilename ){
4702    in = fopen(zDbFilename, "r");
4703    if( in==0 ){
4704      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4705      return 0;
4706    }
4707    nLine = 0;
4708  }else{
4709    in = p->in;
4710    nLine = p->lineno;
4711    if( in==0 ) in = stdin;
4712  }
4713  *pnData = 0;
4714  nLine++;
4715  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4716  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4717  if( rc!=2 ) goto readHexDb_error;
4718  if( n<0 ) goto readHexDb_error;
4719  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4720  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4721  a = sqlite3_malloc( n ? n : 1 );
4722  shell_check_oom(a);
4723  memset(a, 0, n);
4724  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4725    utf8_printf(stderr, "invalid pagesize\n");
4726    goto readHexDb_error;
4727  }
4728  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4729    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4730    if( rc==2 ){
4731      iOffset = k;
4732      continue;
4733    }
4734    if( strncmp(zLine, "| end ", 6)==0 ){
4735      break;
4736    }
4737    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4738                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4739                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4740    if( rc==17 ){
4741      k = iOffset+j;
4742      if( k+16<=n && k>=0 ){
4743        int ii;
4744        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4745      }
4746    }
4747  }
4748  *pnData = n;
4749  if( in!=p->in ){
4750    fclose(in);
4751  }else{
4752    p->lineno = nLine;
4753  }
4754  return a;
4755
4756readHexDb_error:
4757  if( in!=p->in ){
4758    fclose(in);
4759  }else{
4760    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4761      nLine++;
4762      if(strncmp(zLine, "| end ", 6)==0 ) break;
4763    }
4764    p->lineno = nLine;
4765  }
4766  sqlite3_free(a);
4767  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4768  return 0;
4769}
4770#endif /* SQLITE_OMIT_DESERIALIZE */
4771
4772/*
4773** Scalar function "shell_int32". The first argument to this function
4774** must be a blob. The second a non-negative integer. This function
4775** reads and returns a 32-bit big-endian integer from byte
4776** offset (4*<arg2>) of the blob.
4777*/
4778static void shellInt32(
4779  sqlite3_context *context,
4780  int argc,
4781  sqlite3_value **argv
4782){
4783  const unsigned char *pBlob;
4784  int nBlob;
4785  int iInt;
4786
4787  UNUSED_PARAMETER(argc);
4788  nBlob = sqlite3_value_bytes(argv[0]);
4789  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4790  iInt = sqlite3_value_int(argv[1]);
4791
4792  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4793    const unsigned char *a = &pBlob[iInt*4];
4794    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4795                       + ((sqlite3_int64)a[1]<<16)
4796                       + ((sqlite3_int64)a[2]<< 8)
4797                       + ((sqlite3_int64)a[3]<< 0);
4798    sqlite3_result_int64(context, iVal);
4799  }
4800}
4801
4802/*
4803** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4804** using "..." with internal double-quote characters doubled.
4805*/
4806static void shellIdQuote(
4807  sqlite3_context *context,
4808  int argc,
4809  sqlite3_value **argv
4810){
4811  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4812  UNUSED_PARAMETER(argc);
4813  if( zName ){
4814    char *z = sqlite3_mprintf("\"%w\"", zName);
4815    sqlite3_result_text(context, z, -1, sqlite3_free);
4816  }
4817}
4818
4819/*
4820** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4821*/
4822static void shellUSleepFunc(
4823  sqlite3_context *context,
4824  int argcUnused,
4825  sqlite3_value **argv
4826){
4827  int sleep = sqlite3_value_int(argv[0]);
4828  (void)argcUnused;
4829  sqlite3_sleep(sleep/1000);
4830  sqlite3_result_int(context, sleep);
4831}
4832
4833/*
4834** Scalar function "shell_escape_crnl" used by the .recover command.
4835** The argument passed to this function is the output of built-in
4836** function quote(). If the first character of the input is "'",
4837** indicating that the value passed to quote() was a text value,
4838** then this function searches the input for "\n" and "\r" characters
4839** and adds a wrapper similar to the following:
4840**
4841**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4842**
4843** Or, if the first character of the input is not "'", then a copy
4844** of the input is returned.
4845*/
4846static void shellEscapeCrnl(
4847  sqlite3_context *context,
4848  int argc,
4849  sqlite3_value **argv
4850){
4851  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4852  UNUSED_PARAMETER(argc);
4853  if( zText && zText[0]=='\'' ){
4854    int nText = sqlite3_value_bytes(argv[0]);
4855    int i;
4856    char zBuf1[20];
4857    char zBuf2[20];
4858    const char *zNL = 0;
4859    const char *zCR = 0;
4860    int nCR = 0;
4861    int nNL = 0;
4862
4863    for(i=0; zText[i]; i++){
4864      if( zNL==0 && zText[i]=='\n' ){
4865        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4866        nNL = (int)strlen(zNL);
4867      }
4868      if( zCR==0 && zText[i]=='\r' ){
4869        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4870        nCR = (int)strlen(zCR);
4871      }
4872    }
4873
4874    if( zNL || zCR ){
4875      int iOut = 0;
4876      i64 nMax = (nNL > nCR) ? nNL : nCR;
4877      i64 nAlloc = nMax * nText + (nMax+64)*2;
4878      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4879      if( zOut==0 ){
4880        sqlite3_result_error_nomem(context);
4881        return;
4882      }
4883
4884      if( zNL && zCR ){
4885        memcpy(&zOut[iOut], "replace(replace(", 16);
4886        iOut += 16;
4887      }else{
4888        memcpy(&zOut[iOut], "replace(", 8);
4889        iOut += 8;
4890      }
4891      for(i=0; zText[i]; i++){
4892        if( zText[i]=='\n' ){
4893          memcpy(&zOut[iOut], zNL, nNL);
4894          iOut += nNL;
4895        }else if( zText[i]=='\r' ){
4896          memcpy(&zOut[iOut], zCR, nCR);
4897          iOut += nCR;
4898        }else{
4899          zOut[iOut] = zText[i];
4900          iOut++;
4901        }
4902      }
4903
4904      if( zNL ){
4905        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4906        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4907        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4908      }
4909      if( zCR ){
4910        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4911        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4912        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4913      }
4914
4915      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4916      sqlite3_free(zOut);
4917      return;
4918    }
4919  }
4920
4921  sqlite3_result_value(context, argv[0]);
4922}
4923
4924/* Flags for open_db().
4925**
4926** The default behavior of open_db() is to exit(1) if the database fails to
4927** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4928** but still returns without calling exit.
4929**
4930** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4931** ZIP archive if the file does not exist or is empty and its name matches
4932** the *.zip pattern.
4933*/
4934#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4935#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4936
4937/*
4938** Make sure the database is open.  If it is not, then open it.  If
4939** the database fails to open, print an error message and exit.
4940*/
4941static void open_db(ShellState *p, int openFlags){
4942  if( p->db==0 ){
4943    const char *zDbFilename = p->pAuxDb->zDbFilename;
4944    if( p->openMode==SHELL_OPEN_UNSPEC ){
4945      if( zDbFilename==0 || zDbFilename[0]==0 ){
4946        p->openMode = SHELL_OPEN_NORMAL;
4947      }else{
4948        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4949                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4950      }
4951    }
4952    switch( p->openMode ){
4953      case SHELL_OPEN_APPENDVFS: {
4954        sqlite3_open_v2(zDbFilename, &p->db,
4955           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4956        break;
4957      }
4958      case SHELL_OPEN_HEXDB:
4959      case SHELL_OPEN_DESERIALIZE: {
4960        sqlite3_open(0, &p->db);
4961        break;
4962      }
4963      case SHELL_OPEN_ZIPFILE: {
4964        sqlite3_open(":memory:", &p->db);
4965        break;
4966      }
4967      case SHELL_OPEN_READONLY: {
4968        sqlite3_open_v2(zDbFilename, &p->db,
4969            SQLITE_OPEN_READONLY|p->openFlags, 0);
4970        break;
4971      }
4972      case SHELL_OPEN_UNSPEC:
4973      case SHELL_OPEN_NORMAL: {
4974        sqlite3_open_v2(zDbFilename, &p->db,
4975           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4976        break;
4977      }
4978    }
4979    globalDb = p->db;
4980    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4981      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4982          zDbFilename, sqlite3_errmsg(p->db));
4983      if( openFlags & OPEN_DB_KEEPALIVE ){
4984        sqlite3_open(":memory:", &p->db);
4985        return;
4986      }
4987      exit(1);
4988    }
4989#ifndef SQLITE_OMIT_LOAD_EXTENSION
4990    sqlite3_enable_load_extension(p->db, 1);
4991#endif
4992    sqlite3_fileio_init(p->db, 0, 0);
4993    sqlite3_shathree_init(p->db, 0, 0);
4994    sqlite3_completion_init(p->db, 0, 0);
4995    sqlite3_uint_init(p->db, 0, 0);
4996    sqlite3_decimal_init(p->db, 0, 0);
4997    sqlite3_regexp_init(p->db, 0, 0);
4998    sqlite3_ieee_init(p->db, 0, 0);
4999    sqlite3_series_init(p->db, 0, 0);
5000#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5001    sqlite3_dbdata_init(p->db, 0, 0);
5002#endif
5003#ifdef SQLITE_HAVE_ZLIB
5004    if( !p->bSafeModePersist ){
5005      sqlite3_zipfile_init(p->db, 0, 0);
5006      sqlite3_sqlar_init(p->db, 0, 0);
5007    }
5008#endif
5009    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5010                            shellAddSchemaName, 0, 0);
5011    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5012                            shellModuleSchema, 0, 0);
5013    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5014                            shellPutsFunc, 0, 0);
5015    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5016                            shellEscapeCrnl, 0, 0);
5017    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5018                            shellInt32, 0, 0);
5019    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5020                            shellIdQuote, 0, 0);
5021    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5022                            shellUSleepFunc, 0, 0);
5023#ifndef SQLITE_NOHAVE_SYSTEM
5024    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5025                            editFunc, 0, 0);
5026    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5027                            editFunc, 0, 0);
5028#endif
5029    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5030      char *zSql = sqlite3_mprintf(
5031         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5032      shell_check_oom(zSql);
5033      sqlite3_exec(p->db, zSql, 0, 0, 0);
5034      sqlite3_free(zSql);
5035    }
5036#ifndef SQLITE_OMIT_DESERIALIZE
5037    else
5038    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5039      int rc;
5040      int nData = 0;
5041      unsigned char *aData;
5042      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5043        aData = (unsigned char*)readFile(zDbFilename, &nData);
5044      }else{
5045        aData = readHexDb(p, &nData);
5046        if( aData==0 ){
5047          return;
5048        }
5049      }
5050      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5051                   SQLITE_DESERIALIZE_RESIZEABLE |
5052                   SQLITE_DESERIALIZE_FREEONCLOSE);
5053      if( rc ){
5054        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5055      }
5056      if( p->szMax>0 ){
5057        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5058      }
5059    }
5060#endif
5061  }
5062  if( p->bSafeModePersist && p->db!=0 ){
5063    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5064  }
5065}
5066
5067/*
5068** Attempt to close the databaes connection.  Report errors.
5069*/
5070void close_db(sqlite3 *db){
5071  int rc = sqlite3_close(db);
5072  if( rc ){
5073    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5074        rc, sqlite3_errmsg(db));
5075  }
5076}
5077
5078#if HAVE_READLINE || HAVE_EDITLINE
5079/*
5080** Readline completion callbacks
5081*/
5082static char *readline_completion_generator(const char *text, int state){
5083  static sqlite3_stmt *pStmt = 0;
5084  char *zRet;
5085  if( state==0 ){
5086    char *zSql;
5087    sqlite3_finalize(pStmt);
5088    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5089                           "  FROM completion(%Q) ORDER BY 1", text);
5090    shell_check_oom(zSql);
5091    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5092    sqlite3_free(zSql);
5093  }
5094  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5095    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5096    zRet = z ? strdup(z) : 0;
5097  }else{
5098    sqlite3_finalize(pStmt);
5099    pStmt = 0;
5100    zRet = 0;
5101  }
5102  return zRet;
5103}
5104static char **readline_completion(const char *zText, int iStart, int iEnd){
5105  rl_attempted_completion_over = 1;
5106  return rl_completion_matches(zText, readline_completion_generator);
5107}
5108
5109#elif HAVE_LINENOISE
5110/*
5111** Linenoise completion callback
5112*/
5113static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5114  int nLine = strlen30(zLine);
5115  int i, iStart;
5116  sqlite3_stmt *pStmt = 0;
5117  char *zSql;
5118  char zBuf[1000];
5119
5120  if( nLine>sizeof(zBuf)-30 ) return;
5121  if( zLine[0]=='.' || zLine[0]=='#') return;
5122  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5123  if( i==nLine-1 ) return;
5124  iStart = i+1;
5125  memcpy(zBuf, zLine, iStart);
5126  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5127                         "  FROM completion(%Q,%Q) ORDER BY 1",
5128                         &zLine[iStart], zLine);
5129  shell_check_oom(zSql);
5130  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5131  sqlite3_free(zSql);
5132  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5133  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5134    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5135    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5136    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5137      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5138      linenoiseAddCompletion(lc, zBuf);
5139    }
5140  }
5141  sqlite3_finalize(pStmt);
5142}
5143#endif
5144
5145/*
5146** Do C-language style dequoting.
5147**
5148**    \a    -> alarm
5149**    \b    -> backspace
5150**    \t    -> tab
5151**    \n    -> newline
5152**    \v    -> vertical tab
5153**    \f    -> form feed
5154**    \r    -> carriage return
5155**    \s    -> space
5156**    \"    -> "
5157**    \'    -> '
5158**    \\    -> backslash
5159**    \NNN  -> ascii character NNN in octal
5160*/
5161static void resolve_backslashes(char *z){
5162  int i, j;
5163  char c;
5164  while( *z && *z!='\\' ) z++;
5165  for(i=j=0; (c = z[i])!=0; i++, j++){
5166    if( c=='\\' && z[i+1]!=0 ){
5167      c = z[++i];
5168      if( c=='a' ){
5169        c = '\a';
5170      }else if( c=='b' ){
5171        c = '\b';
5172      }else if( c=='t' ){
5173        c = '\t';
5174      }else if( c=='n' ){
5175        c = '\n';
5176      }else if( c=='v' ){
5177        c = '\v';
5178      }else if( c=='f' ){
5179        c = '\f';
5180      }else if( c=='r' ){
5181        c = '\r';
5182      }else if( c=='"' ){
5183        c = '"';
5184      }else if( c=='\'' ){
5185        c = '\'';
5186      }else if( c=='\\' ){
5187        c = '\\';
5188      }else if( c>='0' && c<='7' ){
5189        c -= '0';
5190        if( z[i+1]>='0' && z[i+1]<='7' ){
5191          i++;
5192          c = (c<<3) + z[i] - '0';
5193          if( z[i+1]>='0' && z[i+1]<='7' ){
5194            i++;
5195            c = (c<<3) + z[i] - '0';
5196          }
5197        }
5198      }
5199    }
5200    z[j] = c;
5201  }
5202  if( j<i ) z[j] = 0;
5203}
5204
5205/*
5206** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5207** for TRUE and FALSE.  Return the integer value if appropriate.
5208*/
5209static int booleanValue(const char *zArg){
5210  int i;
5211  if( zArg[0]=='0' && zArg[1]=='x' ){
5212    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5213  }else{
5214    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5215  }
5216  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5217  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5218    return 1;
5219  }
5220  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5221    return 0;
5222  }
5223  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5224          zArg);
5225  return 0;
5226}
5227
5228/*
5229** Set or clear a shell flag according to a boolean value.
5230*/
5231static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5232  if( booleanValue(zArg) ){
5233    ShellSetFlag(p, mFlag);
5234  }else{
5235    ShellClearFlag(p, mFlag);
5236  }
5237}
5238
5239/*
5240** Close an output file, assuming it is not stderr or stdout
5241*/
5242static void output_file_close(FILE *f){
5243  if( f && f!=stdout && f!=stderr ) fclose(f);
5244}
5245
5246/*
5247** Try to open an output file.   The names "stdout" and "stderr" are
5248** recognized and do the right thing.  NULL is returned if the output
5249** filename is "off".
5250*/
5251static FILE *output_file_open(const char *zFile, int bTextMode){
5252  FILE *f;
5253  if( strcmp(zFile,"stdout")==0 ){
5254    f = stdout;
5255  }else if( strcmp(zFile, "stderr")==0 ){
5256    f = stderr;
5257  }else if( strcmp(zFile, "off")==0 ){
5258    f = 0;
5259  }else{
5260    f = fopen(zFile, bTextMode ? "w" : "wb");
5261    if( f==0 ){
5262      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5263    }
5264  }
5265  return f;
5266}
5267
5268#ifndef SQLITE_OMIT_TRACE
5269/*
5270** A routine for handling output from sqlite3_trace().
5271*/
5272static int sql_trace_callback(
5273  unsigned mType,         /* The trace type */
5274  void *pArg,             /* The ShellState pointer */
5275  void *pP,               /* Usually a pointer to sqlite_stmt */
5276  void *pX                /* Auxiliary output */
5277){
5278  ShellState *p = (ShellState*)pArg;
5279  sqlite3_stmt *pStmt;
5280  const char *zSql;
5281  int nSql;
5282  if( p->traceOut==0 ) return 0;
5283  if( mType==SQLITE_TRACE_CLOSE ){
5284    utf8_printf(p->traceOut, "-- closing database connection\n");
5285    return 0;
5286  }
5287  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5288    zSql = (const char*)pX;
5289  }else{
5290    pStmt = (sqlite3_stmt*)pP;
5291    switch( p->eTraceType ){
5292      case SHELL_TRACE_EXPANDED: {
5293        zSql = sqlite3_expanded_sql(pStmt);
5294        break;
5295      }
5296#ifdef SQLITE_ENABLE_NORMALIZE
5297      case SHELL_TRACE_NORMALIZED: {
5298        zSql = sqlite3_normalized_sql(pStmt);
5299        break;
5300      }
5301#endif
5302      default: {
5303        zSql = sqlite3_sql(pStmt);
5304        break;
5305      }
5306    }
5307  }
5308  if( zSql==0 ) return 0;
5309  nSql = strlen30(zSql);
5310  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5311  switch( mType ){
5312    case SQLITE_TRACE_ROW:
5313    case SQLITE_TRACE_STMT: {
5314      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5315      break;
5316    }
5317    case SQLITE_TRACE_PROFILE: {
5318      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5319      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5320      break;
5321    }
5322  }
5323  return 0;
5324}
5325#endif
5326
5327/*
5328** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5329** a useful spot to set a debugger breakpoint.
5330*/
5331static void test_breakpoint(void){
5332  static int nCall = 0;
5333  nCall++;
5334}
5335
5336/*
5337** An object used to read a CSV and other files for import.
5338*/
5339typedef struct ImportCtx ImportCtx;
5340struct ImportCtx {
5341  const char *zFile;  /* Name of the input file */
5342  FILE *in;           /* Read the CSV text from this input stream */
5343  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5344  char *z;            /* Accumulated text for a field */
5345  int n;              /* Number of bytes in z */
5346  int nAlloc;         /* Space allocated for z[] */
5347  int nLine;          /* Current line number */
5348  int nRow;           /* Number of rows imported */
5349  int nErr;           /* Number of errors encountered */
5350  int bNotFirst;      /* True if one or more bytes already read */
5351  int cTerm;          /* Character that terminated the most recent field */
5352  int cColSep;        /* The column separator character.  (Usually ",") */
5353  int cRowSep;        /* The row separator character.  (Usually "\n") */
5354};
5355
5356/* Clean up resourced used by an ImportCtx */
5357static void import_cleanup(ImportCtx *p){
5358  if( p->in!=0 && p->xCloser!=0 ){
5359    p->xCloser(p->in);
5360    p->in = 0;
5361  }
5362  sqlite3_free(p->z);
5363  p->z = 0;
5364}
5365
5366/* Append a single byte to z[] */
5367static void import_append_char(ImportCtx *p, int c){
5368  if( p->n+1>=p->nAlloc ){
5369    p->nAlloc += p->nAlloc + 100;
5370    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5371    shell_check_oom(p->z);
5372  }
5373  p->z[p->n++] = (char)c;
5374}
5375
5376/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5377** with the option of having a separator other than ",".
5378**
5379**   +  Input comes from p->in.
5380**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5381**      from sqlite3_malloc64().
5382**   +  Use p->cSep as the column separator.  The default is ",".
5383**   +  Use p->rSep as the row separator.  The default is "\n".
5384**   +  Keep track of the line number in p->nLine.
5385**   +  Store the character that terminates the field in p->cTerm.  Store
5386**      EOF on end-of-file.
5387**   +  Report syntax errors on stderr
5388*/
5389static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5390  int c;
5391  int cSep = p->cColSep;
5392  int rSep = p->cRowSep;
5393  p->n = 0;
5394  c = fgetc(p->in);
5395  if( c==EOF || seenInterrupt ){
5396    p->cTerm = EOF;
5397    return 0;
5398  }
5399  if( c=='"' ){
5400    int pc, ppc;
5401    int startLine = p->nLine;
5402    int cQuote = c;
5403    pc = ppc = 0;
5404    while( 1 ){
5405      c = fgetc(p->in);
5406      if( c==rSep ) p->nLine++;
5407      if( c==cQuote ){
5408        if( pc==cQuote ){
5409          pc = 0;
5410          continue;
5411        }
5412      }
5413      if( (c==cSep && pc==cQuote)
5414       || (c==rSep && pc==cQuote)
5415       || (c==rSep && pc=='\r' && ppc==cQuote)
5416       || (c==EOF && pc==cQuote)
5417      ){
5418        do{ p->n--; }while( p->z[p->n]!=cQuote );
5419        p->cTerm = c;
5420        break;
5421      }
5422      if( pc==cQuote && c!='\r' ){
5423        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5424                p->zFile, p->nLine, cQuote);
5425      }
5426      if( c==EOF ){
5427        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5428                p->zFile, startLine, cQuote);
5429        p->cTerm = c;
5430        break;
5431      }
5432      import_append_char(p, c);
5433      ppc = pc;
5434      pc = c;
5435    }
5436  }else{
5437    /* If this is the first field being parsed and it begins with the
5438    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5439    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5440      import_append_char(p, c);
5441      c = fgetc(p->in);
5442      if( (c&0xff)==0xbb ){
5443        import_append_char(p, c);
5444        c = fgetc(p->in);
5445        if( (c&0xff)==0xbf ){
5446          p->bNotFirst = 1;
5447          p->n = 0;
5448          return csv_read_one_field(p);
5449        }
5450      }
5451    }
5452    while( c!=EOF && c!=cSep && c!=rSep ){
5453      import_append_char(p, c);
5454      c = fgetc(p->in);
5455    }
5456    if( c==rSep ){
5457      p->nLine++;
5458      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5459    }
5460    p->cTerm = c;
5461  }
5462  if( p->z ) p->z[p->n] = 0;
5463  p->bNotFirst = 1;
5464  return p->z;
5465}
5466
5467/* Read a single field of ASCII delimited text.
5468**
5469**   +  Input comes from p->in.
5470**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5471**      from sqlite3_malloc64().
5472**   +  Use p->cSep as the column separator.  The default is "\x1F".
5473**   +  Use p->rSep as the row separator.  The default is "\x1E".
5474**   +  Keep track of the row number in p->nLine.
5475**   +  Store the character that terminates the field in p->cTerm.  Store
5476**      EOF on end-of-file.
5477**   +  Report syntax errors on stderr
5478*/
5479static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5480  int c;
5481  int cSep = p->cColSep;
5482  int rSep = p->cRowSep;
5483  p->n = 0;
5484  c = fgetc(p->in);
5485  if( c==EOF || seenInterrupt ){
5486    p->cTerm = EOF;
5487    return 0;
5488  }
5489  while( c!=EOF && c!=cSep && c!=rSep ){
5490    import_append_char(p, c);
5491    c = fgetc(p->in);
5492  }
5493  if( c==rSep ){
5494    p->nLine++;
5495  }
5496  p->cTerm = c;
5497  if( p->z ) p->z[p->n] = 0;
5498  return p->z;
5499}
5500
5501/*
5502** Try to transfer data for table zTable.  If an error is seen while
5503** moving forward, try to go backwards.  The backwards movement won't
5504** work for WITHOUT ROWID tables.
5505*/
5506static void tryToCloneData(
5507  ShellState *p,
5508  sqlite3 *newDb,
5509  const char *zTable
5510){
5511  sqlite3_stmt *pQuery = 0;
5512  sqlite3_stmt *pInsert = 0;
5513  char *zQuery = 0;
5514  char *zInsert = 0;
5515  int rc;
5516  int i, j, n;
5517  int nTable = strlen30(zTable);
5518  int k = 0;
5519  int cnt = 0;
5520  const int spinRate = 10000;
5521
5522  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5523  shell_check_oom(zQuery);
5524  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5525  if( rc ){
5526    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5527            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5528            zQuery);
5529    goto end_data_xfer;
5530  }
5531  n = sqlite3_column_count(pQuery);
5532  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5533  shell_check_oom(zInsert);
5534  sqlite3_snprintf(200+nTable,zInsert,
5535                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5536  i = strlen30(zInsert);
5537  for(j=1; j<n; j++){
5538    memcpy(zInsert+i, ",?", 2);
5539    i += 2;
5540  }
5541  memcpy(zInsert+i, ");", 3);
5542  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5543  if( rc ){
5544    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5545            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5546            zQuery);
5547    goto end_data_xfer;
5548  }
5549  for(k=0; k<2; k++){
5550    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5551      for(i=0; i<n; i++){
5552        switch( sqlite3_column_type(pQuery, i) ){
5553          case SQLITE_NULL: {
5554            sqlite3_bind_null(pInsert, i+1);
5555            break;
5556          }
5557          case SQLITE_INTEGER: {
5558            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5559            break;
5560          }
5561          case SQLITE_FLOAT: {
5562            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5563            break;
5564          }
5565          case SQLITE_TEXT: {
5566            sqlite3_bind_text(pInsert, i+1,
5567                             (const char*)sqlite3_column_text(pQuery,i),
5568                             -1, SQLITE_STATIC);
5569            break;
5570          }
5571          case SQLITE_BLOB: {
5572            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5573                                            sqlite3_column_bytes(pQuery,i),
5574                                            SQLITE_STATIC);
5575            break;
5576          }
5577        }
5578      } /* End for */
5579      rc = sqlite3_step(pInsert);
5580      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5581        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5582                        sqlite3_errmsg(newDb));
5583      }
5584      sqlite3_reset(pInsert);
5585      cnt++;
5586      if( (cnt%spinRate)==0 ){
5587        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5588        fflush(stdout);
5589      }
5590    } /* End while */
5591    if( rc==SQLITE_DONE ) break;
5592    sqlite3_finalize(pQuery);
5593    sqlite3_free(zQuery);
5594    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5595                             zTable);
5596    shell_check_oom(zQuery);
5597    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5598    if( rc ){
5599      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5600      break;
5601    }
5602  } /* End for(k=0...) */
5603
5604end_data_xfer:
5605  sqlite3_finalize(pQuery);
5606  sqlite3_finalize(pInsert);
5607  sqlite3_free(zQuery);
5608  sqlite3_free(zInsert);
5609}
5610
5611
5612/*
5613** Try to transfer all rows of the schema that match zWhere.  For
5614** each row, invoke xForEach() on the object defined by that row.
5615** If an error is encountered while moving forward through the
5616** sqlite_schema table, try again moving backwards.
5617*/
5618static void tryToCloneSchema(
5619  ShellState *p,
5620  sqlite3 *newDb,
5621  const char *zWhere,
5622  void (*xForEach)(ShellState*,sqlite3*,const char*)
5623){
5624  sqlite3_stmt *pQuery = 0;
5625  char *zQuery = 0;
5626  int rc;
5627  const unsigned char *zName;
5628  const unsigned char *zSql;
5629  char *zErrMsg = 0;
5630
5631  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5632                           " WHERE %s", zWhere);
5633  shell_check_oom(zQuery);
5634  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5635  if( rc ){
5636    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5637                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5638                    zQuery);
5639    goto end_schema_xfer;
5640  }
5641  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5642    zName = sqlite3_column_text(pQuery, 0);
5643    zSql = sqlite3_column_text(pQuery, 1);
5644    if( zName==0 || zSql==0 ) continue;
5645    printf("%s... ", zName); fflush(stdout);
5646    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5647    if( zErrMsg ){
5648      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5649      sqlite3_free(zErrMsg);
5650      zErrMsg = 0;
5651    }
5652    if( xForEach ){
5653      xForEach(p, newDb, (const char*)zName);
5654    }
5655    printf("done\n");
5656  }
5657  if( rc!=SQLITE_DONE ){
5658    sqlite3_finalize(pQuery);
5659    sqlite3_free(zQuery);
5660    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5661                             " WHERE %s ORDER BY rowid DESC", zWhere);
5662    shell_check_oom(zQuery);
5663    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5664    if( rc ){
5665      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5666                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5667                      zQuery);
5668      goto end_schema_xfer;
5669    }
5670    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5671      zName = sqlite3_column_text(pQuery, 0);
5672      zSql = sqlite3_column_text(pQuery, 1);
5673      if( zName==0 || zSql==0 ) continue;
5674      printf("%s... ", zName); fflush(stdout);
5675      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5676      if( zErrMsg ){
5677        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5678        sqlite3_free(zErrMsg);
5679        zErrMsg = 0;
5680      }
5681      if( xForEach ){
5682        xForEach(p, newDb, (const char*)zName);
5683      }
5684      printf("done\n");
5685    }
5686  }
5687end_schema_xfer:
5688  sqlite3_finalize(pQuery);
5689  sqlite3_free(zQuery);
5690}
5691
5692/*
5693** Open a new database file named "zNewDb".  Try to recover as much information
5694** as possible out of the main database (which might be corrupt) and write it
5695** into zNewDb.
5696*/
5697static void tryToClone(ShellState *p, const char *zNewDb){
5698  int rc;
5699  sqlite3 *newDb = 0;
5700  if( access(zNewDb,0)==0 ){
5701    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5702    return;
5703  }
5704  rc = sqlite3_open(zNewDb, &newDb);
5705  if( rc ){
5706    utf8_printf(stderr, "Cannot create output database: %s\n",
5707            sqlite3_errmsg(newDb));
5708  }else{
5709    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5710    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5711    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5712    tryToCloneSchema(p, newDb, "type!='table'", 0);
5713    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5714    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5715  }
5716  close_db(newDb);
5717}
5718
5719/*
5720** Change the output file back to stdout.
5721**
5722** If the p->doXdgOpen flag is set, that means the output was being
5723** redirected to a temporary file named by p->zTempFile.  In that case,
5724** launch start/open/xdg-open on that temporary file.
5725*/
5726static void output_reset(ShellState *p){
5727  if( p->outfile[0]=='|' ){
5728#ifndef SQLITE_OMIT_POPEN
5729    pclose(p->out);
5730#endif
5731  }else{
5732    output_file_close(p->out);
5733#ifndef SQLITE_NOHAVE_SYSTEM
5734    if( p->doXdgOpen ){
5735      const char *zXdgOpenCmd =
5736#if defined(_WIN32)
5737      "start";
5738#elif defined(__APPLE__)
5739      "open";
5740#else
5741      "xdg-open";
5742#endif
5743      char *zCmd;
5744      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5745      if( system(zCmd) ){
5746        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5747      }else{
5748        /* Give the start/open/xdg-open command some time to get
5749        ** going before we continue, and potential delete the
5750        ** p->zTempFile data file out from under it */
5751        sqlite3_sleep(2000);
5752      }
5753      sqlite3_free(zCmd);
5754      outputModePop(p);
5755      p->doXdgOpen = 0;
5756    }
5757#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5758  }
5759  p->outfile[0] = 0;
5760  p->out = stdout;
5761}
5762
5763/*
5764** Run an SQL command and return the single integer result.
5765*/
5766static int db_int(sqlite3 *db, const char *zSql){
5767  sqlite3_stmt *pStmt;
5768  int res = 0;
5769  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5770  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5771    res = sqlite3_column_int(pStmt,0);
5772  }
5773  sqlite3_finalize(pStmt);
5774  return res;
5775}
5776
5777/*
5778** Convert a 2-byte or 4-byte big-endian integer into a native integer
5779*/
5780static unsigned int get2byteInt(unsigned char *a){
5781  return (a[0]<<8) + a[1];
5782}
5783static unsigned int get4byteInt(unsigned char *a){
5784  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5785}
5786
5787/*
5788** Implementation of the ".dbinfo" command.
5789**
5790** Return 1 on error, 2 to exit, and 0 otherwise.
5791*/
5792static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5793  static const struct { const char *zName; int ofst; } aField[] = {
5794     { "file change counter:",  24  },
5795     { "database page count:",  28  },
5796     { "freelist page count:",  36  },
5797     { "schema cookie:",        40  },
5798     { "schema format:",        44  },
5799     { "default cache size:",   48  },
5800     { "autovacuum top root:",  52  },
5801     { "incremental vacuum:",   64  },
5802     { "text encoding:",        56  },
5803     { "user version:",         60  },
5804     { "application id:",       68  },
5805     { "software version:",     96  },
5806  };
5807  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5808     { "number of tables:",
5809       "SELECT count(*) FROM %s WHERE type='table'" },
5810     { "number of indexes:",
5811       "SELECT count(*) FROM %s WHERE type='index'" },
5812     { "number of triggers:",
5813       "SELECT count(*) FROM %s WHERE type='trigger'" },
5814     { "number of views:",
5815       "SELECT count(*) FROM %s WHERE type='view'" },
5816     { "schema size:",
5817       "SELECT total(length(sql)) FROM %s" },
5818  };
5819  int i, rc;
5820  unsigned iDataVersion;
5821  char *zSchemaTab;
5822  char *zDb = nArg>=2 ? azArg[1] : "main";
5823  sqlite3_stmt *pStmt = 0;
5824  unsigned char aHdr[100];
5825  open_db(p, 0);
5826  if( p->db==0 ) return 1;
5827  rc = sqlite3_prepare_v2(p->db,
5828             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5829             -1, &pStmt, 0);
5830  if( rc ){
5831    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5832    sqlite3_finalize(pStmt);
5833    return 1;
5834  }
5835  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5836  if( sqlite3_step(pStmt)==SQLITE_ROW
5837   && sqlite3_column_bytes(pStmt,0)>100
5838  ){
5839    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5840    sqlite3_finalize(pStmt);
5841  }else{
5842    raw_printf(stderr, "unable to read database header\n");
5843    sqlite3_finalize(pStmt);
5844    return 1;
5845  }
5846  i = get2byteInt(aHdr+16);
5847  if( i==1 ) i = 65536;
5848  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5849  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5850  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5851  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5852  for(i=0; i<ArraySize(aField); i++){
5853    int ofst = aField[i].ofst;
5854    unsigned int val = get4byteInt(aHdr + ofst);
5855    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5856    switch( ofst ){
5857      case 56: {
5858        if( val==1 ) raw_printf(p->out, " (utf8)");
5859        if( val==2 ) raw_printf(p->out, " (utf16le)");
5860        if( val==3 ) raw_printf(p->out, " (utf16be)");
5861      }
5862    }
5863    raw_printf(p->out, "\n");
5864  }
5865  if( zDb==0 ){
5866    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5867  }else if( strcmp(zDb,"temp")==0 ){
5868    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5869  }else{
5870    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5871  }
5872  for(i=0; i<ArraySize(aQuery); i++){
5873    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5874    int val = db_int(p->db, zSql);
5875    sqlite3_free(zSql);
5876    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5877  }
5878  sqlite3_free(zSchemaTab);
5879  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5880  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5881  return 0;
5882}
5883
5884/*
5885** Print the current sqlite3_errmsg() value to stderr and return 1.
5886*/
5887static int shellDatabaseError(sqlite3 *db){
5888  const char *zErr = sqlite3_errmsg(db);
5889  utf8_printf(stderr, "Error: %s\n", zErr);
5890  return 1;
5891}
5892
5893/*
5894** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5895** if they match and FALSE (0) if they do not match.
5896**
5897** Globbing rules:
5898**
5899**      '*'       Matches any sequence of zero or more characters.
5900**
5901**      '?'       Matches exactly one character.
5902**
5903**     [...]      Matches one character from the enclosed list of
5904**                characters.
5905**
5906**     [^...]     Matches one character not in the enclosed list.
5907**
5908**      '#'       Matches any sequence of one or more digits with an
5909**                optional + or - sign in front
5910**
5911**      ' '       Any span of whitespace matches any other span of
5912**                whitespace.
5913**
5914** Extra whitespace at the end of z[] is ignored.
5915*/
5916static int testcase_glob(const char *zGlob, const char *z){
5917  int c, c2;
5918  int invert;
5919  int seen;
5920
5921  while( (c = (*(zGlob++)))!=0 ){
5922    if( IsSpace(c) ){
5923      if( !IsSpace(*z) ) return 0;
5924      while( IsSpace(*zGlob) ) zGlob++;
5925      while( IsSpace(*z) ) z++;
5926    }else if( c=='*' ){
5927      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5928        if( c=='?' && (*(z++))==0 ) return 0;
5929      }
5930      if( c==0 ){
5931        return 1;
5932      }else if( c=='[' ){
5933        while( *z && testcase_glob(zGlob-1,z)==0 ){
5934          z++;
5935        }
5936        return (*z)!=0;
5937      }
5938      while( (c2 = (*(z++)))!=0 ){
5939        while( c2!=c ){
5940          c2 = *(z++);
5941          if( c2==0 ) return 0;
5942        }
5943        if( testcase_glob(zGlob,z) ) return 1;
5944      }
5945      return 0;
5946    }else if( c=='?' ){
5947      if( (*(z++))==0 ) return 0;
5948    }else if( c=='[' ){
5949      int prior_c = 0;
5950      seen = 0;
5951      invert = 0;
5952      c = *(z++);
5953      if( c==0 ) return 0;
5954      c2 = *(zGlob++);
5955      if( c2=='^' ){
5956        invert = 1;
5957        c2 = *(zGlob++);
5958      }
5959      if( c2==']' ){
5960        if( c==']' ) seen = 1;
5961        c2 = *(zGlob++);
5962      }
5963      while( c2 && c2!=']' ){
5964        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5965          c2 = *(zGlob++);
5966          if( c>=prior_c && c<=c2 ) seen = 1;
5967          prior_c = 0;
5968        }else{
5969          if( c==c2 ){
5970            seen = 1;
5971          }
5972          prior_c = c2;
5973        }
5974        c2 = *(zGlob++);
5975      }
5976      if( c2==0 || (seen ^ invert)==0 ) return 0;
5977    }else if( c=='#' ){
5978      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5979      if( !IsDigit(z[0]) ) return 0;
5980      z++;
5981      while( IsDigit(z[0]) ){ z++; }
5982    }else{
5983      if( c!=(*(z++)) ) return 0;
5984    }
5985  }
5986  while( IsSpace(*z) ){ z++; }
5987  return *z==0;
5988}
5989
5990
5991/*
5992** Compare the string as a command-line option with either one or two
5993** initial "-" characters.
5994*/
5995static int optionMatch(const char *zStr, const char *zOpt){
5996  if( zStr[0]!='-' ) return 0;
5997  zStr++;
5998  if( zStr[0]=='-' ) zStr++;
5999  return strcmp(zStr, zOpt)==0;
6000}
6001
6002/*
6003** Delete a file.
6004*/
6005int shellDeleteFile(const char *zFilename){
6006  int rc;
6007#ifdef _WIN32
6008  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6009  rc = _wunlink(z);
6010  sqlite3_free(z);
6011#else
6012  rc = unlink(zFilename);
6013#endif
6014  return rc;
6015}
6016
6017/*
6018** Try to delete the temporary file (if there is one) and free the
6019** memory used to hold the name of the temp file.
6020*/
6021static void clearTempFile(ShellState *p){
6022  if( p->zTempFile==0 ) return;
6023  if( p->doXdgOpen ) return;
6024  if( shellDeleteFile(p->zTempFile) ) return;
6025  sqlite3_free(p->zTempFile);
6026  p->zTempFile = 0;
6027}
6028
6029/*
6030** Create a new temp file name with the given suffix.
6031*/
6032static void newTempFile(ShellState *p, const char *zSuffix){
6033  clearTempFile(p);
6034  sqlite3_free(p->zTempFile);
6035  p->zTempFile = 0;
6036  if( p->db ){
6037    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6038  }
6039  if( p->zTempFile==0 ){
6040    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6041    ** will not work and we will need to fallback to guessing */
6042    char *zTemp;
6043    sqlite3_uint64 r;
6044    sqlite3_randomness(sizeof(r), &r);
6045    zTemp = getenv("TEMP");
6046    if( zTemp==0 ) zTemp = getenv("TMP");
6047    if( zTemp==0 ){
6048#ifdef _WIN32
6049      zTemp = "\\tmp";
6050#else
6051      zTemp = "/tmp";
6052#endif
6053    }
6054    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6055  }else{
6056    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6057  }
6058  shell_check_oom(p->zTempFile);
6059}
6060
6061
6062/*
6063** The implementation of SQL scalar function fkey_collate_clause(), used
6064** by the ".lint fkey-indexes" command. This scalar function is always
6065** called with four arguments - the parent table name, the parent column name,
6066** the child table name and the child column name.
6067**
6068**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6069**
6070** If either of the named tables or columns do not exist, this function
6071** returns an empty string. An empty string is also returned if both tables
6072** and columns exist but have the same default collation sequence. Or,
6073** if both exist but the default collation sequences are different, this
6074** function returns the string " COLLATE <parent-collation>", where
6075** <parent-collation> is the default collation sequence of the parent column.
6076*/
6077static void shellFkeyCollateClause(
6078  sqlite3_context *pCtx,
6079  int nVal,
6080  sqlite3_value **apVal
6081){
6082  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6083  const char *zParent;
6084  const char *zParentCol;
6085  const char *zParentSeq;
6086  const char *zChild;
6087  const char *zChildCol;
6088  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6089  int rc;
6090
6091  assert( nVal==4 );
6092  zParent = (const char*)sqlite3_value_text(apVal[0]);
6093  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6094  zChild = (const char*)sqlite3_value_text(apVal[2]);
6095  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6096
6097  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6098  rc = sqlite3_table_column_metadata(
6099      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6100  );
6101  if( rc==SQLITE_OK ){
6102    rc = sqlite3_table_column_metadata(
6103        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6104    );
6105  }
6106
6107  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6108    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6109    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6110    sqlite3_free(z);
6111  }
6112}
6113
6114
6115/*
6116** The implementation of dot-command ".lint fkey-indexes".
6117*/
6118static int lintFkeyIndexes(
6119  ShellState *pState,             /* Current shell tool state */
6120  char **azArg,                   /* Array of arguments passed to dot command */
6121  int nArg                        /* Number of entries in azArg[] */
6122){
6123  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6124  FILE *out = pState->out;        /* Stream to write non-error output to */
6125  int bVerbose = 0;               /* If -verbose is present */
6126  int bGroupByParent = 0;         /* If -groupbyparent is present */
6127  int i;                          /* To iterate through azArg[] */
6128  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6129  int rc;                         /* Return code */
6130  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6131
6132  /*
6133  ** This SELECT statement returns one row for each foreign key constraint
6134  ** in the schema of the main database. The column values are:
6135  **
6136  ** 0. The text of an SQL statement similar to:
6137  **
6138  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6139  **
6140  **    This SELECT is similar to the one that the foreign keys implementation
6141  **    needs to run internally on child tables. If there is an index that can
6142  **    be used to optimize this query, then it can also be used by the FK
6143  **    implementation to optimize DELETE or UPDATE statements on the parent
6144  **    table.
6145  **
6146  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6147  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6148  **    contains an index that can be used to optimize the query.
6149  **
6150  ** 2. Human readable text that describes the child table and columns. e.g.
6151  **
6152  **       "child_table(child_key1, child_key2)"
6153  **
6154  ** 3. Human readable text that describes the parent table and columns. e.g.
6155  **
6156  **       "parent_table(parent_key1, parent_key2)"
6157  **
6158  ** 4. A full CREATE INDEX statement for an index that could be used to
6159  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6160  **
6161  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6162  **
6163  ** 5. The name of the parent table.
6164  **
6165  ** These six values are used by the C logic below to generate the report.
6166  */
6167  const char *zSql =
6168  "SELECT "
6169    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6170    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6171    "  || fkey_collate_clause("
6172    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6173    ", "
6174    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6175    "  || group_concat('*=?', ' AND ') || ')'"
6176    ", "
6177    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6178    ", "
6179    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6180    ", "
6181    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6182    "  || ' ON ' || quote(s.name) || '('"
6183    "  || group_concat(quote(f.[from]) ||"
6184    "        fkey_collate_clause("
6185    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6186    "  || ');'"
6187    ", "
6188    "     f.[table] "
6189    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6190    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6191    "GROUP BY s.name, f.id "
6192    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6193  ;
6194  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6195
6196  for(i=2; i<nArg; i++){
6197    int n = strlen30(azArg[i]);
6198    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6199      bVerbose = 1;
6200    }
6201    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6202      bGroupByParent = 1;
6203      zIndent = "    ";
6204    }
6205    else{
6206      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6207          azArg[0], azArg[1]
6208      );
6209      return SQLITE_ERROR;
6210    }
6211  }
6212
6213  /* Register the fkey_collate_clause() SQL function */
6214  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6215      0, shellFkeyCollateClause, 0, 0
6216  );
6217
6218
6219  if( rc==SQLITE_OK ){
6220    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6221  }
6222  if( rc==SQLITE_OK ){
6223    sqlite3_bind_int(pSql, 1, bGroupByParent);
6224  }
6225
6226  if( rc==SQLITE_OK ){
6227    int rc2;
6228    char *zPrev = 0;
6229    while( SQLITE_ROW==sqlite3_step(pSql) ){
6230      int res = -1;
6231      sqlite3_stmt *pExplain = 0;
6232      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6233      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6234      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6235      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6236      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6237      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6238
6239      if( zEQP==0 ) continue;
6240      if( zGlob==0 ) continue;
6241      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6242      if( rc!=SQLITE_OK ) break;
6243      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6244        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6245        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6246                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6247      }
6248      rc = sqlite3_finalize(pExplain);
6249      if( rc!=SQLITE_OK ) break;
6250
6251      if( res<0 ){
6252        raw_printf(stderr, "Error: internal error");
6253        break;
6254      }else{
6255        if( bGroupByParent
6256        && (bVerbose || res==0)
6257        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6258        ){
6259          raw_printf(out, "-- Parent table %s\n", zParent);
6260          sqlite3_free(zPrev);
6261          zPrev = sqlite3_mprintf("%s", zParent);
6262        }
6263
6264        if( res==0 ){
6265          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6266        }else if( bVerbose ){
6267          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6268              zIndent, zFrom, zTarget
6269          );
6270        }
6271      }
6272    }
6273    sqlite3_free(zPrev);
6274
6275    if( rc!=SQLITE_OK ){
6276      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6277    }
6278
6279    rc2 = sqlite3_finalize(pSql);
6280    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6281      rc = rc2;
6282      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6283    }
6284  }else{
6285    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6286  }
6287
6288  return rc;
6289}
6290
6291/*
6292** Implementation of ".lint" dot command.
6293*/
6294static int lintDotCommand(
6295  ShellState *pState,             /* Current shell tool state */
6296  char **azArg,                   /* Array of arguments passed to dot command */
6297  int nArg                        /* Number of entries in azArg[] */
6298){
6299  int n;
6300  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6301  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6302  return lintFkeyIndexes(pState, azArg, nArg);
6303
6304 usage:
6305  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6306  raw_printf(stderr, "Where sub-commands are:\n");
6307  raw_printf(stderr, "    fkey-indexes\n");
6308  return SQLITE_ERROR;
6309}
6310
6311#if !defined SQLITE_OMIT_VIRTUALTABLE
6312static void shellPrepare(
6313  sqlite3 *db,
6314  int *pRc,
6315  const char *zSql,
6316  sqlite3_stmt **ppStmt
6317){
6318  *ppStmt = 0;
6319  if( *pRc==SQLITE_OK ){
6320    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6321    if( rc!=SQLITE_OK ){
6322      raw_printf(stderr, "sql error: %s (%d)\n",
6323          sqlite3_errmsg(db), sqlite3_errcode(db)
6324      );
6325      *pRc = rc;
6326    }
6327  }
6328}
6329
6330/*
6331** Create a prepared statement using printf-style arguments for the SQL.
6332**
6333** This routine is could be marked "static".  But it is not always used,
6334** depending on compile-time options.  By omitting the "static", we avoid
6335** nuisance compiler warnings about "defined but not used".
6336*/
6337void shellPreparePrintf(
6338  sqlite3 *db,
6339  int *pRc,
6340  sqlite3_stmt **ppStmt,
6341  const char *zFmt,
6342  ...
6343){
6344  *ppStmt = 0;
6345  if( *pRc==SQLITE_OK ){
6346    va_list ap;
6347    char *z;
6348    va_start(ap, zFmt);
6349    z = sqlite3_vmprintf(zFmt, ap);
6350    va_end(ap);
6351    if( z==0 ){
6352      *pRc = SQLITE_NOMEM;
6353    }else{
6354      shellPrepare(db, pRc, z, ppStmt);
6355      sqlite3_free(z);
6356    }
6357  }
6358}
6359
6360/* Finalize the prepared statement created using shellPreparePrintf().
6361**
6362** This routine is could be marked "static".  But it is not always used,
6363** depending on compile-time options.  By omitting the "static", we avoid
6364** nuisance compiler warnings about "defined but not used".
6365*/
6366void shellFinalize(
6367  int *pRc,
6368  sqlite3_stmt *pStmt
6369){
6370  if( pStmt ){
6371    sqlite3 *db = sqlite3_db_handle(pStmt);
6372    int rc = sqlite3_finalize(pStmt);
6373    if( *pRc==SQLITE_OK ){
6374      if( rc!=SQLITE_OK ){
6375        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6376      }
6377      *pRc = rc;
6378    }
6379  }
6380}
6381
6382/* Reset the prepared statement created using shellPreparePrintf().
6383**
6384** This routine is could be marked "static".  But it is not always used,
6385** depending on compile-time options.  By omitting the "static", we avoid
6386** nuisance compiler warnings about "defined but not used".
6387*/
6388void shellReset(
6389  int *pRc,
6390  sqlite3_stmt *pStmt
6391){
6392  int rc = sqlite3_reset(pStmt);
6393  if( *pRc==SQLITE_OK ){
6394    if( rc!=SQLITE_OK ){
6395      sqlite3 *db = sqlite3_db_handle(pStmt);
6396      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6397    }
6398    *pRc = rc;
6399  }
6400}
6401#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6402
6403#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6404/******************************************************************************
6405** The ".archive" or ".ar" command.
6406*/
6407/*
6408** Structure representing a single ".ar" command.
6409*/
6410typedef struct ArCommand ArCommand;
6411struct ArCommand {
6412  u8 eCmd;                        /* An AR_CMD_* value */
6413  u8 bVerbose;                    /* True if --verbose */
6414  u8 bZip;                        /* True if the archive is a ZIP */
6415  u8 bDryRun;                     /* True if --dry-run */
6416  u8 bAppend;                     /* True if --append */
6417  u8 bGlob;                       /* True if --glob */
6418  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6419  int nArg;                       /* Number of command arguments */
6420  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6421  const char *zFile;              /* --file argument, or NULL */
6422  const char *zDir;               /* --directory argument, or NULL */
6423  char **azArg;                   /* Array of command arguments */
6424  ShellState *p;                  /* Shell state */
6425  sqlite3 *db;                    /* Database containing the archive */
6426};
6427
6428/*
6429** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6430*/
6431static int arUsage(FILE *f){
6432  showHelp(f,"archive");
6433  return SQLITE_ERROR;
6434}
6435
6436/*
6437** Print an error message for the .ar command to stderr and return
6438** SQLITE_ERROR.
6439*/
6440static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6441  va_list ap;
6442  char *z;
6443  va_start(ap, zFmt);
6444  z = sqlite3_vmprintf(zFmt, ap);
6445  va_end(ap);
6446  utf8_printf(stderr, "Error: %s\n", z);
6447  if( pAr->fromCmdLine ){
6448    utf8_printf(stderr, "Use \"-A\" for more help\n");
6449  }else{
6450    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6451  }
6452  sqlite3_free(z);
6453  return SQLITE_ERROR;
6454}
6455
6456/*
6457** Values for ArCommand.eCmd.
6458*/
6459#define AR_CMD_CREATE       1
6460#define AR_CMD_UPDATE       2
6461#define AR_CMD_INSERT       3
6462#define AR_CMD_EXTRACT      4
6463#define AR_CMD_LIST         5
6464#define AR_CMD_HELP         6
6465#define AR_CMD_REMOVE       7
6466
6467/*
6468** Other (non-command) switches.
6469*/
6470#define AR_SWITCH_VERBOSE     8
6471#define AR_SWITCH_FILE        9
6472#define AR_SWITCH_DIRECTORY  10
6473#define AR_SWITCH_APPEND     11
6474#define AR_SWITCH_DRYRUN     12
6475#define AR_SWITCH_GLOB       13
6476
6477static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6478  switch( eSwitch ){
6479    case AR_CMD_CREATE:
6480    case AR_CMD_EXTRACT:
6481    case AR_CMD_LIST:
6482    case AR_CMD_REMOVE:
6483    case AR_CMD_UPDATE:
6484    case AR_CMD_INSERT:
6485    case AR_CMD_HELP:
6486      if( pAr->eCmd ){
6487        return arErrorMsg(pAr, "multiple command options");
6488      }
6489      pAr->eCmd = eSwitch;
6490      break;
6491
6492    case AR_SWITCH_DRYRUN:
6493      pAr->bDryRun = 1;
6494      break;
6495    case AR_SWITCH_GLOB:
6496      pAr->bGlob = 1;
6497      break;
6498    case AR_SWITCH_VERBOSE:
6499      pAr->bVerbose = 1;
6500      break;
6501    case AR_SWITCH_APPEND:
6502      pAr->bAppend = 1;
6503      /* Fall thru into --file */
6504    case AR_SWITCH_FILE:
6505      pAr->zFile = zArg;
6506      break;
6507    case AR_SWITCH_DIRECTORY:
6508      pAr->zDir = zArg;
6509      break;
6510  }
6511
6512  return SQLITE_OK;
6513}
6514
6515/*
6516** Parse the command line for an ".ar" command. The results are written into
6517** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6518** successfully, otherwise an error message is written to stderr and
6519** SQLITE_ERROR returned.
6520*/
6521static int arParseCommand(
6522  char **azArg,                   /* Array of arguments passed to dot command */
6523  int nArg,                       /* Number of entries in azArg[] */
6524  ArCommand *pAr                  /* Populate this object */
6525){
6526  struct ArSwitch {
6527    const char *zLong;
6528    char cShort;
6529    u8 eSwitch;
6530    u8 bArg;
6531  } aSwitch[] = {
6532    { "create",    'c', AR_CMD_CREATE,       0 },
6533    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6534    { "insert",    'i', AR_CMD_INSERT,       0 },
6535    { "list",      't', AR_CMD_LIST,         0 },
6536    { "remove",    'r', AR_CMD_REMOVE,       0 },
6537    { "update",    'u', AR_CMD_UPDATE,       0 },
6538    { "help",      'h', AR_CMD_HELP,         0 },
6539    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6540    { "file",      'f', AR_SWITCH_FILE,      1 },
6541    { "append",    'a', AR_SWITCH_APPEND,    1 },
6542    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6543    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6544    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6545  };
6546  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6547  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6548
6549  if( nArg<=1 ){
6550    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6551    return arUsage(stderr);
6552  }else{
6553    char *z = azArg[1];
6554    if( z[0]!='-' ){
6555      /* Traditional style [tar] invocation */
6556      int i;
6557      int iArg = 2;
6558      for(i=0; z[i]; i++){
6559        const char *zArg = 0;
6560        struct ArSwitch *pOpt;
6561        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6562          if( z[i]==pOpt->cShort ) break;
6563        }
6564        if( pOpt==pEnd ){
6565          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6566        }
6567        if( pOpt->bArg ){
6568          if( iArg>=nArg ){
6569            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6570          }
6571          zArg = azArg[iArg++];
6572        }
6573        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6574      }
6575      pAr->nArg = nArg-iArg;
6576      if( pAr->nArg>0 ){
6577        pAr->azArg = &azArg[iArg];
6578      }
6579    }else{
6580      /* Non-traditional invocation */
6581      int iArg;
6582      for(iArg=1; iArg<nArg; iArg++){
6583        int n;
6584        z = azArg[iArg];
6585        if( z[0]!='-' ){
6586          /* All remaining command line words are command arguments. */
6587          pAr->azArg = &azArg[iArg];
6588          pAr->nArg = nArg-iArg;
6589          break;
6590        }
6591        n = strlen30(z);
6592
6593        if( z[1]!='-' ){
6594          int i;
6595          /* One or more short options */
6596          for(i=1; i<n; i++){
6597            const char *zArg = 0;
6598            struct ArSwitch *pOpt;
6599            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6600              if( z[i]==pOpt->cShort ) break;
6601            }
6602            if( pOpt==pEnd ){
6603              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6604            }
6605            if( pOpt->bArg ){
6606              if( i<(n-1) ){
6607                zArg = &z[i+1];
6608                i = n;
6609              }else{
6610                if( iArg>=(nArg-1) ){
6611                  return arErrorMsg(pAr, "option requires an argument: %c",
6612                                    z[i]);
6613                }
6614                zArg = azArg[++iArg];
6615              }
6616            }
6617            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6618          }
6619        }else if( z[2]=='\0' ){
6620          /* A -- option, indicating that all remaining command line words
6621          ** are command arguments.  */
6622          pAr->azArg = &azArg[iArg+1];
6623          pAr->nArg = nArg-iArg-1;
6624          break;
6625        }else{
6626          /* A long option */
6627          const char *zArg = 0;             /* Argument for option, if any */
6628          struct ArSwitch *pMatch = 0;      /* Matching option */
6629          struct ArSwitch *pOpt;            /* Iterator */
6630          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6631            const char *zLong = pOpt->zLong;
6632            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6633              if( pMatch ){
6634                return arErrorMsg(pAr, "ambiguous option: %s",z);
6635              }else{
6636                pMatch = pOpt;
6637              }
6638            }
6639          }
6640
6641          if( pMatch==0 ){
6642            return arErrorMsg(pAr, "unrecognized option: %s", z);
6643          }
6644          if( pMatch->bArg ){
6645            if( iArg>=(nArg-1) ){
6646              return arErrorMsg(pAr, "option requires an argument: %s", z);
6647            }
6648            zArg = azArg[++iArg];
6649          }
6650          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6651        }
6652      }
6653    }
6654  }
6655
6656  return SQLITE_OK;
6657}
6658
6659/*
6660** This function assumes that all arguments within the ArCommand.azArg[]
6661** array refer to archive members, as for the --extract, --list or --remove
6662** commands. It checks that each of them are "present". If any specified
6663** file is not present in the archive, an error is printed to stderr and an
6664** error code returned. Otherwise, if all specified arguments are present
6665** in the archive, SQLITE_OK is returned. Here, "present" means either an
6666** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6667** when pAr->bGlob is true.
6668**
6669** This function strips any trailing '/' characters from each argument.
6670** This is consistent with the way the [tar] command seems to work on
6671** Linux.
6672*/
6673static int arCheckEntries(ArCommand *pAr){
6674  int rc = SQLITE_OK;
6675  if( pAr->nArg ){
6676    int i, j;
6677    sqlite3_stmt *pTest = 0;
6678    const char *zSel = (pAr->bGlob)
6679      ? "SELECT name FROM %s WHERE glob($name,name)"
6680      : "SELECT name FROM %s WHERE name=$name";
6681
6682    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6683    j = sqlite3_bind_parameter_index(pTest, "$name");
6684    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6685      char *z = pAr->azArg[i];
6686      int n = strlen30(z);
6687      int bOk = 0;
6688      while( n>0 && z[n-1]=='/' ) n--;
6689      z[n] = '\0';
6690      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6691      if( SQLITE_ROW==sqlite3_step(pTest) ){
6692        bOk = 1;
6693      }
6694      shellReset(&rc, pTest);
6695      if( rc==SQLITE_OK && bOk==0 ){
6696        utf8_printf(stderr, "not found in archive: %s\n", z);
6697        rc = SQLITE_ERROR;
6698      }
6699    }
6700    shellFinalize(&rc, pTest);
6701  }
6702  return rc;
6703}
6704
6705/*
6706** Format a WHERE clause that can be used against the "sqlar" table to
6707** identify all archive members that match the command arguments held
6708** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6709** The caller is responsible for eventually calling sqlite3_free() on
6710** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6711** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6712*/
6713static void arWhereClause(
6714  int *pRc,
6715  ArCommand *pAr,
6716  char **pzWhere                  /* OUT: New WHERE clause */
6717){
6718  char *zWhere = 0;
6719  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6720  if( *pRc==SQLITE_OK ){
6721    if( pAr->nArg==0 ){
6722      zWhere = sqlite3_mprintf("1");
6723    }else{
6724      int i;
6725      const char *zSep = "";
6726      for(i=0; i<pAr->nArg; i++){
6727        const char *z = pAr->azArg[i];
6728        zWhere = sqlite3_mprintf(
6729          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6730          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6731        );
6732        if( zWhere==0 ){
6733          *pRc = SQLITE_NOMEM;
6734          break;
6735        }
6736        zSep = " OR ";
6737      }
6738    }
6739  }
6740  *pzWhere = zWhere;
6741}
6742
6743/*
6744** Implementation of .ar "lisT" command.
6745*/
6746static int arListCommand(ArCommand *pAr){
6747  const char *zSql = "SELECT %s FROM %s WHERE %s";
6748  const char *azCols[] = {
6749    "name",
6750    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6751  };
6752
6753  char *zWhere = 0;
6754  sqlite3_stmt *pSql = 0;
6755  int rc;
6756
6757  rc = arCheckEntries(pAr);
6758  arWhereClause(&rc, pAr, &zWhere);
6759
6760  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6761                     pAr->zSrcTable, zWhere);
6762  if( pAr->bDryRun ){
6763    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6764  }else{
6765    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6766      if( pAr->bVerbose ){
6767        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6768            sqlite3_column_text(pSql, 0),
6769            sqlite3_column_int(pSql, 1),
6770            sqlite3_column_text(pSql, 2),
6771            sqlite3_column_text(pSql, 3)
6772        );
6773      }else{
6774        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6775      }
6776    }
6777  }
6778  shellFinalize(&rc, pSql);
6779  sqlite3_free(zWhere);
6780  return rc;
6781}
6782
6783
6784/*
6785** Implementation of .ar "Remove" command.
6786*/
6787static int arRemoveCommand(ArCommand *pAr){
6788  int rc = 0;
6789  char *zSql = 0;
6790  char *zWhere = 0;
6791
6792  if( pAr->nArg ){
6793    /* Verify that args actually exist within the archive before proceeding.
6794    ** And formulate a WHERE clause to match them.  */
6795    rc = arCheckEntries(pAr);
6796    arWhereClause(&rc, pAr, &zWhere);
6797  }
6798  if( rc==SQLITE_OK ){
6799    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6800                           pAr->zSrcTable, zWhere);
6801    if( pAr->bDryRun ){
6802      utf8_printf(pAr->p->out, "%s\n", zSql);
6803    }else{
6804      char *zErr = 0;
6805      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6806      if( rc==SQLITE_OK ){
6807        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6808        if( rc!=SQLITE_OK ){
6809          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6810        }else{
6811          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6812        }
6813      }
6814      if( zErr ){
6815        utf8_printf(stdout, "ERROR: %s\n", zErr);
6816        sqlite3_free(zErr);
6817      }
6818    }
6819  }
6820  sqlite3_free(zWhere);
6821  sqlite3_free(zSql);
6822  return rc;
6823}
6824
6825/*
6826** Implementation of .ar "eXtract" command.
6827*/
6828static int arExtractCommand(ArCommand *pAr){
6829  const char *zSql1 =
6830    "SELECT "
6831    " ($dir || name),"
6832    " writefile(($dir || name), %s, mode, mtime) "
6833    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6834    " AND name NOT GLOB '*..[/\\]*'";
6835
6836  const char *azExtraArg[] = {
6837    "sqlar_uncompress(data, sz)",
6838    "data"
6839  };
6840
6841  sqlite3_stmt *pSql = 0;
6842  int rc = SQLITE_OK;
6843  char *zDir = 0;
6844  char *zWhere = 0;
6845  int i, j;
6846
6847  /* If arguments are specified, check that they actually exist within
6848  ** the archive before proceeding. And formulate a WHERE clause to
6849  ** match them.  */
6850  rc = arCheckEntries(pAr);
6851  arWhereClause(&rc, pAr, &zWhere);
6852
6853  if( rc==SQLITE_OK ){
6854    if( pAr->zDir ){
6855      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6856    }else{
6857      zDir = sqlite3_mprintf("");
6858    }
6859    if( zDir==0 ) rc = SQLITE_NOMEM;
6860  }
6861
6862  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6863      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6864  );
6865
6866  if( rc==SQLITE_OK ){
6867    j = sqlite3_bind_parameter_index(pSql, "$dir");
6868    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6869
6870    /* Run the SELECT statement twice. The first time, writefile() is called
6871    ** for all archive members that should be extracted. The second time,
6872    ** only for the directories. This is because the timestamps for
6873    ** extracted directories must be reset after they are populated (as
6874    ** populating them changes the timestamp).  */
6875    for(i=0; i<2; i++){
6876      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6877      sqlite3_bind_int(pSql, j, i);
6878      if( pAr->bDryRun ){
6879        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6880      }else{
6881        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6882          if( i==0 && pAr->bVerbose ){
6883            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6884          }
6885        }
6886      }
6887      shellReset(&rc, pSql);
6888    }
6889    shellFinalize(&rc, pSql);
6890  }
6891
6892  sqlite3_free(zDir);
6893  sqlite3_free(zWhere);
6894  return rc;
6895}
6896
6897/*
6898** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6899*/
6900static int arExecSql(ArCommand *pAr, const char *zSql){
6901  int rc;
6902  if( pAr->bDryRun ){
6903    utf8_printf(pAr->p->out, "%s\n", zSql);
6904    rc = SQLITE_OK;
6905  }else{
6906    char *zErr = 0;
6907    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6908    if( zErr ){
6909      utf8_printf(stdout, "ERROR: %s\n", zErr);
6910      sqlite3_free(zErr);
6911    }
6912  }
6913  return rc;
6914}
6915
6916
6917/*
6918** Implementation of .ar "create", "insert", and "update" commands.
6919**
6920**     create    ->     Create a new SQL archive
6921**     insert    ->     Insert or reinsert all files listed
6922**     update    ->     Insert files that have changed or that were not
6923**                      previously in the archive
6924**
6925** Create the "sqlar" table in the database if it does not already exist.
6926** Then add each file in the azFile[] array to the archive. Directories
6927** are added recursively. If argument bVerbose is non-zero, a message is
6928** printed on stdout for each file archived.
6929**
6930** The create command is the same as update, except that it drops
6931** any existing "sqlar" table before beginning.  The "insert" command
6932** always overwrites every file named on the command-line, where as
6933** "update" only overwrites if the size or mtime or mode has changed.
6934*/
6935static int arCreateOrUpdateCommand(
6936  ArCommand *pAr,                 /* Command arguments and options */
6937  int bUpdate,                    /* true for a --create. */
6938  int bOnlyIfChanged              /* Only update if file has changed */
6939){
6940  const char *zCreate =
6941      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6942      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6943      "  mode INT,               -- access permissions\n"
6944      "  mtime INT,              -- last modification time\n"
6945      "  sz INT,                 -- original file size\n"
6946      "  data BLOB               -- compressed content\n"
6947      ")";
6948  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6949  const char *zInsertFmt[2] = {
6950     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6951     "  SELECT\n"
6952     "    %s,\n"
6953     "    mode,\n"
6954     "    mtime,\n"
6955     "    CASE substr(lsmode(mode),1,1)\n"
6956     "      WHEN '-' THEN length(data)\n"
6957     "      WHEN 'd' THEN 0\n"
6958     "      ELSE -1 END,\n"
6959     "    sqlar_compress(data)\n"
6960     "  FROM fsdir(%Q,%Q) AS disk\n"
6961     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6962     ,
6963     "REPLACE INTO %s(name,mode,mtime,data)\n"
6964     "  SELECT\n"
6965     "    %s,\n"
6966     "    mode,\n"
6967     "    mtime,\n"
6968     "    data\n"
6969     "  FROM fsdir(%Q,%Q) AS disk\n"
6970     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6971  };
6972  int i;                          /* For iterating through azFile[] */
6973  int rc;                         /* Return code */
6974  const char *zTab = 0;           /* SQL table into which to insert */
6975  char *zSql;
6976  char zTemp[50];
6977  char *zExists = 0;
6978
6979  arExecSql(pAr, "PRAGMA page_size=512");
6980  rc = arExecSql(pAr, "SAVEPOINT ar;");
6981  if( rc!=SQLITE_OK ) return rc;
6982  zTemp[0] = 0;
6983  if( pAr->bZip ){
6984    /* Initialize the zipfile virtual table, if necessary */
6985    if( pAr->zFile ){
6986      sqlite3_uint64 r;
6987      sqlite3_randomness(sizeof(r),&r);
6988      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6989      zTab = zTemp;
6990      zSql = sqlite3_mprintf(
6991         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6992         zTab, pAr->zFile
6993      );
6994      rc = arExecSql(pAr, zSql);
6995      sqlite3_free(zSql);
6996    }else{
6997      zTab = "zip";
6998    }
6999  }else{
7000    /* Initialize the table for an SQLAR */
7001    zTab = "sqlar";
7002    if( bUpdate==0 ){
7003      rc = arExecSql(pAr, zDrop);
7004      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7005    }
7006    rc = arExecSql(pAr, zCreate);
7007  }
7008  if( bOnlyIfChanged ){
7009    zExists = sqlite3_mprintf(
7010      " AND NOT EXISTS("
7011          "SELECT 1 FROM %s AS mem"
7012          " WHERE mem.name=disk.name"
7013          " AND mem.mtime=disk.mtime"
7014          " AND mem.mode=disk.mode)", zTab);
7015  }else{
7016    zExists = sqlite3_mprintf("");
7017  }
7018  if( zExists==0 ) rc = SQLITE_NOMEM;
7019  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7020    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7021        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7022        pAr->azArg[i], pAr->zDir, zExists);
7023    rc = arExecSql(pAr, zSql2);
7024    sqlite3_free(zSql2);
7025  }
7026end_ar_transaction:
7027  if( rc!=SQLITE_OK ){
7028    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7029  }else{
7030    rc = arExecSql(pAr, "RELEASE ar;");
7031    if( pAr->bZip && pAr->zFile ){
7032      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7033      arExecSql(pAr, zSql);
7034      sqlite3_free(zSql);
7035    }
7036  }
7037  sqlite3_free(zExists);
7038  return rc;
7039}
7040
7041/*
7042** Implementation of ".ar" dot command.
7043*/
7044static int arDotCommand(
7045  ShellState *pState,          /* Current shell tool state */
7046  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7047  char **azArg,                /* Array of arguments passed to dot command */
7048  int nArg                     /* Number of entries in azArg[] */
7049){
7050  ArCommand cmd;
7051  int rc;
7052  memset(&cmd, 0, sizeof(cmd));
7053  cmd.fromCmdLine = fromCmdLine;
7054  rc = arParseCommand(azArg, nArg, &cmd);
7055  if( rc==SQLITE_OK ){
7056    int eDbType = SHELL_OPEN_UNSPEC;
7057    cmd.p = pState;
7058    cmd.db = pState->db;
7059    if( cmd.zFile ){
7060      eDbType = deduceDatabaseType(cmd.zFile, 1);
7061    }else{
7062      eDbType = pState->openMode;
7063    }
7064    if( eDbType==SHELL_OPEN_ZIPFILE ){
7065      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7066        if( cmd.zFile==0 ){
7067          cmd.zSrcTable = sqlite3_mprintf("zip");
7068        }else{
7069          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7070        }
7071      }
7072      cmd.bZip = 1;
7073    }else if( cmd.zFile ){
7074      int flags;
7075      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7076      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7077           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7078        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7079      }else{
7080        flags = SQLITE_OPEN_READONLY;
7081      }
7082      cmd.db = 0;
7083      if( cmd.bDryRun ){
7084        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7085             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7086      }
7087      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7088             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7089      if( rc!=SQLITE_OK ){
7090        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7091            cmd.zFile, sqlite3_errmsg(cmd.db)
7092        );
7093        goto end_ar_command;
7094      }
7095      sqlite3_fileio_init(cmd.db, 0, 0);
7096      sqlite3_sqlar_init(cmd.db, 0, 0);
7097      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7098                              shellPutsFunc, 0, 0);
7099
7100    }
7101    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7102      if( cmd.eCmd!=AR_CMD_CREATE
7103       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7104      ){
7105        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7106        rc = SQLITE_ERROR;
7107        goto end_ar_command;
7108      }
7109      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7110    }
7111
7112    switch( cmd.eCmd ){
7113      case AR_CMD_CREATE:
7114        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7115        break;
7116
7117      case AR_CMD_EXTRACT:
7118        rc = arExtractCommand(&cmd);
7119        break;
7120
7121      case AR_CMD_LIST:
7122        rc = arListCommand(&cmd);
7123        break;
7124
7125      case AR_CMD_HELP:
7126        arUsage(pState->out);
7127        break;
7128
7129      case AR_CMD_INSERT:
7130        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7131        break;
7132
7133      case AR_CMD_REMOVE:
7134        rc = arRemoveCommand(&cmd);
7135        break;
7136
7137      default:
7138        assert( cmd.eCmd==AR_CMD_UPDATE );
7139        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7140        break;
7141    }
7142  }
7143end_ar_command:
7144  if( cmd.db!=pState->db ){
7145    close_db(cmd.db);
7146  }
7147  sqlite3_free(cmd.zSrcTable);
7148
7149  return rc;
7150}
7151/* End of the ".archive" or ".ar" command logic
7152*******************************************************************************/
7153#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7154
7155#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7156/*
7157** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7158** Otherwise, the SQL statement or statements in zSql are executed using
7159** database connection db and the error code written to *pRc before
7160** this function returns.
7161*/
7162static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7163  int rc = *pRc;
7164  if( rc==SQLITE_OK ){
7165    char *zErr = 0;
7166    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7167    if( rc!=SQLITE_OK ){
7168      raw_printf(stderr, "SQL error: %s\n", zErr);
7169    }
7170    sqlite3_free(zErr);
7171    *pRc = rc;
7172  }
7173}
7174
7175/*
7176** Like shellExec(), except that zFmt is a printf() style format string.
7177*/
7178static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7179  char *z = 0;
7180  if( *pRc==SQLITE_OK ){
7181    va_list ap;
7182    va_start(ap, zFmt);
7183    z = sqlite3_vmprintf(zFmt, ap);
7184    va_end(ap);
7185    if( z==0 ){
7186      *pRc = SQLITE_NOMEM;
7187    }else{
7188      shellExec(db, pRc, z);
7189    }
7190    sqlite3_free(z);
7191  }
7192}
7193
7194/*
7195** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7196** Otherwise, an attempt is made to allocate, zero and return a pointer
7197** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7198** to SQLITE_NOMEM and NULL returned.
7199*/
7200static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7201  void *pRet = 0;
7202  if( *pRc==SQLITE_OK ){
7203    pRet = sqlite3_malloc64(nByte);
7204    if( pRet==0 ){
7205      *pRc = SQLITE_NOMEM;
7206    }else{
7207      memset(pRet, 0, nByte);
7208    }
7209  }
7210  return pRet;
7211}
7212
7213/*
7214** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7215** Otherwise, zFmt is treated as a printf() style string. The result of
7216** formatting it along with any trailing arguments is written into a
7217** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7218** It is the responsibility of the caller to eventually free this buffer
7219** using a call to sqlite3_free().
7220**
7221** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7222** pointer returned.
7223*/
7224static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7225  char *z = 0;
7226  if( *pRc==SQLITE_OK ){
7227    va_list ap;
7228    va_start(ap, zFmt);
7229    z = sqlite3_vmprintf(zFmt, ap);
7230    va_end(ap);
7231    if( z==0 ){
7232      *pRc = SQLITE_NOMEM;
7233    }
7234  }
7235  return z;
7236}
7237
7238
7239/*
7240** When running the ".recover" command, each output table, and the special
7241** orphaned row table if it is required, is represented by an instance
7242** of the following struct.
7243*/
7244typedef struct RecoverTable RecoverTable;
7245struct RecoverTable {
7246  char *zQuoted;                  /* Quoted version of table name */
7247  int nCol;                       /* Number of columns in table */
7248  char **azlCol;                  /* Array of column lists */
7249  int iPk;                        /* Index of IPK column */
7250};
7251
7252/*
7253** Free a RecoverTable object allocated by recoverFindTable() or
7254** recoverOrphanTable().
7255*/
7256static void recoverFreeTable(RecoverTable *pTab){
7257  if( pTab ){
7258    sqlite3_free(pTab->zQuoted);
7259    if( pTab->azlCol ){
7260      int i;
7261      for(i=0; i<=pTab->nCol; i++){
7262        sqlite3_free(pTab->azlCol[i]);
7263      }
7264      sqlite3_free(pTab->azlCol);
7265    }
7266    sqlite3_free(pTab);
7267  }
7268}
7269
7270/*
7271** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7272** Otherwise, it allocates and returns a RecoverTable object based on the
7273** final four arguments passed to this function. It is the responsibility
7274** of the caller to eventually free the returned object using
7275** recoverFreeTable().
7276*/
7277static RecoverTable *recoverNewTable(
7278  int *pRc,                       /* IN/OUT: Error code */
7279  const char *zName,              /* Name of table */
7280  const char *zSql,               /* CREATE TABLE statement */
7281  int bIntkey,
7282  int nCol
7283){
7284  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7285  int rc = *pRc;
7286  RecoverTable *pTab = 0;
7287
7288  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7289  if( rc==SQLITE_OK ){
7290    int nSqlCol = 0;
7291    int bSqlIntkey = 0;
7292    sqlite3_stmt *pStmt = 0;
7293
7294    rc = sqlite3_open("", &dbtmp);
7295    if( rc==SQLITE_OK ){
7296      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7297                              shellIdQuote, 0, 0);
7298    }
7299    if( rc==SQLITE_OK ){
7300      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7301    }
7302    if( rc==SQLITE_OK ){
7303      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7304      if( rc==SQLITE_ERROR ){
7305        rc = SQLITE_OK;
7306        goto finished;
7307      }
7308    }
7309    shellPreparePrintf(dbtmp, &rc, &pStmt,
7310        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7311    );
7312    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7313      nSqlCol = sqlite3_column_int(pStmt, 0);
7314    }
7315    shellFinalize(&rc, pStmt);
7316
7317    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7318      goto finished;
7319    }
7320
7321    shellPreparePrintf(dbtmp, &rc, &pStmt,
7322      "SELECT ("
7323      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7324      ") FROM sqlite_schema WHERE name = %Q", zName
7325    );
7326    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7327      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7328    }
7329    shellFinalize(&rc, pStmt);
7330
7331    if( bIntkey==bSqlIntkey ){
7332      int i;
7333      const char *zPk = "_rowid_";
7334      sqlite3_stmt *pPkFinder = 0;
7335
7336      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7337      ** set zPk to the name of the PK column, and pTab->iPk to the index
7338      ** of the column, where columns are 0-numbered from left to right.
7339      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7340      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7341      pTab->iPk = -2;
7342      if( bIntkey ){
7343        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7344          "SELECT cid, name FROM pragma_table_info(%Q) "
7345          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7346          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7347          , zName, zName
7348        );
7349        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7350          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7351          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7352          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7353        }
7354      }
7355
7356      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7357      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7358      pTab->nCol = nSqlCol;
7359
7360      if( bIntkey ){
7361        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7362      }else{
7363        pTab->azlCol[0] = shellMPrintf(&rc, "");
7364      }
7365      i = 1;
7366      shellPreparePrintf(dbtmp, &rc, &pStmt,
7367          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7368          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7369          "FROM pragma_table_info(%Q)",
7370          bIntkey ? ", " : "", pTab->iPk,
7371          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7372          zName
7373      );
7374      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7375        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7376        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7377        i++;
7378      }
7379      shellFinalize(&rc, pStmt);
7380
7381      shellFinalize(&rc, pPkFinder);
7382    }
7383  }
7384
7385 finished:
7386  sqlite3_close(dbtmp);
7387  *pRc = rc;
7388  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7389    recoverFreeTable(pTab);
7390    pTab = 0;
7391  }
7392  return pTab;
7393}
7394
7395/*
7396** This function is called to search the schema recovered from the
7397** sqlite_schema table of the (possibly) corrupt database as part
7398** of a ".recover" command. Specifically, for a table with root page
7399** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7400** table must be a WITHOUT ROWID table, or if non-zero, not one of
7401** those.
7402**
7403** If a table is found, a (RecoverTable*) object is returned. Or, if
7404** no such table is found, but bIntkey is false and iRoot is the
7405** root page of an index in the recovered schema, then (*pbNoop) is
7406** set to true and NULL returned. Or, if there is no such table or
7407** index, NULL is returned and (*pbNoop) set to 0, indicating that
7408** the caller should write data to the orphans table.
7409*/
7410static RecoverTable *recoverFindTable(
7411  ShellState *pState,             /* Shell state object */
7412  int *pRc,                       /* IN/OUT: Error code */
7413  int iRoot,                      /* Root page of table */
7414  int bIntkey,                    /* True for an intkey table */
7415  int nCol,                       /* Number of columns in table */
7416  int *pbNoop                     /* OUT: True if iRoot is root of index */
7417){
7418  sqlite3_stmt *pStmt = 0;
7419  RecoverTable *pRet = 0;
7420  int bNoop = 0;
7421  const char *zSql = 0;
7422  const char *zName = 0;
7423
7424  /* Search the recovered schema for an object with root page iRoot. */
7425  shellPreparePrintf(pState->db, pRc, &pStmt,
7426      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7427  );
7428  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7429    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7430    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7431      bNoop = 1;
7432      break;
7433    }
7434    if( sqlite3_stricmp(zType, "table")==0 ){
7435      zName = (const char*)sqlite3_column_text(pStmt, 1);
7436      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7437      if( zName!=0 && zSql!=0 ){
7438        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7439        break;
7440      }
7441    }
7442  }
7443
7444  shellFinalize(pRc, pStmt);
7445  *pbNoop = bNoop;
7446  return pRet;
7447}
7448
7449/*
7450** Return a RecoverTable object representing the orphans table.
7451*/
7452static RecoverTable *recoverOrphanTable(
7453  ShellState *pState,             /* Shell state object */
7454  int *pRc,                       /* IN/OUT: Error code */
7455  const char *zLostAndFound,      /* Base name for orphans table */
7456  int nCol                        /* Number of user data columns */
7457){
7458  RecoverTable *pTab = 0;
7459  if( nCol>=0 && *pRc==SQLITE_OK ){
7460    int i;
7461
7462    /* This block determines the name of the orphan table. The prefered
7463    ** name is zLostAndFound. But if that clashes with another name
7464    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7465    ** and so on until a non-clashing name is found.  */
7466    int iTab = 0;
7467    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7468    sqlite3_stmt *pTest = 0;
7469    shellPrepare(pState->db, pRc,
7470        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7471    );
7472    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7473    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7474      shellReset(pRc, pTest);
7475      sqlite3_free(zTab);
7476      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7477      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7478    }
7479    shellFinalize(pRc, pTest);
7480
7481    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7482    if( pTab ){
7483      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7484      pTab->nCol = nCol;
7485      pTab->iPk = -2;
7486      if( nCol>0 ){
7487        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7488        if( pTab->azlCol ){
7489          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7490          for(i=nCol-1; i>=0; i--){
7491            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7492          }
7493        }
7494      }
7495
7496      if( *pRc!=SQLITE_OK ){
7497        recoverFreeTable(pTab);
7498        pTab = 0;
7499      }else{
7500        raw_printf(pState->out,
7501            "CREATE TABLE %s(rootpgno INTEGER, "
7502            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7503        );
7504        for(i=0; i<nCol; i++){
7505          raw_printf(pState->out, ", c%d", i);
7506        }
7507        raw_printf(pState->out, ");\n");
7508      }
7509    }
7510    sqlite3_free(zTab);
7511  }
7512  return pTab;
7513}
7514
7515/*
7516** This function is called to recover data from the database. A script
7517** to construct a new database containing all recovered data is output
7518** on stream pState->out.
7519*/
7520static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7521  int rc = SQLITE_OK;
7522  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7523  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7524  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7525  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7526  const char *zLostAndFound = "lost_and_found";
7527  int i;
7528  int nOrphan = -1;
7529  RecoverTable *pOrphan = 0;
7530
7531  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7532  int bRowids = 1;                /* 0 if --no-rowids */
7533  for(i=1; i<nArg; i++){
7534    char *z = azArg[i];
7535    int n;
7536    if( z[0]=='-' && z[1]=='-' ) z++;
7537    n = strlen30(z);
7538    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7539      bFreelist = 0;
7540    }else
7541    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7542      i++;
7543      zRecoveryDb = azArg[i];
7544    }else
7545    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7546      i++;
7547      zLostAndFound = azArg[i];
7548    }else
7549    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7550      bRowids = 0;
7551    }
7552    else{
7553      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7554      showHelp(pState->out, azArg[0]);
7555      return 1;
7556    }
7557  }
7558
7559  shellExecPrintf(pState->db, &rc,
7560    /* Attach an in-memory database named 'recovery'. Create an indexed
7561    ** cache of the sqlite_dbptr virtual table. */
7562    "PRAGMA writable_schema = on;"
7563    "ATTACH %Q AS recovery;"
7564    "DROP TABLE IF EXISTS recovery.dbptr;"
7565    "DROP TABLE IF EXISTS recovery.freelist;"
7566    "DROP TABLE IF EXISTS recovery.map;"
7567    "DROP TABLE IF EXISTS recovery.schema;"
7568    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7569  );
7570
7571  if( bFreelist ){
7572    shellExec(pState->db, &rc,
7573      "WITH trunk(pgno) AS ("
7574      "  SELECT shell_int32("
7575      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7576      "      WHERE x>0"
7577      "    UNION"
7578      "  SELECT shell_int32("
7579      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7580      "      FROM trunk WHERE x>0"
7581      "),"
7582      "freelist(data, n, freepgno) AS ("
7583      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7584      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7585      "    UNION ALL"
7586      "  SELECT data, n-1, shell_int32(data, 2+n) "
7587      "      FROM freelist WHERE n>=0"
7588      ")"
7589      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7590    );
7591  }
7592
7593  /* If this is an auto-vacuum database, add all pointer-map pages to
7594  ** the freelist table. Do this regardless of whether or not
7595  ** --freelist-corrupt was specified.  */
7596  shellExec(pState->db, &rc,
7597    "WITH ptrmap(pgno) AS ("
7598    "  SELECT 2 WHERE shell_int32("
7599    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7600    "  )"
7601    "    UNION ALL "
7602    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7603    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7604    ")"
7605    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7606  );
7607
7608  shellExec(pState->db, &rc,
7609    "CREATE TABLE recovery.dbptr("
7610    "      pgno, child, PRIMARY KEY(child, pgno)"
7611    ") WITHOUT ROWID;"
7612    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7613    "    SELECT * FROM sqlite_dbptr"
7614    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7615
7616    /* Delete any pointer to page 1. This ensures that page 1 is considered
7617    ** a root page, regardless of how corrupt the db is. */
7618    "DELETE FROM recovery.dbptr WHERE child = 1;"
7619
7620    /* Delete all pointers to any pages that have more than one pointer
7621    ** to them. Such pages will be treated as root pages when recovering
7622    ** data.  */
7623    "DELETE FROM recovery.dbptr WHERE child IN ("
7624    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7625    ");"
7626
7627    /* Create the "map" table that will (eventually) contain instructions
7628    ** for dealing with each page in the db that contains one or more
7629    ** records. */
7630    "CREATE TABLE recovery.map("
7631      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7632    ");"
7633
7634    /* Populate table [map]. If there are circular loops of pages in the
7635    ** database, the following adds all pages in such a loop to the map
7636    ** as individual root pages. This could be handled better.  */
7637    "WITH pages(i, maxlen) AS ("
7638    "  SELECT page_count, ("
7639    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7640    "  ) FROM pragma_page_count WHERE page_count>0"
7641    "    UNION ALL"
7642    "  SELECT i-1, ("
7643    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7644    "  ) FROM pages WHERE i>=2"
7645    ")"
7646    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7647    "  SELECT i, maxlen, NULL, ("
7648    "    WITH p(orig, pgno, parent) AS ("
7649    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7650    "        UNION "
7651    "      SELECT i, p.parent, "
7652    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7653    "    )"
7654    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7655    ") "
7656    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7657    "UPDATE recovery.map AS o SET intkey = ("
7658    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7659    ");"
7660
7661    /* Extract data from page 1 and any linked pages into table
7662    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7663    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7664    "INSERT INTO recovery.schema SELECT "
7665    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7666    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7667    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7668    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7669    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7670    "FROM sqlite_dbdata WHERE pgno IN ("
7671    "  SELECT pgno FROM recovery.map WHERE root=1"
7672    ")"
7673    "GROUP BY pgno, cell;"
7674    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7675  );
7676
7677  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7678  ** CREATE TABLE statements that extracted from the existing schema.  */
7679  if( rc==SQLITE_OK ){
7680    sqlite3_stmt *pStmt = 0;
7681    /* ".recover" might output content in an order which causes immediate
7682    ** foreign key constraints to be violated. So disable foreign-key
7683    ** constraint enforcement to prevent problems when running the output
7684    ** script. */
7685    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7686    raw_printf(pState->out, "BEGIN;\n");
7687    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7688    shellPrepare(pState->db, &rc,
7689        "SELECT sql FROM recovery.schema "
7690        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7691    );
7692    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7693      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7694      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7695          &zCreateTable[12]
7696      );
7697    }
7698    shellFinalize(&rc, pStmt);
7699  }
7700
7701  /* Figure out if an orphan table will be required. And if so, how many
7702  ** user columns it should contain */
7703  shellPrepare(pState->db, &rc,
7704      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7705      , &pLoop
7706  );
7707  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7708    nOrphan = sqlite3_column_int(pLoop, 0);
7709  }
7710  shellFinalize(&rc, pLoop);
7711  pLoop = 0;
7712
7713  shellPrepare(pState->db, &rc,
7714      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7715  );
7716
7717  shellPrepare(pState->db, &rc,
7718      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7719      "(case when (? AND field<0) then NULL else value end)"
7720      "), ', ')"
7721      ", min(field) "
7722      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7723      "GROUP BY cell", &pCells
7724  );
7725
7726  /* Loop through each root page. */
7727  shellPrepare(pState->db, &rc,
7728      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7729      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7730      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7731      ")", &pLoop
7732  );
7733  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7734    int iRoot = sqlite3_column_int(pLoop, 0);
7735    int bIntkey = sqlite3_column_int(pLoop, 1);
7736    int nCol = sqlite3_column_int(pLoop, 2);
7737    int bNoop = 0;
7738    RecoverTable *pTab;
7739
7740    assert( bIntkey==0 || bIntkey==1 );
7741    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7742    if( bNoop || rc ) continue;
7743    if( pTab==0 ){
7744      if( pOrphan==0 ){
7745        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7746      }
7747      pTab = pOrphan;
7748      if( pTab==0 ) break;
7749    }
7750
7751    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7752      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7753    }
7754    sqlite3_bind_int(pPages, 1, iRoot);
7755    if( bRowids==0 && pTab->iPk<0 ){
7756      sqlite3_bind_int(pCells, 1, 1);
7757    }else{
7758      sqlite3_bind_int(pCells, 1, 0);
7759    }
7760    sqlite3_bind_int(pCells, 3, pTab->iPk);
7761
7762    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7763      int iPgno = sqlite3_column_int(pPages, 0);
7764      sqlite3_bind_int(pCells, 2, iPgno);
7765      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7766        int nField = sqlite3_column_int(pCells, 0);
7767        int iMin = sqlite3_column_int(pCells, 2);
7768        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7769
7770        RecoverTable *pTab2 = pTab;
7771        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7772          if( pOrphan==0 ){
7773            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7774          }
7775          pTab2 = pOrphan;
7776          if( pTab2==0 ) break;
7777        }
7778
7779        nField = nField+1;
7780        if( pTab2==pOrphan ){
7781          raw_printf(pState->out,
7782              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7783              pTab2->zQuoted, iRoot, iPgno, nField,
7784              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7785          );
7786        }else{
7787          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7788              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7789          );
7790        }
7791      }
7792      shellReset(&rc, pCells);
7793    }
7794    shellReset(&rc, pPages);
7795    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7796  }
7797  shellFinalize(&rc, pLoop);
7798  shellFinalize(&rc, pPages);
7799  shellFinalize(&rc, pCells);
7800  recoverFreeTable(pOrphan);
7801
7802  /* The rest of the schema */
7803  if( rc==SQLITE_OK ){
7804    sqlite3_stmt *pStmt = 0;
7805    shellPrepare(pState->db, &rc,
7806        "SELECT sql, name FROM recovery.schema "
7807        "WHERE sql NOT LIKE 'create table%'", &pStmt
7808    );
7809    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7810      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7811      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7812        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7813        char *zPrint = shellMPrintf(&rc,
7814          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7815          zName, zName, zSql
7816        );
7817        raw_printf(pState->out, "%s;\n", zPrint);
7818        sqlite3_free(zPrint);
7819      }else{
7820        raw_printf(pState->out, "%s;\n", zSql);
7821      }
7822    }
7823    shellFinalize(&rc, pStmt);
7824  }
7825
7826  if( rc==SQLITE_OK ){
7827    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7828    raw_printf(pState->out, "COMMIT;\n");
7829  }
7830  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7831  return rc;
7832}
7833#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7834
7835
7836/*
7837 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7838 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7839 *   close db and set it to 0, and return the columns spec, to later
7840 *   be sqlite3_free()'ed by the caller.
7841 * The return is 0 when either:
7842 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7843 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7844 * The 3rd argument, pRenamed, references an out parameter. If the
7845 * pointer is non-zero, its referent will be set to a summary of renames
7846 * done if renaming was necessary, or set to 0 if none was done. The out
7847 * string (if any) must be sqlite3_free()'ed by the caller.
7848 */
7849#ifdef SHELL_DEBUG
7850#define rc_err_oom_die(rc) \
7851  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7852  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7853    fprintf(stderr,"E:%d\n",rc), assert(0)
7854#else
7855static void rc_err_oom_die(int rc){
7856  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7857  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7858}
7859#endif
7860
7861#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7862static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7863#else  /* Otherwise, memory is faster/better for the transient DB. */
7864static const char *zCOL_DB = ":memory:";
7865#endif
7866
7867/* Define character (as C string) to separate generated column ordinal
7868 * from protected part of incoming column names. This defaults to "_"
7869 * so that incoming column identifiers that did not need not be quoted
7870 * remain usable without being quoted. It must be one character.
7871 */
7872#ifndef SHELL_AUTOCOLUMN_SEP
7873# define AUTOCOLUMN_SEP "_"
7874#else
7875# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7876#endif
7877
7878static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7879  /* Queries and D{D,M}L used here */
7880  static const char * const zTabMake = "\
7881CREATE TABLE ColNames(\
7882 cpos INTEGER PRIMARY KEY,\
7883 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7884CREATE VIEW RepeatedNames AS \
7885SELECT DISTINCT t.name FROM ColNames t \
7886WHERE t.name COLLATE NOCASE IN (\
7887 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7888);\
7889";
7890  static const char * const zTabFill = "\
7891INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7892 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7893";
7894  static const char * const zHasDupes = "\
7895SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7896 <count(name) FROM ColNames\
7897";
7898#ifdef SHELL_COLUMN_RENAME_CLEAN
7899  static const char * const zDedoctor = "\
7900UPDATE ColNames SET chop=iif(\
7901  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7902  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7903 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7904 0\
7905)\
7906";
7907#endif
7908  static const char * const zSetReps = "\
7909UPDATE ColNames AS t SET reps=\
7910(SELECT count(*) FROM ColNames d \
7911 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7912 COLLATE NOCASE\
7913)\
7914";
7915#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7916  static const char * const zColDigits = "\
7917SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7918";
7919#endif
7920  static const char * const zRenameRank =
7921#ifdef SHELL_COLUMN_RENAME_CLEAN
7922    "UPDATE ColNames AS t SET suff="
7923    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7924#else /* ...RENAME_MINIMAL_ONE_PASS */
7925"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7926"  SELECT 0 AS nlz"
7927"  UNION"
7928"  SELECT nlz+1 AS nlz FROM Lzn"
7929"  WHERE EXISTS("
7930"   SELECT 1"
7931"   FROM ColNames t, ColNames o"
7932"   WHERE"
7933"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7934"     printf('%s"AUTOCOLUMN_SEP"%s',"
7935"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7936"     t.name"
7937"    )"
7938"    ="
7939"    iif(o.name IN (SELECT * FROM RepeatedNames),"
7940"     printf('%s"AUTOCOLUMN_SEP"%s',"
7941"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7942"     o.name"
7943"    )"
7944"    COLLATE NOCASE"
7945"    AND o.cpos<>t.cpos"
7946"   GROUP BY t.cpos"
7947"  )"
7948") UPDATE Colnames AS t SET"
7949" chop = 0," /* No chopping, never touch incoming names. */
7950" suff = iif(name IN (SELECT * FROM RepeatedNames),"
7951"  printf('"AUTOCOLUMN_SEP"%s', substring("
7952"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7953"  ''"
7954" )"
7955#endif
7956    ;
7957  static const char * const zCollectVar = "\
7958SELECT\
7959 '('||x'0a'\
7960 || group_concat(\
7961  cname||' TEXT',\
7962  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7963 ||')' AS ColsSpec \
7964FROM (\
7965 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7966 FROM ColNames ORDER BY cpos\
7967)";
7968  static const char * const zRenamesDone =
7969    "SELECT group_concat("
7970    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7971    " ','||x'0a')"
7972    "FROM ColNames WHERE suff<>'' OR chop!=0"
7973    ;
7974  int rc;
7975  sqlite3_stmt *pStmt = 0;
7976  assert(pDb!=0);
7977  if( zColNew ){
7978    /* Add initial or additional column. Init db if necessary. */
7979    if( *pDb==0 ){
7980      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7981#ifdef SHELL_COLFIX_DB
7982      if(*zCOL_DB!=':')
7983        sqlite3_exec(*pDb,"drop table if exists ColNames;"
7984                     "drop view if exists RepeatedNames;",0,0,0);
7985#endif
7986      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7987      rc_err_oom_die(rc);
7988    }
7989    assert(*pDb!=0);
7990    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7991    rc_err_oom_die(rc);
7992    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7993    rc_err_oom_die(rc);
7994    rc = sqlite3_step(pStmt);
7995    rc_err_oom_die(rc);
7996    sqlite3_finalize(pStmt);
7997    return 0;
7998  }else if( *pDb==0 ){
7999    return 0;
8000  }else{
8001    /* Formulate the columns spec, close the DB, zero *pDb. */
8002    char *zColsSpec = 0;
8003    int hasDupes = db_int(*pDb, zHasDupes);
8004#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
8005    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8006#else
8007# define nDigits 2
8008#endif
8009    if( hasDupes ){
8010#ifdef SHELL_COLUMN_RENAME_CLEAN
8011      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8012      rc_err_oom_die(rc);
8013#endif
8014      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8015      rc_err_oom_die(rc);
8016      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8017      rc_err_oom_die(rc);
8018      sqlite3_bind_int(pStmt, 1, nDigits);
8019      rc = sqlite3_step(pStmt);
8020      sqlite3_finalize(pStmt);
8021      assert(rc==SQLITE_DONE);
8022    }
8023    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8024    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8025    rc_err_oom_die(rc);
8026    rc = sqlite3_step(pStmt);
8027    if( rc==SQLITE_ROW ){
8028      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8029    }else{
8030      zColsSpec = 0;
8031    }
8032    if( pzRenamed!=0 ){
8033      if( !hasDupes ) *pzRenamed = 0;
8034      else{
8035        sqlite3_finalize(pStmt);
8036        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8037            && SQLITE_ROW==sqlite3_step(pStmt) ){
8038          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8039        }else
8040          *pzRenamed = 0;
8041      }
8042    }
8043    sqlite3_finalize(pStmt);
8044    sqlite3_close(*pDb);
8045    *pDb = 0;
8046    return zColsSpec;
8047  }
8048}
8049
8050/*
8051** If an input line begins with "." then invoke this routine to
8052** process that line.
8053**
8054** Return 1 on error, 2 to exit, and 0 otherwise.
8055*/
8056static int do_meta_command(char *zLine, ShellState *p){
8057  int h = 1;
8058  int nArg = 0;
8059  int n, c;
8060  int rc = 0;
8061  char *azArg[52];
8062
8063#ifndef SQLITE_OMIT_VIRTUALTABLE
8064  if( p->expert.pExpert ){
8065    expertFinish(p, 1, 0);
8066  }
8067#endif
8068
8069  /* Parse the input line into tokens.
8070  */
8071  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8072    while( IsSpace(zLine[h]) ){ h++; }
8073    if( zLine[h]==0 ) break;
8074    if( zLine[h]=='\'' || zLine[h]=='"' ){
8075      int delim = zLine[h++];
8076      azArg[nArg++] = &zLine[h];
8077      while( zLine[h] && zLine[h]!=delim ){
8078        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8079        h++;
8080      }
8081      if( zLine[h]==delim ){
8082        zLine[h++] = 0;
8083      }
8084      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8085    }else{
8086      azArg[nArg++] = &zLine[h];
8087      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8088      if( zLine[h] ) zLine[h++] = 0;
8089      resolve_backslashes(azArg[nArg-1]);
8090    }
8091  }
8092  azArg[nArg] = 0;
8093
8094  /* Process the input line.
8095  */
8096  if( nArg==0 ) return 0; /* no tokens, no error */
8097  n = strlen30(azArg[0]);
8098  c = azArg[0][0];
8099  clearTempFile(p);
8100
8101#ifndef SQLITE_OMIT_AUTHORIZATION
8102  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8103    if( nArg!=2 ){
8104      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8105      rc = 1;
8106      goto meta_command_exit;
8107    }
8108    open_db(p, 0);
8109    if( booleanValue(azArg[1]) ){
8110      sqlite3_set_authorizer(p->db, shellAuth, p);
8111    }else if( p->bSafeModePersist ){
8112      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8113    }else{
8114      sqlite3_set_authorizer(p->db, 0, 0);
8115    }
8116  }else
8117#endif
8118
8119#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8120  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8121    open_db(p, 0);
8122    failIfSafeMode(p, "cannot run .archive in safe mode");
8123    rc = arDotCommand(p, 0, azArg, nArg);
8124  }else
8125#endif
8126
8127  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8128   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8129  ){
8130    const char *zDestFile = 0;
8131    const char *zDb = 0;
8132    sqlite3 *pDest;
8133    sqlite3_backup *pBackup;
8134    int j;
8135    int bAsync = 0;
8136    const char *zVfs = 0;
8137    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8138    for(j=1; j<nArg; j++){
8139      const char *z = azArg[j];
8140      if( z[0]=='-' ){
8141        if( z[1]=='-' ) z++;
8142        if( strcmp(z, "-append")==0 ){
8143          zVfs = "apndvfs";
8144        }else
8145        if( strcmp(z, "-async")==0 ){
8146          bAsync = 1;
8147        }else
8148        {
8149          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8150          return 1;
8151        }
8152      }else if( zDestFile==0 ){
8153        zDestFile = azArg[j];
8154      }else if( zDb==0 ){
8155        zDb = zDestFile;
8156        zDestFile = azArg[j];
8157      }else{
8158        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8159        return 1;
8160      }
8161    }
8162    if( zDestFile==0 ){
8163      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8164      return 1;
8165    }
8166    if( zDb==0 ) zDb = "main";
8167    rc = sqlite3_open_v2(zDestFile, &pDest,
8168                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8169    if( rc!=SQLITE_OK ){
8170      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8171      close_db(pDest);
8172      return 1;
8173    }
8174    if( bAsync ){
8175      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8176                   0, 0, 0);
8177    }
8178    open_db(p, 0);
8179    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8180    if( pBackup==0 ){
8181      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8182      close_db(pDest);
8183      return 1;
8184    }
8185    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8186    sqlite3_backup_finish(pBackup);
8187    if( rc==SQLITE_DONE ){
8188      rc = 0;
8189    }else{
8190      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8191      rc = 1;
8192    }
8193    close_db(pDest);
8194  }else
8195
8196  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8197    if( nArg==2 ){
8198      bail_on_error = booleanValue(azArg[1]);
8199    }else{
8200      raw_printf(stderr, "Usage: .bail on|off\n");
8201      rc = 1;
8202    }
8203  }else
8204
8205  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8206    if( nArg==2 ){
8207      if( booleanValue(azArg[1]) ){
8208        setBinaryMode(p->out, 1);
8209      }else{
8210        setTextMode(p->out, 1);
8211      }
8212    }else{
8213      raw_printf(stderr, "Usage: .binary on|off\n");
8214      rc = 1;
8215    }
8216  }else
8217
8218  /* The undocumented ".breakpoint" command causes a call to the no-op
8219  ** routine named test_breakpoint().
8220  */
8221  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8222    test_breakpoint();
8223  }else
8224
8225  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8226    failIfSafeMode(p, "cannot run .cd in safe mode");
8227    if( nArg==2 ){
8228#if defined(_WIN32) || defined(WIN32)
8229      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8230      rc = !SetCurrentDirectoryW(z);
8231      sqlite3_free(z);
8232#else
8233      rc = chdir(azArg[1]);
8234#endif
8235      if( rc ){
8236        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8237        rc = 1;
8238      }
8239    }else{
8240      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8241      rc = 1;
8242    }
8243  }else
8244
8245  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8246    if( nArg==2 ){
8247      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8248    }else{
8249      raw_printf(stderr, "Usage: .changes on|off\n");
8250      rc = 1;
8251    }
8252  }else
8253
8254  /* Cancel output redirection, if it is currently set (by .testcase)
8255  ** Then read the content of the testcase-out.txt file and compare against
8256  ** azArg[1].  If there are differences, report an error and exit.
8257  */
8258  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8259    char *zRes = 0;
8260    output_reset(p);
8261    if( nArg!=2 ){
8262      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8263      rc = 2;
8264    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8265      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8266      rc = 2;
8267    }else if( testcase_glob(azArg[1],zRes)==0 ){
8268      utf8_printf(stderr,
8269                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8270                 p->zTestcase, azArg[1], zRes);
8271      rc = 1;
8272    }else{
8273      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8274      p->nCheck++;
8275    }
8276    sqlite3_free(zRes);
8277  }else
8278
8279  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8280    failIfSafeMode(p, "cannot run .clone in safe mode");
8281    if( nArg==2 ){
8282      tryToClone(p, azArg[1]);
8283    }else{
8284      raw_printf(stderr, "Usage: .clone FILENAME\n");
8285      rc = 1;
8286    }
8287  }else
8288
8289  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8290    if( nArg==1 ){
8291      /* List available connections */
8292      int i;
8293      for(i=0; i<ArraySize(p->aAuxDb); i++){
8294        const char *zFile = p->aAuxDb[i].zDbFilename;
8295        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8296          zFile = "(not open)";
8297        }else if( zFile==0 ){
8298          zFile = "(memory)";
8299        }else if( zFile[0]==0 ){
8300          zFile = "(temporary-file)";
8301        }
8302        if( p->pAuxDb == &p->aAuxDb[i] ){
8303          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8304        }else if( p->aAuxDb[i].db!=0 ){
8305          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8306        }
8307      }
8308    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8309      int i = azArg[1][0] - '0';
8310      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8311        p->pAuxDb->db = p->db;
8312        p->pAuxDb = &p->aAuxDb[i];
8313        globalDb = p->db = p->pAuxDb->db;
8314        p->pAuxDb->db = 0;
8315      }
8316    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8317           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8318      int i = azArg[2][0] - '0';
8319      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8320        /* No-op */
8321      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8322        raw_printf(stderr, "cannot close the active database connection\n");
8323        rc = 1;
8324      }else if( p->aAuxDb[i].db ){
8325        session_close_all(p, i);
8326        close_db(p->aAuxDb[i].db);
8327        p->aAuxDb[i].db = 0;
8328      }
8329    }else{
8330      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8331      rc = 1;
8332    }
8333  }else
8334
8335  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8336    char **azName = 0;
8337    int nName = 0;
8338    sqlite3_stmt *pStmt;
8339    int i;
8340    open_db(p, 0);
8341    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8342    if( rc ){
8343      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8344      rc = 1;
8345    }else{
8346      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8347        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8348        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8349        if( zSchema==0 || zFile==0 ) continue;
8350        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8351        shell_check_oom(azName);
8352        azName[nName*2] = strdup(zSchema);
8353        azName[nName*2+1] = strdup(zFile);
8354        nName++;
8355      }
8356    }
8357    sqlite3_finalize(pStmt);
8358    for(i=0; i<nName; i++){
8359      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8360      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8361      const char *z = azName[i*2+1];
8362      utf8_printf(p->out, "%s: %s %s%s\n",
8363         azName[i*2],
8364         z && z[0] ? z : "\"\"",
8365         bRdonly ? "r/o" : "r/w",
8366         eTxn==SQLITE_TXN_NONE ? "" :
8367            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8368      free(azName[i*2]);
8369      free(azName[i*2+1]);
8370    }
8371    sqlite3_free(azName);
8372  }else
8373
8374  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8375    static const struct DbConfigChoices {
8376      const char *zName;
8377      int op;
8378    } aDbConfig[] = {
8379        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8380        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8381        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8382        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8383        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8384        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8385        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8386        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8387        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8388        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8389        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8390        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8391        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8392        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8393        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8394        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8395    };
8396    int ii, v;
8397    open_db(p, 0);
8398    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8399      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8400      if( nArg>=3 ){
8401        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8402      }
8403      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8404      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8405      if( nArg>1 ) break;
8406    }
8407    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8408      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8409      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8410    }
8411  }else
8412
8413  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8414    rc = shell_dbinfo_command(p, nArg, azArg);
8415  }else
8416
8417#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8418  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8419    open_db(p, 0);
8420    rc = recoverDatabaseCmd(p, nArg, azArg);
8421  }else
8422#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8423
8424  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8425    char *zLike = 0;
8426    char *zSql;
8427    int i;
8428    int savedShowHeader = p->showHeader;
8429    int savedShellFlags = p->shellFlgs;
8430    ShellClearFlag(p,
8431       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8432       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8433    for(i=1; i<nArg; i++){
8434      if( azArg[i][0]=='-' ){
8435        const char *z = azArg[i]+1;
8436        if( z[0]=='-' ) z++;
8437        if( strcmp(z,"preserve-rowids")==0 ){
8438#ifdef SQLITE_OMIT_VIRTUALTABLE
8439          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8440                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8441          rc = 1;
8442          sqlite3_free(zLike);
8443          goto meta_command_exit;
8444#else
8445          ShellSetFlag(p, SHFLG_PreserveRowid);
8446#endif
8447        }else
8448        if( strcmp(z,"newlines")==0 ){
8449          ShellSetFlag(p, SHFLG_Newlines);
8450        }else
8451        if( strcmp(z,"data-only")==0 ){
8452          ShellSetFlag(p, SHFLG_DumpDataOnly);
8453        }else
8454        if( strcmp(z,"nosys")==0 ){
8455          ShellSetFlag(p, SHFLG_DumpNoSys);
8456        }else
8457        {
8458          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8459          rc = 1;
8460          sqlite3_free(zLike);
8461          goto meta_command_exit;
8462        }
8463      }else{
8464        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8465        ** only dump data for tables for which either the table name matches
8466        ** the LIKE pattern, or the table appears to be a shadow table of
8467        ** a virtual table for which the name matches the LIKE pattern.
8468        */
8469        char *zExpr = sqlite3_mprintf(
8470            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8471            "  SELECT 1 FROM sqlite_schema WHERE "
8472            "    name LIKE %Q ESCAPE '\\' AND"
8473            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8474            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8475            ")", azArg[i], azArg[i]
8476        );
8477
8478        if( zLike ){
8479          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8480        }else{
8481          zLike = zExpr;
8482        }
8483      }
8484    }
8485
8486    open_db(p, 0);
8487
8488    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8489      /* When playing back a "dump", the content might appear in an order
8490      ** which causes immediate foreign key constraints to be violated.
8491      ** So disable foreign-key constraint enforcement to prevent problems. */
8492      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8493      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8494    }
8495    p->writableSchema = 0;
8496    p->showHeader = 0;
8497    /* Set writable_schema=ON since doing so forces SQLite to initialize
8498    ** as much of the schema as it can even if the sqlite_schema table is
8499    ** corrupt. */
8500    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8501    p->nErr = 0;
8502    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8503    zSql = sqlite3_mprintf(
8504      "SELECT name, type, sql FROM sqlite_schema AS o "
8505      "WHERE (%s) AND type=='table'"
8506      "  AND sql NOT NULL"
8507      " ORDER BY tbl_name='sqlite_sequence', rowid",
8508      zLike
8509    );
8510    run_schema_dump_query(p,zSql);
8511    sqlite3_free(zSql);
8512    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8513      zSql = sqlite3_mprintf(
8514        "SELECT sql FROM sqlite_schema AS o "
8515        "WHERE (%s) AND sql NOT NULL"
8516        "  AND type IN ('index','trigger','view')",
8517        zLike
8518      );
8519      run_table_dump_query(p, zSql);
8520      sqlite3_free(zSql);
8521    }
8522    sqlite3_free(zLike);
8523    if( p->writableSchema ){
8524      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8525      p->writableSchema = 0;
8526    }
8527    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8528    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8529    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8530      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8531    }
8532    p->showHeader = savedShowHeader;
8533    p->shellFlgs = savedShellFlags;
8534  }else
8535
8536  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8537    if( nArg==2 ){
8538      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8539    }else{
8540      raw_printf(stderr, "Usage: .echo on|off\n");
8541      rc = 1;
8542    }
8543  }else
8544
8545  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8546    if( nArg==2 ){
8547      p->autoEQPtest = 0;
8548      if( p->autoEQPtrace ){
8549        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8550        p->autoEQPtrace = 0;
8551      }
8552      if( strcmp(azArg[1],"full")==0 ){
8553        p->autoEQP = AUTOEQP_full;
8554      }else if( strcmp(azArg[1],"trigger")==0 ){
8555        p->autoEQP = AUTOEQP_trigger;
8556#ifdef SQLITE_DEBUG
8557      }else if( strcmp(azArg[1],"test")==0 ){
8558        p->autoEQP = AUTOEQP_on;
8559        p->autoEQPtest = 1;
8560      }else if( strcmp(azArg[1],"trace")==0 ){
8561        p->autoEQP = AUTOEQP_full;
8562        p->autoEQPtrace = 1;
8563        open_db(p, 0);
8564        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8565        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8566#endif
8567      }else{
8568        p->autoEQP = (u8)booleanValue(azArg[1]);
8569      }
8570    }else{
8571      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8572      rc = 1;
8573    }
8574  }else
8575
8576  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8577    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8578    rc = 2;
8579  }else
8580
8581  /* The ".explain" command is automatic now.  It is largely pointless.  It
8582  ** retained purely for backwards compatibility */
8583  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8584    int val = 1;
8585    if( nArg>=2 ){
8586      if( strcmp(azArg[1],"auto")==0 ){
8587        val = 99;
8588      }else{
8589        val =  booleanValue(azArg[1]);
8590      }
8591    }
8592    if( val==1 && p->mode!=MODE_Explain ){
8593      p->normalMode = p->mode;
8594      p->mode = MODE_Explain;
8595      p->autoExplain = 0;
8596    }else if( val==0 ){
8597      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8598      p->autoExplain = 0;
8599    }else if( val==99 ){
8600      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8601      p->autoExplain = 1;
8602    }
8603  }else
8604
8605#ifndef SQLITE_OMIT_VIRTUALTABLE
8606  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8607    if( p->bSafeMode ){
8608      raw_printf(stderr,
8609        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8610        azArg[0]);
8611      rc = 1;
8612    }else{
8613      open_db(p, 0);
8614      expertDotCommand(p, azArg, nArg);
8615    }
8616  }else
8617#endif
8618
8619  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8620    static const struct {
8621       const char *zCtrlName;   /* Name of a test-control option */
8622       int ctrlCode;            /* Integer code for that option */
8623       const char *zUsage;      /* Usage notes */
8624    } aCtrl[] = {
8625      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8626      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8627      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8628      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8629      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8630   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8631      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8632      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8633      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8634      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8635   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8636    };
8637    int filectrl = -1;
8638    int iCtrl = -1;
8639    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8640    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8641    int n2, i;
8642    const char *zCmd = 0;
8643    const char *zSchema = 0;
8644
8645    open_db(p, 0);
8646    zCmd = nArg>=2 ? azArg[1] : "help";
8647
8648    if( zCmd[0]=='-'
8649     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8650     && nArg>=4
8651    ){
8652      zSchema = azArg[2];
8653      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8654      nArg -= 2;
8655      zCmd = azArg[1];
8656    }
8657
8658    /* The argument can optionally begin with "-" or "--" */
8659    if( zCmd[0]=='-' && zCmd[1] ){
8660      zCmd++;
8661      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8662    }
8663
8664    /* --help lists all file-controls */
8665    if( strcmp(zCmd,"help")==0 ){
8666      utf8_printf(p->out, "Available file-controls:\n");
8667      for(i=0; i<ArraySize(aCtrl); i++){
8668        utf8_printf(p->out, "  .filectrl %s %s\n",
8669                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8670      }
8671      rc = 1;
8672      goto meta_command_exit;
8673    }
8674
8675    /* convert filectrl text option to value. allow any unique prefix
8676    ** of the option name, or a numerical value. */
8677    n2 = strlen30(zCmd);
8678    for(i=0; i<ArraySize(aCtrl); i++){
8679      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8680        if( filectrl<0 ){
8681          filectrl = aCtrl[i].ctrlCode;
8682          iCtrl = i;
8683        }else{
8684          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8685                              "Use \".filectrl --help\" for help\n", zCmd);
8686          rc = 1;
8687          goto meta_command_exit;
8688        }
8689      }
8690    }
8691    if( filectrl<0 ){
8692      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8693                         "Use \".filectrl --help\" for help\n", zCmd);
8694    }else{
8695      switch(filectrl){
8696        case SQLITE_FCNTL_SIZE_LIMIT: {
8697          if( nArg!=2 && nArg!=3 ) break;
8698          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8699          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8700          isOk = 1;
8701          break;
8702        }
8703        case SQLITE_FCNTL_LOCK_TIMEOUT:
8704        case SQLITE_FCNTL_CHUNK_SIZE: {
8705          int x;
8706          if( nArg!=3 ) break;
8707          x = (int)integerValue(azArg[2]);
8708          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8709          isOk = 2;
8710          break;
8711        }
8712        case SQLITE_FCNTL_PERSIST_WAL:
8713        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8714          int x;
8715          if( nArg!=2 && nArg!=3 ) break;
8716          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8717          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8718          iRes = x;
8719          isOk = 1;
8720          break;
8721        }
8722        case SQLITE_FCNTL_DATA_VERSION:
8723        case SQLITE_FCNTL_HAS_MOVED: {
8724          int x;
8725          if( nArg!=2 ) break;
8726          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8727          iRes = x;
8728          isOk = 1;
8729          break;
8730        }
8731        case SQLITE_FCNTL_TEMPFILENAME: {
8732          char *z = 0;
8733          if( nArg!=2 ) break;
8734          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8735          if( z ){
8736            utf8_printf(p->out, "%s\n", z);
8737            sqlite3_free(z);
8738          }
8739          isOk = 2;
8740          break;
8741        }
8742        case SQLITE_FCNTL_RESERVE_BYTES: {
8743          int x;
8744          if( nArg>=3 ){
8745            x = atoi(azArg[2]);
8746            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8747          }
8748          x = -1;
8749          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8750          utf8_printf(p->out,"%d\n", x);
8751          isOk = 2;
8752          break;
8753        }
8754      }
8755    }
8756    if( isOk==0 && iCtrl>=0 ){
8757      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8758      rc = 1;
8759    }else if( isOk==1 ){
8760      char zBuf[100];
8761      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8762      raw_printf(p->out, "%s\n", zBuf);
8763    }
8764  }else
8765
8766  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8767    ShellState data;
8768    int doStats = 0;
8769    memcpy(&data, p, sizeof(data));
8770    data.showHeader = 0;
8771    data.cMode = data.mode = MODE_Semi;
8772    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8773      data.cMode = data.mode = MODE_Pretty;
8774      nArg = 1;
8775    }
8776    if( nArg!=1 ){
8777      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8778      rc = 1;
8779      goto meta_command_exit;
8780    }
8781    open_db(p, 0);
8782    rc = sqlite3_exec(p->db,
8783       "SELECT sql FROM"
8784       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8785       "     FROM sqlite_schema UNION ALL"
8786       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8787       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8788       "ORDER BY x",
8789       callback, &data, 0
8790    );
8791    if( rc==SQLITE_OK ){
8792      sqlite3_stmt *pStmt;
8793      rc = sqlite3_prepare_v2(p->db,
8794               "SELECT rowid FROM sqlite_schema"
8795               " WHERE name GLOB 'sqlite_stat[134]'",
8796               -1, &pStmt, 0);
8797      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8798      sqlite3_finalize(pStmt);
8799    }
8800    if( doStats==0 ){
8801      raw_printf(p->out, "/* No STAT tables available */\n");
8802    }else{
8803      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8804      data.cMode = data.mode = MODE_Insert;
8805      data.zDestTable = "sqlite_stat1";
8806      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8807      data.zDestTable = "sqlite_stat4";
8808      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8809      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8810    }
8811  }else
8812
8813  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8814    if( nArg==2 ){
8815      p->showHeader = booleanValue(azArg[1]);
8816      p->shellFlgs |= SHFLG_HeaderSet;
8817    }else{
8818      raw_printf(stderr, "Usage: .headers on|off\n");
8819      rc = 1;
8820    }
8821  }else
8822
8823  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8824    if( nArg>=2 ){
8825      n = showHelp(p->out, azArg[1]);
8826      if( n==0 ){
8827        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8828      }
8829    }else{
8830      showHelp(p->out, 0);
8831    }
8832  }else
8833
8834  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8835    char *zTable = 0;           /* Insert data into this table */
8836    char *zSchema = 0;          /* within this schema (may default to "main") */
8837    char *zFile = 0;            /* Name of file to extra content from */
8838    sqlite3_stmt *pStmt = NULL; /* A statement */
8839    int nCol;                   /* Number of columns in the table */
8840    int nByte;                  /* Number of bytes in an SQL string */
8841    int i, j;                   /* Loop counters */
8842    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8843    int nSep;                   /* Number of bytes in p->colSeparator[] */
8844    char *zSql;                 /* An SQL statement */
8845    char *zFullTabName;         /* Table name with schema if applicable */
8846    ImportCtx sCtx;             /* Reader context */
8847    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8848    int eVerbose = 0;           /* Larger for more console output */
8849    int nSkip = 0;              /* Initial lines to skip */
8850    int useOutputMode = 1;      /* Use output mode to determine separators */
8851    char *zCreate = 0;          /* CREATE TABLE statement text */
8852
8853    failIfSafeMode(p, "cannot run .import in safe mode");
8854    memset(&sCtx, 0, sizeof(sCtx));
8855    sCtx.z = sqlite3_malloc64(120);
8856    if( sCtx.z==0 ){
8857      import_cleanup(&sCtx);
8858      shell_out_of_memory();
8859    }
8860    if( p->mode==MODE_Ascii ){
8861      xRead = ascii_read_one_field;
8862    }else{
8863      xRead = csv_read_one_field;
8864    }
8865    for(i=1; i<nArg; i++){
8866      char *z = azArg[i];
8867      if( z[0]=='-' && z[1]=='-' ) z++;
8868      if( z[0]!='-' ){
8869        if( zFile==0 ){
8870          zFile = z;
8871        }else if( zTable==0 ){
8872          zTable = z;
8873        }else{
8874          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8875          showHelp(p->out, "import");
8876          rc = 1;
8877          goto meta_command_exit;
8878        }
8879      }else if( strcmp(z,"-v")==0 ){
8880        eVerbose++;
8881      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8882        zSchema = azArg[++i];
8883      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8884        nSkip = integerValue(azArg[++i]);
8885      }else if( strcmp(z,"-ascii")==0 ){
8886        sCtx.cColSep = SEP_Unit[0];
8887        sCtx.cRowSep = SEP_Record[0];
8888        xRead = ascii_read_one_field;
8889        useOutputMode = 0;
8890      }else if( strcmp(z,"-csv")==0 ){
8891        sCtx.cColSep = ',';
8892        sCtx.cRowSep = '\n';
8893        xRead = csv_read_one_field;
8894        useOutputMode = 0;
8895      }else{
8896        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8897        showHelp(p->out, "import");
8898        rc = 1;
8899        goto meta_command_exit;
8900      }
8901    }
8902    if( zTable==0 ){
8903      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8904                  zFile==0 ? "FILE" : "TABLE");
8905      showHelp(p->out, "import");
8906      rc = 1;
8907      goto meta_command_exit;
8908    }
8909    seenInterrupt = 0;
8910    open_db(p, 0);
8911    if( useOutputMode ){
8912      /* If neither the --csv or --ascii options are specified, then set
8913      ** the column and row separator characters from the output mode. */
8914      nSep = strlen30(p->colSeparator);
8915      if( nSep==0 ){
8916        raw_printf(stderr,
8917                   "Error: non-null column separator required for import\n");
8918        rc = 1;
8919        goto meta_command_exit;
8920      }
8921      if( nSep>1 ){
8922        raw_printf(stderr,
8923              "Error: multi-character column separators not allowed"
8924              " for import\n");
8925        rc = 1;
8926        goto meta_command_exit;
8927      }
8928      nSep = strlen30(p->rowSeparator);
8929      if( nSep==0 ){
8930        raw_printf(stderr,
8931            "Error: non-null row separator required for import\n");
8932        rc = 1;
8933        goto meta_command_exit;
8934      }
8935      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8936        /* When importing CSV (only), if the row separator is set to the
8937        ** default output row separator, change it to the default input
8938        ** row separator.  This avoids having to maintain different input
8939        ** and output row separators. */
8940        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8941        nSep = strlen30(p->rowSeparator);
8942      }
8943      if( nSep>1 ){
8944        raw_printf(stderr, "Error: multi-character row separators not allowed"
8945                           " for import\n");
8946        rc = 1;
8947        goto meta_command_exit;
8948      }
8949      sCtx.cColSep = p->colSeparator[0];
8950      sCtx.cRowSep = p->rowSeparator[0];
8951    }
8952    sCtx.zFile = zFile;
8953    sCtx.nLine = 1;
8954    if( sCtx.zFile[0]=='|' ){
8955#ifdef SQLITE_OMIT_POPEN
8956      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8957      rc = 1;
8958      goto meta_command_exit;
8959#else
8960      sCtx.in = popen(sCtx.zFile+1, "r");
8961      sCtx.zFile = "<pipe>";
8962      sCtx.xCloser = pclose;
8963#endif
8964    }else{
8965      sCtx.in = fopen(sCtx.zFile, "rb");
8966      sCtx.xCloser = fclose;
8967    }
8968    if( sCtx.in==0 ){
8969      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8970      rc = 1;
8971      import_cleanup(&sCtx);
8972      goto meta_command_exit;
8973    }
8974    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8975      char zSep[2];
8976      zSep[1] = 0;
8977      zSep[0] = sCtx.cColSep;
8978      utf8_printf(p->out, "Column separator ");
8979      output_c_string(p->out, zSep);
8980      utf8_printf(p->out, ", row separator ");
8981      zSep[0] = sCtx.cRowSep;
8982      output_c_string(p->out, zSep);
8983      utf8_printf(p->out, "\n");
8984    }
8985    /* Below, resources must be freed before exit. */
8986    while( (nSkip--)>0 ){
8987      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8988    }
8989    if( zSchema!=0 ){
8990      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8991    }else{
8992      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8993    }
8994    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8995    if( zSql==0 || zFullTabName==0 ){
8996      import_cleanup(&sCtx);
8997      shell_out_of_memory();
8998    }
8999    nByte = strlen30(zSql);
9000    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9001    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9002    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9003      sqlite3 *dbCols = 0;
9004      char *zRenames = 0;
9005      char *zColDefs;
9006      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9007      while( xRead(&sCtx) ){
9008        zAutoColumn(sCtx.z, &dbCols, 0);
9009        if( sCtx.cTerm!=sCtx.cColSep ) break;
9010      }
9011      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9012      if( zRenames!=0 ){
9013        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9014                    "Columns renamed during .import %s due to duplicates:\n"
9015                    "%s\n", sCtx.zFile, zRenames);
9016        sqlite3_free(zRenames);
9017      }
9018      assert(dbCols==0);
9019      if( zColDefs==0 ){
9020        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9021      import_fail:
9022        sqlite3_free(zCreate);
9023        sqlite3_free(zSql);
9024        sqlite3_free(zFullTabName);
9025        import_cleanup(&sCtx);
9026        rc = 1;
9027        goto meta_command_exit;
9028      }
9029      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9030      if( eVerbose>=1 ){
9031        utf8_printf(p->out, "%s\n", zCreate);
9032      }
9033      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9034      if( rc ){
9035        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9036        goto import_fail;
9037      }
9038      sqlite3_free(zCreate);
9039      zCreate = 0;
9040      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9041    }
9042    if( rc ){
9043      if (pStmt) sqlite3_finalize(pStmt);
9044      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9045      goto import_fail;
9046    }
9047    sqlite3_free(zSql);
9048    nCol = sqlite3_column_count(pStmt);
9049    sqlite3_finalize(pStmt);
9050    pStmt = 0;
9051    if( nCol==0 ) return 0; /* no columns, no error */
9052    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9053    if( zSql==0 ){
9054      import_cleanup(&sCtx);
9055      shell_out_of_memory();
9056    }
9057    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9058    j = strlen30(zSql);
9059    for(i=1; i<nCol; i++){
9060      zSql[j++] = ',';
9061      zSql[j++] = '?';
9062    }
9063    zSql[j++] = ')';
9064    zSql[j] = 0;
9065    if( eVerbose>=2 ){
9066      utf8_printf(p->out, "Insert using: %s\n", zSql);
9067    }
9068    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9069    if( rc ){
9070      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9071      if (pStmt) sqlite3_finalize(pStmt);
9072      goto import_fail;
9073    }
9074    sqlite3_free(zSql);
9075    sqlite3_free(zFullTabName);
9076    needCommit = sqlite3_get_autocommit(p->db);
9077    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9078    do{
9079      int startLine = sCtx.nLine;
9080      for(i=0; i<nCol; i++){
9081        char *z = xRead(&sCtx);
9082        /*
9083        ** Did we reach end-of-file before finding any columns?
9084        ** If so, stop instead of NULL filling the remaining columns.
9085        */
9086        if( z==0 && i==0 ) break;
9087        /*
9088        ** Did we reach end-of-file OR end-of-line before finding any
9089        ** columns in ASCII mode?  If so, stop instead of NULL filling
9090        ** the remaining columns.
9091        */
9092        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9093        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9094        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9095          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9096                          "filling the rest with NULL\n",
9097                          sCtx.zFile, startLine, nCol, i+1);
9098          i += 2;
9099          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9100        }
9101      }
9102      if( sCtx.cTerm==sCtx.cColSep ){
9103        do{
9104          xRead(&sCtx);
9105          i++;
9106        }while( sCtx.cTerm==sCtx.cColSep );
9107        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9108                        "extras ignored\n",
9109                        sCtx.zFile, startLine, nCol, i);
9110      }
9111      if( i>=nCol ){
9112        sqlite3_step(pStmt);
9113        rc = sqlite3_reset(pStmt);
9114        if( rc!=SQLITE_OK ){
9115          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9116                      startLine, sqlite3_errmsg(p->db));
9117          sCtx.nErr++;
9118        }else{
9119          sCtx.nRow++;
9120        }
9121      }
9122    }while( sCtx.cTerm!=EOF );
9123
9124    import_cleanup(&sCtx);
9125    sqlite3_finalize(pStmt);
9126    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9127    if( eVerbose>0 ){
9128      utf8_printf(p->out,
9129          "Added %d rows with %d errors using %d lines of input\n",
9130          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9131    }
9132  }else
9133
9134#ifndef SQLITE_UNTESTABLE
9135  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9136    char *zSql;
9137    char *zCollist = 0;
9138    sqlite3_stmt *pStmt;
9139    int tnum = 0;
9140    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9141    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9142    int i;
9143    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9144      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9145                          "       .imposter off\n");
9146      /* Also allowed, but not documented:
9147      **
9148      **    .imposter TABLE IMPOSTER
9149      **
9150      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9151      ** imposter is another WITHOUT ROWID table with the columns in
9152      ** storage order. */
9153      rc = 1;
9154      goto meta_command_exit;
9155    }
9156    open_db(p, 0);
9157    if( nArg==2 ){
9158      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9159      goto meta_command_exit;
9160    }
9161    zSql = sqlite3_mprintf(
9162      "SELECT rootpage, 0 FROM sqlite_schema"
9163      " WHERE name='%q' AND type='index'"
9164      "UNION ALL "
9165      "SELECT rootpage, 1 FROM sqlite_schema"
9166      " WHERE name='%q' AND type='table'"
9167      "   AND sql LIKE '%%without%%rowid%%'",
9168      azArg[1], azArg[1]
9169    );
9170    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9171    sqlite3_free(zSql);
9172    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9173      tnum = sqlite3_column_int(pStmt, 0);
9174      isWO = sqlite3_column_int(pStmt, 1);
9175    }
9176    sqlite3_finalize(pStmt);
9177    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9178    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9179    sqlite3_free(zSql);
9180    i = 0;
9181    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9182      char zLabel[20];
9183      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9184      i++;
9185      if( zCol==0 ){
9186        if( sqlite3_column_int(pStmt,1)==-1 ){
9187          zCol = "_ROWID_";
9188        }else{
9189          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9190          zCol = zLabel;
9191        }
9192      }
9193      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9194        lenPK = (int)strlen(zCollist);
9195      }
9196      if( zCollist==0 ){
9197        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9198      }else{
9199        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9200      }
9201    }
9202    sqlite3_finalize(pStmt);
9203    if( i==0 || tnum==0 ){
9204      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9205      rc = 1;
9206      sqlite3_free(zCollist);
9207      goto meta_command_exit;
9208    }
9209    if( lenPK==0 ) lenPK = 100000;
9210    zSql = sqlite3_mprintf(
9211          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9212          azArg[2], zCollist, lenPK, zCollist);
9213    sqlite3_free(zCollist);
9214    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9215    if( rc==SQLITE_OK ){
9216      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9217      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9218      if( rc ){
9219        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9220      }else{
9221        utf8_printf(stdout, "%s;\n", zSql);
9222        raw_printf(stdout,
9223          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9224          azArg[1], isWO ? "table" : "index"
9225        );
9226      }
9227    }else{
9228      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9229      rc = 1;
9230    }
9231    sqlite3_free(zSql);
9232  }else
9233#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9234
9235#ifdef SQLITE_ENABLE_IOTRACE
9236  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9237    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9238    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9239    iotrace = 0;
9240    if( nArg<2 ){
9241      sqlite3IoTrace = 0;
9242    }else if( strcmp(azArg[1], "-")==0 ){
9243      sqlite3IoTrace = iotracePrintf;
9244      iotrace = stdout;
9245    }else{
9246      iotrace = fopen(azArg[1], "w");
9247      if( iotrace==0 ){
9248        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9249        sqlite3IoTrace = 0;
9250        rc = 1;
9251      }else{
9252        sqlite3IoTrace = iotracePrintf;
9253      }
9254    }
9255  }else
9256#endif
9257
9258  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9259    static const struct {
9260       const char *zLimitName;   /* Name of a limit */
9261       int limitCode;            /* Integer code for that limit */
9262    } aLimit[] = {
9263      { "length",                SQLITE_LIMIT_LENGTH                    },
9264      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9265      { "column",                SQLITE_LIMIT_COLUMN                    },
9266      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9267      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9268      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9269      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9270      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9271      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9272      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9273      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9274      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9275    };
9276    int i, n2;
9277    open_db(p, 0);
9278    if( nArg==1 ){
9279      for(i=0; i<ArraySize(aLimit); i++){
9280        printf("%20s %d\n", aLimit[i].zLimitName,
9281               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9282      }
9283    }else if( nArg>3 ){
9284      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9285      rc = 1;
9286      goto meta_command_exit;
9287    }else{
9288      int iLimit = -1;
9289      n2 = strlen30(azArg[1]);
9290      for(i=0; i<ArraySize(aLimit); i++){
9291        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9292          if( iLimit<0 ){
9293            iLimit = i;
9294          }else{
9295            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9296            rc = 1;
9297            goto meta_command_exit;
9298          }
9299        }
9300      }
9301      if( iLimit<0 ){
9302        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9303                        "enter \".limits\" with no arguments for a list.\n",
9304                         azArg[1]);
9305        rc = 1;
9306        goto meta_command_exit;
9307      }
9308      if( nArg==3 ){
9309        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9310                      (int)integerValue(azArg[2]));
9311      }
9312      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9313             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9314    }
9315  }else
9316
9317  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9318    open_db(p, 0);
9319    lintDotCommand(p, azArg, nArg);
9320  }else
9321
9322#ifndef SQLITE_OMIT_LOAD_EXTENSION
9323  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9324    const char *zFile, *zProc;
9325    char *zErrMsg = 0;
9326    failIfSafeMode(p, "cannot run .load in safe mode");
9327    if( nArg<2 ){
9328      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9329      rc = 1;
9330      goto meta_command_exit;
9331    }
9332    zFile = azArg[1];
9333    zProc = nArg>=3 ? azArg[2] : 0;
9334    open_db(p, 0);
9335    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9336    if( rc!=SQLITE_OK ){
9337      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9338      sqlite3_free(zErrMsg);
9339      rc = 1;
9340    }
9341  }else
9342#endif
9343
9344  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9345    failIfSafeMode(p, "cannot run .log in safe mode");
9346    if( nArg!=2 ){
9347      raw_printf(stderr, "Usage: .log FILENAME\n");
9348      rc = 1;
9349    }else{
9350      const char *zFile = azArg[1];
9351      output_file_close(p->pLog);
9352      p->pLog = output_file_open(zFile, 0);
9353    }
9354  }else
9355
9356  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9357    const char *zMode = 0;
9358    const char *zTabname = 0;
9359    int i, n2;
9360    ColModeOpts cmOpts = ColModeOpts_default;
9361    for(i=1; i<nArg; i++){
9362      const char *z = azArg[i];
9363      if( optionMatch(z,"wrap") && i+1<nArg ){
9364        cmOpts.iWrap = integerValue(azArg[++i]);
9365      }else if( optionMatch(z,"ww") ){
9366        cmOpts.bWordWrap = 1;
9367      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9368        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9369      }else if( optionMatch(z,"quote") ){
9370        cmOpts.bQuote = 1;
9371      }else if( optionMatch(z,"noquote") ){
9372        cmOpts.bQuote = 0;
9373      }else if( zMode==0 ){
9374        zMode = z;
9375        /* Apply defaults for qbox pseudo-mods. If that
9376         * overwrites already-set values, user was informed of this.
9377         */
9378        if( strcmp(z, "qbox")==0 ){
9379          ColModeOpts cmo = ColModeOpts_default_qbox;
9380          zMode = "box";
9381          cmOpts = cmo;
9382        }
9383      }else if( zTabname==0 ){
9384        zTabname = z;
9385      }else if( z[0]=='-' ){
9386        utf8_printf(stderr, "unknown option: %s\n", z);
9387        utf8_printf(stderr, "options:\n"
9388                            "  --noquote\n"
9389                            "  --quote\n"
9390                            "  --wordwrap on/off\n"
9391                            "  --wrap N\n"
9392                            "  --ww\n");
9393        rc = 1;
9394        goto meta_command_exit;
9395      }else{
9396        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9397        rc = 1;
9398        goto meta_command_exit;
9399      }
9400    }
9401    if( zMode==0 ){
9402      if( p->mode==MODE_Column
9403       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9404      ){
9405        raw_printf
9406          (p->out,
9407           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9408           modeDescr[p->mode], p->cmOpts.iWrap,
9409           p->cmOpts.bWordWrap ? "on" : "off",
9410           p->cmOpts.bQuote ? "" : "no");
9411      }else{
9412        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9413      }
9414      zMode = modeDescr[p->mode];
9415    }
9416    n2 = strlen30(zMode);
9417    if( strncmp(zMode,"lines",n2)==0 ){
9418      p->mode = MODE_Line;
9419      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9420    }else if( strncmp(zMode,"columns",n2)==0 ){
9421      p->mode = MODE_Column;
9422      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9423        p->showHeader = 1;
9424      }
9425      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9426      p->cmOpts = cmOpts;
9427    }else if( strncmp(zMode,"list",n2)==0 ){
9428      p->mode = MODE_List;
9429      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9430      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9431    }else if( strncmp(zMode,"html",n2)==0 ){
9432      p->mode = MODE_Html;
9433    }else if( strncmp(zMode,"tcl",n2)==0 ){
9434      p->mode = MODE_Tcl;
9435      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9436      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9437    }else if( strncmp(zMode,"csv",n2)==0 ){
9438      p->mode = MODE_Csv;
9439      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9440      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9441    }else if( strncmp(zMode,"tabs",n2)==0 ){
9442      p->mode = MODE_List;
9443      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9444    }else if( strncmp(zMode,"insert",n2)==0 ){
9445      p->mode = MODE_Insert;
9446      set_table_name(p, zTabname ? zTabname : "table");
9447    }else if( strncmp(zMode,"quote",n2)==0 ){
9448      p->mode = MODE_Quote;
9449      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9450      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9451    }else if( strncmp(zMode,"ascii",n2)==0 ){
9452      p->mode = MODE_Ascii;
9453      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9454      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9455    }else if( strncmp(zMode,"markdown",n2)==0 ){
9456      p->mode = MODE_Markdown;
9457      p->cmOpts = cmOpts;
9458    }else if( strncmp(zMode,"table",n2)==0 ){
9459      p->mode = MODE_Table;
9460      p->cmOpts = cmOpts;
9461    }else if( strncmp(zMode,"box",n2)==0 ){
9462      p->mode = MODE_Box;
9463      p->cmOpts = cmOpts;
9464    }else if( strncmp(zMode,"count",n2)==0 ){
9465      p->mode = MODE_Count;
9466    }else if( strncmp(zMode,"off",n2)==0 ){
9467      p->mode = MODE_Off;
9468    }else if( strncmp(zMode,"json",n2)==0 ){
9469      p->mode = MODE_Json;
9470    }else{
9471      raw_printf(stderr, "Error: mode should be one of: "
9472         "ascii box column csv html insert json line list markdown "
9473         "qbox quote table tabs tcl\n");
9474      rc = 1;
9475    }
9476    p->cMode = p->mode;
9477  }else
9478
9479  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9480    if( nArg!=2 ){
9481      raw_printf(stderr, "Usage: .nonce NONCE\n");
9482      rc = 1;
9483    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9484      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9485                 p->lineno, azArg[1]);
9486      exit(1);
9487    }else{
9488      p->bSafeMode = 0;
9489      return 0;  /* Return immediately to bypass the safe mode reset
9490                 ** at the end of this procedure */
9491    }
9492  }else
9493
9494  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9495    if( nArg==2 ){
9496      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9497                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9498    }else{
9499      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9500      rc = 1;
9501    }
9502  }else
9503
9504  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9505    const char *zFN = 0;     /* Pointer to constant filename */
9506    char *zNewFilename = 0;  /* Name of the database file to open */
9507    int iName = 1;           /* Index in azArg[] of the filename */
9508    int newFlag = 0;         /* True to delete file before opening */
9509    int openMode = SHELL_OPEN_UNSPEC;
9510
9511    /* Check for command-line arguments */
9512    for(iName=1; iName<nArg; iName++){
9513      const char *z = azArg[iName];
9514      if( optionMatch(z,"new") ){
9515        newFlag = 1;
9516#ifdef SQLITE_HAVE_ZLIB
9517      }else if( optionMatch(z, "zip") ){
9518        openMode = SHELL_OPEN_ZIPFILE;
9519#endif
9520      }else if( optionMatch(z, "append") ){
9521        openMode = SHELL_OPEN_APPENDVFS;
9522      }else if( optionMatch(z, "readonly") ){
9523        openMode = SHELL_OPEN_READONLY;
9524      }else if( optionMatch(z, "nofollow") ){
9525        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9526#ifndef SQLITE_OMIT_DESERIALIZE
9527      }else if( optionMatch(z, "deserialize") ){
9528        openMode = SHELL_OPEN_DESERIALIZE;
9529      }else if( optionMatch(z, "hexdb") ){
9530        openMode = SHELL_OPEN_HEXDB;
9531      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9532        p->szMax = integerValue(azArg[++iName]);
9533#endif /* SQLITE_OMIT_DESERIALIZE */
9534      }else if( z[0]=='-' ){
9535        utf8_printf(stderr, "unknown option: %s\n", z);
9536        rc = 1;
9537        goto meta_command_exit;
9538      }else if( zFN ){
9539        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9540        rc = 1;
9541        goto meta_command_exit;
9542      }else{
9543        zFN = z;
9544      }
9545    }
9546
9547    /* Close the existing database */
9548    session_close_all(p, -1);
9549    close_db(p->db);
9550    p->db = 0;
9551    p->pAuxDb->zDbFilename = 0;
9552    sqlite3_free(p->pAuxDb->zFreeOnClose);
9553    p->pAuxDb->zFreeOnClose = 0;
9554    p->openMode = openMode;
9555    p->openFlags = 0;
9556    p->szMax = 0;
9557
9558    /* If a filename is specified, try to open it first */
9559    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9560      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9561      if( p->bSafeMode
9562       && p->openMode!=SHELL_OPEN_HEXDB
9563       && zFN
9564       && strcmp(zFN,":memory:")!=0
9565      ){
9566        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9567      }
9568      if( zFN ){
9569        zNewFilename = sqlite3_mprintf("%s", zFN);
9570        shell_check_oom(zNewFilename);
9571      }else{
9572        zNewFilename = 0;
9573      }
9574      p->pAuxDb->zDbFilename = zNewFilename;
9575      open_db(p, OPEN_DB_KEEPALIVE);
9576      if( p->db==0 ){
9577        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9578        sqlite3_free(zNewFilename);
9579      }else{
9580        p->pAuxDb->zFreeOnClose = zNewFilename;
9581      }
9582    }
9583    if( p->db==0 ){
9584      /* As a fall-back open a TEMP database */
9585      p->pAuxDb->zDbFilename = 0;
9586      open_db(p, 0);
9587    }
9588  }else
9589
9590  if( (c=='o'
9591        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9592   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9593  ){
9594    char *zFile = 0;
9595    int bTxtMode = 0;
9596    int i;
9597    int eMode = 0;
9598    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9599    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9600
9601    zBOM[0] = 0;
9602    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9603    if( c=='e' ){
9604      eMode = 'x';
9605      bOnce = 2;
9606    }else if( strncmp(azArg[0],"once",n)==0 ){
9607      bOnce = 1;
9608    }
9609    for(i=1; i<nArg; i++){
9610      char *z = azArg[i];
9611      if( z[0]=='-' ){
9612        if( z[1]=='-' ) z++;
9613        if( strcmp(z,"-bom")==0 ){
9614          zBOM[0] = 0xef;
9615          zBOM[1] = 0xbb;
9616          zBOM[2] = 0xbf;
9617          zBOM[3] = 0;
9618        }else if( c!='e' && strcmp(z,"-x")==0 ){
9619          eMode = 'x';  /* spreadsheet */
9620        }else if( c!='e' && strcmp(z,"-e")==0 ){
9621          eMode = 'e';  /* text editor */
9622        }else{
9623          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9624                      azArg[i]);
9625          showHelp(p->out, azArg[0]);
9626          rc = 1;
9627          goto meta_command_exit;
9628        }
9629      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9630        zFile = sqlite3_mprintf("%s", z);
9631        if( zFile && zFile[0]=='|' ){
9632          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9633          break;
9634        }
9635      }else{
9636        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9637                    azArg[i]);
9638        showHelp(p->out, azArg[0]);
9639        rc = 1;
9640        sqlite3_free(zFile);
9641        goto meta_command_exit;
9642      }
9643    }
9644    if( zFile==0 ){
9645      zFile = sqlite3_mprintf("stdout");
9646    }
9647    if( bOnce ){
9648      p->outCount = 2;
9649    }else{
9650      p->outCount = 0;
9651    }
9652    output_reset(p);
9653#ifndef SQLITE_NOHAVE_SYSTEM
9654    if( eMode=='e' || eMode=='x' ){
9655      p->doXdgOpen = 1;
9656      outputModePush(p);
9657      if( eMode=='x' ){
9658        /* spreadsheet mode.  Output as CSV. */
9659        newTempFile(p, "csv");
9660        ShellClearFlag(p, SHFLG_Echo);
9661        p->mode = MODE_Csv;
9662        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9663        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9664      }else{
9665        /* text editor mode */
9666        newTempFile(p, "txt");
9667        bTxtMode = 1;
9668      }
9669      sqlite3_free(zFile);
9670      zFile = sqlite3_mprintf("%s", p->zTempFile);
9671    }
9672#endif /* SQLITE_NOHAVE_SYSTEM */
9673    shell_check_oom(zFile);
9674    if( zFile[0]=='|' ){
9675#ifdef SQLITE_OMIT_POPEN
9676      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9677      rc = 1;
9678      p->out = stdout;
9679#else
9680      p->out = popen(zFile + 1, "w");
9681      if( p->out==0 ){
9682        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9683        p->out = stdout;
9684        rc = 1;
9685      }else{
9686        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9687        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9688      }
9689#endif
9690    }else{
9691      p->out = output_file_open(zFile, bTxtMode);
9692      if( p->out==0 ){
9693        if( strcmp(zFile,"off")!=0 ){
9694          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9695        }
9696        p->out = stdout;
9697        rc = 1;
9698      } else {
9699        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9700        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9701      }
9702    }
9703    sqlite3_free(zFile);
9704  }else
9705
9706  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9707    open_db(p,0);
9708    if( nArg<=1 ) goto parameter_syntax_error;
9709
9710    /* .parameter clear
9711    ** Clear all bind parameters by dropping the TEMP table that holds them.
9712    */
9713    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9714      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9715                   0, 0, 0);
9716    }else
9717
9718    /* .parameter list
9719    ** List all bind parameters.
9720    */
9721    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9722      sqlite3_stmt *pStmt = 0;
9723      int rx;
9724      int len = 0;
9725      rx = sqlite3_prepare_v2(p->db,
9726             "SELECT max(length(key)) "
9727             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9728      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9729        len = sqlite3_column_int(pStmt, 0);
9730        if( len>40 ) len = 40;
9731      }
9732      sqlite3_finalize(pStmt);
9733      pStmt = 0;
9734      if( len ){
9735        rx = sqlite3_prepare_v2(p->db,
9736             "SELECT key, quote(value) "
9737             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9738        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9739          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9740                      sqlite3_column_text(pStmt,1));
9741        }
9742        sqlite3_finalize(pStmt);
9743      }
9744    }else
9745
9746    /* .parameter init
9747    ** Make sure the TEMP table used to hold bind parameters exists.
9748    ** Create it if necessary.
9749    */
9750    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9751      bind_table_init(p);
9752    }else
9753
9754    /* .parameter set NAME VALUE
9755    ** Set or reset a bind parameter.  NAME should be the full parameter
9756    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9757    ** VALUE can be in either SQL literal notation, or if not it will be
9758    ** understood to be a text string.
9759    */
9760    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9761      int rx;
9762      char *zSql;
9763      sqlite3_stmt *pStmt;
9764      const char *zKey = azArg[2];
9765      const char *zValue = azArg[3];
9766      bind_table_init(p);
9767      zSql = sqlite3_mprintf(
9768                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9769                  "VALUES(%Q,%s);", zKey, zValue);
9770      shell_check_oom(zSql);
9771      pStmt = 0;
9772      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9773      sqlite3_free(zSql);
9774      if( rx!=SQLITE_OK ){
9775        sqlite3_finalize(pStmt);
9776        pStmt = 0;
9777        zSql = sqlite3_mprintf(
9778                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9779                   "VALUES(%Q,%Q);", zKey, zValue);
9780        shell_check_oom(zSql);
9781        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9782        sqlite3_free(zSql);
9783        if( rx!=SQLITE_OK ){
9784          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9785          sqlite3_finalize(pStmt);
9786          pStmt = 0;
9787          rc = 1;
9788        }
9789      }
9790      sqlite3_step(pStmt);
9791      sqlite3_finalize(pStmt);
9792    }else
9793
9794    /* .parameter unset NAME
9795    ** Remove the NAME binding from the parameter binding table, if it
9796    ** exists.
9797    */
9798    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9799      char *zSql = sqlite3_mprintf(
9800          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9801      shell_check_oom(zSql);
9802      sqlite3_exec(p->db, zSql, 0, 0, 0);
9803      sqlite3_free(zSql);
9804    }else
9805    /* If no command name matches, show a syntax error */
9806    parameter_syntax_error:
9807    showHelp(p->out, "parameter");
9808  }else
9809
9810  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9811    int i;
9812    for(i=1; i<nArg; i++){
9813      if( i>1 ) raw_printf(p->out, " ");
9814      utf8_printf(p->out, "%s", azArg[i]);
9815    }
9816    raw_printf(p->out, "\n");
9817  }else
9818
9819#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9820  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9821    int i;
9822    int nn = 0;
9823    p->flgProgress = 0;
9824    p->mxProgress = 0;
9825    p->nProgress = 0;
9826    for(i=1; i<nArg; i++){
9827      const char *z = azArg[i];
9828      if( z[0]=='-' ){
9829        z++;
9830        if( z[0]=='-' ) z++;
9831        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9832          p->flgProgress |= SHELL_PROGRESS_QUIET;
9833          continue;
9834        }
9835        if( strcmp(z,"reset")==0 ){
9836          p->flgProgress |= SHELL_PROGRESS_RESET;
9837          continue;
9838        }
9839        if( strcmp(z,"once")==0 ){
9840          p->flgProgress |= SHELL_PROGRESS_ONCE;
9841          continue;
9842        }
9843        if( strcmp(z,"limit")==0 ){
9844          if( i+1>=nArg ){
9845            utf8_printf(stderr, "Error: missing argument on --limit\n");
9846            rc = 1;
9847            goto meta_command_exit;
9848          }else{
9849            p->mxProgress = (int)integerValue(azArg[++i]);
9850          }
9851          continue;
9852        }
9853        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9854        rc = 1;
9855        goto meta_command_exit;
9856      }else{
9857        nn = (int)integerValue(z);
9858      }
9859    }
9860    open_db(p, 0);
9861    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9862  }else
9863#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9864
9865  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9866    if( nArg >= 2) {
9867      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9868    }
9869    if( nArg >= 3) {
9870      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9871    }
9872  }else
9873
9874  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9875    rc = 2;
9876  }else
9877
9878  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9879    FILE *inSaved = p->in;
9880    int savedLineno = p->lineno;
9881    failIfSafeMode(p, "cannot run .read in safe mode");
9882    if( nArg!=2 ){
9883      raw_printf(stderr, "Usage: .read FILE\n");
9884      rc = 1;
9885      goto meta_command_exit;
9886    }
9887    if( azArg[1][0]=='|' ){
9888#ifdef SQLITE_OMIT_POPEN
9889      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9890      rc = 1;
9891      p->out = stdout;
9892#else
9893      p->in = popen(azArg[1]+1, "r");
9894      if( p->in==0 ){
9895        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9896        rc = 1;
9897      }else{
9898        rc = process_input(p);
9899        pclose(p->in);
9900      }
9901#endif
9902    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9903      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9904      rc = 1;
9905    }else{
9906      rc = process_input(p);
9907      fclose(p->in);
9908    }
9909    p->in = inSaved;
9910    p->lineno = savedLineno;
9911  }else
9912
9913  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9914    const char *zSrcFile;
9915    const char *zDb;
9916    sqlite3 *pSrc;
9917    sqlite3_backup *pBackup;
9918    int nTimeout = 0;
9919
9920    failIfSafeMode(p, "cannot run .restore in safe mode");
9921    if( nArg==2 ){
9922      zSrcFile = azArg[1];
9923      zDb = "main";
9924    }else if( nArg==3 ){
9925      zSrcFile = azArg[2];
9926      zDb = azArg[1];
9927    }else{
9928      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9929      rc = 1;
9930      goto meta_command_exit;
9931    }
9932    rc = sqlite3_open(zSrcFile, &pSrc);
9933    if( rc!=SQLITE_OK ){
9934      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9935      close_db(pSrc);
9936      return 1;
9937    }
9938    open_db(p, 0);
9939    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9940    if( pBackup==0 ){
9941      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9942      close_db(pSrc);
9943      return 1;
9944    }
9945    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9946          || rc==SQLITE_BUSY  ){
9947      if( rc==SQLITE_BUSY ){
9948        if( nTimeout++ >= 3 ) break;
9949        sqlite3_sleep(100);
9950      }
9951    }
9952    sqlite3_backup_finish(pBackup);
9953    if( rc==SQLITE_DONE ){
9954      rc = 0;
9955    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9956      raw_printf(stderr, "Error: source database is busy\n");
9957      rc = 1;
9958    }else{
9959      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9960      rc = 1;
9961    }
9962    close_db(pSrc);
9963  }else
9964
9965  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9966    if( nArg==2 ){
9967      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9968#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9969      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9970#endif
9971    }else{
9972      raw_printf(stderr, "Usage: .scanstats on|off\n");
9973      rc = 1;
9974    }
9975  }else
9976
9977  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9978    ShellText sSelect;
9979    ShellState data;
9980    char *zErrMsg = 0;
9981    const char *zDiv = "(";
9982    const char *zName = 0;
9983    int iSchema = 0;
9984    int bDebug = 0;
9985    int bNoSystemTabs = 0;
9986    int ii;
9987
9988    open_db(p, 0);
9989    memcpy(&data, p, sizeof(data));
9990    data.showHeader = 0;
9991    data.cMode = data.mode = MODE_Semi;
9992    initText(&sSelect);
9993    for(ii=1; ii<nArg; ii++){
9994      if( optionMatch(azArg[ii],"indent") ){
9995        data.cMode = data.mode = MODE_Pretty;
9996      }else if( optionMatch(azArg[ii],"debug") ){
9997        bDebug = 1;
9998      }else if( optionMatch(azArg[ii],"nosys") ){
9999        bNoSystemTabs = 1;
10000      }else if( azArg[ii][0]=='-' ){
10001        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10002        rc = 1;
10003        goto meta_command_exit;
10004      }else if( zName==0 ){
10005        zName = azArg[ii];
10006      }else{
10007        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10008        rc = 1;
10009        goto meta_command_exit;
10010      }
10011    }
10012    if( zName!=0 ){
10013      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10014                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10015                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10016                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10017      if( isSchema ){
10018        char *new_argv[2], *new_colv[2];
10019        new_argv[0] = sqlite3_mprintf(
10020                      "CREATE TABLE %s (\n"
10021                      "  type text,\n"
10022                      "  name text,\n"
10023                      "  tbl_name text,\n"
10024                      "  rootpage integer,\n"
10025                      "  sql text\n"
10026                      ")", zName);
10027        shell_check_oom(new_argv[0]);
10028        new_argv[1] = 0;
10029        new_colv[0] = "sql";
10030        new_colv[1] = 0;
10031        callback(&data, 1, new_argv, new_colv);
10032        sqlite3_free(new_argv[0]);
10033      }
10034    }
10035    if( zDiv ){
10036      sqlite3_stmt *pStmt = 0;
10037      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10038                              -1, &pStmt, 0);
10039      if( rc ){
10040        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10041        sqlite3_finalize(pStmt);
10042        rc = 1;
10043        goto meta_command_exit;
10044      }
10045      appendText(&sSelect, "SELECT sql FROM", 0);
10046      iSchema = 0;
10047      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10048        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10049        char zScNum[30];
10050        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10051        appendText(&sSelect, zDiv, 0);
10052        zDiv = " UNION ALL ";
10053        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10054        if( sqlite3_stricmp(zDb, "main")!=0 ){
10055          appendText(&sSelect, zDb, '\'');
10056        }else{
10057          appendText(&sSelect, "NULL", 0);
10058        }
10059        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10060        appendText(&sSelect, zScNum, 0);
10061        appendText(&sSelect, " AS snum, ", 0);
10062        appendText(&sSelect, zDb, '\'');
10063        appendText(&sSelect, " AS sname FROM ", 0);
10064        appendText(&sSelect, zDb, quoteChar(zDb));
10065        appendText(&sSelect, ".sqlite_schema", 0);
10066      }
10067      sqlite3_finalize(pStmt);
10068#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10069      if( zName ){
10070        appendText(&sSelect,
10071           " UNION ALL SELECT shell_module_schema(name),"
10072           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10073        0);
10074      }
10075#endif
10076      appendText(&sSelect, ") WHERE ", 0);
10077      if( zName ){
10078        char *zQarg = sqlite3_mprintf("%Q", zName);
10079        int bGlob;
10080        shell_check_oom(zQarg);
10081        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10082                strchr(zName, '[') != 0;
10083        if( strchr(zName, '.') ){
10084          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10085        }else{
10086          appendText(&sSelect, "lower(tbl_name)", 0);
10087        }
10088        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10089        appendText(&sSelect, zQarg, 0);
10090        if( !bGlob ){
10091          appendText(&sSelect, " ESCAPE '\\' ", 0);
10092        }
10093        appendText(&sSelect, " AND ", 0);
10094        sqlite3_free(zQarg);
10095      }
10096      if( bNoSystemTabs ){
10097        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10098      }
10099      appendText(&sSelect, "sql IS NOT NULL"
10100                           " ORDER BY snum, rowid", 0);
10101      if( bDebug ){
10102        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10103      }else{
10104        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10105      }
10106      freeText(&sSelect);
10107    }
10108    if( zErrMsg ){
10109      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10110      sqlite3_free(zErrMsg);
10111      rc = 1;
10112    }else if( rc != SQLITE_OK ){
10113      raw_printf(stderr,"Error: querying schema information\n");
10114      rc = 1;
10115    }else{
10116      rc = 0;
10117    }
10118  }else
10119
10120  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10121   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10122  ){
10123    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10124    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10125  }else
10126
10127#if defined(SQLITE_ENABLE_SESSION)
10128  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10129    struct AuxDb *pAuxDb = p->pAuxDb;
10130    OpenSession *pSession = &pAuxDb->aSession[0];
10131    char **azCmd = &azArg[1];
10132    int iSes = 0;
10133    int nCmd = nArg - 1;
10134    int i;
10135    if( nArg<=1 ) goto session_syntax_error;
10136    open_db(p, 0);
10137    if( nArg>=3 ){
10138      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10139        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10140      }
10141      if( iSes<pAuxDb->nSession ){
10142        pSession = &pAuxDb->aSession[iSes];
10143        azCmd++;
10144        nCmd--;
10145      }else{
10146        pSession = &pAuxDb->aSession[0];
10147        iSes = 0;
10148      }
10149    }
10150
10151    /* .session attach TABLE
10152    ** Invoke the sqlite3session_attach() interface to attach a particular
10153    ** table so that it is never filtered.
10154    */
10155    if( strcmp(azCmd[0],"attach")==0 ){
10156      if( nCmd!=2 ) goto session_syntax_error;
10157      if( pSession->p==0 ){
10158        session_not_open:
10159        raw_printf(stderr, "ERROR: No sessions are open\n");
10160      }else{
10161        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10162        if( rc ){
10163          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10164          rc = 0;
10165        }
10166      }
10167    }else
10168
10169    /* .session changeset FILE
10170    ** .session patchset FILE
10171    ** Write a changeset or patchset into a file.  The file is overwritten.
10172    */
10173    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10174      FILE *out = 0;
10175      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10176      if( nCmd!=2 ) goto session_syntax_error;
10177      if( pSession->p==0 ) goto session_not_open;
10178      out = fopen(azCmd[1], "wb");
10179      if( out==0 ){
10180        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10181                    azCmd[1]);
10182      }else{
10183        int szChng;
10184        void *pChng;
10185        if( azCmd[0][0]=='c' ){
10186          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10187        }else{
10188          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10189        }
10190        if( rc ){
10191          printf("Error: error code %d\n", rc);
10192          rc = 0;
10193        }
10194        if( pChng
10195          && fwrite(pChng, szChng, 1, out)!=1 ){
10196          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10197                  szChng);
10198        }
10199        sqlite3_free(pChng);
10200        fclose(out);
10201      }
10202    }else
10203
10204    /* .session close
10205    ** Close the identified session
10206    */
10207    if( strcmp(azCmd[0], "close")==0 ){
10208      if( nCmd!=1 ) goto session_syntax_error;
10209      if( pAuxDb->nSession ){
10210        session_close(pSession);
10211        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10212      }
10213    }else
10214
10215    /* .session enable ?BOOLEAN?
10216    ** Query or set the enable flag
10217    */
10218    if( strcmp(azCmd[0], "enable")==0 ){
10219      int ii;
10220      if( nCmd>2 ) goto session_syntax_error;
10221      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10222      if( pAuxDb->nSession ){
10223        ii = sqlite3session_enable(pSession->p, ii);
10224        utf8_printf(p->out, "session %s enable flag = %d\n",
10225                    pSession->zName, ii);
10226      }
10227    }else
10228
10229    /* .session filter GLOB ....
10230    ** Set a list of GLOB patterns of table names to be excluded.
10231    */
10232    if( strcmp(azCmd[0], "filter")==0 ){
10233      int ii, nByte;
10234      if( nCmd<2 ) goto session_syntax_error;
10235      if( pAuxDb->nSession ){
10236        for(ii=0; ii<pSession->nFilter; ii++){
10237          sqlite3_free(pSession->azFilter[ii]);
10238        }
10239        sqlite3_free(pSession->azFilter);
10240        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10241        pSession->azFilter = sqlite3_malloc( nByte );
10242        if( pSession->azFilter==0 ){
10243          raw_printf(stderr, "Error: out or memory\n");
10244          exit(1);
10245        }
10246        for(ii=1; ii<nCmd; ii++){
10247          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10248          shell_check_oom(x);
10249        }
10250        pSession->nFilter = ii-1;
10251      }
10252    }else
10253
10254    /* .session indirect ?BOOLEAN?
10255    ** Query or set the indirect flag
10256    */
10257    if( strcmp(azCmd[0], "indirect")==0 ){
10258      int ii;
10259      if( nCmd>2 ) goto session_syntax_error;
10260      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10261      if( pAuxDb->nSession ){
10262        ii = sqlite3session_indirect(pSession->p, ii);
10263        utf8_printf(p->out, "session %s indirect flag = %d\n",
10264                    pSession->zName, ii);
10265      }
10266    }else
10267
10268    /* .session isempty
10269    ** Determine if the session is empty
10270    */
10271    if( strcmp(azCmd[0], "isempty")==0 ){
10272      int ii;
10273      if( nCmd!=1 ) goto session_syntax_error;
10274      if( pAuxDb->nSession ){
10275        ii = sqlite3session_isempty(pSession->p);
10276        utf8_printf(p->out, "session %s isempty flag = %d\n",
10277                    pSession->zName, ii);
10278      }
10279    }else
10280
10281    /* .session list
10282    ** List all currently open sessions
10283    */
10284    if( strcmp(azCmd[0],"list")==0 ){
10285      for(i=0; i<pAuxDb->nSession; i++){
10286        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10287      }
10288    }else
10289
10290    /* .session open DB NAME
10291    ** Open a new session called NAME on the attached database DB.
10292    ** DB is normally "main".
10293    */
10294    if( strcmp(azCmd[0],"open")==0 ){
10295      char *zName;
10296      if( nCmd!=3 ) goto session_syntax_error;
10297      zName = azCmd[2];
10298      if( zName[0]==0 ) goto session_syntax_error;
10299      for(i=0; i<pAuxDb->nSession; i++){
10300        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10301          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10302          goto meta_command_exit;
10303        }
10304      }
10305      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10306        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10307        goto meta_command_exit;
10308      }
10309      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10310      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10311      if( rc ){
10312        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10313        rc = 0;
10314        goto meta_command_exit;
10315      }
10316      pSession->nFilter = 0;
10317      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10318      pAuxDb->nSession++;
10319      pSession->zName = sqlite3_mprintf("%s", zName);
10320      shell_check_oom(pSession->zName);
10321    }else
10322    /* If no command name matches, show a syntax error */
10323    session_syntax_error:
10324    showHelp(p->out, "session");
10325  }else
10326#endif
10327
10328#ifdef SQLITE_DEBUG
10329  /* Undocumented commands for internal testing.  Subject to change
10330  ** without notice. */
10331  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10332    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10333      int i, v;
10334      for(i=1; i<nArg; i++){
10335        v = booleanValue(azArg[i]);
10336        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10337      }
10338    }
10339    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10340      int i; sqlite3_int64 v;
10341      for(i=1; i<nArg; i++){
10342        char zBuf[200];
10343        v = integerValue(azArg[i]);
10344        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10345        utf8_printf(p->out, "%s", zBuf);
10346      }
10347    }
10348  }else
10349#endif
10350
10351  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10352    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10353    int bVerbose = 0;        /* Verbose output */
10354    int bSelftestExists;     /* True if SELFTEST already exists */
10355    int i, k;                /* Loop counters */
10356    int nTest = 0;           /* Number of tests runs */
10357    int nErr = 0;            /* Number of errors seen */
10358    ShellText str;           /* Answer for a query */
10359    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10360
10361    open_db(p,0);
10362    for(i=1; i<nArg; i++){
10363      const char *z = azArg[i];
10364      if( z[0]=='-' && z[1]=='-' ) z++;
10365      if( strcmp(z,"-init")==0 ){
10366        bIsInit = 1;
10367      }else
10368      if( strcmp(z,"-v")==0 ){
10369        bVerbose++;
10370      }else
10371      {
10372        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10373                    azArg[i], azArg[0]);
10374        raw_printf(stderr, "Should be one of: --init -v\n");
10375        rc = 1;
10376        goto meta_command_exit;
10377      }
10378    }
10379    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10380           != SQLITE_OK ){
10381      bSelftestExists = 0;
10382    }else{
10383      bSelftestExists = 1;
10384    }
10385    if( bIsInit ){
10386      createSelftestTable(p);
10387      bSelftestExists = 1;
10388    }
10389    initText(&str);
10390    appendText(&str, "x", 0);
10391    for(k=bSelftestExists; k>=0; k--){
10392      if( k==1 ){
10393        rc = sqlite3_prepare_v2(p->db,
10394            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10395            -1, &pStmt, 0);
10396      }else{
10397        rc = sqlite3_prepare_v2(p->db,
10398          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10399          "      (1,'run','PRAGMA integrity_check','ok')",
10400          -1, &pStmt, 0);
10401      }
10402      if( rc ){
10403        raw_printf(stderr, "Error querying the selftest table\n");
10404        rc = 1;
10405        sqlite3_finalize(pStmt);
10406        goto meta_command_exit;
10407      }
10408      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10409        int tno = sqlite3_column_int(pStmt, 0);
10410        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10411        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10412        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10413
10414        if( zOp==0 ) continue;
10415        if( zSql==0 ) continue;
10416        if( zAns==0 ) continue;
10417        k = 0;
10418        if( bVerbose>0 ){
10419          printf("%d: %s %s\n", tno, zOp, zSql);
10420        }
10421        if( strcmp(zOp,"memo")==0 ){
10422          utf8_printf(p->out, "%s\n", zSql);
10423        }else
10424        if( strcmp(zOp,"run")==0 ){
10425          char *zErrMsg = 0;
10426          str.n = 0;
10427          str.z[0] = 0;
10428          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10429          nTest++;
10430          if( bVerbose ){
10431            utf8_printf(p->out, "Result: %s\n", str.z);
10432          }
10433          if( rc || zErrMsg ){
10434            nErr++;
10435            rc = 1;
10436            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10437            sqlite3_free(zErrMsg);
10438          }else if( strcmp(zAns,str.z)!=0 ){
10439            nErr++;
10440            rc = 1;
10441            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10442            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10443          }
10444        }else
10445        {
10446          utf8_printf(stderr,
10447            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10448          rc = 1;
10449          break;
10450        }
10451      } /* End loop over rows of content from SELFTEST */
10452      sqlite3_finalize(pStmt);
10453    } /* End loop over k */
10454    freeText(&str);
10455    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10456  }else
10457
10458  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10459    if( nArg<2 || nArg>3 ){
10460      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10461      rc = 1;
10462    }
10463    if( nArg>=2 ){
10464      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10465                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10466    }
10467    if( nArg>=3 ){
10468      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10469                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10470    }
10471  }else
10472
10473  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10474    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10475    int i;                   /* Loop counter */
10476    int bSchema = 0;         /* Also hash the schema */
10477    int bSeparate = 0;       /* Hash each table separately */
10478    int iSize = 224;         /* Hash algorithm to use */
10479    int bDebug = 0;          /* Only show the query that would have run */
10480    sqlite3_stmt *pStmt;     /* For querying tables names */
10481    char *zSql;              /* SQL to be run */
10482    char *zSep;              /* Separator */
10483    ShellText sSql;          /* Complete SQL for the query to run the hash */
10484    ShellText sQuery;        /* Set of queries used to read all content */
10485    open_db(p, 0);
10486    for(i=1; i<nArg; i++){
10487      const char *z = azArg[i];
10488      if( z[0]=='-' ){
10489        z++;
10490        if( z[0]=='-' ) z++;
10491        if( strcmp(z,"schema")==0 ){
10492          bSchema = 1;
10493        }else
10494        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10495         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10496        ){
10497          iSize = atoi(&z[5]);
10498        }else
10499        if( strcmp(z,"debug")==0 ){
10500          bDebug = 1;
10501        }else
10502        {
10503          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10504                      azArg[i], azArg[0]);
10505          showHelp(p->out, azArg[0]);
10506          rc = 1;
10507          goto meta_command_exit;
10508        }
10509      }else if( zLike ){
10510        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10511        rc = 1;
10512        goto meta_command_exit;
10513      }else{
10514        zLike = z;
10515        bSeparate = 1;
10516        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10517      }
10518    }
10519    if( bSchema ){
10520      zSql = "SELECT lower(name) FROM sqlite_schema"
10521             " WHERE type='table' AND coalesce(rootpage,0)>1"
10522             " UNION ALL SELECT 'sqlite_schema'"
10523             " ORDER BY 1 collate nocase";
10524    }else{
10525      zSql = "SELECT lower(name) FROM sqlite_schema"
10526             " WHERE type='table' AND coalesce(rootpage,0)>1"
10527             " AND name NOT LIKE 'sqlite_%'"
10528             " ORDER BY 1 collate nocase";
10529    }
10530    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10531    initText(&sQuery);
10532    initText(&sSql);
10533    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10534    zSep = "VALUES(";
10535    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10536      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10537      if( zTab==0 ) continue;
10538      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10539      if( strncmp(zTab, "sqlite_",7)!=0 ){
10540        appendText(&sQuery,"SELECT * FROM ", 0);
10541        appendText(&sQuery,zTab,'"');
10542        appendText(&sQuery," NOT INDEXED;", 0);
10543      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10544        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10545                           " ORDER BY name;", 0);
10546      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10547        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10548                           " ORDER BY name;", 0);
10549      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10550        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10551                           " ORDER BY tbl,idx;", 0);
10552      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10553        appendText(&sQuery, "SELECT * FROM ", 0);
10554        appendText(&sQuery, zTab, 0);
10555        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10556      }
10557      appendText(&sSql, zSep, 0);
10558      appendText(&sSql, sQuery.z, '\'');
10559      sQuery.n = 0;
10560      appendText(&sSql, ",", 0);
10561      appendText(&sSql, zTab, '\'');
10562      zSep = "),(";
10563    }
10564    sqlite3_finalize(pStmt);
10565    if( bSeparate ){
10566      zSql = sqlite3_mprintf(
10567          "%s))"
10568          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10569          "   FROM [sha3sum$query]",
10570          sSql.z, iSize);
10571    }else{
10572      zSql = sqlite3_mprintf(
10573          "%s))"
10574          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10575          "   FROM [sha3sum$query]",
10576          sSql.z, iSize);
10577    }
10578    shell_check_oom(zSql);
10579    freeText(&sQuery);
10580    freeText(&sSql);
10581    if( bDebug ){
10582      utf8_printf(p->out, "%s\n", zSql);
10583    }else{
10584      shell_exec(p, zSql, 0);
10585    }
10586    sqlite3_free(zSql);
10587  }else
10588
10589#ifndef SQLITE_NOHAVE_SYSTEM
10590  if( c=='s'
10591   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10592  ){
10593    char *zCmd;
10594    int i, x;
10595    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10596    if( nArg<2 ){
10597      raw_printf(stderr, "Usage: .system COMMAND\n");
10598      rc = 1;
10599      goto meta_command_exit;
10600    }
10601    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10602    for(i=2; i<nArg && zCmd!=0; i++){
10603      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10604                             zCmd, azArg[i]);
10605    }
10606    x = zCmd!=0 ? system(zCmd) : 1;
10607    sqlite3_free(zCmd);
10608    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10609  }else
10610#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10611
10612  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10613    static const char *azBool[] = { "off", "on", "trigger", "full"};
10614    const char *zOut;
10615    int i;
10616    if( nArg!=1 ){
10617      raw_printf(stderr, "Usage: .show\n");
10618      rc = 1;
10619      goto meta_command_exit;
10620    }
10621    utf8_printf(p->out, "%12.12s: %s\n","echo",
10622                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10623    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10624    utf8_printf(p->out, "%12.12s: %s\n","explain",
10625         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10626    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10627    if( p->mode==MODE_Column
10628     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10629    ){
10630      utf8_printf
10631        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10632         modeDescr[p->mode], p->cmOpts.iWrap,
10633         p->cmOpts.bWordWrap ? "on" : "off",
10634         p->cmOpts.bQuote ? "" : "no");
10635    }else{
10636      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10637    }
10638    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10639      output_c_string(p->out, p->nullValue);
10640      raw_printf(p->out, "\n");
10641    utf8_printf(p->out,"%12.12s: %s\n","output",
10642            strlen30(p->outfile) ? p->outfile : "stdout");
10643    utf8_printf(p->out,"%12.12s: ", "colseparator");
10644      output_c_string(p->out, p->colSeparator);
10645      raw_printf(p->out, "\n");
10646    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10647      output_c_string(p->out, p->rowSeparator);
10648      raw_printf(p->out, "\n");
10649    switch( p->statsOn ){
10650      case 0:  zOut = "off";     break;
10651      default: zOut = "on";      break;
10652      case 2:  zOut = "stmt";    break;
10653      case 3:  zOut = "vmstep";  break;
10654    }
10655    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10656    utf8_printf(p->out, "%12.12s: ", "width");
10657    for (i=0;i<p->nWidth;i++) {
10658      raw_printf(p->out, "%d ", p->colWidth[i]);
10659    }
10660    raw_printf(p->out, "\n");
10661    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10662                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10663  }else
10664
10665  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10666    if( nArg==2 ){
10667      if( strcmp(azArg[1],"stmt")==0 ){
10668        p->statsOn = 2;
10669      }else if( strcmp(azArg[1],"vmstep")==0 ){
10670        p->statsOn = 3;
10671      }else{
10672        p->statsOn = (u8)booleanValue(azArg[1]);
10673      }
10674    }else if( nArg==1 ){
10675      display_stats(p->db, p, 0);
10676    }else{
10677      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10678      rc = 1;
10679    }
10680  }else
10681
10682  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10683   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10684                 || strncmp(azArg[0], "indexes", n)==0) )
10685  ){
10686    sqlite3_stmt *pStmt;
10687    char **azResult;
10688    int nRow, nAlloc;
10689    int ii;
10690    ShellText s;
10691    initText(&s);
10692    open_db(p, 0);
10693    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10694    if( rc ){
10695      sqlite3_finalize(pStmt);
10696      return shellDatabaseError(p->db);
10697    }
10698
10699    if( nArg>2 && c=='i' ){
10700      /* It is an historical accident that the .indexes command shows an error
10701      ** when called with the wrong number of arguments whereas the .tables
10702      ** command does not. */
10703      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10704      rc = 1;
10705      sqlite3_finalize(pStmt);
10706      goto meta_command_exit;
10707    }
10708    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10709      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10710      if( zDbName==0 ) continue;
10711      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10712      if( sqlite3_stricmp(zDbName, "main")==0 ){
10713        appendText(&s, "SELECT name FROM ", 0);
10714      }else{
10715        appendText(&s, "SELECT ", 0);
10716        appendText(&s, zDbName, '\'');
10717        appendText(&s, "||'.'||name FROM ", 0);
10718      }
10719      appendText(&s, zDbName, '"');
10720      appendText(&s, ".sqlite_schema ", 0);
10721      if( c=='t' ){
10722        appendText(&s," WHERE type IN ('table','view')"
10723                      "   AND name NOT LIKE 'sqlite_%'"
10724                      "   AND name LIKE ?1", 0);
10725      }else{
10726        appendText(&s," WHERE type='index'"
10727                      "   AND tbl_name LIKE ?1", 0);
10728      }
10729    }
10730    rc = sqlite3_finalize(pStmt);
10731    if( rc==SQLITE_OK ){
10732      appendText(&s, " ORDER BY 1", 0);
10733      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10734    }
10735    freeText(&s);
10736    if( rc ) return shellDatabaseError(p->db);
10737
10738    /* Run the SQL statement prepared by the above block. Store the results
10739    ** as an array of nul-terminated strings in azResult[].  */
10740    nRow = nAlloc = 0;
10741    azResult = 0;
10742    if( nArg>1 ){
10743      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10744    }else{
10745      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10746    }
10747    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10748      if( nRow>=nAlloc ){
10749        char **azNew;
10750        int n2 = nAlloc*2 + 10;
10751        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10752        shell_check_oom(azNew);
10753        nAlloc = n2;
10754        azResult = azNew;
10755      }
10756      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10757      shell_check_oom(azResult[nRow]);
10758      nRow++;
10759    }
10760    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10761      rc = shellDatabaseError(p->db);
10762    }
10763
10764    /* Pretty-print the contents of array azResult[] to the output */
10765    if( rc==0 && nRow>0 ){
10766      int len, maxlen = 0;
10767      int i, j;
10768      int nPrintCol, nPrintRow;
10769      for(i=0; i<nRow; i++){
10770        len = strlen30(azResult[i]);
10771        if( len>maxlen ) maxlen = len;
10772      }
10773      nPrintCol = 80/(maxlen+2);
10774      if( nPrintCol<1 ) nPrintCol = 1;
10775      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10776      for(i=0; i<nPrintRow; i++){
10777        for(j=i; j<nRow; j+=nPrintRow){
10778          char *zSp = j<nPrintRow ? "" : "  ";
10779          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10780                      azResult[j] ? azResult[j]:"");
10781        }
10782        raw_printf(p->out, "\n");
10783      }
10784    }
10785
10786    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10787    sqlite3_free(azResult);
10788  }else
10789
10790  /* Begin redirecting output to the file "testcase-out.txt" */
10791  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10792    output_reset(p);
10793    p->out = output_file_open("testcase-out.txt", 0);
10794    if( p->out==0 ){
10795      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10796    }
10797    if( nArg>=2 ){
10798      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10799    }else{
10800      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10801    }
10802  }else
10803
10804#ifndef SQLITE_UNTESTABLE
10805  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10806    static const struct {
10807       const char *zCtrlName;   /* Name of a test-control option */
10808       int ctrlCode;            /* Integer code for that option */
10809       int unSafe;              /* Not valid for --safe mode */
10810       const char *zUsage;      /* Usage notes */
10811    } aCtrl[] = {
10812      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10813      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10814    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10815    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10816      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10817      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10818    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10819      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10820      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10821      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10822      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10823      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10824#ifdef YYCOVERAGE
10825      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10826#endif
10827      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10828      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10829      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10830      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10831      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10832      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10833      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10834    };
10835    int testctrl = -1;
10836    int iCtrl = -1;
10837    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10838    int isOk = 0;
10839    int i, n2;
10840    const char *zCmd = 0;
10841
10842    open_db(p, 0);
10843    zCmd = nArg>=2 ? azArg[1] : "help";
10844
10845    /* The argument can optionally begin with "-" or "--" */
10846    if( zCmd[0]=='-' && zCmd[1] ){
10847      zCmd++;
10848      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10849    }
10850
10851    /* --help lists all test-controls */
10852    if( strcmp(zCmd,"help")==0 ){
10853      utf8_printf(p->out, "Available test-controls:\n");
10854      for(i=0; i<ArraySize(aCtrl); i++){
10855        utf8_printf(p->out, "  .testctrl %s %s\n",
10856                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10857      }
10858      rc = 1;
10859      goto meta_command_exit;
10860    }
10861
10862    /* convert testctrl text option to value. allow any unique prefix
10863    ** of the option name, or a numerical value. */
10864    n2 = strlen30(zCmd);
10865    for(i=0; i<ArraySize(aCtrl); i++){
10866      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10867        if( testctrl<0 ){
10868          testctrl = aCtrl[i].ctrlCode;
10869          iCtrl = i;
10870        }else{
10871          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10872                              "Use \".testctrl --help\" for help\n", zCmd);
10873          rc = 1;
10874          goto meta_command_exit;
10875        }
10876      }
10877    }
10878    if( testctrl<0 ){
10879      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10880                         "Use \".testctrl --help\" for help\n", zCmd);
10881    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10882      utf8_printf(stderr,
10883         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10884         p->lineno, aCtrl[iCtrl].zCtrlName);
10885      exit(1);
10886    }else{
10887      switch(testctrl){
10888
10889        /* sqlite3_test_control(int, db, int) */
10890        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10891          if( nArg==3 ){
10892            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10893            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10894            isOk = 3;
10895          }
10896          break;
10897
10898        /* sqlite3_test_control(int) */
10899        case SQLITE_TESTCTRL_PRNG_SAVE:
10900        case SQLITE_TESTCTRL_PRNG_RESTORE:
10901        case SQLITE_TESTCTRL_BYTEORDER:
10902          if( nArg==2 ){
10903            rc2 = sqlite3_test_control(testctrl);
10904            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10905          }
10906          break;
10907
10908        /* sqlite3_test_control(int, uint) */
10909        case SQLITE_TESTCTRL_PENDING_BYTE:
10910          if( nArg==3 ){
10911            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10912            rc2 = sqlite3_test_control(testctrl, opt);
10913            isOk = 3;
10914          }
10915          break;
10916
10917        /* sqlite3_test_control(int, int, sqlite3*) */
10918        case SQLITE_TESTCTRL_PRNG_SEED:
10919          if( nArg==3 || nArg==4 ){
10920            int ii = (int)integerValue(azArg[2]);
10921            sqlite3 *db;
10922            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10923              sqlite3_randomness(sizeof(ii),&ii);
10924              printf("-- random seed: %d\n", ii);
10925            }
10926            if( nArg==3 ){
10927              db = 0;
10928            }else{
10929              db = p->db;
10930              /* Make sure the schema has been loaded */
10931              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10932            }
10933            rc2 = sqlite3_test_control(testctrl, ii, db);
10934            isOk = 3;
10935          }
10936          break;
10937
10938        /* sqlite3_test_control(int, int) */
10939        case SQLITE_TESTCTRL_ASSERT:
10940        case SQLITE_TESTCTRL_ALWAYS:
10941          if( nArg==3 ){
10942            int opt = booleanValue(azArg[2]);
10943            rc2 = sqlite3_test_control(testctrl, opt);
10944            isOk = 1;
10945          }
10946          break;
10947
10948        /* sqlite3_test_control(int, int) */
10949        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10950        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10951          if( nArg==3 ){
10952            int opt = booleanValue(azArg[2]);
10953            rc2 = sqlite3_test_control(testctrl, opt);
10954            isOk = 3;
10955          }
10956          break;
10957
10958        /* sqlite3_test_control(sqlite3*) */
10959        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10960          rc2 = sqlite3_test_control(testctrl, p->db);
10961          isOk = 3;
10962          break;
10963
10964        case SQLITE_TESTCTRL_IMPOSTER:
10965          if( nArg==5 ){
10966            rc2 = sqlite3_test_control(testctrl, p->db,
10967                          azArg[2],
10968                          integerValue(azArg[3]),
10969                          integerValue(azArg[4]));
10970            isOk = 3;
10971          }
10972          break;
10973
10974        case SQLITE_TESTCTRL_SEEK_COUNT: {
10975          u64 x = 0;
10976          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10977          utf8_printf(p->out, "%llu\n", x);
10978          isOk = 3;
10979          break;
10980        }
10981
10982#ifdef YYCOVERAGE
10983        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10984          if( nArg==2 ){
10985            sqlite3_test_control(testctrl, p->out);
10986            isOk = 3;
10987          }
10988          break;
10989        }
10990#endif
10991#ifdef SQLITE_DEBUG
10992        case SQLITE_TESTCTRL_TUNE: {
10993          if( nArg==4 ){
10994            int id = (int)integerValue(azArg[2]);
10995            int val = (int)integerValue(azArg[3]);
10996            sqlite3_test_control(testctrl, id, &val);
10997            isOk = 3;
10998          }else if( nArg==3 ){
10999            int id = (int)integerValue(azArg[2]);
11000            sqlite3_test_control(testctrl, -id, &rc2);
11001            isOk = 1;
11002          }else if( nArg==2 ){
11003            int id = 1;
11004            while(1){
11005              int val = 0;
11006              rc2 = sqlite3_test_control(testctrl, -id, &val);
11007              if( rc2!=SQLITE_OK ) break;
11008              if( id>1 ) utf8_printf(p->out, "  ");
11009              utf8_printf(p->out, "%d: %d", id, val);
11010              id++;
11011            }
11012            if( id>1 ) utf8_printf(p->out, "\n");
11013            isOk = 3;
11014          }
11015          break;
11016        }
11017#endif
11018        case SQLITE_TESTCTRL_SORTER_MMAP:
11019          if( nArg==3 ){
11020            int opt = (unsigned int)integerValue(azArg[2]);
11021            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11022            isOk = 3;
11023          }
11024          break;
11025      }
11026    }
11027    if( isOk==0 && iCtrl>=0 ){
11028      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11029      rc = 1;
11030    }else if( isOk==1 ){
11031      raw_printf(p->out, "%d\n", rc2);
11032    }else if( isOk==2 ){
11033      raw_printf(p->out, "0x%08x\n", rc2);
11034    }
11035  }else
11036#endif /* !defined(SQLITE_UNTESTABLE) */
11037
11038  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11039    open_db(p, 0);
11040    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11041  }else
11042
11043  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11044    if( nArg==2 ){
11045      enableTimer = booleanValue(azArg[1]);
11046      if( enableTimer && !HAS_TIMER ){
11047        raw_printf(stderr, "Error: timer not available on this system.\n");
11048        enableTimer = 0;
11049      }
11050    }else{
11051      raw_printf(stderr, "Usage: .timer on|off\n");
11052      rc = 1;
11053    }
11054  }else
11055
11056#ifndef SQLITE_OMIT_TRACE
11057  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11058    int mType = 0;
11059    int jj;
11060    open_db(p, 0);
11061    for(jj=1; jj<nArg; jj++){
11062      const char *z = azArg[jj];
11063      if( z[0]=='-' ){
11064        if( optionMatch(z, "expanded") ){
11065          p->eTraceType = SHELL_TRACE_EXPANDED;
11066        }
11067#ifdef SQLITE_ENABLE_NORMALIZE
11068        else if( optionMatch(z, "normalized") ){
11069          p->eTraceType = SHELL_TRACE_NORMALIZED;
11070        }
11071#endif
11072        else if( optionMatch(z, "plain") ){
11073          p->eTraceType = SHELL_TRACE_PLAIN;
11074        }
11075        else if( optionMatch(z, "profile") ){
11076          mType |= SQLITE_TRACE_PROFILE;
11077        }
11078        else if( optionMatch(z, "row") ){
11079          mType |= SQLITE_TRACE_ROW;
11080        }
11081        else if( optionMatch(z, "stmt") ){
11082          mType |= SQLITE_TRACE_STMT;
11083        }
11084        else if( optionMatch(z, "close") ){
11085          mType |= SQLITE_TRACE_CLOSE;
11086        }
11087        else {
11088          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11089          rc = 1;
11090          goto meta_command_exit;
11091        }
11092      }else{
11093        output_file_close(p->traceOut);
11094        p->traceOut = output_file_open(azArg[1], 0);
11095      }
11096    }
11097    if( p->traceOut==0 ){
11098      sqlite3_trace_v2(p->db, 0, 0, 0);
11099    }else{
11100      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11101      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11102    }
11103  }else
11104#endif /* !defined(SQLITE_OMIT_TRACE) */
11105
11106#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11107  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11108    int ii;
11109    int lenOpt;
11110    char *zOpt;
11111    if( nArg<2 ){
11112      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11113      rc = 1;
11114      goto meta_command_exit;
11115    }
11116    open_db(p, 0);
11117    zOpt = azArg[1];
11118    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11119    lenOpt = (int)strlen(zOpt);
11120    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11121      assert( azArg[nArg]==0 );
11122      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11123    }else{
11124      for(ii=1; ii<nArg; ii++){
11125        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11126      }
11127    }
11128  }else
11129#endif
11130
11131#if SQLITE_USER_AUTHENTICATION
11132  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11133    if( nArg<2 ){
11134      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11135      rc = 1;
11136      goto meta_command_exit;
11137    }
11138    open_db(p, 0);
11139    if( strcmp(azArg[1],"login")==0 ){
11140      if( nArg!=4 ){
11141        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11142        rc = 1;
11143        goto meta_command_exit;
11144      }
11145      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11146                                     strlen30(azArg[3]));
11147      if( rc ){
11148        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11149        rc = 1;
11150      }
11151    }else if( strcmp(azArg[1],"add")==0 ){
11152      if( nArg!=5 ){
11153        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11154        rc = 1;
11155        goto meta_command_exit;
11156      }
11157      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11158                            booleanValue(azArg[4]));
11159      if( rc ){
11160        raw_printf(stderr, "User-Add failed: %d\n", rc);
11161        rc = 1;
11162      }
11163    }else if( strcmp(azArg[1],"edit")==0 ){
11164      if( nArg!=5 ){
11165        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11166        rc = 1;
11167        goto meta_command_exit;
11168      }
11169      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11170                              booleanValue(azArg[4]));
11171      if( rc ){
11172        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11173        rc = 1;
11174      }
11175    }else if( strcmp(azArg[1],"delete")==0 ){
11176      if( nArg!=3 ){
11177        raw_printf(stderr, "Usage: .user delete USER\n");
11178        rc = 1;
11179        goto meta_command_exit;
11180      }
11181      rc = sqlite3_user_delete(p->db, azArg[2]);
11182      if( rc ){
11183        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11184        rc = 1;
11185      }
11186    }else{
11187      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11188      rc = 1;
11189      goto meta_command_exit;
11190    }
11191  }else
11192#endif /* SQLITE_USER_AUTHENTICATION */
11193
11194  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11195    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11196        sqlite3_libversion(), sqlite3_sourceid());
11197#if SQLITE_HAVE_ZLIB
11198    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11199#endif
11200#define CTIMEOPT_VAL_(opt) #opt
11201#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11202#if defined(__clang__) && defined(__clang_major__)
11203    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11204                    CTIMEOPT_VAL(__clang_minor__) "."
11205                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11206#elif defined(_MSC_VER)
11207    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11208#elif defined(__GNUC__) && defined(__VERSION__)
11209    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11210#endif
11211  }else
11212
11213  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11214    const char *zDbName = nArg==2 ? azArg[1] : "main";
11215    sqlite3_vfs *pVfs = 0;
11216    if( p->db ){
11217      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11218      if( pVfs ){
11219        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11220        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11221        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11222        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11223      }
11224    }
11225  }else
11226
11227  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11228    sqlite3_vfs *pVfs;
11229    sqlite3_vfs *pCurrent = 0;
11230    if( p->db ){
11231      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11232    }
11233    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11234      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11235           pVfs==pCurrent ? "  <--- CURRENT" : "");
11236      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11237      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11238      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11239      if( pVfs->pNext ){
11240        raw_printf(p->out, "-----------------------------------\n");
11241      }
11242    }
11243  }else
11244
11245  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11246    const char *zDbName = nArg==2 ? azArg[1] : "main";
11247    char *zVfsName = 0;
11248    if( p->db ){
11249      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11250      if( zVfsName ){
11251        utf8_printf(p->out, "%s\n", zVfsName);
11252        sqlite3_free(zVfsName);
11253      }
11254    }
11255  }else
11256
11257  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11258    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11259    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11260  }else
11261
11262  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11263    int j;
11264    assert( nArg<=ArraySize(azArg) );
11265    p->nWidth = nArg-1;
11266    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11267    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11268    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11269    for(j=1; j<nArg; j++){
11270      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11271    }
11272  }else
11273
11274  {
11275    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11276      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11277    rc = 1;
11278  }
11279
11280meta_command_exit:
11281  if( p->outCount ){
11282    p->outCount--;
11283    if( p->outCount==0 ) output_reset(p);
11284  }
11285  p->bSafeMode = p->bSafeModePersist;
11286  return rc;
11287}
11288
11289/* Line scan result and intermediate states (supporting scan resumption)
11290*/
11291#ifndef CHAR_BIT
11292# define CHAR_BIT 8
11293#endif
11294typedef enum {
11295  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11296  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11297  QSS_Start = 0
11298} QuickScanState;
11299#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11300#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11301#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11302#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11303#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11304
11305/*
11306** Scan line for classification to guide shell's handling.
11307** The scan is resumable for subsequent lines when prior
11308** return values are passed as the 2nd argument.
11309*/
11310static QuickScanState quickscan(char *zLine, QuickScanState qss){
11311  char cin;
11312  char cWait = (char)qss; /* intentional narrowing loss */
11313  if( cWait==0 ){
11314  PlainScan:
11315    assert( cWait==0 );
11316    while( (cin = *zLine++)!=0 ){
11317      if( IsSpace(cin) )
11318        continue;
11319      switch (cin){
11320      case '-':
11321        if( *zLine!='-' )
11322          break;
11323        while((cin = *++zLine)!=0 )
11324          if( cin=='\n')
11325            goto PlainScan;
11326        return qss;
11327      case ';':
11328        qss |= QSS_EndingSemi;
11329        continue;
11330      case '/':
11331        if( *zLine=='*' ){
11332          ++zLine;
11333          cWait = '*';
11334          qss = QSS_SETV(qss, cWait);
11335          goto TermScan;
11336        }
11337        break;
11338      case '[':
11339        cin = ']';
11340        /* fall thru */
11341      case '`': case '\'': case '"':
11342        cWait = cin;
11343        qss = QSS_HasDark | cWait;
11344        goto TermScan;
11345      default:
11346        break;
11347      }
11348      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11349    }
11350  }else{
11351  TermScan:
11352    while( (cin = *zLine++)!=0 ){
11353      if( cin==cWait ){
11354        switch( cWait ){
11355        case '*':
11356          if( *zLine != '/' )
11357            continue;
11358          ++zLine;
11359          cWait = 0;
11360          qss = QSS_SETV(qss, 0);
11361          goto PlainScan;
11362        case '`': case '\'': case '"':
11363          if(*zLine==cWait){
11364            ++zLine;
11365            continue;
11366          }
11367          /* fall thru */
11368        case ']':
11369          cWait = 0;
11370          qss = QSS_SETV(qss, 0);
11371          goto PlainScan;
11372        default: assert(0);
11373        }
11374      }
11375    }
11376  }
11377  return qss;
11378}
11379
11380/*
11381** Return TRUE if the line typed in is an SQL command terminator other
11382** than a semi-colon.  The SQL Server style "go" command is understood
11383** as is the Oracle "/".
11384*/
11385static int line_is_command_terminator(char *zLine){
11386  while( IsSpace(zLine[0]) ){ zLine++; };
11387  if( zLine[0]=='/' )
11388    zLine += 1; /* Oracle */
11389  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11390    zLine += 2; /* SQL Server */
11391  else
11392    return 0;
11393  return quickscan(zLine,QSS_Start)==QSS_Start;
11394}
11395
11396/*
11397** We need a default sqlite3_complete() implementation to use in case
11398** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11399** any arbitrary text is a complete SQL statement.  This is not very
11400** user-friendly, but it does seem to work.
11401*/
11402#ifdef SQLITE_OMIT_COMPLETE
11403#define sqlite3_complete(x) 1
11404#endif
11405
11406/*
11407** Return true if zSql is a complete SQL statement.  Return false if it
11408** ends in the middle of a string literal or C-style comment.
11409*/
11410static int line_is_complete(char *zSql, int nSql){
11411  int rc;
11412  if( zSql==0 ) return 1;
11413  zSql[nSql] = ';';
11414  zSql[nSql+1] = 0;
11415  rc = sqlite3_complete(zSql);
11416  zSql[nSql] = 0;
11417  return rc;
11418}
11419
11420/*
11421** Run a single line of SQL.  Return the number of errors.
11422*/
11423static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11424  int rc;
11425  char *zErrMsg = 0;
11426
11427  open_db(p, 0);
11428  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11429  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11430  BEGIN_TIMER;
11431  rc = shell_exec(p, zSql, &zErrMsg);
11432  END_TIMER;
11433  if( rc || zErrMsg ){
11434    char zPrefix[100];
11435    const char *zErrorTail;
11436    const char *zErrorType;
11437    if( zErrMsg==0 ){
11438      zErrorType = "Error";
11439      zErrorTail = sqlite3_errmsg(p->db);
11440    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11441      zErrorType = "Parse error";
11442      zErrorTail = &zErrMsg[12];
11443    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11444      zErrorType = "Runtime error";
11445      zErrorTail = &zErrMsg[10];
11446    }else{
11447      zErrorType = "Error";
11448      zErrorTail = zErrMsg;
11449    }
11450    if( in!=0 || !stdin_is_interactive ){
11451      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11452                       "%s near line %d:", zErrorType, startline);
11453    }else{
11454      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11455    }
11456    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11457    sqlite3_free(zErrMsg);
11458    zErrMsg = 0;
11459    return 1;
11460  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11461    char zLineBuf[2000];
11462    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11463            "changes: %lld   total_changes: %lld",
11464            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11465    raw_printf(p->out, "%s\n", zLineBuf);
11466  }
11467  return 0;
11468}
11469
11470
11471/*
11472** Read input from *in and process it.  If *in==0 then input
11473** is interactive - the user is typing it it.  Otherwise, input
11474** is coming from a file or device.  A prompt is issued and history
11475** is saved only if input is interactive.  An interrupt signal will
11476** cause this routine to exit immediately, unless input is interactive.
11477**
11478** Return the number of errors.
11479*/
11480static int process_input(ShellState *p){
11481  char *zLine = 0;          /* A single input line */
11482  char *zSql = 0;           /* Accumulated SQL text */
11483  int nLine;                /* Length of current line */
11484  int nSql = 0;             /* Bytes of zSql[] used */
11485  int nAlloc = 0;           /* Allocated zSql[] space */
11486  int rc;                   /* Error code */
11487  int errCnt = 0;           /* Number of errors seen */
11488  int startline = 0;        /* Line number for start of current input */
11489  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11490
11491  if( p->inputNesting==MAX_INPUT_NESTING ){
11492    /* This will be more informative in a later version. */
11493    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11494                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11495    return 1;
11496  }
11497  ++p->inputNesting;
11498  p->lineno = 0;
11499  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11500    fflush(p->out);
11501    zLine = one_input_line(p->in, zLine, nSql>0);
11502    if( zLine==0 ){
11503      /* End of input */
11504      if( p->in==0 && stdin_is_interactive ) printf("\n");
11505      break;
11506    }
11507    if( seenInterrupt ){
11508      if( p->in!=0 ) break;
11509      seenInterrupt = 0;
11510    }
11511    p->lineno++;
11512    if( QSS_INPLAIN(qss)
11513        && line_is_command_terminator(zLine)
11514        && line_is_complete(zSql, nSql) ){
11515      memcpy(zLine,";",2);
11516    }
11517    qss = quickscan(zLine, qss);
11518    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11519      if( ShellHasFlag(p, SHFLG_Echo) )
11520        printf("%s\n", zLine);
11521      /* Just swallow single-line whitespace */
11522      qss = QSS_Start;
11523      continue;
11524    }
11525    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11526      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
11527      if( zLine[0]=='.' ){
11528        rc = do_meta_command(zLine, p);
11529        if( rc==2 ){ /* exit requested */
11530          break;
11531        }else if( rc ){
11532          errCnt++;
11533        }
11534      }
11535      qss = QSS_Start;
11536      continue;
11537    }
11538    /* No single-line dispositions remain; accumulate line(s). */
11539    nLine = strlen30(zLine);
11540    if( nSql+nLine+2>=nAlloc ){
11541      /* Grow buffer by half-again increments when big. */
11542      nAlloc = nSql+(nSql>>1)+nLine+100;
11543      zSql = realloc(zSql, nAlloc);
11544      shell_check_oom(zSql);
11545    }
11546    if( nSql==0 ){
11547      int i;
11548      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11549      assert( nAlloc>0 && zSql!=0 );
11550      memcpy(zSql, zLine+i, nLine+1-i);
11551      startline = p->lineno;
11552      nSql = nLine-i;
11553    }else{
11554      zSql[nSql++] = '\n';
11555      memcpy(zSql+nSql, zLine, nLine+1);
11556      nSql += nLine;
11557    }
11558    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11559      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11560      nSql = 0;
11561      if( p->outCount ){
11562        output_reset(p);
11563        p->outCount = 0;
11564      }else{
11565        clearTempFile(p);
11566      }
11567      p->bSafeMode = p->bSafeModePersist;
11568      qss = QSS_Start;
11569    }else if( nSql && QSS_PLAINWHITE(qss) ){
11570      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
11571      nSql = 0;
11572      qss = QSS_Start;
11573    }
11574  }
11575  if( nSql ){
11576    /* This may be incomplete. Let the SQL parser deal with that. */
11577    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11578  }
11579  free(zSql);
11580  free(zLine);
11581  --p->inputNesting;
11582  return errCnt>0;
11583}
11584
11585/*
11586** Return a pathname which is the user's home directory.  A
11587** 0 return indicates an error of some kind.
11588*/
11589static char *find_home_dir(int clearFlag){
11590  static char *home_dir = NULL;
11591  if( clearFlag ){
11592    free(home_dir);
11593    home_dir = 0;
11594    return 0;
11595  }
11596  if( home_dir ) return home_dir;
11597
11598#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11599     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11600  {
11601    struct passwd *pwent;
11602    uid_t uid = getuid();
11603    if( (pwent=getpwuid(uid)) != NULL) {
11604      home_dir = pwent->pw_dir;
11605    }
11606  }
11607#endif
11608
11609#if defined(_WIN32_WCE)
11610  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11611   */
11612  home_dir = "/";
11613#else
11614
11615#if defined(_WIN32) || defined(WIN32)
11616  if (!home_dir) {
11617    home_dir = getenv("USERPROFILE");
11618  }
11619#endif
11620
11621  if (!home_dir) {
11622    home_dir = getenv("HOME");
11623  }
11624
11625#if defined(_WIN32) || defined(WIN32)
11626  if (!home_dir) {
11627    char *zDrive, *zPath;
11628    int n;
11629    zDrive = getenv("HOMEDRIVE");
11630    zPath = getenv("HOMEPATH");
11631    if( zDrive && zPath ){
11632      n = strlen30(zDrive) + strlen30(zPath) + 1;
11633      home_dir = malloc( n );
11634      if( home_dir==0 ) return 0;
11635      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11636      return home_dir;
11637    }
11638    home_dir = "c:\\";
11639  }
11640#endif
11641
11642#endif /* !_WIN32_WCE */
11643
11644  if( home_dir ){
11645    int n = strlen30(home_dir) + 1;
11646    char *z = malloc( n );
11647    if( z ) memcpy(z, home_dir, n);
11648    home_dir = z;
11649  }
11650
11651  return home_dir;
11652}
11653
11654/*
11655** Read input from the file given by sqliterc_override.  Or if that
11656** parameter is NULL, take input from ~/.sqliterc
11657**
11658** Returns the number of errors.
11659*/
11660static void process_sqliterc(
11661  ShellState *p,                  /* Configuration data */
11662  const char *sqliterc_override   /* Name of config file. NULL to use default */
11663){
11664  char *home_dir = NULL;
11665  const char *sqliterc = sqliterc_override;
11666  char *zBuf = 0;
11667  FILE *inSaved = p->in;
11668  int savedLineno = p->lineno;
11669
11670  if (sqliterc == NULL) {
11671    home_dir = find_home_dir(0);
11672    if( home_dir==0 ){
11673      raw_printf(stderr, "-- warning: cannot find home directory;"
11674                      " cannot read ~/.sqliterc\n");
11675      return;
11676    }
11677    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11678    shell_check_oom(zBuf);
11679    sqliterc = zBuf;
11680  }
11681  p->in = fopen(sqliterc,"rb");
11682  if( p->in ){
11683    if( stdin_is_interactive ){
11684      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11685    }
11686    if( process_input(p) && bail_on_error ) exit(1);
11687    fclose(p->in);
11688  }else if( sqliterc_override!=0 ){
11689    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11690    if( bail_on_error ) exit(1);
11691  }
11692  p->in = inSaved;
11693  p->lineno = savedLineno;
11694  sqlite3_free(zBuf);
11695}
11696
11697/*
11698** Show available command line options
11699*/
11700static const char zOptions[] =
11701#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11702  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11703#endif
11704  "   -append              append the database to the end of the file\n"
11705  "   -ascii               set output mode to 'ascii'\n"
11706  "   -bail                stop after hitting an error\n"
11707  "   -batch               force batch I/O\n"
11708  "   -box                 set output mode to 'box'\n"
11709  "   -column              set output mode to 'column'\n"
11710  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11711  "   -csv                 set output mode to 'csv'\n"
11712#if !defined(SQLITE_OMIT_DESERIALIZE)
11713  "   -deserialize         open the database using sqlite3_deserialize()\n"
11714#endif
11715  "   -echo                print commands before execution\n"
11716  "   -init FILENAME       read/process named file\n"
11717  "   -[no]header          turn headers on or off\n"
11718#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11719  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11720#endif
11721  "   -help                show this message\n"
11722  "   -html                set output mode to HTML\n"
11723  "   -interactive         force interactive I/O\n"
11724  "   -json                set output mode to 'json'\n"
11725  "   -line                set output mode to 'line'\n"
11726  "   -list                set output mode to 'list'\n"
11727  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11728  "   -markdown            set output mode to 'markdown'\n"
11729#if !defined(SQLITE_OMIT_DESERIALIZE)
11730  "   -maxsize N           maximum size for a --deserialize database\n"
11731#endif
11732  "   -memtrace            trace all memory allocations and deallocations\n"
11733  "   -mmap N              default mmap size set to N\n"
11734#ifdef SQLITE_ENABLE_MULTIPLEX
11735  "   -multiplex           enable the multiplexor VFS\n"
11736#endif
11737  "   -newline SEP         set output row separator. Default: '\\n'\n"
11738  "   -nofollow            refuse to open symbolic links to database files\n"
11739  "   -nonce STRING        set the safe-mode escape nonce\n"
11740  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11741  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11742  "   -quote               set output mode to 'quote'\n"
11743  "   -readonly            open the database read-only\n"
11744  "   -safe                enable safe-mode\n"
11745  "   -separator SEP       set output column separator. Default: '|'\n"
11746#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11747  "   -sorterref SIZE      sorter references threshold size\n"
11748#endif
11749  "   -stats               print memory stats before each finalize\n"
11750  "   -table               set output mode to 'table'\n"
11751  "   -tabs                set output mode to 'tabs'\n"
11752  "   -version             show SQLite version\n"
11753  "   -vfs NAME            use NAME as the default VFS\n"
11754#ifdef SQLITE_ENABLE_VFSTRACE
11755  "   -vfstrace            enable tracing of all VFS calls\n"
11756#endif
11757#ifdef SQLITE_HAVE_ZLIB
11758  "   -zip                 open the file as a ZIP Archive\n"
11759#endif
11760;
11761static void usage(int showDetail){
11762  utf8_printf(stderr,
11763      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11764      "FILENAME is the name of an SQLite database. A new database is created\n"
11765      "if the file does not previously exist.\n", Argv0);
11766  if( showDetail ){
11767    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11768  }else{
11769    raw_printf(stderr, "Use the -help option for additional information\n");
11770  }
11771  exit(1);
11772}
11773
11774/*
11775** Internal check:  Verify that the SQLite is uninitialized.  Print a
11776** error message if it is initialized.
11777*/
11778static void verify_uninitialized(void){
11779  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11780    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11781                        " initialization.\n");
11782  }
11783}
11784
11785/*
11786** Initialize the state information in data
11787*/
11788static void main_init(ShellState *data) {
11789  memset(data, 0, sizeof(*data));
11790  data->normalMode = data->cMode = data->mode = MODE_List;
11791  data->autoExplain = 1;
11792  data->pAuxDb = &data->aAuxDb[0];
11793  memcpy(data->colSeparator,SEP_Column, 2);
11794  memcpy(data->rowSeparator,SEP_Row, 2);
11795  data->showHeader = 0;
11796  data->shellFlgs = SHFLG_Lookaside;
11797  verify_uninitialized();
11798  sqlite3_config(SQLITE_CONFIG_URI, 1);
11799  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11800  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11801  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11802  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11803}
11804
11805/*
11806** Output text to the console in a font that attracts extra attention.
11807*/
11808#ifdef _WIN32
11809static void printBold(const char *zText){
11810#if !SQLITE_OS_WINRT
11811  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11812  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11813  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11814  SetConsoleTextAttribute(out,
11815         FOREGROUND_RED|FOREGROUND_INTENSITY
11816  );
11817#endif
11818  printf("%s", zText);
11819#if !SQLITE_OS_WINRT
11820  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11821#endif
11822}
11823#else
11824static void printBold(const char *zText){
11825  printf("\033[1m%s\033[0m", zText);
11826}
11827#endif
11828
11829/*
11830** Get the argument to an --option.  Throw an error and die if no argument
11831** is available.
11832*/
11833static char *cmdline_option_value(int argc, char **argv, int i){
11834  if( i==argc ){
11835    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11836            argv[0], argv[argc-1]);
11837    exit(1);
11838  }
11839  return argv[i];
11840}
11841
11842#ifndef SQLITE_SHELL_IS_UTF8
11843#  if (defined(_WIN32) || defined(WIN32)) \
11844   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11845#    define SQLITE_SHELL_IS_UTF8          (0)
11846#  else
11847#    define SQLITE_SHELL_IS_UTF8          (1)
11848#  endif
11849#endif
11850
11851#if SQLITE_SHELL_IS_UTF8
11852int SQLITE_CDECL main(int argc, char **argv){
11853#else
11854int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11855  char **argv;
11856#endif
11857  char *zErrMsg = 0;
11858  ShellState data;
11859  const char *zInitFile = 0;
11860  int i;
11861  int rc = 0;
11862  int warnInmemoryDb = 0;
11863  int readStdin = 1;
11864  int nCmd = 0;
11865  char **azCmd = 0;
11866  const char *zVfs = 0;           /* Value of -vfs command-line option */
11867#if !SQLITE_SHELL_IS_UTF8
11868  char **argvToFree = 0;
11869  int argcToFree = 0;
11870#endif
11871
11872  setBinaryMode(stdin, 0);
11873  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11874  stdin_is_interactive = isatty(0);
11875  stdout_is_console = isatty(1);
11876
11877#if !defined(_WIN32_WCE)
11878  if( getenv("SQLITE_DEBUG_BREAK") ){
11879    if( isatty(0) && isatty(2) ){
11880      fprintf(stderr,
11881          "attach debugger to process %d and press any key to continue.\n",
11882          GETPID());
11883      fgetc(stdin);
11884    }else{
11885#if defined(_WIN32) || defined(WIN32)
11886#if SQLITE_OS_WINRT
11887      __debugbreak();
11888#else
11889      DebugBreak();
11890#endif
11891#elif defined(SIGTRAP)
11892      raise(SIGTRAP);
11893#endif
11894    }
11895  }
11896#endif
11897
11898#if USE_SYSTEM_SQLITE+0!=1
11899  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11900    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11901            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11902    exit(1);
11903  }
11904#endif
11905  main_init(&data);
11906
11907  /* On Windows, we must translate command-line arguments into UTF-8.
11908  ** The SQLite memory allocator subsystem has to be enabled in order to
11909  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11910  ** subsequent sqlite3_config() calls will work.  So copy all results into
11911  ** memory that does not come from the SQLite memory allocator.
11912  */
11913#if !SQLITE_SHELL_IS_UTF8
11914  sqlite3_initialize();
11915  argvToFree = malloc(sizeof(argv[0])*argc*2);
11916  shell_check_oom(argvToFree);
11917  argcToFree = argc;
11918  argv = argvToFree + argc;
11919  for(i=0; i<argc; i++){
11920    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11921    int n;
11922    shell_check_oom(z);
11923    n = (int)strlen(z);
11924    argv[i] = malloc( n+1 );
11925    shell_check_oom(argv[i]);
11926    memcpy(argv[i], z, n+1);
11927    argvToFree[i] = argv[i];
11928    sqlite3_free(z);
11929  }
11930  sqlite3_shutdown();
11931#endif
11932
11933  assert( argc>=1 && argv && argv[0] );
11934  Argv0 = argv[0];
11935
11936  /* Make sure we have a valid signal handler early, before anything
11937  ** else is done.
11938  */
11939#ifdef SIGINT
11940  signal(SIGINT, interrupt_handler);
11941#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11942  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11943#endif
11944
11945#ifdef SQLITE_SHELL_DBNAME_PROC
11946  {
11947    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11948    ** of a C-function that will provide the name of the database file.  Use
11949    ** this compile-time option to embed this shell program in larger
11950    ** applications. */
11951    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11952    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11953    warnInmemoryDb = 0;
11954  }
11955#endif
11956
11957  /* Do an initial pass through the command-line argument to locate
11958  ** the name of the database file, the name of the initialization file,
11959  ** the size of the alternative malloc heap,
11960  ** and the first command to execute.
11961  */
11962  verify_uninitialized();
11963  for(i=1; i<argc; i++){
11964    char *z;
11965    z = argv[i];
11966    if( z[0]!='-' ){
11967      if( data.aAuxDb->zDbFilename==0 ){
11968        data.aAuxDb->zDbFilename = z;
11969      }else{
11970        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11971        ** mean that nothing is read from stdin */
11972        readStdin = 0;
11973        nCmd++;
11974        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11975        shell_check_oom(azCmd);
11976        azCmd[nCmd-1] = z;
11977      }
11978    }
11979    if( z[1]=='-' ) z++;
11980    if( strcmp(z,"-separator")==0
11981     || strcmp(z,"-nullvalue")==0
11982     || strcmp(z,"-newline")==0
11983     || strcmp(z,"-cmd")==0
11984    ){
11985      (void)cmdline_option_value(argc, argv, ++i);
11986    }else if( strcmp(z,"-init")==0 ){
11987      zInitFile = cmdline_option_value(argc, argv, ++i);
11988    }else if( strcmp(z,"-batch")==0 ){
11989      /* Need to check for batch mode here to so we can avoid printing
11990      ** informational messages (like from process_sqliterc) before
11991      ** we do the actual processing of arguments later in a second pass.
11992      */
11993      stdin_is_interactive = 0;
11994    }else if( strcmp(z,"-heap")==0 ){
11995#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11996      const char *zSize;
11997      sqlite3_int64 szHeap;
11998
11999      zSize = cmdline_option_value(argc, argv, ++i);
12000      szHeap = integerValue(zSize);
12001      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12002      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12003#else
12004      (void)cmdline_option_value(argc, argv, ++i);
12005#endif
12006    }else if( strcmp(z,"-pagecache")==0 ){
12007      sqlite3_int64 n, sz;
12008      sz = integerValue(cmdline_option_value(argc,argv,++i));
12009      if( sz>70000 ) sz = 70000;
12010      if( sz<0 ) sz = 0;
12011      n = integerValue(cmdline_option_value(argc,argv,++i));
12012      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12013        n = 0xffffffffffffLL/sz;
12014      }
12015      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12016                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12017      data.shellFlgs |= SHFLG_Pagecache;
12018    }else if( strcmp(z,"-lookaside")==0 ){
12019      int n, sz;
12020      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12021      if( sz<0 ) sz = 0;
12022      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12023      if( n<0 ) n = 0;
12024      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12025      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12026    }else if( strcmp(z,"-threadsafe")==0 ){
12027      int n;
12028      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12029      switch( n ){
12030         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12031         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12032         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12033      }
12034#ifdef SQLITE_ENABLE_VFSTRACE
12035    }else if( strcmp(z,"-vfstrace")==0 ){
12036      extern int vfstrace_register(
12037         const char *zTraceName,
12038         const char *zOldVfsName,
12039         int (*xOut)(const char*,void*),
12040         void *pOutArg,
12041         int makeDefault
12042      );
12043      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12044#endif
12045#ifdef SQLITE_ENABLE_MULTIPLEX
12046    }else if( strcmp(z,"-multiplex")==0 ){
12047      extern int sqlite3_multiple_initialize(const char*,int);
12048      sqlite3_multiplex_initialize(0, 1);
12049#endif
12050    }else if( strcmp(z,"-mmap")==0 ){
12051      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12052      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12053#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12054    }else if( strcmp(z,"-sorterref")==0 ){
12055      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12056      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12057#endif
12058    }else if( strcmp(z,"-vfs")==0 ){
12059      zVfs = cmdline_option_value(argc, argv, ++i);
12060#ifdef SQLITE_HAVE_ZLIB
12061    }else if( strcmp(z,"-zip")==0 ){
12062      data.openMode = SHELL_OPEN_ZIPFILE;
12063#endif
12064    }else if( strcmp(z,"-append")==0 ){
12065      data.openMode = SHELL_OPEN_APPENDVFS;
12066#ifndef SQLITE_OMIT_DESERIALIZE
12067    }else if( strcmp(z,"-deserialize")==0 ){
12068      data.openMode = SHELL_OPEN_DESERIALIZE;
12069    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12070      data.szMax = integerValue(argv[++i]);
12071#endif
12072    }else if( strcmp(z,"-readonly")==0 ){
12073      data.openMode = SHELL_OPEN_READONLY;
12074    }else if( strcmp(z,"-nofollow")==0 ){
12075      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12076#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12077    }else if( strncmp(z, "-A",2)==0 ){
12078      /* All remaining command-line arguments are passed to the ".archive"
12079      ** command, so ignore them */
12080      break;
12081#endif
12082    }else if( strcmp(z, "-memtrace")==0 ){
12083      sqlite3MemTraceActivate(stderr);
12084    }else if( strcmp(z,"-bail")==0 ){
12085      bail_on_error = 1;
12086    }else if( strcmp(z,"-nonce")==0 ){
12087      free(data.zNonce);
12088      data.zNonce = strdup(argv[++i]);
12089    }else if( strcmp(z,"-safe")==0 ){
12090      /* no-op - catch this on the second pass */
12091    }
12092  }
12093  verify_uninitialized();
12094
12095
12096#ifdef SQLITE_SHELL_INIT_PROC
12097  {
12098    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12099    ** of a C-function that will perform initialization actions on SQLite that
12100    ** occur just before or after sqlite3_initialize(). Use this compile-time
12101    ** option to embed this shell program in larger applications. */
12102    extern void SQLITE_SHELL_INIT_PROC(void);
12103    SQLITE_SHELL_INIT_PROC();
12104  }
12105#else
12106  /* All the sqlite3_config() calls have now been made. So it is safe
12107  ** to call sqlite3_initialize() and process any command line -vfs option. */
12108  sqlite3_initialize();
12109#endif
12110
12111  if( zVfs ){
12112    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12113    if( pVfs ){
12114      sqlite3_vfs_register(pVfs, 1);
12115    }else{
12116      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12117      exit(1);
12118    }
12119  }
12120
12121  if( data.pAuxDb->zDbFilename==0 ){
12122#ifndef SQLITE_OMIT_MEMORYDB
12123    data.pAuxDb->zDbFilename = ":memory:";
12124    warnInmemoryDb = argc==1;
12125#else
12126    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12127    return 1;
12128#endif
12129  }
12130  data.out = stdout;
12131  sqlite3_appendvfs_init(0,0,0);
12132
12133  /* Go ahead and open the database file if it already exists.  If the
12134  ** file does not exist, delay opening it.  This prevents empty database
12135  ** files from being created if a user mistypes the database name argument
12136  ** to the sqlite command-line tool.
12137  */
12138  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12139    open_db(&data, 0);
12140  }
12141
12142  /* Process the initialization file if there is one.  If no -init option
12143  ** is given on the command line, look for a file named ~/.sqliterc and
12144  ** try to process it.
12145  */
12146  process_sqliterc(&data,zInitFile);
12147
12148  /* Make a second pass through the command-line argument and set
12149  ** options.  This second pass is delayed until after the initialization
12150  ** file is processed so that the command-line arguments will override
12151  ** settings in the initialization file.
12152  */
12153  for(i=1; i<argc; i++){
12154    char *z = argv[i];
12155    if( z[0]!='-' ) continue;
12156    if( z[1]=='-' ){ z++; }
12157    if( strcmp(z,"-init")==0 ){
12158      i++;
12159    }else if( strcmp(z,"-html")==0 ){
12160      data.mode = MODE_Html;
12161    }else if( strcmp(z,"-list")==0 ){
12162      data.mode = MODE_List;
12163    }else if( strcmp(z,"-quote")==0 ){
12164      data.mode = MODE_Quote;
12165      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12166      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12167    }else if( strcmp(z,"-line")==0 ){
12168      data.mode = MODE_Line;
12169    }else if( strcmp(z,"-column")==0 ){
12170      data.mode = MODE_Column;
12171    }else if( strcmp(z,"-json")==0 ){
12172      data.mode = MODE_Json;
12173    }else if( strcmp(z,"-markdown")==0 ){
12174      data.mode = MODE_Markdown;
12175    }else if( strcmp(z,"-table")==0 ){
12176      data.mode = MODE_Table;
12177    }else if( strcmp(z,"-box")==0 ){
12178      data.mode = MODE_Box;
12179    }else if( strcmp(z,"-csv")==0 ){
12180      data.mode = MODE_Csv;
12181      memcpy(data.colSeparator,",",2);
12182#ifdef SQLITE_HAVE_ZLIB
12183    }else if( strcmp(z,"-zip")==0 ){
12184      data.openMode = SHELL_OPEN_ZIPFILE;
12185#endif
12186    }else if( strcmp(z,"-append")==0 ){
12187      data.openMode = SHELL_OPEN_APPENDVFS;
12188#ifndef SQLITE_OMIT_DESERIALIZE
12189    }else if( strcmp(z,"-deserialize")==0 ){
12190      data.openMode = SHELL_OPEN_DESERIALIZE;
12191    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12192      data.szMax = integerValue(argv[++i]);
12193#endif
12194    }else if( strcmp(z,"-readonly")==0 ){
12195      data.openMode = SHELL_OPEN_READONLY;
12196    }else if( strcmp(z,"-nofollow")==0 ){
12197      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12198    }else if( strcmp(z,"-ascii")==0 ){
12199      data.mode = MODE_Ascii;
12200      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12201      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12202    }else if( strcmp(z,"-tabs")==0 ){
12203      data.mode = MODE_List;
12204      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12205      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12206    }else if( strcmp(z,"-separator")==0 ){
12207      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12208                       "%s",cmdline_option_value(argc,argv,++i));
12209    }else if( strcmp(z,"-newline")==0 ){
12210      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12211                       "%s",cmdline_option_value(argc,argv,++i));
12212    }else if( strcmp(z,"-nullvalue")==0 ){
12213      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12214                       "%s",cmdline_option_value(argc,argv,++i));
12215    }else if( strcmp(z,"-header")==0 ){
12216      data.showHeader = 1;
12217      ShellSetFlag(&data, SHFLG_HeaderSet);
12218     }else if( strcmp(z,"-noheader")==0 ){
12219      data.showHeader = 0;
12220      ShellSetFlag(&data, SHFLG_HeaderSet);
12221    }else if( strcmp(z,"-echo")==0 ){
12222      ShellSetFlag(&data, SHFLG_Echo);
12223    }else if( strcmp(z,"-eqp")==0 ){
12224      data.autoEQP = AUTOEQP_on;
12225    }else if( strcmp(z,"-eqpfull")==0 ){
12226      data.autoEQP = AUTOEQP_full;
12227    }else if( strcmp(z,"-stats")==0 ){
12228      data.statsOn = 1;
12229    }else if( strcmp(z,"-scanstats")==0 ){
12230      data.scanstatsOn = 1;
12231    }else if( strcmp(z,"-backslash")==0 ){
12232      /* Undocumented command-line option: -backslash
12233      ** Causes C-style backslash escapes to be evaluated in SQL statements
12234      ** prior to sending the SQL into SQLite.  Useful for injecting
12235      ** crazy bytes in the middle of SQL statements for testing and debugging.
12236      */
12237      ShellSetFlag(&data, SHFLG_Backslash);
12238    }else if( strcmp(z,"-bail")==0 ){
12239      /* No-op.  The bail_on_error flag should already be set. */
12240    }else if( strcmp(z,"-version")==0 ){
12241      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12242      return 0;
12243    }else if( strcmp(z,"-interactive")==0 ){
12244      stdin_is_interactive = 1;
12245    }else if( strcmp(z,"-batch")==0 ){
12246      stdin_is_interactive = 0;
12247    }else if( strcmp(z,"-heap")==0 ){
12248      i++;
12249    }else if( strcmp(z,"-pagecache")==0 ){
12250      i+=2;
12251    }else if( strcmp(z,"-lookaside")==0 ){
12252      i+=2;
12253    }else if( strcmp(z,"-threadsafe")==0 ){
12254      i+=2;
12255    }else if( strcmp(z,"-nonce")==0 ){
12256      i += 2;
12257    }else if( strcmp(z,"-mmap")==0 ){
12258      i++;
12259    }else if( strcmp(z,"-memtrace")==0 ){
12260      i++;
12261#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12262    }else if( strcmp(z,"-sorterref")==0 ){
12263      i++;
12264#endif
12265    }else if( strcmp(z,"-vfs")==0 ){
12266      i++;
12267#ifdef SQLITE_ENABLE_VFSTRACE
12268    }else if( strcmp(z,"-vfstrace")==0 ){
12269      i++;
12270#endif
12271#ifdef SQLITE_ENABLE_MULTIPLEX
12272    }else if( strcmp(z,"-multiplex")==0 ){
12273      i++;
12274#endif
12275    }else if( strcmp(z,"-help")==0 ){
12276      usage(1);
12277    }else if( strcmp(z,"-cmd")==0 ){
12278      /* Run commands that follow -cmd first and separately from commands
12279      ** that simply appear on the command-line.  This seems goofy.  It would
12280      ** be better if all commands ran in the order that they appear.  But
12281      ** we retain the goofy behavior for historical compatibility. */
12282      if( i==argc-1 ) break;
12283      z = cmdline_option_value(argc,argv,++i);
12284      if( z[0]=='.' ){
12285        rc = do_meta_command(z, &data);
12286        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12287      }else{
12288        open_db(&data, 0);
12289        rc = shell_exec(&data, z, &zErrMsg);
12290        if( zErrMsg!=0 ){
12291          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12292          if( bail_on_error ) return rc!=0 ? rc : 1;
12293        }else if( rc!=0 ){
12294          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12295          if( bail_on_error ) return rc;
12296        }
12297      }
12298#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12299    }else if( strncmp(z, "-A", 2)==0 ){
12300      if( nCmd>0 ){
12301        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12302                            " with \"%s\"\n", z);
12303        return 1;
12304      }
12305      open_db(&data, OPEN_DB_ZIPFILE);
12306      if( z[2] ){
12307        argv[i] = &z[2];
12308        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12309      }else{
12310        arDotCommand(&data, 1, argv+i, argc-i);
12311      }
12312      readStdin = 0;
12313      break;
12314#endif
12315    }else if( strcmp(z,"-safe")==0 ){
12316      data.bSafeMode = data.bSafeModePersist = 1;
12317    }else{
12318      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12319      raw_printf(stderr,"Use -help for a list of options.\n");
12320      return 1;
12321    }
12322    data.cMode = data.mode;
12323  }
12324
12325  if( !readStdin ){
12326    /* Run all arguments that do not begin with '-' as if they were separate
12327    ** command-line inputs, except for the argToSkip argument which contains
12328    ** the database filename.
12329    */
12330    for(i=0; i<nCmd; i++){
12331      if( azCmd[i][0]=='.' ){
12332        rc = do_meta_command(azCmd[i], &data);
12333        if( rc ){
12334          free(azCmd);
12335          return rc==2 ? 0 : rc;
12336        }
12337      }else{
12338        open_db(&data, 0);
12339        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12340        if( zErrMsg || rc ){
12341          if( zErrMsg!=0 ){
12342            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12343          }else{
12344            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12345          }
12346          sqlite3_free(zErrMsg);
12347          free(azCmd);
12348          return rc!=0 ? rc : 1;
12349        }
12350      }
12351    }
12352  }else{
12353    /* Run commands received from standard input
12354    */
12355    if( stdin_is_interactive ){
12356      char *zHome;
12357      char *zHistory;
12358      int nHistory;
12359      printf(
12360        "SQLite version %s %.19s\n" /*extra-version-info*/
12361        "Enter \".help\" for usage hints.\n",
12362        sqlite3_libversion(), sqlite3_sourceid()
12363      );
12364      if( warnInmemoryDb ){
12365        printf("Connected to a ");
12366        printBold("transient in-memory database");
12367        printf(".\nUse \".open FILENAME\" to reopen on a "
12368               "persistent database.\n");
12369      }
12370      zHistory = getenv("SQLITE_HISTORY");
12371      if( zHistory ){
12372        zHistory = strdup(zHistory);
12373      }else if( (zHome = find_home_dir(0))!=0 ){
12374        nHistory = strlen30(zHome) + 20;
12375        if( (zHistory = malloc(nHistory))!=0 ){
12376          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12377        }
12378      }
12379      if( zHistory ){ shell_read_history(zHistory); }
12380#if HAVE_READLINE || HAVE_EDITLINE
12381      rl_attempted_completion_function = readline_completion;
12382#elif HAVE_LINENOISE
12383      linenoiseSetCompletionCallback(linenoise_completion);
12384#endif
12385      data.in = 0;
12386      rc = process_input(&data);
12387      if( zHistory ){
12388        shell_stifle_history(2000);
12389        shell_write_history(zHistory);
12390        free(zHistory);
12391      }
12392    }else{
12393      data.in = stdin;
12394      rc = process_input(&data);
12395    }
12396  }
12397  free(azCmd);
12398  set_table_name(&data, 0);
12399  if( data.db ){
12400    session_close_all(&data, -1);
12401    close_db(data.db);
12402  }
12403  for(i=0; i<ArraySize(data.aAuxDb); i++){
12404    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12405    if( data.aAuxDb[i].db ){
12406      session_close_all(&data, i);
12407      close_db(data.aAuxDb[i].db);
12408    }
12409  }
12410  find_home_dir(1);
12411  output_reset(&data);
12412  data.doXdgOpen = 0;
12413  clearTempFile(&data);
12414#if !SQLITE_SHELL_IS_UTF8
12415  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12416  free(argvToFree);
12417#endif
12418  free(data.colWidth);
12419  free(data.zNonce);
12420  /* Clear the global data structure so that valgrind will detect memory
12421  ** leaks */
12422  memset(&data, 0, sizeof(data));
12423  return rc;
12424}
12425