xref: /sqlite-3.40.0/src/shell.c.in (revision de7a820f)
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  const char *zEmpty = "";
3354  const char *zShowNull = p->nullValue;
3355
3356  rc = sqlite3_step(pStmt);
3357  if( rc!=SQLITE_ROW ) return;
3358  nColumn = sqlite3_column_count(pStmt);
3359  nAlloc = nColumn*4;
3360  if( nAlloc<=0 ) nAlloc = 1;
3361  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3362  shell_check_oom(azData);
3363  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3364  shell_check_oom((void*)azNextLine);
3365  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3366  if( p->cmOpts.bQuote ){
3367    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3368    shell_check_oom(azQuoted);
3369    memset(azQuoted, 0, nColumn*sizeof(char*) );
3370  }
3371  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3372  shell_check_oom(abRowDiv);
3373  if( nColumn>p->nWidth ){
3374    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3375    shell_check_oom(p->colWidth);
3376    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3377    p->nWidth = nColumn;
3378    p->actualWidth = &p->colWidth[nColumn];
3379  }
3380  memset(p->actualWidth, 0, nColumn*sizeof(int));
3381  for(i=0; i<nColumn; i++){
3382    w = p->colWidth[i];
3383    if( w<0 ) w = -w;
3384    p->actualWidth[i] = w;
3385  }
3386  for(i=0; i<nColumn; i++){
3387    const unsigned char *zNotUsed;
3388    int wx = p->colWidth[i];
3389    if( wx==0 ){
3390      wx = p->cmOpts.iWrap;
3391    }
3392    if( wx<0 ) wx = -wx;
3393    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3394    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3395  }
3396  do{
3397    int useNextLine = bNextLine;
3398    bNextLine = 0;
3399    if( (nRow+2)*nColumn >= nAlloc ){
3400      nAlloc *= 2;
3401      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3402      shell_check_oom(azData);
3403      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3404      shell_check_oom(abRowDiv);
3405    }
3406    abRowDiv[nRow] = 1;
3407    nRow++;
3408    for(i=0; i<nColumn; i++){
3409      int wx = p->colWidth[i];
3410      if( wx==0 ){
3411        wx = p->cmOpts.iWrap;
3412      }
3413      if( wx<0 ) wx = -wx;
3414      if( useNextLine ){
3415        uz = azNextLine[i];
3416        if( uz==0 ) uz = (u8*)zEmpty;
3417      }else if( p->cmOpts.bQuote ){
3418        sqlite3_free(azQuoted[i]);
3419        azQuoted[i] = quoted_column(pStmt,i);
3420        uz = (const unsigned char*)azQuoted[i];
3421      }else{
3422        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3423        if( uz==0 ) uz = (u8*)zShowNull;
3424      }
3425      azData[nRow*nColumn + i]
3426        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3427      if( azNextLine[i] ){
3428        bNextLine = 1;
3429        abRowDiv[nRow-1] = 0;
3430        bMultiLineRowExists = 1;
3431      }
3432    }
3433  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3434  nTotal = nColumn*(nRow+1);
3435  for(i=0; i<nTotal; i++){
3436    z = azData[i];
3437    if( z==0 ) z = (char*)zEmpty;
3438    n = strlenChar(z);
3439    j = i%nColumn;
3440    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3441  }
3442  if( seenInterrupt ) goto columnar_end;
3443  if( nColumn==0 ) goto columnar_end;
3444  switch( p->cMode ){
3445    case MODE_Column: {
3446      colSep = "  ";
3447      rowSep = "\n";
3448      if( p->showHeader ){
3449        for(i=0; i<nColumn; i++){
3450          w = p->actualWidth[i];
3451          if( p->colWidth[i]<0 ) w = -w;
3452          utf8_width_print(p->out, w, azData[i]);
3453          fputs(i==nColumn-1?"\n":"  ", p->out);
3454        }
3455        for(i=0; i<nColumn; i++){
3456          print_dashes(p->out, p->actualWidth[i]);
3457          fputs(i==nColumn-1?"\n":"  ", p->out);
3458        }
3459      }
3460      break;
3461    }
3462    case MODE_Table: {
3463      colSep = " | ";
3464      rowSep = " |\n";
3465      print_row_separator(p, nColumn, "+");
3466      fputs("| ", p->out);
3467      for(i=0; i<nColumn; i++){
3468        w = p->actualWidth[i];
3469        n = strlenChar(azData[i]);
3470        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3471        fputs(i==nColumn-1?" |\n":" | ", p->out);
3472      }
3473      print_row_separator(p, nColumn, "+");
3474      break;
3475    }
3476    case MODE_Markdown: {
3477      colSep = " | ";
3478      rowSep = " |\n";
3479      fputs("| ", p->out);
3480      for(i=0; i<nColumn; i++){
3481        w = p->actualWidth[i];
3482        n = strlenChar(azData[i]);
3483        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3484        fputs(i==nColumn-1?" |\n":" | ", p->out);
3485      }
3486      print_row_separator(p, nColumn, "|");
3487      break;
3488    }
3489    case MODE_Box: {
3490      colSep = " " BOX_13 " ";
3491      rowSep = " " BOX_13 "\n";
3492      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3493      utf8_printf(p->out, BOX_13 " ");
3494      for(i=0; i<nColumn; i++){
3495        w = p->actualWidth[i];
3496        n = strlenChar(azData[i]);
3497        utf8_printf(p->out, "%*s%s%*s%s",
3498            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3499            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3500      }
3501      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3502      break;
3503    }
3504  }
3505  for(i=nColumn, j=0; i<nTotal; i++, j++){
3506    if( j==0 && p->cMode!=MODE_Column ){
3507      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3508    }
3509    z = azData[i];
3510    if( z==0 ) z = p->nullValue;
3511    w = p->actualWidth[j];
3512    if( p->colWidth[j]<0 ) w = -w;
3513    utf8_width_print(p->out, w, z);
3514    if( j==nColumn-1 ){
3515      utf8_printf(p->out, "%s", rowSep);
3516      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3517        if( p->cMode==MODE_Table ){
3518          print_row_separator(p, nColumn, "+");
3519        }else if( p->cMode==MODE_Box ){
3520          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3521        }else if( p->cMode==MODE_Column ){
3522          raw_printf(p->out, "\n");
3523        }
3524      }
3525      j = -1;
3526      if( seenInterrupt ) goto columnar_end;
3527    }else{
3528      utf8_printf(p->out, "%s", colSep);
3529    }
3530  }
3531  if( p->cMode==MODE_Table ){
3532    print_row_separator(p, nColumn, "+");
3533  }else if( p->cMode==MODE_Box ){
3534    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3535  }
3536columnar_end:
3537  if( seenInterrupt ){
3538    utf8_printf(p->out, "Interrupt\n");
3539  }
3540  nData = (nRow+1)*nColumn;
3541  for(i=0; i<nData; i++){
3542    z = azData[i];
3543    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3544  }
3545  sqlite3_free(azData);
3546  sqlite3_free((void*)azNextLine);
3547  sqlite3_free(abRowDiv);
3548  if( azQuoted ){
3549    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3550    sqlite3_free(azQuoted);
3551  }
3552}
3553
3554/*
3555** Run a prepared statement
3556*/
3557static void exec_prepared_stmt(
3558  ShellState *pArg,                                /* Pointer to ShellState */
3559  sqlite3_stmt *pStmt                              /* Statment to run */
3560){
3561  int rc;
3562  sqlite3_uint64 nRow = 0;
3563
3564  if( pArg->cMode==MODE_Column
3565   || pArg->cMode==MODE_Table
3566   || pArg->cMode==MODE_Box
3567   || pArg->cMode==MODE_Markdown
3568  ){
3569    exec_prepared_stmt_columnar(pArg, pStmt);
3570    return;
3571  }
3572
3573  /* perform the first step.  this will tell us if we
3574  ** have a result set or not and how wide it is.
3575  */
3576  rc = sqlite3_step(pStmt);
3577  /* if we have a result set... */
3578  if( SQLITE_ROW == rc ){
3579    /* allocate space for col name ptr, value ptr, and type */
3580    int nCol = sqlite3_column_count(pStmt);
3581    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3582    if( !pData ){
3583      shell_out_of_memory();
3584    }else{
3585      char **azCols = (char **)pData;      /* Names of result columns */
3586      char **azVals = &azCols[nCol];       /* Results */
3587      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3588      int i, x;
3589      assert(sizeof(int) <= sizeof(char *));
3590      /* save off ptrs to column names */
3591      for(i=0; i<nCol; i++){
3592        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3593      }
3594      do{
3595        nRow++;
3596        /* extract the data and data types */
3597        for(i=0; i<nCol; i++){
3598          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3599          if( x==SQLITE_BLOB
3600           && pArg
3601           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3602          ){
3603            azVals[i] = "";
3604          }else{
3605            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3606          }
3607          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3608            rc = SQLITE_NOMEM;
3609            break; /* from for */
3610          }
3611        } /* end for */
3612
3613        /* if data and types extracted successfully... */
3614        if( SQLITE_ROW == rc ){
3615          /* call the supplied callback with the result row data */
3616          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3617            rc = SQLITE_ABORT;
3618          }else{
3619            rc = sqlite3_step(pStmt);
3620          }
3621        }
3622      } while( SQLITE_ROW == rc );
3623      sqlite3_free(pData);
3624      if( pArg->cMode==MODE_Json ){
3625        fputs("]\n", pArg->out);
3626      }else if( pArg->cMode==MODE_Count ){
3627        char zBuf[200];
3628        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3629                         nRow, nRow!=1 ? "s" : "");
3630        printf("%s", zBuf);
3631      }
3632    }
3633  }
3634}
3635
3636#ifndef SQLITE_OMIT_VIRTUALTABLE
3637/*
3638** This function is called to process SQL if the previous shell command
3639** was ".expert". It passes the SQL in the second argument directly to
3640** the sqlite3expert object.
3641**
3642** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3643** code. In this case, (*pzErr) may be set to point to a buffer containing
3644** an English language error message. It is the responsibility of the
3645** caller to eventually free this buffer using sqlite3_free().
3646*/
3647static int expertHandleSQL(
3648  ShellState *pState,
3649  const char *zSql,
3650  char **pzErr
3651){
3652  assert( pState->expert.pExpert );
3653  assert( pzErr==0 || *pzErr==0 );
3654  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3655}
3656
3657/*
3658** This function is called either to silently clean up the object
3659** created by the ".expert" command (if bCancel==1), or to generate a
3660** report from it and then clean it up (if bCancel==0).
3661**
3662** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3663** code. In this case, (*pzErr) may be set to point to a buffer containing
3664** an English language error message. It is the responsibility of the
3665** caller to eventually free this buffer using sqlite3_free().
3666*/
3667static int expertFinish(
3668  ShellState *pState,
3669  int bCancel,
3670  char **pzErr
3671){
3672  int rc = SQLITE_OK;
3673  sqlite3expert *p = pState->expert.pExpert;
3674  assert( p );
3675  assert( bCancel || pzErr==0 || *pzErr==0 );
3676  if( bCancel==0 ){
3677    FILE *out = pState->out;
3678    int bVerbose = pState->expert.bVerbose;
3679
3680    rc = sqlite3_expert_analyze(p, pzErr);
3681    if( rc==SQLITE_OK ){
3682      int nQuery = sqlite3_expert_count(p);
3683      int i;
3684
3685      if( bVerbose ){
3686        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3687        raw_printf(out, "-- Candidates -----------------------------\n");
3688        raw_printf(out, "%s\n", zCand);
3689      }
3690      for(i=0; i<nQuery; i++){
3691        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3692        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3693        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3694        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3695        if( bVerbose ){
3696          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3697          raw_printf(out, "%s\n\n", zSql);
3698        }
3699        raw_printf(out, "%s\n", zIdx);
3700        raw_printf(out, "%s\n", zEQP);
3701      }
3702    }
3703  }
3704  sqlite3_expert_destroy(p);
3705  pState->expert.pExpert = 0;
3706  return rc;
3707}
3708
3709/*
3710** Implementation of ".expert" dot command.
3711*/
3712static int expertDotCommand(
3713  ShellState *pState,             /* Current shell tool state */
3714  char **azArg,                   /* Array of arguments passed to dot command */
3715  int nArg                        /* Number of entries in azArg[] */
3716){
3717  int rc = SQLITE_OK;
3718  char *zErr = 0;
3719  int i;
3720  int iSample = 0;
3721
3722  assert( pState->expert.pExpert==0 );
3723  memset(&pState->expert, 0, sizeof(ExpertInfo));
3724
3725  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3726    char *z = azArg[i];
3727    int n;
3728    if( z[0]=='-' && z[1]=='-' ) z++;
3729    n = strlen30(z);
3730    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3731      pState->expert.bVerbose = 1;
3732    }
3733    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3734      if( i==(nArg-1) ){
3735        raw_printf(stderr, "option requires an argument: %s\n", z);
3736        rc = SQLITE_ERROR;
3737      }else{
3738        iSample = (int)integerValue(azArg[++i]);
3739        if( iSample<0 || iSample>100 ){
3740          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3741          rc = SQLITE_ERROR;
3742        }
3743      }
3744    }
3745    else{
3746      raw_printf(stderr, "unknown option: %s\n", z);
3747      rc = SQLITE_ERROR;
3748    }
3749  }
3750
3751  if( rc==SQLITE_OK ){
3752    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3753    if( pState->expert.pExpert==0 ){
3754      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3755      rc = SQLITE_ERROR;
3756    }else{
3757      sqlite3_expert_config(
3758          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3759      );
3760    }
3761  }
3762  sqlite3_free(zErr);
3763
3764  return rc;
3765}
3766#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3767
3768/*
3769** Execute a statement or set of statements.  Print
3770** any result rows/columns depending on the current mode
3771** set via the supplied callback.
3772**
3773** This is very similar to SQLite's built-in sqlite3_exec()
3774** function except it takes a slightly different callback
3775** and callback data argument.
3776*/
3777static int shell_exec(
3778  ShellState *pArg,                         /* Pointer to ShellState */
3779  const char *zSql,                         /* SQL to be evaluated */
3780  char **pzErrMsg                           /* Error msg written here */
3781){
3782  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3783  int rc = SQLITE_OK;             /* Return Code */
3784  int rc2;
3785  const char *zLeftover;          /* Tail of unprocessed SQL */
3786  sqlite3 *db = pArg->db;
3787
3788  if( pzErrMsg ){
3789    *pzErrMsg = NULL;
3790  }
3791
3792#ifndef SQLITE_OMIT_VIRTUALTABLE
3793  if( pArg->expert.pExpert ){
3794    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3795    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3796  }
3797#endif
3798
3799  while( zSql[0] && (SQLITE_OK == rc) ){
3800    static const char *zStmtSql;
3801    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3802    if( SQLITE_OK != rc ){
3803      if( pzErrMsg ){
3804        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3805      }
3806    }else{
3807      if( !pStmt ){
3808        /* this happens for a comment or white-space */
3809        zSql = zLeftover;
3810        while( IsSpace(zSql[0]) ) zSql++;
3811        continue;
3812      }
3813      zStmtSql = sqlite3_sql(pStmt);
3814      if( zStmtSql==0 ) zStmtSql = "";
3815      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3816
3817      /* save off the prepared statment handle and reset row count */
3818      if( pArg ){
3819        pArg->pStmt = pStmt;
3820        pArg->cnt = 0;
3821      }
3822
3823      /* echo the sql statement if echo on */
3824      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3825        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3826      }
3827
3828      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3829      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3830        sqlite3_stmt *pExplain;
3831        char *zEQP;
3832        int triggerEQP = 0;
3833        disable_debug_trace_modes();
3834        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3835        if( pArg->autoEQP>=AUTOEQP_trigger ){
3836          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3837        }
3838        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3839        shell_check_oom(zEQP);
3840        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3841        if( rc==SQLITE_OK ){
3842          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3843            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3844            int iEqpId = sqlite3_column_int(pExplain, 0);
3845            int iParentId = sqlite3_column_int(pExplain, 1);
3846            if( zEQPLine==0 ) zEQPLine = "";
3847            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3848            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3849          }
3850          eqp_render(pArg);
3851        }
3852        sqlite3_finalize(pExplain);
3853        sqlite3_free(zEQP);
3854        if( pArg->autoEQP>=AUTOEQP_full ){
3855          /* Also do an EXPLAIN for ".eqp full" mode */
3856          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3857          shell_check_oom(zEQP);
3858          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3859          if( rc==SQLITE_OK ){
3860            pArg->cMode = MODE_Explain;
3861            explain_data_prepare(pArg, pExplain);
3862            exec_prepared_stmt(pArg, pExplain);
3863            explain_data_delete(pArg);
3864          }
3865          sqlite3_finalize(pExplain);
3866          sqlite3_free(zEQP);
3867        }
3868        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3869          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3870          /* Reprepare pStmt before reactiving trace modes */
3871          sqlite3_finalize(pStmt);
3872          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3873          if( pArg ) pArg->pStmt = pStmt;
3874        }
3875        restore_debug_trace_modes();
3876      }
3877
3878      if( pArg ){
3879        pArg->cMode = pArg->mode;
3880        if( pArg->autoExplain ){
3881          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3882            pArg->cMode = MODE_Explain;
3883          }
3884          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3885            pArg->cMode = MODE_EQP;
3886          }
3887        }
3888
3889        /* If the shell is currently in ".explain" mode, gather the extra
3890        ** data required to add indents to the output.*/
3891        if( pArg->cMode==MODE_Explain ){
3892          explain_data_prepare(pArg, pStmt);
3893        }
3894      }
3895
3896      bind_prepared_stmt(pArg, pStmt);
3897      exec_prepared_stmt(pArg, pStmt);
3898      explain_data_delete(pArg);
3899      eqp_render(pArg);
3900
3901      /* print usage stats if stats on */
3902      if( pArg && pArg->statsOn ){
3903        display_stats(db, pArg, 0);
3904      }
3905
3906      /* print loop-counters if required */
3907      if( pArg && pArg->scanstatsOn ){
3908        display_scanstats(db, pArg);
3909      }
3910
3911      /* Finalize the statement just executed. If this fails, save a
3912      ** copy of the error message. Otherwise, set zSql to point to the
3913      ** next statement to execute. */
3914      rc2 = sqlite3_finalize(pStmt);
3915      if( rc!=SQLITE_NOMEM ) rc = rc2;
3916      if( rc==SQLITE_OK ){
3917        zSql = zLeftover;
3918        while( IsSpace(zSql[0]) ) zSql++;
3919      }else if( pzErrMsg ){
3920        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3921      }
3922
3923      /* clear saved stmt handle */
3924      if( pArg ){
3925        pArg->pStmt = NULL;
3926      }
3927    }
3928  } /* end while */
3929
3930  return rc;
3931}
3932
3933/*
3934** Release memory previously allocated by tableColumnList().
3935*/
3936static void freeColumnList(char **azCol){
3937  int i;
3938  for(i=1; azCol[i]; i++){
3939    sqlite3_free(azCol[i]);
3940  }
3941  /* azCol[0] is a static string */
3942  sqlite3_free(azCol);
3943}
3944
3945/*
3946** Return a list of pointers to strings which are the names of all
3947** columns in table zTab.   The memory to hold the names is dynamically
3948** allocated and must be released by the caller using a subsequent call
3949** to freeColumnList().
3950**
3951** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3952** value that needs to be preserved, then azCol[0] is filled in with the
3953** name of the rowid column.
3954**
3955** The first regular column in the table is azCol[1].  The list is terminated
3956** by an entry with azCol[i]==0.
3957*/
3958static char **tableColumnList(ShellState *p, const char *zTab){
3959  char **azCol = 0;
3960  sqlite3_stmt *pStmt;
3961  char *zSql;
3962  int nCol = 0;
3963  int nAlloc = 0;
3964  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3965  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3966  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3967  int rc;
3968
3969  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3970  shell_check_oom(zSql);
3971  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3972  sqlite3_free(zSql);
3973  if( rc ) return 0;
3974  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3975    if( nCol>=nAlloc-2 ){
3976      nAlloc = nAlloc*2 + nCol + 10;
3977      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3978      shell_check_oom(azCol);
3979    }
3980    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3981    shell_check_oom(azCol[nCol]);
3982    if( sqlite3_column_int(pStmt, 5) ){
3983      nPK++;
3984      if( nPK==1
3985       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3986                          "INTEGER")==0
3987      ){
3988        isIPK = 1;
3989      }else{
3990        isIPK = 0;
3991      }
3992    }
3993  }
3994  sqlite3_finalize(pStmt);
3995  if( azCol==0 ) return 0;
3996  azCol[0] = 0;
3997  azCol[nCol+1] = 0;
3998
3999  /* The decision of whether or not a rowid really needs to be preserved
4000  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4001  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4002  ** rowids on tables where the rowid is inaccessible because there are other
4003  ** columns in the table named "rowid", "_rowid_", and "oid".
4004  */
4005  if( preserveRowid && isIPK ){
4006    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4007    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4008    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4009    ** ROWID aliases.  To distinguish these cases, check to see if
4010    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4011    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4012    */
4013    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4014                           " WHERE origin='pk'", zTab);
4015    shell_check_oom(zSql);
4016    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4017    sqlite3_free(zSql);
4018    if( rc ){
4019      freeColumnList(azCol);
4020      return 0;
4021    }
4022    rc = sqlite3_step(pStmt);
4023    sqlite3_finalize(pStmt);
4024    preserveRowid = rc==SQLITE_ROW;
4025  }
4026  if( preserveRowid ){
4027    /* Only preserve the rowid if we can find a name to use for the
4028    ** rowid */
4029    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4030    int i, j;
4031    for(j=0; j<3; j++){
4032      for(i=1; i<=nCol; i++){
4033        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4034      }
4035      if( i>nCol ){
4036        /* At this point, we know that azRowid[j] is not the name of any
4037        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4038        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4039        ** tables will fail this last check */
4040        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4041        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4042        break;
4043      }
4044    }
4045  }
4046  return azCol;
4047}
4048
4049/*
4050** Toggle the reverse_unordered_selects setting.
4051*/
4052static void toggleSelectOrder(sqlite3 *db){
4053  sqlite3_stmt *pStmt = 0;
4054  int iSetting = 0;
4055  char zStmt[100];
4056  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4057  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4058    iSetting = sqlite3_column_int(pStmt, 0);
4059  }
4060  sqlite3_finalize(pStmt);
4061  sqlite3_snprintf(sizeof(zStmt), zStmt,
4062       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4063  sqlite3_exec(db, zStmt, 0, 0, 0);
4064}
4065
4066/*
4067** This is a different callback routine used for dumping the database.
4068** Each row received by this callback consists of a table name,
4069** the table type ("index" or "table") and SQL to create the table.
4070** This routine should print text sufficient to recreate the table.
4071*/
4072static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4073  int rc;
4074  const char *zTable;
4075  const char *zType;
4076  const char *zSql;
4077  ShellState *p = (ShellState *)pArg;
4078  int dataOnly;
4079  int noSys;
4080
4081  UNUSED_PARAMETER(azNotUsed);
4082  if( nArg!=3 || azArg==0 ) return 0;
4083  zTable = azArg[0];
4084  zType = azArg[1];
4085  zSql = azArg[2];
4086  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4087  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4088
4089  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4090    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4091  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4092    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4093  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4094    return 0;
4095  }else if( dataOnly ){
4096    /* no-op */
4097  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4098    char *zIns;
4099    if( !p->writableSchema ){
4100      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4101      p->writableSchema = 1;
4102    }
4103    zIns = sqlite3_mprintf(
4104       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4105       "VALUES('table','%q','%q',0,'%q');",
4106       zTable, zTable, zSql);
4107    shell_check_oom(zIns);
4108    utf8_printf(p->out, "%s\n", zIns);
4109    sqlite3_free(zIns);
4110    return 0;
4111  }else{
4112    printSchemaLine(p->out, zSql, ";\n");
4113  }
4114
4115  if( strcmp(zType, "table")==0 ){
4116    ShellText sSelect;
4117    ShellText sTable;
4118    char **azCol;
4119    int i;
4120    char *savedDestTable;
4121    int savedMode;
4122
4123    azCol = tableColumnList(p, zTable);
4124    if( azCol==0 ){
4125      p->nErr++;
4126      return 0;
4127    }
4128
4129    /* Always quote the table name, even if it appears to be pure ascii,
4130    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4131    initText(&sTable);
4132    appendText(&sTable, zTable, quoteChar(zTable));
4133    /* If preserving the rowid, add a column list after the table name.
4134    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4135    ** instead of the usual "INSERT INTO tab VALUES(...)".
4136    */
4137    if( azCol[0] ){
4138      appendText(&sTable, "(", 0);
4139      appendText(&sTable, azCol[0], 0);
4140      for(i=1; azCol[i]; i++){
4141        appendText(&sTable, ",", 0);
4142        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4143      }
4144      appendText(&sTable, ")", 0);
4145    }
4146
4147    /* Build an appropriate SELECT statement */
4148    initText(&sSelect);
4149    appendText(&sSelect, "SELECT ", 0);
4150    if( azCol[0] ){
4151      appendText(&sSelect, azCol[0], 0);
4152      appendText(&sSelect, ",", 0);
4153    }
4154    for(i=1; azCol[i]; i++){
4155      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4156      if( azCol[i+1] ){
4157        appendText(&sSelect, ",", 0);
4158      }
4159    }
4160    freeColumnList(azCol);
4161    appendText(&sSelect, " FROM ", 0);
4162    appendText(&sSelect, zTable, quoteChar(zTable));
4163
4164    savedDestTable = p->zDestTable;
4165    savedMode = p->mode;
4166    p->zDestTable = sTable.z;
4167    p->mode = p->cMode = MODE_Insert;
4168    rc = shell_exec(p, sSelect.z, 0);
4169    if( (rc&0xff)==SQLITE_CORRUPT ){
4170      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4171      toggleSelectOrder(p->db);
4172      shell_exec(p, sSelect.z, 0);
4173      toggleSelectOrder(p->db);
4174    }
4175    p->zDestTable = savedDestTable;
4176    p->mode = savedMode;
4177    freeText(&sTable);
4178    freeText(&sSelect);
4179    if( rc ) p->nErr++;
4180  }
4181  return 0;
4182}
4183
4184/*
4185** Run zQuery.  Use dump_callback() as the callback routine so that
4186** the contents of the query are output as SQL statements.
4187**
4188** If we get a SQLITE_CORRUPT error, rerun the query after appending
4189** "ORDER BY rowid DESC" to the end.
4190*/
4191static int run_schema_dump_query(
4192  ShellState *p,
4193  const char *zQuery
4194){
4195  int rc;
4196  char *zErr = 0;
4197  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4198  if( rc==SQLITE_CORRUPT ){
4199    char *zQ2;
4200    int len = strlen30(zQuery);
4201    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4202    if( zErr ){
4203      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4204      sqlite3_free(zErr);
4205      zErr = 0;
4206    }
4207    zQ2 = malloc( len+100 );
4208    if( zQ2==0 ) return rc;
4209    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4210    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4211    if( rc ){
4212      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4213    }else{
4214      rc = SQLITE_CORRUPT;
4215    }
4216    sqlite3_free(zErr);
4217    free(zQ2);
4218  }
4219  return rc;
4220}
4221
4222/*
4223** Text of help messages.
4224**
4225** The help text for each individual command begins with a line that starts
4226** with ".".  Subsequent lines are supplimental information.
4227**
4228** There must be two or more spaces between the end of the command and the
4229** start of the description of what that command does.
4230*/
4231static const char *(azHelp[]) = {
4232#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
4233  ".archive ...             Manage SQL archives",
4234  "   Each command must have exactly one of the following options:",
4235  "     -c, --create               Create a new archive",
4236  "     -u, --update               Add or update files with changed mtime",
4237  "     -i, --insert               Like -u but always add even if unchanged",
4238  "     -r, --remove               Remove files from archive",
4239  "     -t, --list                 List contents of archive",
4240  "     -x, --extract              Extract files from archive",
4241  "   Optional arguments:",
4242  "     -v, --verbose              Print each filename as it is processed",
4243  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4244  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4245  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4246  "     -g, --glob                 Use glob matching for names in archive",
4247  "     -n, --dryrun               Show the SQL that would have occurred",
4248  "   Examples:",
4249  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4250  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4251  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4252  "   See also:",
4253  "      http://sqlite.org/cli.html#sqlite_archive_support",
4254#endif
4255#ifndef SQLITE_OMIT_AUTHORIZATION
4256  ".auth ON|OFF             Show authorizer callbacks",
4257#endif
4258  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4259  "   Options:",
4260  "       --append            Use the appendvfs",
4261  "       --async             Write to FILE without journal and fsync()",
4262  ".bail on|off             Stop after hitting an error.  Default OFF",
4263  ".binary on|off           Turn binary output on or off.  Default OFF",
4264  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4265  ".changes on|off          Show number of rows changed by SQL",
4266  ".check GLOB              Fail if output since .testcase does not match",
4267  ".clone NEWDB             Clone data into NEWDB from the existing database",
4268  ".connection [close] [#]  Open or close an auxiliary database connection",
4269  ".databases               List names and files of attached databases",
4270  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4271  ".dbinfo ?DB?             Show status information about the database",
4272  ".dump ?OBJECTS?          Render database content as SQL",
4273  "   Options:",
4274  "     --data-only            Output only INSERT statements",
4275  "     --newlines             Allow unescaped newline characters in output",
4276  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4277  "     --preserve-rowids      Include ROWID values in the output",
4278  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4279  "   Additional LIKE patterns can be given in subsequent arguments",
4280  ".echo on|off             Turn command echo on or off",
4281  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4282  "   Other Modes:",
4283#ifdef SQLITE_DEBUG
4284  "      test                  Show raw EXPLAIN QUERY PLAN output",
4285  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4286#endif
4287  "      trigger               Like \"full\" but also show trigger bytecode",
4288  ".excel                   Display the output of next command in spreadsheet",
4289  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4290  ".exit ?CODE?             Exit this program with return-code CODE",
4291  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4292  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4293  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4294  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4295  "   --help                  Show CMD details",
4296  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4297  ".headers on|off          Turn display of headers on or off",
4298  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4299  ".import FILE TABLE       Import data from FILE into TABLE",
4300  "   Options:",
4301  "     --ascii               Use \\037 and \\036 as column and row separators",
4302  "     --csv                 Use , and \\n as column and row separators",
4303  "     --skip N              Skip the first N rows of input",
4304  "     --schema S            Target table to be S.TABLE",
4305  "     -v                    \"Verbose\" - increase auxiliary output",
4306  "   Notes:",
4307  "     *  If TABLE does not exist, it is created.  The first row of input",
4308  "        determines the column names.",
4309  "     *  If neither --csv or --ascii are used, the input mode is derived",
4310  "        from the \".mode\" output mode",
4311  "     *  If FILE begins with \"|\" then it is a command that generates the",
4312  "        input text.",
4313#ifndef SQLITE_OMIT_TEST_CONTROL
4314  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4315#endif
4316  ".indexes ?TABLE?         Show names of indexes",
4317  "                           If TABLE is specified, only show indexes for",
4318  "                           tables matching TABLE using the LIKE operator.",
4319#ifdef SQLITE_ENABLE_IOTRACE
4320  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4321#endif
4322  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4323  ".lint OPTIONS            Report potential schema issues.",
4324  "     Options:",
4325  "        fkey-indexes     Find missing foreign key indexes",
4326#ifndef SQLITE_OMIT_LOAD_EXTENSION
4327  ".load FILE ?ENTRY?       Load an extension library",
4328#endif
4329  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4330  ".mode MODE ?OPTIONS?     Set output mode",
4331  "   MODE is one of:",
4332  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4333  "     box         Tables using unicode box-drawing characters",
4334  "     csv         Comma-separated values",
4335  "     column      Output in columns.  (See .width)",
4336  "     html        HTML <table> code",
4337  "     insert      SQL insert statements for TABLE",
4338  "     json        Results in a JSON array",
4339  "     line        One value per line",
4340  "     list        Values delimited by \"|\"",
4341  "     markdown    Markdown table format",
4342  "     qbox        Shorthand for \"box --width 60 --quote\"",
4343  "     quote       Escape answers as for SQL",
4344  "     table       ASCII-art table",
4345  "     tabs        Tab-separated values",
4346  "     tcl         TCL list elements",
4347  "   OPTIONS: (for columnar modes or insert mode):",
4348  "     --wrap N       Wrap output lines to no longer than N characters",
4349  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4350  "     --ww           Shorthand for \"--wordwrap 1\"",
4351  "     --quote        Quote output text as SQL literals",
4352  "     --noquote      Do not quote output text",
4353  "     TABLE          The name of SQL table used for \"insert\" mode",
4354  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4355  ".nullvalue STRING        Use STRING in place of NULL values",
4356  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4357  "     If FILE begins with '|' then open as a pipe",
4358  "       --bom  Put a UTF8 byte-order mark at the beginning",
4359  "       -e     Send output to the system text editor",
4360  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4361  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4362  "     Options:",
4363  "        --append        Use appendvfs to append database to the end of FILE",
4364#ifndef SQLITE_OMIT_DESERIALIZE
4365  "        --deserialize   Load into memory using sqlite3_deserialize()",
4366  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4367  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4368#endif
4369  "        --new           Initialize FILE to an empty database",
4370  "        --nofollow      Do not follow symbolic links",
4371  "        --readonly      Open FILE readonly",
4372  "        --zip           FILE is a ZIP archive",
4373  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4374  "   If FILE begins with '|' then open it as a pipe.",
4375  "   Options:",
4376  "     --bom                 Prefix output with a UTF8 byte-order mark",
4377  "     -e                    Send output to the system text editor",
4378  "     -x                    Send output as CSV to a spreadsheet",
4379  ".parameter CMD ...       Manage SQL parameter bindings",
4380  "   clear                   Erase all bindings",
4381  "   init                    Initialize the TEMP table that holds bindings",
4382  "   list                    List the current parameter bindings",
4383  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4384  "                           PARAMETER should start with one of: $ : @ ?",
4385  "   unset PARAMETER         Remove PARAMETER from the binding table",
4386  ".print STRING...         Print literal STRING",
4387#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4388  ".progress N              Invoke progress handler after every N opcodes",
4389  "   --limit N                 Interrupt after N progress callbacks",
4390  "   --once                    Do no more than one progress interrupt",
4391  "   --quiet|-q                No output except at interrupts",
4392  "   --reset                   Reset the count for each input and interrupt",
4393#endif
4394  ".prompt MAIN CONTINUE    Replace the standard prompts",
4395  ".quit                    Exit this program",
4396  ".read FILE               Read input from FILE or command output",
4397  "    If FILE begins with \"|\", it is a command that generates the input.",
4398#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4399  ".recover                 Recover as much data as possible from corrupt db.",
4400  "   --freelist-corrupt       Assume the freelist is corrupt",
4401  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4402  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4403  "   --no-rowids              Do not attempt to recover rowid values",
4404  "                            that are not also INTEGER PRIMARY KEYs",
4405#endif
4406  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4407  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4408  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4409  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4410  "   Options:",
4411  "      --indent             Try to pretty-print the schema",
4412  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4413  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4414  "    Options:",
4415  "       --init               Create a new SELFTEST table",
4416  "       -v                   Verbose output",
4417  ".separator COL ?ROW?     Change the column and row separators",
4418#if defined(SQLITE_ENABLE_SESSION)
4419  ".session ?NAME? CMD ...  Create or control sessions",
4420  "   Subcommands:",
4421  "     attach TABLE             Attach TABLE",
4422  "     changeset FILE           Write a changeset into FILE",
4423  "     close                    Close one session",
4424  "     enable ?BOOLEAN?         Set or query the enable bit",
4425  "     filter GLOB...           Reject tables matching GLOBs",
4426  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4427  "     isempty                  Query whether the session is empty",
4428  "     list                     List currently open session names",
4429  "     open DB NAME             Open a new session on DB",
4430  "     patchset FILE            Write a patchset into FILE",
4431  "   If ?NAME? is omitted, the first defined session is used.",
4432#endif
4433  ".sha3sum ...             Compute a SHA3 hash of database content",
4434  "    Options:",
4435  "      --schema              Also hash the sqlite_schema table",
4436  "      --sha3-224            Use the sha3-224 algorithm",
4437  "      --sha3-256            Use the sha3-256 algorithm (default)",
4438  "      --sha3-384            Use the sha3-384 algorithm",
4439  "      --sha3-512            Use the sha3-512 algorithm",
4440  "    Any other argument is a LIKE pattern for tables to hash",
4441#ifndef SQLITE_NOHAVE_SYSTEM
4442  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4443#endif
4444  ".show                    Show the current values for various settings",
4445  ".stats ?ARG?             Show stats or turn stats on or off",
4446  "   off                      Turn off automatic stat display",
4447  "   on                       Turn on automatic stat display",
4448  "   stmt                     Show statement stats",
4449  "   vmstep                   Show the virtual machine step count only",
4450#ifndef SQLITE_NOHAVE_SYSTEM
4451  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4452#endif
4453  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4454  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4455  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4456  "                           Run \".testctrl\" with no arguments for details",
4457  ".timeout MS              Try opening locked tables for MS milliseconds",
4458  ".timer on|off            Turn SQL timer on or off",
4459#ifndef SQLITE_OMIT_TRACE
4460  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4461  "    FILE                    Send output to FILE",
4462  "    stdout                  Send output to stdout",
4463  "    stderr                  Send output to stderr",
4464  "    off                     Disable tracing",
4465  "    --expanded              Expand query parameters",
4466#ifdef SQLITE_ENABLE_NORMALIZE
4467  "    --normalized            Normal the SQL statements",
4468#endif
4469  "    --plain                 Show SQL as it is input",
4470  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4471  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4472  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4473  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4474#endif /* SQLITE_OMIT_TRACE */
4475#ifdef SQLITE_DEBUG
4476  ".unmodule NAME ...       Unregister virtual table modules",
4477  "    --allexcept             Unregister everything except those named",
4478#endif
4479  ".vfsinfo ?AUX?           Information about the top-level VFS",
4480  ".vfslist                 List all available VFSes",
4481  ".vfsname ?AUX?           Print the name of the VFS stack",
4482  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4483  "     Negative values right-justify",
4484};
4485
4486/*
4487** Output help text.
4488**
4489** zPattern describes the set of commands for which help text is provided.
4490** If zPattern is NULL, then show all commands, but only give a one-line
4491** description of each.
4492**
4493** Return the number of matches.
4494*/
4495static int showHelp(FILE *out, const char *zPattern){
4496  int i = 0;
4497  int j = 0;
4498  int n = 0;
4499  char *zPat;
4500  if( zPattern==0
4501   || zPattern[0]=='0'
4502   || strcmp(zPattern,"-a")==0
4503   || strcmp(zPattern,"-all")==0
4504   || strcmp(zPattern,"--all")==0
4505  ){
4506    /* Show all commands, but only one line per command */
4507    if( zPattern==0 ) zPattern = "";
4508    for(i=0; i<ArraySize(azHelp); i++){
4509      if( azHelp[i][0]=='.' || zPattern[0] ){
4510        utf8_printf(out, "%s\n", azHelp[i]);
4511        n++;
4512      }
4513    }
4514  }else{
4515    /* Look for commands that for which zPattern is an exact prefix */
4516    zPat = sqlite3_mprintf(".%s*", zPattern);
4517    shell_check_oom(zPat);
4518    for(i=0; i<ArraySize(azHelp); i++){
4519      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4520        utf8_printf(out, "%s\n", azHelp[i]);
4521        j = i+1;
4522        n++;
4523      }
4524    }
4525    sqlite3_free(zPat);
4526    if( n ){
4527      if( n==1 ){
4528        /* when zPattern is a prefix of exactly one command, then include the
4529        ** details of that command, which should begin at offset j */
4530        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4531          utf8_printf(out, "%s\n", azHelp[j]);
4532          j++;
4533        }
4534      }
4535      return n;
4536    }
4537    /* Look for commands that contain zPattern anywhere.  Show the complete
4538    ** text of all commands that match. */
4539    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4540    shell_check_oom(zPat);
4541    for(i=0; i<ArraySize(azHelp); i++){
4542      if( azHelp[i][0]=='.' ) j = i;
4543      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4544        utf8_printf(out, "%s\n", azHelp[j]);
4545        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4546          j++;
4547          utf8_printf(out, "%s\n", azHelp[j]);
4548        }
4549        i = j;
4550        n++;
4551      }
4552    }
4553    sqlite3_free(zPat);
4554  }
4555  return n;
4556}
4557
4558/* Forward reference */
4559static int process_input(ShellState *p);
4560
4561/*
4562** Read the content of file zName into memory obtained from sqlite3_malloc64()
4563** and return a pointer to the buffer. The caller is responsible for freeing
4564** the memory.
4565**
4566** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4567** read.
4568**
4569** For convenience, a nul-terminator byte is always appended to the data read
4570** from the file before the buffer is returned. This byte is not included in
4571** the final value of (*pnByte), if applicable.
4572**
4573** NULL is returned if any error is encountered. The final value of *pnByte
4574** is undefined in this case.
4575*/
4576static char *readFile(const char *zName, int *pnByte){
4577  FILE *in = fopen(zName, "rb");
4578  long nIn;
4579  size_t nRead;
4580  char *pBuf;
4581  if( in==0 ) return 0;
4582  fseek(in, 0, SEEK_END);
4583  nIn = ftell(in);
4584  rewind(in);
4585  pBuf = sqlite3_malloc64( nIn+1 );
4586  if( pBuf==0 ){ fclose(in); return 0; }
4587  nRead = fread(pBuf, nIn, 1, in);
4588  fclose(in);
4589  if( nRead!=1 ){
4590    sqlite3_free(pBuf);
4591    return 0;
4592  }
4593  pBuf[nIn] = 0;
4594  if( pnByte ) *pnByte = nIn;
4595  return pBuf;
4596}
4597
4598#if defined(SQLITE_ENABLE_SESSION)
4599/*
4600** Close a single OpenSession object and release all of its associated
4601** resources.
4602*/
4603static void session_close(OpenSession *pSession){
4604  int i;
4605  sqlite3session_delete(pSession->p);
4606  sqlite3_free(pSession->zName);
4607  for(i=0; i<pSession->nFilter; i++){
4608    sqlite3_free(pSession->azFilter[i]);
4609  }
4610  sqlite3_free(pSession->azFilter);
4611  memset(pSession, 0, sizeof(OpenSession));
4612}
4613#endif
4614
4615/*
4616** Close all OpenSession objects and release all associated resources.
4617*/
4618#if defined(SQLITE_ENABLE_SESSION)
4619static void session_close_all(ShellState *p, int i){
4620  int j;
4621  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4622  for(j=0; j<pAuxDb->nSession; j++){
4623    session_close(&pAuxDb->aSession[j]);
4624  }
4625  pAuxDb->nSession = 0;
4626}
4627#else
4628# define session_close_all(X,Y)
4629#endif
4630
4631/*
4632** Implementation of the xFilter function for an open session.  Omit
4633** any tables named by ".session filter" but let all other table through.
4634*/
4635#if defined(SQLITE_ENABLE_SESSION)
4636static int session_filter(void *pCtx, const char *zTab){
4637  OpenSession *pSession = (OpenSession*)pCtx;
4638  int i;
4639  for(i=0; i<pSession->nFilter; i++){
4640    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4641  }
4642  return 1;
4643}
4644#endif
4645
4646/*
4647** Try to deduce the type of file for zName based on its content.  Return
4648** one of the SHELL_OPEN_* constants.
4649**
4650** If the file does not exist or is empty but its name looks like a ZIP
4651** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4652** Otherwise, assume an ordinary database regardless of the filename if
4653** the type cannot be determined from content.
4654*/
4655int deduceDatabaseType(const char *zName, int dfltZip){
4656  FILE *f = fopen(zName, "rb");
4657  size_t n;
4658  int rc = SHELL_OPEN_UNSPEC;
4659  char zBuf[100];
4660  if( f==0 ){
4661    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4662       return SHELL_OPEN_ZIPFILE;
4663    }else{
4664       return SHELL_OPEN_NORMAL;
4665    }
4666  }
4667  n = fread(zBuf, 16, 1, f);
4668  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4669    fclose(f);
4670    return SHELL_OPEN_NORMAL;
4671  }
4672  fseek(f, -25, SEEK_END);
4673  n = fread(zBuf, 25, 1, f);
4674  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4675    rc = SHELL_OPEN_APPENDVFS;
4676  }else{
4677    fseek(f, -22, SEEK_END);
4678    n = fread(zBuf, 22, 1, f);
4679    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4680       && zBuf[3]==0x06 ){
4681      rc = SHELL_OPEN_ZIPFILE;
4682    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4683      rc = SHELL_OPEN_ZIPFILE;
4684    }
4685  }
4686  fclose(f);
4687  return rc;
4688}
4689
4690#ifndef SQLITE_OMIT_DESERIALIZE
4691/*
4692** Reconstruct an in-memory database using the output from the "dbtotxt"
4693** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4694** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4695*/
4696static unsigned char *readHexDb(ShellState *p, int *pnData){
4697  unsigned char *a = 0;
4698  int nLine;
4699  int n = 0;
4700  int pgsz = 0;
4701  int iOffset = 0;
4702  int j, k;
4703  int rc;
4704  FILE *in;
4705  const char *zDbFilename = p->pAuxDb->zDbFilename;
4706  unsigned int x[16];
4707  char zLine[1000];
4708  if( zDbFilename ){
4709    in = fopen(zDbFilename, "r");
4710    if( in==0 ){
4711      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4712      return 0;
4713    }
4714    nLine = 0;
4715  }else{
4716    in = p->in;
4717    nLine = p->lineno;
4718    if( in==0 ) in = stdin;
4719  }
4720  *pnData = 0;
4721  nLine++;
4722  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4723  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4724  if( rc!=2 ) goto readHexDb_error;
4725  if( n<0 ) goto readHexDb_error;
4726  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4727  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4728  a = sqlite3_malloc( n ? n : 1 );
4729  shell_check_oom(a);
4730  memset(a, 0, n);
4731  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4732    utf8_printf(stderr, "invalid pagesize\n");
4733    goto readHexDb_error;
4734  }
4735  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4736    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4737    if( rc==2 ){
4738      iOffset = k;
4739      continue;
4740    }
4741    if( strncmp(zLine, "| end ", 6)==0 ){
4742      break;
4743    }
4744    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4745                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4746                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4747    if( rc==17 ){
4748      k = iOffset+j;
4749      if( k+16<=n && k>=0 ){
4750        int ii;
4751        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4752      }
4753    }
4754  }
4755  *pnData = n;
4756  if( in!=p->in ){
4757    fclose(in);
4758  }else{
4759    p->lineno = nLine;
4760  }
4761  return a;
4762
4763readHexDb_error:
4764  if( in!=p->in ){
4765    fclose(in);
4766  }else{
4767    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4768      nLine++;
4769      if(strncmp(zLine, "| end ", 6)==0 ) break;
4770    }
4771    p->lineno = nLine;
4772  }
4773  sqlite3_free(a);
4774  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4775  return 0;
4776}
4777#endif /* SQLITE_OMIT_DESERIALIZE */
4778
4779/*
4780** Scalar function "shell_int32". The first argument to this function
4781** must be a blob. The second a non-negative integer. This function
4782** reads and returns a 32-bit big-endian integer from byte
4783** offset (4*<arg2>) of the blob.
4784*/
4785static void shellInt32(
4786  sqlite3_context *context,
4787  int argc,
4788  sqlite3_value **argv
4789){
4790  const unsigned char *pBlob;
4791  int nBlob;
4792  int iInt;
4793
4794  UNUSED_PARAMETER(argc);
4795  nBlob = sqlite3_value_bytes(argv[0]);
4796  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4797  iInt = sqlite3_value_int(argv[1]);
4798
4799  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4800    const unsigned char *a = &pBlob[iInt*4];
4801    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4802                       + ((sqlite3_int64)a[1]<<16)
4803                       + ((sqlite3_int64)a[2]<< 8)
4804                       + ((sqlite3_int64)a[3]<< 0);
4805    sqlite3_result_int64(context, iVal);
4806  }
4807}
4808
4809/*
4810** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4811** using "..." with internal double-quote characters doubled.
4812*/
4813static void shellIdQuote(
4814  sqlite3_context *context,
4815  int argc,
4816  sqlite3_value **argv
4817){
4818  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4819  UNUSED_PARAMETER(argc);
4820  if( zName ){
4821    char *z = sqlite3_mprintf("\"%w\"", zName);
4822    sqlite3_result_text(context, z, -1, sqlite3_free);
4823  }
4824}
4825
4826/*
4827** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4828*/
4829static void shellUSleepFunc(
4830  sqlite3_context *context,
4831  int argcUnused,
4832  sqlite3_value **argv
4833){
4834  int sleep = sqlite3_value_int(argv[0]);
4835  (void)argcUnused;
4836  sqlite3_sleep(sleep/1000);
4837  sqlite3_result_int(context, sleep);
4838}
4839
4840/*
4841** Scalar function "shell_escape_crnl" used by the .recover command.
4842** The argument passed to this function is the output of built-in
4843** function quote(). If the first character of the input is "'",
4844** indicating that the value passed to quote() was a text value,
4845** then this function searches the input for "\n" and "\r" characters
4846** and adds a wrapper similar to the following:
4847**
4848**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4849**
4850** Or, if the first character of the input is not "'", then a copy
4851** of the input is returned.
4852*/
4853static void shellEscapeCrnl(
4854  sqlite3_context *context,
4855  int argc,
4856  sqlite3_value **argv
4857){
4858  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4859  UNUSED_PARAMETER(argc);
4860  if( zText && zText[0]=='\'' ){
4861    int nText = sqlite3_value_bytes(argv[0]);
4862    int i;
4863    char zBuf1[20];
4864    char zBuf2[20];
4865    const char *zNL = 0;
4866    const char *zCR = 0;
4867    int nCR = 0;
4868    int nNL = 0;
4869
4870    for(i=0; zText[i]; i++){
4871      if( zNL==0 && zText[i]=='\n' ){
4872        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4873        nNL = (int)strlen(zNL);
4874      }
4875      if( zCR==0 && zText[i]=='\r' ){
4876        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4877        nCR = (int)strlen(zCR);
4878      }
4879    }
4880
4881    if( zNL || zCR ){
4882      int iOut = 0;
4883      i64 nMax = (nNL > nCR) ? nNL : nCR;
4884      i64 nAlloc = nMax * nText + (nMax+64)*2;
4885      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4886      if( zOut==0 ){
4887        sqlite3_result_error_nomem(context);
4888        return;
4889      }
4890
4891      if( zNL && zCR ){
4892        memcpy(&zOut[iOut], "replace(replace(", 16);
4893        iOut += 16;
4894      }else{
4895        memcpy(&zOut[iOut], "replace(", 8);
4896        iOut += 8;
4897      }
4898      for(i=0; zText[i]; i++){
4899        if( zText[i]=='\n' ){
4900          memcpy(&zOut[iOut], zNL, nNL);
4901          iOut += nNL;
4902        }else if( zText[i]=='\r' ){
4903          memcpy(&zOut[iOut], zCR, nCR);
4904          iOut += nCR;
4905        }else{
4906          zOut[iOut] = zText[i];
4907          iOut++;
4908        }
4909      }
4910
4911      if( zNL ){
4912        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4913        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4914        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4915      }
4916      if( zCR ){
4917        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4918        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4919        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4920      }
4921
4922      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4923      sqlite3_free(zOut);
4924      return;
4925    }
4926  }
4927
4928  sqlite3_result_value(context, argv[0]);
4929}
4930
4931/* Flags for open_db().
4932**
4933** The default behavior of open_db() is to exit(1) if the database fails to
4934** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4935** but still returns without calling exit.
4936**
4937** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4938** ZIP archive if the file does not exist or is empty and its name matches
4939** the *.zip pattern.
4940*/
4941#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4942#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4943
4944/*
4945** Make sure the database is open.  If it is not, then open it.  If
4946** the database fails to open, print an error message and exit.
4947*/
4948static void open_db(ShellState *p, int openFlags){
4949  if( p->db==0 ){
4950    const char *zDbFilename = p->pAuxDb->zDbFilename;
4951    if( p->openMode==SHELL_OPEN_UNSPEC ){
4952      if( zDbFilename==0 || zDbFilename[0]==0 ){
4953        p->openMode = SHELL_OPEN_NORMAL;
4954      }else{
4955        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4956                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4957      }
4958    }
4959    switch( p->openMode ){
4960      case SHELL_OPEN_APPENDVFS: {
4961        sqlite3_open_v2(zDbFilename, &p->db,
4962           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4963        break;
4964      }
4965      case SHELL_OPEN_HEXDB:
4966      case SHELL_OPEN_DESERIALIZE: {
4967        sqlite3_open(0, &p->db);
4968        break;
4969      }
4970      case SHELL_OPEN_ZIPFILE: {
4971        sqlite3_open(":memory:", &p->db);
4972        break;
4973      }
4974      case SHELL_OPEN_READONLY: {
4975        sqlite3_open_v2(zDbFilename, &p->db,
4976            SQLITE_OPEN_READONLY|p->openFlags, 0);
4977        break;
4978      }
4979      case SHELL_OPEN_UNSPEC:
4980      case SHELL_OPEN_NORMAL: {
4981        sqlite3_open_v2(zDbFilename, &p->db,
4982           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4983        break;
4984      }
4985    }
4986    globalDb = p->db;
4987    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4988      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4989          zDbFilename, sqlite3_errmsg(p->db));
4990      if( openFlags & OPEN_DB_KEEPALIVE ){
4991        sqlite3_open(":memory:", &p->db);
4992        return;
4993      }
4994      exit(1);
4995    }
4996#ifndef SQLITE_OMIT_LOAD_EXTENSION
4997    sqlite3_enable_load_extension(p->db, 1);
4998#endif
4999    sqlite3_fileio_init(p->db, 0, 0);
5000    sqlite3_shathree_init(p->db, 0, 0);
5001    sqlite3_completion_init(p->db, 0, 0);
5002    sqlite3_uint_init(p->db, 0, 0);
5003    sqlite3_decimal_init(p->db, 0, 0);
5004    sqlite3_regexp_init(p->db, 0, 0);
5005    sqlite3_ieee_init(p->db, 0, 0);
5006    sqlite3_series_init(p->db, 0, 0);
5007#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5008    sqlite3_dbdata_init(p->db, 0, 0);
5009#endif
5010#ifdef SQLITE_HAVE_ZLIB
5011    if( !p->bSafeModePersist ){
5012      sqlite3_zipfile_init(p->db, 0, 0);
5013      sqlite3_sqlar_init(p->db, 0, 0);
5014    }
5015#endif
5016    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5017                            shellAddSchemaName, 0, 0);
5018    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5019                            shellModuleSchema, 0, 0);
5020    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5021                            shellPutsFunc, 0, 0);
5022    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5023                            shellEscapeCrnl, 0, 0);
5024    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5025                            shellInt32, 0, 0);
5026    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5027                            shellIdQuote, 0, 0);
5028    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5029                            shellUSleepFunc, 0, 0);
5030#ifndef SQLITE_NOHAVE_SYSTEM
5031    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5032                            editFunc, 0, 0);
5033    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5034                            editFunc, 0, 0);
5035#endif
5036    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5037      char *zSql = sqlite3_mprintf(
5038         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5039      shell_check_oom(zSql);
5040      sqlite3_exec(p->db, zSql, 0, 0, 0);
5041      sqlite3_free(zSql);
5042    }
5043#ifndef SQLITE_OMIT_DESERIALIZE
5044    else
5045    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5046      int rc;
5047      int nData = 0;
5048      unsigned char *aData;
5049      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5050        aData = (unsigned char*)readFile(zDbFilename, &nData);
5051      }else{
5052        aData = readHexDb(p, &nData);
5053        if( aData==0 ){
5054          return;
5055        }
5056      }
5057      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5058                   SQLITE_DESERIALIZE_RESIZEABLE |
5059                   SQLITE_DESERIALIZE_FREEONCLOSE);
5060      if( rc ){
5061        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5062      }
5063      if( p->szMax>0 ){
5064        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5065      }
5066    }
5067#endif
5068  }
5069  if( p->bSafeModePersist && p->db!=0 ){
5070    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5071  }
5072}
5073
5074/*
5075** Attempt to close the databaes connection.  Report errors.
5076*/
5077void close_db(sqlite3 *db){
5078  int rc = sqlite3_close(db);
5079  if( rc ){
5080    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5081        rc, sqlite3_errmsg(db));
5082  }
5083}
5084
5085#if HAVE_READLINE || HAVE_EDITLINE
5086/*
5087** Readline completion callbacks
5088*/
5089static char *readline_completion_generator(const char *text, int state){
5090  static sqlite3_stmt *pStmt = 0;
5091  char *zRet;
5092  if( state==0 ){
5093    char *zSql;
5094    sqlite3_finalize(pStmt);
5095    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5096                           "  FROM completion(%Q) ORDER BY 1", text);
5097    shell_check_oom(zSql);
5098    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5099    sqlite3_free(zSql);
5100  }
5101  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5102    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5103    zRet = z ? strdup(z) : 0;
5104  }else{
5105    sqlite3_finalize(pStmt);
5106    pStmt = 0;
5107    zRet = 0;
5108  }
5109  return zRet;
5110}
5111static char **readline_completion(const char *zText, int iStart, int iEnd){
5112  rl_attempted_completion_over = 1;
5113  return rl_completion_matches(zText, readline_completion_generator);
5114}
5115
5116#elif HAVE_LINENOISE
5117/*
5118** Linenoise completion callback
5119*/
5120static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5121  int nLine = strlen30(zLine);
5122  int i, iStart;
5123  sqlite3_stmt *pStmt = 0;
5124  char *zSql;
5125  char zBuf[1000];
5126
5127  if( nLine>sizeof(zBuf)-30 ) return;
5128  if( zLine[0]=='.' || zLine[0]=='#') return;
5129  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5130  if( i==nLine-1 ) return;
5131  iStart = i+1;
5132  memcpy(zBuf, zLine, iStart);
5133  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5134                         "  FROM completion(%Q,%Q) ORDER BY 1",
5135                         &zLine[iStart], zLine);
5136  shell_check_oom(zSql);
5137  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5138  sqlite3_free(zSql);
5139  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5140  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5141    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5142    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5143    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5144      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5145      linenoiseAddCompletion(lc, zBuf);
5146    }
5147  }
5148  sqlite3_finalize(pStmt);
5149}
5150#endif
5151
5152/*
5153** Do C-language style dequoting.
5154**
5155**    \a    -> alarm
5156**    \b    -> backspace
5157**    \t    -> tab
5158**    \n    -> newline
5159**    \v    -> vertical tab
5160**    \f    -> form feed
5161**    \r    -> carriage return
5162**    \s    -> space
5163**    \"    -> "
5164**    \'    -> '
5165**    \\    -> backslash
5166**    \NNN  -> ascii character NNN in octal
5167*/
5168static void resolve_backslashes(char *z){
5169  int i, j;
5170  char c;
5171  while( *z && *z!='\\' ) z++;
5172  for(i=j=0; (c = z[i])!=0; i++, j++){
5173    if( c=='\\' && z[i+1]!=0 ){
5174      c = z[++i];
5175      if( c=='a' ){
5176        c = '\a';
5177      }else if( c=='b' ){
5178        c = '\b';
5179      }else if( c=='t' ){
5180        c = '\t';
5181      }else if( c=='n' ){
5182        c = '\n';
5183      }else if( c=='v' ){
5184        c = '\v';
5185      }else if( c=='f' ){
5186        c = '\f';
5187      }else if( c=='r' ){
5188        c = '\r';
5189      }else if( c=='"' ){
5190        c = '"';
5191      }else if( c=='\'' ){
5192        c = '\'';
5193      }else if( c=='\\' ){
5194        c = '\\';
5195      }else if( c>='0' && c<='7' ){
5196        c -= '0';
5197        if( z[i+1]>='0' && z[i+1]<='7' ){
5198          i++;
5199          c = (c<<3) + z[i] - '0';
5200          if( z[i+1]>='0' && z[i+1]<='7' ){
5201            i++;
5202            c = (c<<3) + z[i] - '0';
5203          }
5204        }
5205      }
5206    }
5207    z[j] = c;
5208  }
5209  if( j<i ) z[j] = 0;
5210}
5211
5212/*
5213** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5214** for TRUE and FALSE.  Return the integer value if appropriate.
5215*/
5216static int booleanValue(const char *zArg){
5217  int i;
5218  if( zArg[0]=='0' && zArg[1]=='x' ){
5219    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5220  }else{
5221    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5222  }
5223  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5224  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5225    return 1;
5226  }
5227  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5228    return 0;
5229  }
5230  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5231          zArg);
5232  return 0;
5233}
5234
5235/*
5236** Set or clear a shell flag according to a boolean value.
5237*/
5238static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5239  if( booleanValue(zArg) ){
5240    ShellSetFlag(p, mFlag);
5241  }else{
5242    ShellClearFlag(p, mFlag);
5243  }
5244}
5245
5246/*
5247** Close an output file, assuming it is not stderr or stdout
5248*/
5249static void output_file_close(FILE *f){
5250  if( f && f!=stdout && f!=stderr ) fclose(f);
5251}
5252
5253/*
5254** Try to open an output file.   The names "stdout" and "stderr" are
5255** recognized and do the right thing.  NULL is returned if the output
5256** filename is "off".
5257*/
5258static FILE *output_file_open(const char *zFile, int bTextMode){
5259  FILE *f;
5260  if( strcmp(zFile,"stdout")==0 ){
5261    f = stdout;
5262  }else if( strcmp(zFile, "stderr")==0 ){
5263    f = stderr;
5264  }else if( strcmp(zFile, "off")==0 ){
5265    f = 0;
5266  }else{
5267    f = fopen(zFile, bTextMode ? "w" : "wb");
5268    if( f==0 ){
5269      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5270    }
5271  }
5272  return f;
5273}
5274
5275#ifndef SQLITE_OMIT_TRACE
5276/*
5277** A routine for handling output from sqlite3_trace().
5278*/
5279static int sql_trace_callback(
5280  unsigned mType,         /* The trace type */
5281  void *pArg,             /* The ShellState pointer */
5282  void *pP,               /* Usually a pointer to sqlite_stmt */
5283  void *pX                /* Auxiliary output */
5284){
5285  ShellState *p = (ShellState*)pArg;
5286  sqlite3_stmt *pStmt;
5287  const char *zSql;
5288  int nSql;
5289  if( p->traceOut==0 ) return 0;
5290  if( mType==SQLITE_TRACE_CLOSE ){
5291    utf8_printf(p->traceOut, "-- closing database connection\n");
5292    return 0;
5293  }
5294  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5295    zSql = (const char*)pX;
5296  }else{
5297    pStmt = (sqlite3_stmt*)pP;
5298    switch( p->eTraceType ){
5299      case SHELL_TRACE_EXPANDED: {
5300        zSql = sqlite3_expanded_sql(pStmt);
5301        break;
5302      }
5303#ifdef SQLITE_ENABLE_NORMALIZE
5304      case SHELL_TRACE_NORMALIZED: {
5305        zSql = sqlite3_normalized_sql(pStmt);
5306        break;
5307      }
5308#endif
5309      default: {
5310        zSql = sqlite3_sql(pStmt);
5311        break;
5312      }
5313    }
5314  }
5315  if( zSql==0 ) return 0;
5316  nSql = strlen30(zSql);
5317  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5318  switch( mType ){
5319    case SQLITE_TRACE_ROW:
5320    case SQLITE_TRACE_STMT: {
5321      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5322      break;
5323    }
5324    case SQLITE_TRACE_PROFILE: {
5325      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5326      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5327      break;
5328    }
5329  }
5330  return 0;
5331}
5332#endif
5333
5334/*
5335** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5336** a useful spot to set a debugger breakpoint.
5337*/
5338static void test_breakpoint(void){
5339  static int nCall = 0;
5340  nCall++;
5341}
5342
5343/*
5344** An object used to read a CSV and other files for import.
5345*/
5346typedef struct ImportCtx ImportCtx;
5347struct ImportCtx {
5348  const char *zFile;  /* Name of the input file */
5349  FILE *in;           /* Read the CSV text from this input stream */
5350  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5351  char *z;            /* Accumulated text for a field */
5352  int n;              /* Number of bytes in z */
5353  int nAlloc;         /* Space allocated for z[] */
5354  int nLine;          /* Current line number */
5355  int nRow;           /* Number of rows imported */
5356  int nErr;           /* Number of errors encountered */
5357  int bNotFirst;      /* True if one or more bytes already read */
5358  int cTerm;          /* Character that terminated the most recent field */
5359  int cColSep;        /* The column separator character.  (Usually ",") */
5360  int cRowSep;        /* The row separator character.  (Usually "\n") */
5361};
5362
5363/* Clean up resourced used by an ImportCtx */
5364static void import_cleanup(ImportCtx *p){
5365  if( p->in!=0 && p->xCloser!=0 ){
5366    p->xCloser(p->in);
5367    p->in = 0;
5368  }
5369  sqlite3_free(p->z);
5370  p->z = 0;
5371}
5372
5373/* Append a single byte to z[] */
5374static void import_append_char(ImportCtx *p, int c){
5375  if( p->n+1>=p->nAlloc ){
5376    p->nAlloc += p->nAlloc + 100;
5377    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5378    shell_check_oom(p->z);
5379  }
5380  p->z[p->n++] = (char)c;
5381}
5382
5383/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5384** with the option of having a separator other than ",".
5385**
5386**   +  Input comes from p->in.
5387**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5388**      from sqlite3_malloc64().
5389**   +  Use p->cSep as the column separator.  The default is ",".
5390**   +  Use p->rSep as the row separator.  The default is "\n".
5391**   +  Keep track of the line number in p->nLine.
5392**   +  Store the character that terminates the field in p->cTerm.  Store
5393**      EOF on end-of-file.
5394**   +  Report syntax errors on stderr
5395*/
5396static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5397  int c;
5398  int cSep = p->cColSep;
5399  int rSep = p->cRowSep;
5400  p->n = 0;
5401  c = fgetc(p->in);
5402  if( c==EOF || seenInterrupt ){
5403    p->cTerm = EOF;
5404    return 0;
5405  }
5406  if( c=='"' ){
5407    int pc, ppc;
5408    int startLine = p->nLine;
5409    int cQuote = c;
5410    pc = ppc = 0;
5411    while( 1 ){
5412      c = fgetc(p->in);
5413      if( c==rSep ) p->nLine++;
5414      if( c==cQuote ){
5415        if( pc==cQuote ){
5416          pc = 0;
5417          continue;
5418        }
5419      }
5420      if( (c==cSep && pc==cQuote)
5421       || (c==rSep && pc==cQuote)
5422       || (c==rSep && pc=='\r' && ppc==cQuote)
5423       || (c==EOF && pc==cQuote)
5424      ){
5425        do{ p->n--; }while( p->z[p->n]!=cQuote );
5426        p->cTerm = c;
5427        break;
5428      }
5429      if( pc==cQuote && c!='\r' ){
5430        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5431                p->zFile, p->nLine, cQuote);
5432      }
5433      if( c==EOF ){
5434        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5435                p->zFile, startLine, cQuote);
5436        p->cTerm = c;
5437        break;
5438      }
5439      import_append_char(p, c);
5440      ppc = pc;
5441      pc = c;
5442    }
5443  }else{
5444    /* If this is the first field being parsed and it begins with the
5445    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5446    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5447      import_append_char(p, c);
5448      c = fgetc(p->in);
5449      if( (c&0xff)==0xbb ){
5450        import_append_char(p, c);
5451        c = fgetc(p->in);
5452        if( (c&0xff)==0xbf ){
5453          p->bNotFirst = 1;
5454          p->n = 0;
5455          return csv_read_one_field(p);
5456        }
5457      }
5458    }
5459    while( c!=EOF && c!=cSep && c!=rSep ){
5460      import_append_char(p, c);
5461      c = fgetc(p->in);
5462    }
5463    if( c==rSep ){
5464      p->nLine++;
5465      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5466    }
5467    p->cTerm = c;
5468  }
5469  if( p->z ) p->z[p->n] = 0;
5470  p->bNotFirst = 1;
5471  return p->z;
5472}
5473
5474/* Read a single field of ASCII delimited text.
5475**
5476**   +  Input comes from p->in.
5477**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5478**      from sqlite3_malloc64().
5479**   +  Use p->cSep as the column separator.  The default is "\x1F".
5480**   +  Use p->rSep as the row separator.  The default is "\x1E".
5481**   +  Keep track of the row number in p->nLine.
5482**   +  Store the character that terminates the field in p->cTerm.  Store
5483**      EOF on end-of-file.
5484**   +  Report syntax errors on stderr
5485*/
5486static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5487  int c;
5488  int cSep = p->cColSep;
5489  int rSep = p->cRowSep;
5490  p->n = 0;
5491  c = fgetc(p->in);
5492  if( c==EOF || seenInterrupt ){
5493    p->cTerm = EOF;
5494    return 0;
5495  }
5496  while( c!=EOF && c!=cSep && c!=rSep ){
5497    import_append_char(p, c);
5498    c = fgetc(p->in);
5499  }
5500  if( c==rSep ){
5501    p->nLine++;
5502  }
5503  p->cTerm = c;
5504  if( p->z ) p->z[p->n] = 0;
5505  return p->z;
5506}
5507
5508/*
5509** Try to transfer data for table zTable.  If an error is seen while
5510** moving forward, try to go backwards.  The backwards movement won't
5511** work for WITHOUT ROWID tables.
5512*/
5513static void tryToCloneData(
5514  ShellState *p,
5515  sqlite3 *newDb,
5516  const char *zTable
5517){
5518  sqlite3_stmt *pQuery = 0;
5519  sqlite3_stmt *pInsert = 0;
5520  char *zQuery = 0;
5521  char *zInsert = 0;
5522  int rc;
5523  int i, j, n;
5524  int nTable = strlen30(zTable);
5525  int k = 0;
5526  int cnt = 0;
5527  const int spinRate = 10000;
5528
5529  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5530  shell_check_oom(zQuery);
5531  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5532  if( rc ){
5533    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5534            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5535            zQuery);
5536    goto end_data_xfer;
5537  }
5538  n = sqlite3_column_count(pQuery);
5539  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5540  shell_check_oom(zInsert);
5541  sqlite3_snprintf(200+nTable,zInsert,
5542                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5543  i = strlen30(zInsert);
5544  for(j=1; j<n; j++){
5545    memcpy(zInsert+i, ",?", 2);
5546    i += 2;
5547  }
5548  memcpy(zInsert+i, ");", 3);
5549  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5550  if( rc ){
5551    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5552            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5553            zQuery);
5554    goto end_data_xfer;
5555  }
5556  for(k=0; k<2; k++){
5557    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5558      for(i=0; i<n; i++){
5559        switch( sqlite3_column_type(pQuery, i) ){
5560          case SQLITE_NULL: {
5561            sqlite3_bind_null(pInsert, i+1);
5562            break;
5563          }
5564          case SQLITE_INTEGER: {
5565            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5566            break;
5567          }
5568          case SQLITE_FLOAT: {
5569            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5570            break;
5571          }
5572          case SQLITE_TEXT: {
5573            sqlite3_bind_text(pInsert, i+1,
5574                             (const char*)sqlite3_column_text(pQuery,i),
5575                             -1, SQLITE_STATIC);
5576            break;
5577          }
5578          case SQLITE_BLOB: {
5579            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5580                                            sqlite3_column_bytes(pQuery,i),
5581                                            SQLITE_STATIC);
5582            break;
5583          }
5584        }
5585      } /* End for */
5586      rc = sqlite3_step(pInsert);
5587      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5588        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5589                        sqlite3_errmsg(newDb));
5590      }
5591      sqlite3_reset(pInsert);
5592      cnt++;
5593      if( (cnt%spinRate)==0 ){
5594        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5595        fflush(stdout);
5596      }
5597    } /* End while */
5598    if( rc==SQLITE_DONE ) break;
5599    sqlite3_finalize(pQuery);
5600    sqlite3_free(zQuery);
5601    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5602                             zTable);
5603    shell_check_oom(zQuery);
5604    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5605    if( rc ){
5606      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5607      break;
5608    }
5609  } /* End for(k=0...) */
5610
5611end_data_xfer:
5612  sqlite3_finalize(pQuery);
5613  sqlite3_finalize(pInsert);
5614  sqlite3_free(zQuery);
5615  sqlite3_free(zInsert);
5616}
5617
5618
5619/*
5620** Try to transfer all rows of the schema that match zWhere.  For
5621** each row, invoke xForEach() on the object defined by that row.
5622** If an error is encountered while moving forward through the
5623** sqlite_schema table, try again moving backwards.
5624*/
5625static void tryToCloneSchema(
5626  ShellState *p,
5627  sqlite3 *newDb,
5628  const char *zWhere,
5629  void (*xForEach)(ShellState*,sqlite3*,const char*)
5630){
5631  sqlite3_stmt *pQuery = 0;
5632  char *zQuery = 0;
5633  int rc;
5634  const unsigned char *zName;
5635  const unsigned char *zSql;
5636  char *zErrMsg = 0;
5637
5638  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5639                           " WHERE %s", zWhere);
5640  shell_check_oom(zQuery);
5641  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5642  if( rc ){
5643    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5644                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5645                    zQuery);
5646    goto end_schema_xfer;
5647  }
5648  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5649    zName = sqlite3_column_text(pQuery, 0);
5650    zSql = sqlite3_column_text(pQuery, 1);
5651    if( zName==0 || zSql==0 ) continue;
5652    printf("%s... ", zName); fflush(stdout);
5653    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5654    if( zErrMsg ){
5655      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5656      sqlite3_free(zErrMsg);
5657      zErrMsg = 0;
5658    }
5659    if( xForEach ){
5660      xForEach(p, newDb, (const char*)zName);
5661    }
5662    printf("done\n");
5663  }
5664  if( rc!=SQLITE_DONE ){
5665    sqlite3_finalize(pQuery);
5666    sqlite3_free(zQuery);
5667    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5668                             " WHERE %s ORDER BY rowid DESC", zWhere);
5669    shell_check_oom(zQuery);
5670    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5671    if( rc ){
5672      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5673                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5674                      zQuery);
5675      goto end_schema_xfer;
5676    }
5677    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5678      zName = sqlite3_column_text(pQuery, 0);
5679      zSql = sqlite3_column_text(pQuery, 1);
5680      if( zName==0 || zSql==0 ) continue;
5681      printf("%s... ", zName); fflush(stdout);
5682      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5683      if( zErrMsg ){
5684        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5685        sqlite3_free(zErrMsg);
5686        zErrMsg = 0;
5687      }
5688      if( xForEach ){
5689        xForEach(p, newDb, (const char*)zName);
5690      }
5691      printf("done\n");
5692    }
5693  }
5694end_schema_xfer:
5695  sqlite3_finalize(pQuery);
5696  sqlite3_free(zQuery);
5697}
5698
5699/*
5700** Open a new database file named "zNewDb".  Try to recover as much information
5701** as possible out of the main database (which might be corrupt) and write it
5702** into zNewDb.
5703*/
5704static void tryToClone(ShellState *p, const char *zNewDb){
5705  int rc;
5706  sqlite3 *newDb = 0;
5707  if( access(zNewDb,0)==0 ){
5708    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5709    return;
5710  }
5711  rc = sqlite3_open(zNewDb, &newDb);
5712  if( rc ){
5713    utf8_printf(stderr, "Cannot create output database: %s\n",
5714            sqlite3_errmsg(newDb));
5715  }else{
5716    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5717    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5718    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5719    tryToCloneSchema(p, newDb, "type!='table'", 0);
5720    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5721    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5722  }
5723  close_db(newDb);
5724}
5725
5726/*
5727** Change the output file back to stdout.
5728**
5729** If the p->doXdgOpen flag is set, that means the output was being
5730** redirected to a temporary file named by p->zTempFile.  In that case,
5731** launch start/open/xdg-open on that temporary file.
5732*/
5733static void output_reset(ShellState *p){
5734  if( p->outfile[0]=='|' ){
5735#ifndef SQLITE_OMIT_POPEN
5736    pclose(p->out);
5737#endif
5738  }else{
5739    output_file_close(p->out);
5740#ifndef SQLITE_NOHAVE_SYSTEM
5741    if( p->doXdgOpen ){
5742      const char *zXdgOpenCmd =
5743#if defined(_WIN32)
5744      "start";
5745#elif defined(__APPLE__)
5746      "open";
5747#else
5748      "xdg-open";
5749#endif
5750      char *zCmd;
5751      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5752      if( system(zCmd) ){
5753        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5754      }else{
5755        /* Give the start/open/xdg-open command some time to get
5756        ** going before we continue, and potential delete the
5757        ** p->zTempFile data file out from under it */
5758        sqlite3_sleep(2000);
5759      }
5760      sqlite3_free(zCmd);
5761      outputModePop(p);
5762      p->doXdgOpen = 0;
5763    }
5764#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5765  }
5766  p->outfile[0] = 0;
5767  p->out = stdout;
5768}
5769
5770/*
5771** Run an SQL command and return the single integer result.
5772*/
5773static int db_int(sqlite3 *db, const char *zSql){
5774  sqlite3_stmt *pStmt;
5775  int res = 0;
5776  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5777  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5778    res = sqlite3_column_int(pStmt,0);
5779  }
5780  sqlite3_finalize(pStmt);
5781  return res;
5782}
5783
5784/*
5785** Convert a 2-byte or 4-byte big-endian integer into a native integer
5786*/
5787static unsigned int get2byteInt(unsigned char *a){
5788  return (a[0]<<8) + a[1];
5789}
5790static unsigned int get4byteInt(unsigned char *a){
5791  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5792}
5793
5794/*
5795** Implementation of the ".dbinfo" command.
5796**
5797** Return 1 on error, 2 to exit, and 0 otherwise.
5798*/
5799static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5800  static const struct { const char *zName; int ofst; } aField[] = {
5801     { "file change counter:",  24  },
5802     { "database page count:",  28  },
5803     { "freelist page count:",  36  },
5804     { "schema cookie:",        40  },
5805     { "schema format:",        44  },
5806     { "default cache size:",   48  },
5807     { "autovacuum top root:",  52  },
5808     { "incremental vacuum:",   64  },
5809     { "text encoding:",        56  },
5810     { "user version:",         60  },
5811     { "application id:",       68  },
5812     { "software version:",     96  },
5813  };
5814  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5815     { "number of tables:",
5816       "SELECT count(*) FROM %s WHERE type='table'" },
5817     { "number of indexes:",
5818       "SELECT count(*) FROM %s WHERE type='index'" },
5819     { "number of triggers:",
5820       "SELECT count(*) FROM %s WHERE type='trigger'" },
5821     { "number of views:",
5822       "SELECT count(*) FROM %s WHERE type='view'" },
5823     { "schema size:",
5824       "SELECT total(length(sql)) FROM %s" },
5825  };
5826  int i, rc;
5827  unsigned iDataVersion;
5828  char *zSchemaTab;
5829  char *zDb = nArg>=2 ? azArg[1] : "main";
5830  sqlite3_stmt *pStmt = 0;
5831  unsigned char aHdr[100];
5832  open_db(p, 0);
5833  if( p->db==0 ) return 1;
5834  rc = sqlite3_prepare_v2(p->db,
5835             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5836             -1, &pStmt, 0);
5837  if( rc ){
5838    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5839    sqlite3_finalize(pStmt);
5840    return 1;
5841  }
5842  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5843  if( sqlite3_step(pStmt)==SQLITE_ROW
5844   && sqlite3_column_bytes(pStmt,0)>100
5845  ){
5846    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5847    sqlite3_finalize(pStmt);
5848  }else{
5849    raw_printf(stderr, "unable to read database header\n");
5850    sqlite3_finalize(pStmt);
5851    return 1;
5852  }
5853  i = get2byteInt(aHdr+16);
5854  if( i==1 ) i = 65536;
5855  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5856  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5857  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5858  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5859  for(i=0; i<ArraySize(aField); i++){
5860    int ofst = aField[i].ofst;
5861    unsigned int val = get4byteInt(aHdr + ofst);
5862    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5863    switch( ofst ){
5864      case 56: {
5865        if( val==1 ) raw_printf(p->out, " (utf8)");
5866        if( val==2 ) raw_printf(p->out, " (utf16le)");
5867        if( val==3 ) raw_printf(p->out, " (utf16be)");
5868      }
5869    }
5870    raw_printf(p->out, "\n");
5871  }
5872  if( zDb==0 ){
5873    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5874  }else if( strcmp(zDb,"temp")==0 ){
5875    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5876  }else{
5877    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5878  }
5879  for(i=0; i<ArraySize(aQuery); i++){
5880    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5881    int val = db_int(p->db, zSql);
5882    sqlite3_free(zSql);
5883    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5884  }
5885  sqlite3_free(zSchemaTab);
5886  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5887  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5888  return 0;
5889}
5890
5891/*
5892** Print the current sqlite3_errmsg() value to stderr and return 1.
5893*/
5894static int shellDatabaseError(sqlite3 *db){
5895  const char *zErr = sqlite3_errmsg(db);
5896  utf8_printf(stderr, "Error: %s\n", zErr);
5897  return 1;
5898}
5899
5900/*
5901** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5902** if they match and FALSE (0) if they do not match.
5903**
5904** Globbing rules:
5905**
5906**      '*'       Matches any sequence of zero or more characters.
5907**
5908**      '?'       Matches exactly one character.
5909**
5910**     [...]      Matches one character from the enclosed list of
5911**                characters.
5912**
5913**     [^...]     Matches one character not in the enclosed list.
5914**
5915**      '#'       Matches any sequence of one or more digits with an
5916**                optional + or - sign in front
5917**
5918**      ' '       Any span of whitespace matches any other span of
5919**                whitespace.
5920**
5921** Extra whitespace at the end of z[] is ignored.
5922*/
5923static int testcase_glob(const char *zGlob, const char *z){
5924  int c, c2;
5925  int invert;
5926  int seen;
5927
5928  while( (c = (*(zGlob++)))!=0 ){
5929    if( IsSpace(c) ){
5930      if( !IsSpace(*z) ) return 0;
5931      while( IsSpace(*zGlob) ) zGlob++;
5932      while( IsSpace(*z) ) z++;
5933    }else if( c=='*' ){
5934      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5935        if( c=='?' && (*(z++))==0 ) return 0;
5936      }
5937      if( c==0 ){
5938        return 1;
5939      }else if( c=='[' ){
5940        while( *z && testcase_glob(zGlob-1,z)==0 ){
5941          z++;
5942        }
5943        return (*z)!=0;
5944      }
5945      while( (c2 = (*(z++)))!=0 ){
5946        while( c2!=c ){
5947          c2 = *(z++);
5948          if( c2==0 ) return 0;
5949        }
5950        if( testcase_glob(zGlob,z) ) return 1;
5951      }
5952      return 0;
5953    }else if( c=='?' ){
5954      if( (*(z++))==0 ) return 0;
5955    }else if( c=='[' ){
5956      int prior_c = 0;
5957      seen = 0;
5958      invert = 0;
5959      c = *(z++);
5960      if( c==0 ) return 0;
5961      c2 = *(zGlob++);
5962      if( c2=='^' ){
5963        invert = 1;
5964        c2 = *(zGlob++);
5965      }
5966      if( c2==']' ){
5967        if( c==']' ) seen = 1;
5968        c2 = *(zGlob++);
5969      }
5970      while( c2 && c2!=']' ){
5971        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5972          c2 = *(zGlob++);
5973          if( c>=prior_c && c<=c2 ) seen = 1;
5974          prior_c = 0;
5975        }else{
5976          if( c==c2 ){
5977            seen = 1;
5978          }
5979          prior_c = c2;
5980        }
5981        c2 = *(zGlob++);
5982      }
5983      if( c2==0 || (seen ^ invert)==0 ) return 0;
5984    }else if( c=='#' ){
5985      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5986      if( !IsDigit(z[0]) ) return 0;
5987      z++;
5988      while( IsDigit(z[0]) ){ z++; }
5989    }else{
5990      if( c!=(*(z++)) ) return 0;
5991    }
5992  }
5993  while( IsSpace(*z) ){ z++; }
5994  return *z==0;
5995}
5996
5997
5998/*
5999** Compare the string as a command-line option with either one or two
6000** initial "-" characters.
6001*/
6002static int optionMatch(const char *zStr, const char *zOpt){
6003  if( zStr[0]!='-' ) return 0;
6004  zStr++;
6005  if( zStr[0]=='-' ) zStr++;
6006  return strcmp(zStr, zOpt)==0;
6007}
6008
6009/*
6010** Delete a file.
6011*/
6012int shellDeleteFile(const char *zFilename){
6013  int rc;
6014#ifdef _WIN32
6015  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6016  rc = _wunlink(z);
6017  sqlite3_free(z);
6018#else
6019  rc = unlink(zFilename);
6020#endif
6021  return rc;
6022}
6023
6024/*
6025** Try to delete the temporary file (if there is one) and free the
6026** memory used to hold the name of the temp file.
6027*/
6028static void clearTempFile(ShellState *p){
6029  if( p->zTempFile==0 ) return;
6030  if( p->doXdgOpen ) return;
6031  if( shellDeleteFile(p->zTempFile) ) return;
6032  sqlite3_free(p->zTempFile);
6033  p->zTempFile = 0;
6034}
6035
6036/*
6037** Create a new temp file name with the given suffix.
6038*/
6039static void newTempFile(ShellState *p, const char *zSuffix){
6040  clearTempFile(p);
6041  sqlite3_free(p->zTempFile);
6042  p->zTempFile = 0;
6043  if( p->db ){
6044    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6045  }
6046  if( p->zTempFile==0 ){
6047    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6048    ** will not work and we will need to fallback to guessing */
6049    char *zTemp;
6050    sqlite3_uint64 r;
6051    sqlite3_randomness(sizeof(r), &r);
6052    zTemp = getenv("TEMP");
6053    if( zTemp==0 ) zTemp = getenv("TMP");
6054    if( zTemp==0 ){
6055#ifdef _WIN32
6056      zTemp = "\\tmp";
6057#else
6058      zTemp = "/tmp";
6059#endif
6060    }
6061    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6062  }else{
6063    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6064  }
6065  shell_check_oom(p->zTempFile);
6066}
6067
6068
6069/*
6070** The implementation of SQL scalar function fkey_collate_clause(), used
6071** by the ".lint fkey-indexes" command. This scalar function is always
6072** called with four arguments - the parent table name, the parent column name,
6073** the child table name and the child column name.
6074**
6075**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6076**
6077** If either of the named tables or columns do not exist, this function
6078** returns an empty string. An empty string is also returned if both tables
6079** and columns exist but have the same default collation sequence. Or,
6080** if both exist but the default collation sequences are different, this
6081** function returns the string " COLLATE <parent-collation>", where
6082** <parent-collation> is the default collation sequence of the parent column.
6083*/
6084static void shellFkeyCollateClause(
6085  sqlite3_context *pCtx,
6086  int nVal,
6087  sqlite3_value **apVal
6088){
6089  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6090  const char *zParent;
6091  const char *zParentCol;
6092  const char *zParentSeq;
6093  const char *zChild;
6094  const char *zChildCol;
6095  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6096  int rc;
6097
6098  assert( nVal==4 );
6099  zParent = (const char*)sqlite3_value_text(apVal[0]);
6100  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6101  zChild = (const char*)sqlite3_value_text(apVal[2]);
6102  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6103
6104  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6105  rc = sqlite3_table_column_metadata(
6106      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6107  );
6108  if( rc==SQLITE_OK ){
6109    rc = sqlite3_table_column_metadata(
6110        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6111    );
6112  }
6113
6114  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6115    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6116    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6117    sqlite3_free(z);
6118  }
6119}
6120
6121
6122/*
6123** The implementation of dot-command ".lint fkey-indexes".
6124*/
6125static int lintFkeyIndexes(
6126  ShellState *pState,             /* Current shell tool state */
6127  char **azArg,                   /* Array of arguments passed to dot command */
6128  int nArg                        /* Number of entries in azArg[] */
6129){
6130  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6131  FILE *out = pState->out;        /* Stream to write non-error output to */
6132  int bVerbose = 0;               /* If -verbose is present */
6133  int bGroupByParent = 0;         /* If -groupbyparent is present */
6134  int i;                          /* To iterate through azArg[] */
6135  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6136  int rc;                         /* Return code */
6137  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6138
6139  /*
6140  ** This SELECT statement returns one row for each foreign key constraint
6141  ** in the schema of the main database. The column values are:
6142  **
6143  ** 0. The text of an SQL statement similar to:
6144  **
6145  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6146  **
6147  **    This SELECT is similar to the one that the foreign keys implementation
6148  **    needs to run internally on child tables. If there is an index that can
6149  **    be used to optimize this query, then it can also be used by the FK
6150  **    implementation to optimize DELETE or UPDATE statements on the parent
6151  **    table.
6152  **
6153  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6154  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6155  **    contains an index that can be used to optimize the query.
6156  **
6157  ** 2. Human readable text that describes the child table and columns. e.g.
6158  **
6159  **       "child_table(child_key1, child_key2)"
6160  **
6161  ** 3. Human readable text that describes the parent table and columns. e.g.
6162  **
6163  **       "parent_table(parent_key1, parent_key2)"
6164  **
6165  ** 4. A full CREATE INDEX statement for an index that could be used to
6166  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6167  **
6168  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6169  **
6170  ** 5. The name of the parent table.
6171  **
6172  ** These six values are used by the C logic below to generate the report.
6173  */
6174  const char *zSql =
6175  "SELECT "
6176    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6177    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6178    "  || fkey_collate_clause("
6179    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6180    ", "
6181    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6182    "  || group_concat('*=?', ' AND ') || ')'"
6183    ", "
6184    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6185    ", "
6186    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6187    ", "
6188    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6189    "  || ' ON ' || quote(s.name) || '('"
6190    "  || group_concat(quote(f.[from]) ||"
6191    "        fkey_collate_clause("
6192    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6193    "  || ');'"
6194    ", "
6195    "     f.[table] "
6196    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6197    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6198    "GROUP BY s.name, f.id "
6199    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6200  ;
6201  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6202
6203  for(i=2; i<nArg; i++){
6204    int n = strlen30(azArg[i]);
6205    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6206      bVerbose = 1;
6207    }
6208    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6209      bGroupByParent = 1;
6210      zIndent = "    ";
6211    }
6212    else{
6213      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6214          azArg[0], azArg[1]
6215      );
6216      return SQLITE_ERROR;
6217    }
6218  }
6219
6220  /* Register the fkey_collate_clause() SQL function */
6221  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6222      0, shellFkeyCollateClause, 0, 0
6223  );
6224
6225
6226  if( rc==SQLITE_OK ){
6227    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6228  }
6229  if( rc==SQLITE_OK ){
6230    sqlite3_bind_int(pSql, 1, bGroupByParent);
6231  }
6232
6233  if( rc==SQLITE_OK ){
6234    int rc2;
6235    char *zPrev = 0;
6236    while( SQLITE_ROW==sqlite3_step(pSql) ){
6237      int res = -1;
6238      sqlite3_stmt *pExplain = 0;
6239      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6240      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6241      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6242      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6243      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6244      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6245
6246      if( zEQP==0 ) continue;
6247      if( zGlob==0 ) continue;
6248      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6249      if( rc!=SQLITE_OK ) break;
6250      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6251        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6252        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6253                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6254      }
6255      rc = sqlite3_finalize(pExplain);
6256      if( rc!=SQLITE_OK ) break;
6257
6258      if( res<0 ){
6259        raw_printf(stderr, "Error: internal error");
6260        break;
6261      }else{
6262        if( bGroupByParent
6263        && (bVerbose || res==0)
6264        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6265        ){
6266          raw_printf(out, "-- Parent table %s\n", zParent);
6267          sqlite3_free(zPrev);
6268          zPrev = sqlite3_mprintf("%s", zParent);
6269        }
6270
6271        if( res==0 ){
6272          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6273        }else if( bVerbose ){
6274          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6275              zIndent, zFrom, zTarget
6276          );
6277        }
6278      }
6279    }
6280    sqlite3_free(zPrev);
6281
6282    if( rc!=SQLITE_OK ){
6283      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6284    }
6285
6286    rc2 = sqlite3_finalize(pSql);
6287    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6288      rc = rc2;
6289      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6290    }
6291  }else{
6292    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6293  }
6294
6295  return rc;
6296}
6297
6298/*
6299** Implementation of ".lint" dot command.
6300*/
6301static int lintDotCommand(
6302  ShellState *pState,             /* Current shell tool state */
6303  char **azArg,                   /* Array of arguments passed to dot command */
6304  int nArg                        /* Number of entries in azArg[] */
6305){
6306  int n;
6307  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6308  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6309  return lintFkeyIndexes(pState, azArg, nArg);
6310
6311 usage:
6312  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6313  raw_printf(stderr, "Where sub-commands are:\n");
6314  raw_printf(stderr, "    fkey-indexes\n");
6315  return SQLITE_ERROR;
6316}
6317
6318#if !defined SQLITE_OMIT_VIRTUALTABLE
6319static void shellPrepare(
6320  sqlite3 *db,
6321  int *pRc,
6322  const char *zSql,
6323  sqlite3_stmt **ppStmt
6324){
6325  *ppStmt = 0;
6326  if( *pRc==SQLITE_OK ){
6327    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6328    if( rc!=SQLITE_OK ){
6329      raw_printf(stderr, "sql error: %s (%d)\n",
6330          sqlite3_errmsg(db), sqlite3_errcode(db)
6331      );
6332      *pRc = rc;
6333    }
6334  }
6335}
6336
6337/*
6338** Create a prepared statement using printf-style arguments for the SQL.
6339**
6340** This routine is could be marked "static".  But it is not always used,
6341** depending on compile-time options.  By omitting the "static", we avoid
6342** nuisance compiler warnings about "defined but not used".
6343*/
6344void shellPreparePrintf(
6345  sqlite3 *db,
6346  int *pRc,
6347  sqlite3_stmt **ppStmt,
6348  const char *zFmt,
6349  ...
6350){
6351  *ppStmt = 0;
6352  if( *pRc==SQLITE_OK ){
6353    va_list ap;
6354    char *z;
6355    va_start(ap, zFmt);
6356    z = sqlite3_vmprintf(zFmt, ap);
6357    va_end(ap);
6358    if( z==0 ){
6359      *pRc = SQLITE_NOMEM;
6360    }else{
6361      shellPrepare(db, pRc, z, ppStmt);
6362      sqlite3_free(z);
6363    }
6364  }
6365}
6366
6367/* Finalize the prepared statement created using shellPreparePrintf().
6368**
6369** This routine is could be marked "static".  But it is not always used,
6370** depending on compile-time options.  By omitting the "static", we avoid
6371** nuisance compiler warnings about "defined but not used".
6372*/
6373void shellFinalize(
6374  int *pRc,
6375  sqlite3_stmt *pStmt
6376){
6377  if( pStmt ){
6378    sqlite3 *db = sqlite3_db_handle(pStmt);
6379    int rc = sqlite3_finalize(pStmt);
6380    if( *pRc==SQLITE_OK ){
6381      if( rc!=SQLITE_OK ){
6382        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6383      }
6384      *pRc = rc;
6385    }
6386  }
6387}
6388
6389/* Reset the prepared statement created using shellPreparePrintf().
6390**
6391** This routine is could be marked "static".  But it is not always used,
6392** depending on compile-time options.  By omitting the "static", we avoid
6393** nuisance compiler warnings about "defined but not used".
6394*/
6395void shellReset(
6396  int *pRc,
6397  sqlite3_stmt *pStmt
6398){
6399  int rc = sqlite3_reset(pStmt);
6400  if( *pRc==SQLITE_OK ){
6401    if( rc!=SQLITE_OK ){
6402      sqlite3 *db = sqlite3_db_handle(pStmt);
6403      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6404    }
6405    *pRc = rc;
6406  }
6407}
6408#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6409
6410#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6411/******************************************************************************
6412** The ".archive" or ".ar" command.
6413*/
6414/*
6415** Structure representing a single ".ar" command.
6416*/
6417typedef struct ArCommand ArCommand;
6418struct ArCommand {
6419  u8 eCmd;                        /* An AR_CMD_* value */
6420  u8 bVerbose;                    /* True if --verbose */
6421  u8 bZip;                        /* True if the archive is a ZIP */
6422  u8 bDryRun;                     /* True if --dry-run */
6423  u8 bAppend;                     /* True if --append */
6424  u8 bGlob;                       /* True if --glob */
6425  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6426  int nArg;                       /* Number of command arguments */
6427  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6428  const char *zFile;              /* --file argument, or NULL */
6429  const char *zDir;               /* --directory argument, or NULL */
6430  char **azArg;                   /* Array of command arguments */
6431  ShellState *p;                  /* Shell state */
6432  sqlite3 *db;                    /* Database containing the archive */
6433};
6434
6435/*
6436** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6437*/
6438static int arUsage(FILE *f){
6439  showHelp(f,"archive");
6440  return SQLITE_ERROR;
6441}
6442
6443/*
6444** Print an error message for the .ar command to stderr and return
6445** SQLITE_ERROR.
6446*/
6447static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6448  va_list ap;
6449  char *z;
6450  va_start(ap, zFmt);
6451  z = sqlite3_vmprintf(zFmt, ap);
6452  va_end(ap);
6453  utf8_printf(stderr, "Error: %s\n", z);
6454  if( pAr->fromCmdLine ){
6455    utf8_printf(stderr, "Use \"-A\" for more help\n");
6456  }else{
6457    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6458  }
6459  sqlite3_free(z);
6460  return SQLITE_ERROR;
6461}
6462
6463/*
6464** Values for ArCommand.eCmd.
6465*/
6466#define AR_CMD_CREATE       1
6467#define AR_CMD_UPDATE       2
6468#define AR_CMD_INSERT       3
6469#define AR_CMD_EXTRACT      4
6470#define AR_CMD_LIST         5
6471#define AR_CMD_HELP         6
6472#define AR_CMD_REMOVE       7
6473
6474/*
6475** Other (non-command) switches.
6476*/
6477#define AR_SWITCH_VERBOSE     8
6478#define AR_SWITCH_FILE        9
6479#define AR_SWITCH_DIRECTORY  10
6480#define AR_SWITCH_APPEND     11
6481#define AR_SWITCH_DRYRUN     12
6482#define AR_SWITCH_GLOB       13
6483
6484static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6485  switch( eSwitch ){
6486    case AR_CMD_CREATE:
6487    case AR_CMD_EXTRACT:
6488    case AR_CMD_LIST:
6489    case AR_CMD_REMOVE:
6490    case AR_CMD_UPDATE:
6491    case AR_CMD_INSERT:
6492    case AR_CMD_HELP:
6493      if( pAr->eCmd ){
6494        return arErrorMsg(pAr, "multiple command options");
6495      }
6496      pAr->eCmd = eSwitch;
6497      break;
6498
6499    case AR_SWITCH_DRYRUN:
6500      pAr->bDryRun = 1;
6501      break;
6502    case AR_SWITCH_GLOB:
6503      pAr->bGlob = 1;
6504      break;
6505    case AR_SWITCH_VERBOSE:
6506      pAr->bVerbose = 1;
6507      break;
6508    case AR_SWITCH_APPEND:
6509      pAr->bAppend = 1;
6510      /* Fall thru into --file */
6511    case AR_SWITCH_FILE:
6512      pAr->zFile = zArg;
6513      break;
6514    case AR_SWITCH_DIRECTORY:
6515      pAr->zDir = zArg;
6516      break;
6517  }
6518
6519  return SQLITE_OK;
6520}
6521
6522/*
6523** Parse the command line for an ".ar" command. The results are written into
6524** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6525** successfully, otherwise an error message is written to stderr and
6526** SQLITE_ERROR returned.
6527*/
6528static int arParseCommand(
6529  char **azArg,                   /* Array of arguments passed to dot command */
6530  int nArg,                       /* Number of entries in azArg[] */
6531  ArCommand *pAr                  /* Populate this object */
6532){
6533  struct ArSwitch {
6534    const char *zLong;
6535    char cShort;
6536    u8 eSwitch;
6537    u8 bArg;
6538  } aSwitch[] = {
6539    { "create",    'c', AR_CMD_CREATE,       0 },
6540    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6541    { "insert",    'i', AR_CMD_INSERT,       0 },
6542    { "list",      't', AR_CMD_LIST,         0 },
6543    { "remove",    'r', AR_CMD_REMOVE,       0 },
6544    { "update",    'u', AR_CMD_UPDATE,       0 },
6545    { "help",      'h', AR_CMD_HELP,         0 },
6546    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6547    { "file",      'f', AR_SWITCH_FILE,      1 },
6548    { "append",    'a', AR_SWITCH_APPEND,    1 },
6549    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6550    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6551    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6552  };
6553  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6554  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6555
6556  if( nArg<=1 ){
6557    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6558    return arUsage(stderr);
6559  }else{
6560    char *z = azArg[1];
6561    if( z[0]!='-' ){
6562      /* Traditional style [tar] invocation */
6563      int i;
6564      int iArg = 2;
6565      for(i=0; z[i]; i++){
6566        const char *zArg = 0;
6567        struct ArSwitch *pOpt;
6568        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6569          if( z[i]==pOpt->cShort ) break;
6570        }
6571        if( pOpt==pEnd ){
6572          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6573        }
6574        if( pOpt->bArg ){
6575          if( iArg>=nArg ){
6576            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6577          }
6578          zArg = azArg[iArg++];
6579        }
6580        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6581      }
6582      pAr->nArg = nArg-iArg;
6583      if( pAr->nArg>0 ){
6584        pAr->azArg = &azArg[iArg];
6585      }
6586    }else{
6587      /* Non-traditional invocation */
6588      int iArg;
6589      for(iArg=1; iArg<nArg; iArg++){
6590        int n;
6591        z = azArg[iArg];
6592        if( z[0]!='-' ){
6593          /* All remaining command line words are command arguments. */
6594          pAr->azArg = &azArg[iArg];
6595          pAr->nArg = nArg-iArg;
6596          break;
6597        }
6598        n = strlen30(z);
6599
6600        if( z[1]!='-' ){
6601          int i;
6602          /* One or more short options */
6603          for(i=1; i<n; i++){
6604            const char *zArg = 0;
6605            struct ArSwitch *pOpt;
6606            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6607              if( z[i]==pOpt->cShort ) break;
6608            }
6609            if( pOpt==pEnd ){
6610              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6611            }
6612            if( pOpt->bArg ){
6613              if( i<(n-1) ){
6614                zArg = &z[i+1];
6615                i = n;
6616              }else{
6617                if( iArg>=(nArg-1) ){
6618                  return arErrorMsg(pAr, "option requires an argument: %c",
6619                                    z[i]);
6620                }
6621                zArg = azArg[++iArg];
6622              }
6623            }
6624            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6625          }
6626        }else if( z[2]=='\0' ){
6627          /* A -- option, indicating that all remaining command line words
6628          ** are command arguments.  */
6629          pAr->azArg = &azArg[iArg+1];
6630          pAr->nArg = nArg-iArg-1;
6631          break;
6632        }else{
6633          /* A long option */
6634          const char *zArg = 0;             /* Argument for option, if any */
6635          struct ArSwitch *pMatch = 0;      /* Matching option */
6636          struct ArSwitch *pOpt;            /* Iterator */
6637          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6638            const char *zLong = pOpt->zLong;
6639            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6640              if( pMatch ){
6641                return arErrorMsg(pAr, "ambiguous option: %s",z);
6642              }else{
6643                pMatch = pOpt;
6644              }
6645            }
6646          }
6647
6648          if( pMatch==0 ){
6649            return arErrorMsg(pAr, "unrecognized option: %s", z);
6650          }
6651          if( pMatch->bArg ){
6652            if( iArg>=(nArg-1) ){
6653              return arErrorMsg(pAr, "option requires an argument: %s", z);
6654            }
6655            zArg = azArg[++iArg];
6656          }
6657          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6658        }
6659      }
6660    }
6661  }
6662
6663  return SQLITE_OK;
6664}
6665
6666/*
6667** This function assumes that all arguments within the ArCommand.azArg[]
6668** array refer to archive members, as for the --extract, --list or --remove
6669** commands. It checks that each of them are "present". If any specified
6670** file is not present in the archive, an error is printed to stderr and an
6671** error code returned. Otherwise, if all specified arguments are present
6672** in the archive, SQLITE_OK is returned. Here, "present" means either an
6673** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6674** when pAr->bGlob is true.
6675**
6676** This function strips any trailing '/' characters from each argument.
6677** This is consistent with the way the [tar] command seems to work on
6678** Linux.
6679*/
6680static int arCheckEntries(ArCommand *pAr){
6681  int rc = SQLITE_OK;
6682  if( pAr->nArg ){
6683    int i, j;
6684    sqlite3_stmt *pTest = 0;
6685    const char *zSel = (pAr->bGlob)
6686      ? "SELECT name FROM %s WHERE glob($name,name)"
6687      : "SELECT name FROM %s WHERE name=$name";
6688
6689    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6690    j = sqlite3_bind_parameter_index(pTest, "$name");
6691    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6692      char *z = pAr->azArg[i];
6693      int n = strlen30(z);
6694      int bOk = 0;
6695      while( n>0 && z[n-1]=='/' ) n--;
6696      z[n] = '\0';
6697      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6698      if( SQLITE_ROW==sqlite3_step(pTest) ){
6699        bOk = 1;
6700      }
6701      shellReset(&rc, pTest);
6702      if( rc==SQLITE_OK && bOk==0 ){
6703        utf8_printf(stderr, "not found in archive: %s\n", z);
6704        rc = SQLITE_ERROR;
6705      }
6706    }
6707    shellFinalize(&rc, pTest);
6708  }
6709  return rc;
6710}
6711
6712/*
6713** Format a WHERE clause that can be used against the "sqlar" table to
6714** identify all archive members that match the command arguments held
6715** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6716** The caller is responsible for eventually calling sqlite3_free() on
6717** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6718** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6719*/
6720static void arWhereClause(
6721  int *pRc,
6722  ArCommand *pAr,
6723  char **pzWhere                  /* OUT: New WHERE clause */
6724){
6725  char *zWhere = 0;
6726  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6727  if( *pRc==SQLITE_OK ){
6728    if( pAr->nArg==0 ){
6729      zWhere = sqlite3_mprintf("1");
6730    }else{
6731      int i;
6732      const char *zSep = "";
6733      for(i=0; i<pAr->nArg; i++){
6734        const char *z = pAr->azArg[i];
6735        zWhere = sqlite3_mprintf(
6736          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6737          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6738        );
6739        if( zWhere==0 ){
6740          *pRc = SQLITE_NOMEM;
6741          break;
6742        }
6743        zSep = " OR ";
6744      }
6745    }
6746  }
6747  *pzWhere = zWhere;
6748}
6749
6750/*
6751** Implementation of .ar "lisT" command.
6752*/
6753static int arListCommand(ArCommand *pAr){
6754  const char *zSql = "SELECT %s FROM %s WHERE %s";
6755  const char *azCols[] = {
6756    "name",
6757    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6758  };
6759
6760  char *zWhere = 0;
6761  sqlite3_stmt *pSql = 0;
6762  int rc;
6763
6764  rc = arCheckEntries(pAr);
6765  arWhereClause(&rc, pAr, &zWhere);
6766
6767  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6768                     pAr->zSrcTable, zWhere);
6769  if( pAr->bDryRun ){
6770    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6771  }else{
6772    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6773      if( pAr->bVerbose ){
6774        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6775            sqlite3_column_text(pSql, 0),
6776            sqlite3_column_int(pSql, 1),
6777            sqlite3_column_text(pSql, 2),
6778            sqlite3_column_text(pSql, 3)
6779        );
6780      }else{
6781        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6782      }
6783    }
6784  }
6785  shellFinalize(&rc, pSql);
6786  sqlite3_free(zWhere);
6787  return rc;
6788}
6789
6790
6791/*
6792** Implementation of .ar "Remove" command.
6793*/
6794static int arRemoveCommand(ArCommand *pAr){
6795  int rc = 0;
6796  char *zSql = 0;
6797  char *zWhere = 0;
6798
6799  if( pAr->nArg ){
6800    /* Verify that args actually exist within the archive before proceeding.
6801    ** And formulate a WHERE clause to match them.  */
6802    rc = arCheckEntries(pAr);
6803    arWhereClause(&rc, pAr, &zWhere);
6804  }
6805  if( rc==SQLITE_OK ){
6806    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6807                           pAr->zSrcTable, zWhere);
6808    if( pAr->bDryRun ){
6809      utf8_printf(pAr->p->out, "%s\n", zSql);
6810    }else{
6811      char *zErr = 0;
6812      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6813      if( rc==SQLITE_OK ){
6814        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6815        if( rc!=SQLITE_OK ){
6816          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6817        }else{
6818          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6819        }
6820      }
6821      if( zErr ){
6822        utf8_printf(stdout, "ERROR: %s\n", zErr);
6823        sqlite3_free(zErr);
6824      }
6825    }
6826  }
6827  sqlite3_free(zWhere);
6828  sqlite3_free(zSql);
6829  return rc;
6830}
6831
6832/*
6833** Implementation of .ar "eXtract" command.
6834*/
6835static int arExtractCommand(ArCommand *pAr){
6836  const char *zSql1 =
6837    "SELECT "
6838    " ($dir || name),"
6839    " writefile(($dir || name), %s, mode, mtime) "
6840    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6841    " AND name NOT GLOB '*..[/\\]*'";
6842
6843  const char *azExtraArg[] = {
6844    "sqlar_uncompress(data, sz)",
6845    "data"
6846  };
6847
6848  sqlite3_stmt *pSql = 0;
6849  int rc = SQLITE_OK;
6850  char *zDir = 0;
6851  char *zWhere = 0;
6852  int i, j;
6853
6854  /* If arguments are specified, check that they actually exist within
6855  ** the archive before proceeding. And formulate a WHERE clause to
6856  ** match them.  */
6857  rc = arCheckEntries(pAr);
6858  arWhereClause(&rc, pAr, &zWhere);
6859
6860  if( rc==SQLITE_OK ){
6861    if( pAr->zDir ){
6862      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6863    }else{
6864      zDir = sqlite3_mprintf("");
6865    }
6866    if( zDir==0 ) rc = SQLITE_NOMEM;
6867  }
6868
6869  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6870      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6871  );
6872
6873  if( rc==SQLITE_OK ){
6874    j = sqlite3_bind_parameter_index(pSql, "$dir");
6875    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6876
6877    /* Run the SELECT statement twice. The first time, writefile() is called
6878    ** for all archive members that should be extracted. The second time,
6879    ** only for the directories. This is because the timestamps for
6880    ** extracted directories must be reset after they are populated (as
6881    ** populating them changes the timestamp).  */
6882    for(i=0; i<2; i++){
6883      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6884      sqlite3_bind_int(pSql, j, i);
6885      if( pAr->bDryRun ){
6886        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6887      }else{
6888        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6889          if( i==0 && pAr->bVerbose ){
6890            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6891          }
6892        }
6893      }
6894      shellReset(&rc, pSql);
6895    }
6896    shellFinalize(&rc, pSql);
6897  }
6898
6899  sqlite3_free(zDir);
6900  sqlite3_free(zWhere);
6901  return rc;
6902}
6903
6904/*
6905** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6906*/
6907static int arExecSql(ArCommand *pAr, const char *zSql){
6908  int rc;
6909  if( pAr->bDryRun ){
6910    utf8_printf(pAr->p->out, "%s\n", zSql);
6911    rc = SQLITE_OK;
6912  }else{
6913    char *zErr = 0;
6914    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6915    if( zErr ){
6916      utf8_printf(stdout, "ERROR: %s\n", zErr);
6917      sqlite3_free(zErr);
6918    }
6919  }
6920  return rc;
6921}
6922
6923
6924/*
6925** Implementation of .ar "create", "insert", and "update" commands.
6926**
6927**     create    ->     Create a new SQL archive
6928**     insert    ->     Insert or reinsert all files listed
6929**     update    ->     Insert files that have changed or that were not
6930**                      previously in the archive
6931**
6932** Create the "sqlar" table in the database if it does not already exist.
6933** Then add each file in the azFile[] array to the archive. Directories
6934** are added recursively. If argument bVerbose is non-zero, a message is
6935** printed on stdout for each file archived.
6936**
6937** The create command is the same as update, except that it drops
6938** any existing "sqlar" table before beginning.  The "insert" command
6939** always overwrites every file named on the command-line, where as
6940** "update" only overwrites if the size or mtime or mode has changed.
6941*/
6942static int arCreateOrUpdateCommand(
6943  ArCommand *pAr,                 /* Command arguments and options */
6944  int bUpdate,                    /* true for a --create. */
6945  int bOnlyIfChanged              /* Only update if file has changed */
6946){
6947  const char *zCreate =
6948      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6949      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6950      "  mode INT,               -- access permissions\n"
6951      "  mtime INT,              -- last modification time\n"
6952      "  sz INT,                 -- original file size\n"
6953      "  data BLOB               -- compressed content\n"
6954      ")";
6955  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6956  const char *zInsertFmt[2] = {
6957     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6958     "  SELECT\n"
6959     "    %s,\n"
6960     "    mode,\n"
6961     "    mtime,\n"
6962     "    CASE substr(lsmode(mode),1,1)\n"
6963     "      WHEN '-' THEN length(data)\n"
6964     "      WHEN 'd' THEN 0\n"
6965     "      ELSE -1 END,\n"
6966     "    sqlar_compress(data)\n"
6967     "  FROM fsdir(%Q,%Q) AS disk\n"
6968     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6969     ,
6970     "REPLACE INTO %s(name,mode,mtime,data)\n"
6971     "  SELECT\n"
6972     "    %s,\n"
6973     "    mode,\n"
6974     "    mtime,\n"
6975     "    data\n"
6976     "  FROM fsdir(%Q,%Q) AS disk\n"
6977     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6978  };
6979  int i;                          /* For iterating through azFile[] */
6980  int rc;                         /* Return code */
6981  const char *zTab = 0;           /* SQL table into which to insert */
6982  char *zSql;
6983  char zTemp[50];
6984  char *zExists = 0;
6985
6986  arExecSql(pAr, "PRAGMA page_size=512");
6987  rc = arExecSql(pAr, "SAVEPOINT ar;");
6988  if( rc!=SQLITE_OK ) return rc;
6989  zTemp[0] = 0;
6990  if( pAr->bZip ){
6991    /* Initialize the zipfile virtual table, if necessary */
6992    if( pAr->zFile ){
6993      sqlite3_uint64 r;
6994      sqlite3_randomness(sizeof(r),&r);
6995      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6996      zTab = zTemp;
6997      zSql = sqlite3_mprintf(
6998         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6999         zTab, pAr->zFile
7000      );
7001      rc = arExecSql(pAr, zSql);
7002      sqlite3_free(zSql);
7003    }else{
7004      zTab = "zip";
7005    }
7006  }else{
7007    /* Initialize the table for an SQLAR */
7008    zTab = "sqlar";
7009    if( bUpdate==0 ){
7010      rc = arExecSql(pAr, zDrop);
7011      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7012    }
7013    rc = arExecSql(pAr, zCreate);
7014  }
7015  if( bOnlyIfChanged ){
7016    zExists = sqlite3_mprintf(
7017      " AND NOT EXISTS("
7018          "SELECT 1 FROM %s AS mem"
7019          " WHERE mem.name=disk.name"
7020          " AND mem.mtime=disk.mtime"
7021          " AND mem.mode=disk.mode)", zTab);
7022  }else{
7023    zExists = sqlite3_mprintf("");
7024  }
7025  if( zExists==0 ) rc = SQLITE_NOMEM;
7026  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7027    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7028        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7029        pAr->azArg[i], pAr->zDir, zExists);
7030    rc = arExecSql(pAr, zSql2);
7031    sqlite3_free(zSql2);
7032  }
7033end_ar_transaction:
7034  if( rc!=SQLITE_OK ){
7035    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7036  }else{
7037    rc = arExecSql(pAr, "RELEASE ar;");
7038    if( pAr->bZip && pAr->zFile ){
7039      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7040      arExecSql(pAr, zSql);
7041      sqlite3_free(zSql);
7042    }
7043  }
7044  sqlite3_free(zExists);
7045  return rc;
7046}
7047
7048/*
7049** Implementation of ".ar" dot command.
7050*/
7051static int arDotCommand(
7052  ShellState *pState,          /* Current shell tool state */
7053  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7054  char **azArg,                /* Array of arguments passed to dot command */
7055  int nArg                     /* Number of entries in azArg[] */
7056){
7057  ArCommand cmd;
7058  int rc;
7059  memset(&cmd, 0, sizeof(cmd));
7060  cmd.fromCmdLine = fromCmdLine;
7061  rc = arParseCommand(azArg, nArg, &cmd);
7062  if( rc==SQLITE_OK ){
7063    int eDbType = SHELL_OPEN_UNSPEC;
7064    cmd.p = pState;
7065    cmd.db = pState->db;
7066    if( cmd.zFile ){
7067      eDbType = deduceDatabaseType(cmd.zFile, 1);
7068    }else{
7069      eDbType = pState->openMode;
7070    }
7071    if( eDbType==SHELL_OPEN_ZIPFILE ){
7072      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7073        if( cmd.zFile==0 ){
7074          cmd.zSrcTable = sqlite3_mprintf("zip");
7075        }else{
7076          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7077        }
7078      }
7079      cmd.bZip = 1;
7080    }else if( cmd.zFile ){
7081      int flags;
7082      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7083      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7084           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7085        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7086      }else{
7087        flags = SQLITE_OPEN_READONLY;
7088      }
7089      cmd.db = 0;
7090      if( cmd.bDryRun ){
7091        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7092             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7093      }
7094      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7095             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7096      if( rc!=SQLITE_OK ){
7097        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7098            cmd.zFile, sqlite3_errmsg(cmd.db)
7099        );
7100        goto end_ar_command;
7101      }
7102      sqlite3_fileio_init(cmd.db, 0, 0);
7103      sqlite3_sqlar_init(cmd.db, 0, 0);
7104      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7105                              shellPutsFunc, 0, 0);
7106
7107    }
7108    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7109      if( cmd.eCmd!=AR_CMD_CREATE
7110       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7111      ){
7112        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7113        rc = SQLITE_ERROR;
7114        goto end_ar_command;
7115      }
7116      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7117    }
7118
7119    switch( cmd.eCmd ){
7120      case AR_CMD_CREATE:
7121        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7122        break;
7123
7124      case AR_CMD_EXTRACT:
7125        rc = arExtractCommand(&cmd);
7126        break;
7127
7128      case AR_CMD_LIST:
7129        rc = arListCommand(&cmd);
7130        break;
7131
7132      case AR_CMD_HELP:
7133        arUsage(pState->out);
7134        break;
7135
7136      case AR_CMD_INSERT:
7137        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7138        break;
7139
7140      case AR_CMD_REMOVE:
7141        rc = arRemoveCommand(&cmd);
7142        break;
7143
7144      default:
7145        assert( cmd.eCmd==AR_CMD_UPDATE );
7146        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7147        break;
7148    }
7149  }
7150end_ar_command:
7151  if( cmd.db!=pState->db ){
7152    close_db(cmd.db);
7153  }
7154  sqlite3_free(cmd.zSrcTable);
7155
7156  return rc;
7157}
7158/* End of the ".archive" or ".ar" command logic
7159*******************************************************************************/
7160#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7161
7162#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7163/*
7164** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7165** Otherwise, the SQL statement or statements in zSql are executed using
7166** database connection db and the error code written to *pRc before
7167** this function returns.
7168*/
7169static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7170  int rc = *pRc;
7171  if( rc==SQLITE_OK ){
7172    char *zErr = 0;
7173    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7174    if( rc!=SQLITE_OK ){
7175      raw_printf(stderr, "SQL error: %s\n", zErr);
7176    }
7177    sqlite3_free(zErr);
7178    *pRc = rc;
7179  }
7180}
7181
7182/*
7183** Like shellExec(), except that zFmt is a printf() style format string.
7184*/
7185static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7186  char *z = 0;
7187  if( *pRc==SQLITE_OK ){
7188    va_list ap;
7189    va_start(ap, zFmt);
7190    z = sqlite3_vmprintf(zFmt, ap);
7191    va_end(ap);
7192    if( z==0 ){
7193      *pRc = SQLITE_NOMEM;
7194    }else{
7195      shellExec(db, pRc, z);
7196    }
7197    sqlite3_free(z);
7198  }
7199}
7200
7201/*
7202** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7203** Otherwise, an attempt is made to allocate, zero and return a pointer
7204** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7205** to SQLITE_NOMEM and NULL returned.
7206*/
7207static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7208  void *pRet = 0;
7209  if( *pRc==SQLITE_OK ){
7210    pRet = sqlite3_malloc64(nByte);
7211    if( pRet==0 ){
7212      *pRc = SQLITE_NOMEM;
7213    }else{
7214      memset(pRet, 0, nByte);
7215    }
7216  }
7217  return pRet;
7218}
7219
7220/*
7221** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7222** Otherwise, zFmt is treated as a printf() style string. The result of
7223** formatting it along with any trailing arguments is written into a
7224** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7225** It is the responsibility of the caller to eventually free this buffer
7226** using a call to sqlite3_free().
7227**
7228** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7229** pointer returned.
7230*/
7231static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7232  char *z = 0;
7233  if( *pRc==SQLITE_OK ){
7234    va_list ap;
7235    va_start(ap, zFmt);
7236    z = sqlite3_vmprintf(zFmt, ap);
7237    va_end(ap);
7238    if( z==0 ){
7239      *pRc = SQLITE_NOMEM;
7240    }
7241  }
7242  return z;
7243}
7244
7245
7246/*
7247** When running the ".recover" command, each output table, and the special
7248** orphaned row table if it is required, is represented by an instance
7249** of the following struct.
7250*/
7251typedef struct RecoverTable RecoverTable;
7252struct RecoverTable {
7253  char *zQuoted;                  /* Quoted version of table name */
7254  int nCol;                       /* Number of columns in table */
7255  char **azlCol;                  /* Array of column lists */
7256  int iPk;                        /* Index of IPK column */
7257};
7258
7259/*
7260** Free a RecoverTable object allocated by recoverFindTable() or
7261** recoverOrphanTable().
7262*/
7263static void recoverFreeTable(RecoverTable *pTab){
7264  if( pTab ){
7265    sqlite3_free(pTab->zQuoted);
7266    if( pTab->azlCol ){
7267      int i;
7268      for(i=0; i<=pTab->nCol; i++){
7269        sqlite3_free(pTab->azlCol[i]);
7270      }
7271      sqlite3_free(pTab->azlCol);
7272    }
7273    sqlite3_free(pTab);
7274  }
7275}
7276
7277/*
7278** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7279** Otherwise, it allocates and returns a RecoverTable object based on the
7280** final four arguments passed to this function. It is the responsibility
7281** of the caller to eventually free the returned object using
7282** recoverFreeTable().
7283*/
7284static RecoverTable *recoverNewTable(
7285  int *pRc,                       /* IN/OUT: Error code */
7286  const char *zName,              /* Name of table */
7287  const char *zSql,               /* CREATE TABLE statement */
7288  int bIntkey,
7289  int nCol
7290){
7291  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7292  int rc = *pRc;
7293  RecoverTable *pTab = 0;
7294
7295  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7296  if( rc==SQLITE_OK ){
7297    int nSqlCol = 0;
7298    int bSqlIntkey = 0;
7299    sqlite3_stmt *pStmt = 0;
7300
7301    rc = sqlite3_open("", &dbtmp);
7302    if( rc==SQLITE_OK ){
7303      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7304                              shellIdQuote, 0, 0);
7305    }
7306    if( rc==SQLITE_OK ){
7307      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7308    }
7309    if( rc==SQLITE_OK ){
7310      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7311      if( rc==SQLITE_ERROR ){
7312        rc = SQLITE_OK;
7313        goto finished;
7314      }
7315    }
7316    shellPreparePrintf(dbtmp, &rc, &pStmt,
7317        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7318    );
7319    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7320      nSqlCol = sqlite3_column_int(pStmt, 0);
7321    }
7322    shellFinalize(&rc, pStmt);
7323
7324    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7325      goto finished;
7326    }
7327
7328    shellPreparePrintf(dbtmp, &rc, &pStmt,
7329      "SELECT ("
7330      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7331      ") FROM sqlite_schema WHERE name = %Q", zName
7332    );
7333    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7334      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7335    }
7336    shellFinalize(&rc, pStmt);
7337
7338    if( bIntkey==bSqlIntkey ){
7339      int i;
7340      const char *zPk = "_rowid_";
7341      sqlite3_stmt *pPkFinder = 0;
7342
7343      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7344      ** set zPk to the name of the PK column, and pTab->iPk to the index
7345      ** of the column, where columns are 0-numbered from left to right.
7346      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7347      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7348      pTab->iPk = -2;
7349      if( bIntkey ){
7350        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7351          "SELECT cid, name FROM pragma_table_info(%Q) "
7352          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7353          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7354          , zName, zName
7355        );
7356        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7357          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7358          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7359          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7360        }
7361      }
7362
7363      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7364      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7365      pTab->nCol = nSqlCol;
7366
7367      if( bIntkey ){
7368        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7369      }else{
7370        pTab->azlCol[0] = shellMPrintf(&rc, "");
7371      }
7372      i = 1;
7373      shellPreparePrintf(dbtmp, &rc, &pStmt,
7374          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7375          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7376          "FROM pragma_table_info(%Q)",
7377          bIntkey ? ", " : "", pTab->iPk,
7378          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7379          zName
7380      );
7381      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7382        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7383        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7384        i++;
7385      }
7386      shellFinalize(&rc, pStmt);
7387
7388      shellFinalize(&rc, pPkFinder);
7389    }
7390  }
7391
7392 finished:
7393  sqlite3_close(dbtmp);
7394  *pRc = rc;
7395  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7396    recoverFreeTable(pTab);
7397    pTab = 0;
7398  }
7399  return pTab;
7400}
7401
7402/*
7403** This function is called to search the schema recovered from the
7404** sqlite_schema table of the (possibly) corrupt database as part
7405** of a ".recover" command. Specifically, for a table with root page
7406** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7407** table must be a WITHOUT ROWID table, or if non-zero, not one of
7408** those.
7409**
7410** If a table is found, a (RecoverTable*) object is returned. Or, if
7411** no such table is found, but bIntkey is false and iRoot is the
7412** root page of an index in the recovered schema, then (*pbNoop) is
7413** set to true and NULL returned. Or, if there is no such table or
7414** index, NULL is returned and (*pbNoop) set to 0, indicating that
7415** the caller should write data to the orphans table.
7416*/
7417static RecoverTable *recoverFindTable(
7418  ShellState *pState,             /* Shell state object */
7419  int *pRc,                       /* IN/OUT: Error code */
7420  int iRoot,                      /* Root page of table */
7421  int bIntkey,                    /* True for an intkey table */
7422  int nCol,                       /* Number of columns in table */
7423  int *pbNoop                     /* OUT: True if iRoot is root of index */
7424){
7425  sqlite3_stmt *pStmt = 0;
7426  RecoverTable *pRet = 0;
7427  int bNoop = 0;
7428  const char *zSql = 0;
7429  const char *zName = 0;
7430
7431  /* Search the recovered schema for an object with root page iRoot. */
7432  shellPreparePrintf(pState->db, pRc, &pStmt,
7433      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7434  );
7435  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7436    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7437    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7438      bNoop = 1;
7439      break;
7440    }
7441    if( sqlite3_stricmp(zType, "table")==0 ){
7442      zName = (const char*)sqlite3_column_text(pStmt, 1);
7443      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7444      if( zName!=0 && zSql!=0 ){
7445        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7446        break;
7447      }
7448    }
7449  }
7450
7451  shellFinalize(pRc, pStmt);
7452  *pbNoop = bNoop;
7453  return pRet;
7454}
7455
7456/*
7457** Return a RecoverTable object representing the orphans table.
7458*/
7459static RecoverTable *recoverOrphanTable(
7460  ShellState *pState,             /* Shell state object */
7461  int *pRc,                       /* IN/OUT: Error code */
7462  const char *zLostAndFound,      /* Base name for orphans table */
7463  int nCol                        /* Number of user data columns */
7464){
7465  RecoverTable *pTab = 0;
7466  if( nCol>=0 && *pRc==SQLITE_OK ){
7467    int i;
7468
7469    /* This block determines the name of the orphan table. The prefered
7470    ** name is zLostAndFound. But if that clashes with another name
7471    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7472    ** and so on until a non-clashing name is found.  */
7473    int iTab = 0;
7474    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7475    sqlite3_stmt *pTest = 0;
7476    shellPrepare(pState->db, pRc,
7477        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7478    );
7479    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7480    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7481      shellReset(pRc, pTest);
7482      sqlite3_free(zTab);
7483      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7484      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7485    }
7486    shellFinalize(pRc, pTest);
7487
7488    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7489    if( pTab ){
7490      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7491      pTab->nCol = nCol;
7492      pTab->iPk = -2;
7493      if( nCol>0 ){
7494        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7495        if( pTab->azlCol ){
7496          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7497          for(i=nCol-1; i>=0; i--){
7498            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7499          }
7500        }
7501      }
7502
7503      if( *pRc!=SQLITE_OK ){
7504        recoverFreeTable(pTab);
7505        pTab = 0;
7506      }else{
7507        raw_printf(pState->out,
7508            "CREATE TABLE %s(rootpgno INTEGER, "
7509            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7510        );
7511        for(i=0; i<nCol; i++){
7512          raw_printf(pState->out, ", c%d", i);
7513        }
7514        raw_printf(pState->out, ");\n");
7515      }
7516    }
7517    sqlite3_free(zTab);
7518  }
7519  return pTab;
7520}
7521
7522/*
7523** This function is called to recover data from the database. A script
7524** to construct a new database containing all recovered data is output
7525** on stream pState->out.
7526*/
7527static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7528  int rc = SQLITE_OK;
7529  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7530  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7531  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7532  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7533  const char *zLostAndFound = "lost_and_found";
7534  int i;
7535  int nOrphan = -1;
7536  RecoverTable *pOrphan = 0;
7537
7538  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7539  int bRowids = 1;                /* 0 if --no-rowids */
7540  for(i=1; i<nArg; i++){
7541    char *z = azArg[i];
7542    int n;
7543    if( z[0]=='-' && z[1]=='-' ) z++;
7544    n = strlen30(z);
7545    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7546      bFreelist = 0;
7547    }else
7548    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7549      i++;
7550      zRecoveryDb = azArg[i];
7551    }else
7552    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7553      i++;
7554      zLostAndFound = azArg[i];
7555    }else
7556    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7557      bRowids = 0;
7558    }
7559    else{
7560      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7561      showHelp(pState->out, azArg[0]);
7562      return 1;
7563    }
7564  }
7565
7566  shellExecPrintf(pState->db, &rc,
7567    /* Attach an in-memory database named 'recovery'. Create an indexed
7568    ** cache of the sqlite_dbptr virtual table. */
7569    "PRAGMA writable_schema = on;"
7570    "ATTACH %Q AS recovery;"
7571    "DROP TABLE IF EXISTS recovery.dbptr;"
7572    "DROP TABLE IF EXISTS recovery.freelist;"
7573    "DROP TABLE IF EXISTS recovery.map;"
7574    "DROP TABLE IF EXISTS recovery.schema;"
7575    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7576  );
7577
7578  if( bFreelist ){
7579    shellExec(pState->db, &rc,
7580      "WITH trunk(pgno) AS ("
7581      "  SELECT shell_int32("
7582      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7583      "      WHERE x>0"
7584      "    UNION"
7585      "  SELECT shell_int32("
7586      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7587      "      FROM trunk WHERE x>0"
7588      "),"
7589      "freelist(data, n, freepgno) AS ("
7590      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7591      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7592      "    UNION ALL"
7593      "  SELECT data, n-1, shell_int32(data, 2+n) "
7594      "      FROM freelist WHERE n>=0"
7595      ")"
7596      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7597    );
7598  }
7599
7600  /* If this is an auto-vacuum database, add all pointer-map pages to
7601  ** the freelist table. Do this regardless of whether or not
7602  ** --freelist-corrupt was specified.  */
7603  shellExec(pState->db, &rc,
7604    "WITH ptrmap(pgno) AS ("
7605    "  SELECT 2 WHERE shell_int32("
7606    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7607    "  )"
7608    "    UNION ALL "
7609    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7610    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7611    ")"
7612    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7613  );
7614
7615  shellExec(pState->db, &rc,
7616    "CREATE TABLE recovery.dbptr("
7617    "      pgno, child, PRIMARY KEY(child, pgno)"
7618    ") WITHOUT ROWID;"
7619    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7620    "    SELECT * FROM sqlite_dbptr"
7621    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7622
7623    /* Delete any pointer to page 1. This ensures that page 1 is considered
7624    ** a root page, regardless of how corrupt the db is. */
7625    "DELETE FROM recovery.dbptr WHERE child = 1;"
7626
7627    /* Delete all pointers to any pages that have more than one pointer
7628    ** to them. Such pages will be treated as root pages when recovering
7629    ** data.  */
7630    "DELETE FROM recovery.dbptr WHERE child IN ("
7631    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7632    ");"
7633
7634    /* Create the "map" table that will (eventually) contain instructions
7635    ** for dealing with each page in the db that contains one or more
7636    ** records. */
7637    "CREATE TABLE recovery.map("
7638      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7639    ");"
7640
7641    /* Populate table [map]. If there are circular loops of pages in the
7642    ** database, the following adds all pages in such a loop to the map
7643    ** as individual root pages. This could be handled better.  */
7644    "WITH pages(i, maxlen) AS ("
7645    "  SELECT page_count, ("
7646    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7647    "  ) FROM pragma_page_count WHERE page_count>0"
7648    "    UNION ALL"
7649    "  SELECT i-1, ("
7650    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7651    "  ) FROM pages WHERE i>=2"
7652    ")"
7653    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7654    "  SELECT i, maxlen, NULL, ("
7655    "    WITH p(orig, pgno, parent) AS ("
7656    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7657    "        UNION "
7658    "      SELECT i, p.parent, "
7659    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7660    "    )"
7661    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7662    ") "
7663    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7664    "UPDATE recovery.map AS o SET intkey = ("
7665    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7666    ");"
7667
7668    /* Extract data from page 1 and any linked pages into table
7669    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7670    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7671    "INSERT INTO recovery.schema SELECT "
7672    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7673    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7674    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7675    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7676    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7677    "FROM sqlite_dbdata WHERE pgno IN ("
7678    "  SELECT pgno FROM recovery.map WHERE root=1"
7679    ")"
7680    "GROUP BY pgno, cell;"
7681    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7682  );
7683
7684  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7685  ** CREATE TABLE statements that extracted from the existing schema.  */
7686  if( rc==SQLITE_OK ){
7687    sqlite3_stmt *pStmt = 0;
7688    /* ".recover" might output content in an order which causes immediate
7689    ** foreign key constraints to be violated. So disable foreign-key
7690    ** constraint enforcement to prevent problems when running the output
7691    ** script. */
7692    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7693    raw_printf(pState->out, "BEGIN;\n");
7694    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7695    shellPrepare(pState->db, &rc,
7696        "SELECT sql FROM recovery.schema "
7697        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7698    );
7699    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7700      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7701      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7702          &zCreateTable[12]
7703      );
7704    }
7705    shellFinalize(&rc, pStmt);
7706  }
7707
7708  /* Figure out if an orphan table will be required. And if so, how many
7709  ** user columns it should contain */
7710  shellPrepare(pState->db, &rc,
7711      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7712      , &pLoop
7713  );
7714  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7715    nOrphan = sqlite3_column_int(pLoop, 0);
7716  }
7717  shellFinalize(&rc, pLoop);
7718  pLoop = 0;
7719
7720  shellPrepare(pState->db, &rc,
7721      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7722  );
7723
7724  shellPrepare(pState->db, &rc,
7725      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7726      "(case when (? AND field<0) then NULL else value end)"
7727      "), ', ')"
7728      ", min(field) "
7729      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7730      "GROUP BY cell", &pCells
7731  );
7732
7733  /* Loop through each root page. */
7734  shellPrepare(pState->db, &rc,
7735      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7736      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7737      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7738      ")", &pLoop
7739  );
7740  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7741    int iRoot = sqlite3_column_int(pLoop, 0);
7742    int bIntkey = sqlite3_column_int(pLoop, 1);
7743    int nCol = sqlite3_column_int(pLoop, 2);
7744    int bNoop = 0;
7745    RecoverTable *pTab;
7746
7747    assert( bIntkey==0 || bIntkey==1 );
7748    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7749    if( bNoop || rc ) continue;
7750    if( pTab==0 ){
7751      if( pOrphan==0 ){
7752        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7753      }
7754      pTab = pOrphan;
7755      if( pTab==0 ) break;
7756    }
7757
7758    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7759      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7760    }
7761    sqlite3_bind_int(pPages, 1, iRoot);
7762    if( bRowids==0 && pTab->iPk<0 ){
7763      sqlite3_bind_int(pCells, 1, 1);
7764    }else{
7765      sqlite3_bind_int(pCells, 1, 0);
7766    }
7767    sqlite3_bind_int(pCells, 3, pTab->iPk);
7768
7769    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7770      int iPgno = sqlite3_column_int(pPages, 0);
7771      sqlite3_bind_int(pCells, 2, iPgno);
7772      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7773        int nField = sqlite3_column_int(pCells, 0);
7774        int iMin = sqlite3_column_int(pCells, 2);
7775        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7776
7777        RecoverTable *pTab2 = pTab;
7778        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7779          if( pOrphan==0 ){
7780            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7781          }
7782          pTab2 = pOrphan;
7783          if( pTab2==0 ) break;
7784        }
7785
7786        nField = nField+1;
7787        if( pTab2==pOrphan ){
7788          raw_printf(pState->out,
7789              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7790              pTab2->zQuoted, iRoot, iPgno, nField,
7791              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7792          );
7793        }else{
7794          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7795              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7796          );
7797        }
7798      }
7799      shellReset(&rc, pCells);
7800    }
7801    shellReset(&rc, pPages);
7802    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7803  }
7804  shellFinalize(&rc, pLoop);
7805  shellFinalize(&rc, pPages);
7806  shellFinalize(&rc, pCells);
7807  recoverFreeTable(pOrphan);
7808
7809  /* The rest of the schema */
7810  if( rc==SQLITE_OK ){
7811    sqlite3_stmt *pStmt = 0;
7812    shellPrepare(pState->db, &rc,
7813        "SELECT sql, name FROM recovery.schema "
7814        "WHERE sql NOT LIKE 'create table%'", &pStmt
7815    );
7816    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7817      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7818      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7819        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7820        char *zPrint = shellMPrintf(&rc,
7821          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7822          zName, zName, zSql
7823        );
7824        raw_printf(pState->out, "%s;\n", zPrint);
7825        sqlite3_free(zPrint);
7826      }else{
7827        raw_printf(pState->out, "%s;\n", zSql);
7828      }
7829    }
7830    shellFinalize(&rc, pStmt);
7831  }
7832
7833  if( rc==SQLITE_OK ){
7834    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7835    raw_printf(pState->out, "COMMIT;\n");
7836  }
7837  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7838  return rc;
7839}
7840#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7841
7842
7843/*
7844 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7845 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7846 *   close db and set it to 0, and return the columns spec, to later
7847 *   be sqlite3_free()'ed by the caller.
7848 * The return is 0 when either:
7849 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7850 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7851 * The 3rd argument, pRenamed, references an out parameter. If the
7852 * pointer is non-zero, its referent will be set to a summary of renames
7853 * done if renaming was necessary, or set to 0 if none was done. The out
7854 * string (if any) must be sqlite3_free()'ed by the caller.
7855 */
7856#ifdef SHELL_DEBUG
7857#define rc_err_oom_die(rc) \
7858  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7859  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7860    fprintf(stderr,"E:%d\n",rc), assert(0)
7861#else
7862static void rc_err_oom_die(int rc){
7863  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7864  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7865}
7866#endif
7867
7868#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7869static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7870#else  /* Otherwise, memory is faster/better for the transient DB. */
7871static const char *zCOL_DB = ":memory:";
7872#endif
7873
7874/* Define character (as C string) to separate generated column ordinal
7875 * from protected part of incoming column names. This defaults to "_"
7876 * so that incoming column identifiers that did not need not be quoted
7877 * remain usable without being quoted. It must be one character.
7878 */
7879#ifndef SHELL_AUTOCOLUMN_SEP
7880# define AUTOCOLUMN_SEP "_"
7881#else
7882# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7883#endif
7884
7885static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7886  /* Queries and D{D,M}L used here */
7887  static const char * const zTabMake = "\
7888CREATE TABLE ColNames(\
7889 cpos INTEGER PRIMARY KEY,\
7890 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7891CREATE VIEW RepeatedNames AS \
7892SELECT DISTINCT t.name FROM ColNames t \
7893WHERE t.name COLLATE NOCASE IN (\
7894 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7895);\
7896";
7897  static const char * const zTabFill = "\
7898INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7899 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7900";
7901  static const char * const zHasDupes = "\
7902SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7903 <count(name) FROM ColNames\
7904";
7905#ifdef SHELL_COLUMN_RENAME_CLEAN
7906  static const char * const zDedoctor = "\
7907UPDATE ColNames SET chop=iif(\
7908  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7909  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7910 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7911 0\
7912)\
7913";
7914#endif
7915  static const char * const zSetReps = "\
7916UPDATE ColNames AS t SET reps=\
7917(SELECT count(*) FROM ColNames d \
7918 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7919 COLLATE NOCASE\
7920)\
7921";
7922#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7923  static const char * const zColDigits = "\
7924SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7925";
7926#else
7927  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7928  static const char * const zColDigits = "\
7929SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7930 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7931 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7932";
7933#endif
7934  static const char * const zRenameRank =
7935#ifdef SHELL_COLUMN_RENAME_CLEAN
7936    "UPDATE ColNames AS t SET suff="
7937    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7938#else /* ...RENAME_MINIMAL_ONE_PASS */
7939"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7940"  SELECT 0 AS nlz"
7941"  UNION"
7942"  SELECT nlz+1 AS nlz FROM Lzn"
7943"  WHERE EXISTS("
7944"   SELECT 1"
7945"   FROM ColNames t, ColNames o"
7946"   WHERE"
7947"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7948"     printf('%s"AUTOCOLUMN_SEP"%s',"
7949"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7950"     t.name"
7951"    )"
7952"    ="
7953"    iif(o.name IN (SELECT * FROM RepeatedNames),"
7954"     printf('%s"AUTOCOLUMN_SEP"%s',"
7955"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7956"     o.name"
7957"    )"
7958"    COLLATE NOCASE"
7959"    AND o.cpos<>t.cpos"
7960"   GROUP BY t.cpos"
7961"  )"
7962") UPDATE Colnames AS t SET"
7963" chop = 0," /* No chopping, never touch incoming names. */
7964" suff = iif(name IN (SELECT * FROM RepeatedNames),"
7965"  printf('"AUTOCOLUMN_SEP"%s', substring("
7966"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7967"  ''"
7968" )"
7969#endif
7970    ;
7971  static const char * const zCollectVar = "\
7972SELECT\
7973 '('||x'0a'\
7974 || group_concat(\
7975  cname||' TEXT',\
7976  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7977 ||')' AS ColsSpec \
7978FROM (\
7979 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7980 FROM ColNames ORDER BY cpos\
7981)";
7982  static const char * const zRenamesDone =
7983    "SELECT group_concat("
7984    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7985    " ','||x'0a')"
7986    "FROM ColNames WHERE suff<>'' OR chop!=0"
7987    ;
7988  int rc;
7989  sqlite3_stmt *pStmt = 0;
7990  assert(pDb!=0);
7991  if( zColNew ){
7992    /* Add initial or additional column. Init db if necessary. */
7993    if( *pDb==0 ){
7994      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7995#ifdef SHELL_COLFIX_DB
7996      if(*zCOL_DB!=':')
7997        sqlite3_exec(*pDb,"drop table if exists ColNames;"
7998                     "drop view if exists RepeatedNames;",0,0,0);
7999#endif
8000      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8001      rc_err_oom_die(rc);
8002    }
8003    assert(*pDb!=0);
8004    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8005    rc_err_oom_die(rc);
8006    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8007    rc_err_oom_die(rc);
8008    rc = sqlite3_step(pStmt);
8009    rc_err_oom_die(rc);
8010    sqlite3_finalize(pStmt);
8011    return 0;
8012  }else if( *pDb==0 ){
8013    return 0;
8014  }else{
8015    /* Formulate the columns spec, close the DB, zero *pDb. */
8016    char *zColsSpec = 0;
8017    int hasDupes = db_int(*pDb, zHasDupes);
8018    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8019    if( hasDupes ){
8020#ifdef SHELL_COLUMN_RENAME_CLEAN
8021      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8022      rc_err_oom_die(rc);
8023#endif
8024      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8025      rc_err_oom_die(rc);
8026      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8027      rc_err_oom_die(rc);
8028      sqlite3_bind_int(pStmt, 1, nDigits);
8029      rc = sqlite3_step(pStmt);
8030      sqlite3_finalize(pStmt);
8031      assert(rc==SQLITE_DONE);
8032    }
8033    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8034    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8035    rc_err_oom_die(rc);
8036    rc = sqlite3_step(pStmt);
8037    if( rc==SQLITE_ROW ){
8038      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8039    }else{
8040      zColsSpec = 0;
8041    }
8042    if( pzRenamed!=0 ){
8043      if( !hasDupes ) *pzRenamed = 0;
8044      else{
8045        sqlite3_finalize(pStmt);
8046        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8047            && SQLITE_ROW==sqlite3_step(pStmt) ){
8048          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8049        }else
8050          *pzRenamed = 0;
8051      }
8052    }
8053    sqlite3_finalize(pStmt);
8054    sqlite3_close(*pDb);
8055    *pDb = 0;
8056    return zColsSpec;
8057  }
8058}
8059
8060/*
8061** If an input line begins with "." then invoke this routine to
8062** process that line.
8063**
8064** Return 1 on error, 2 to exit, and 0 otherwise.
8065*/
8066static int do_meta_command(char *zLine, ShellState *p){
8067  int h = 1;
8068  int nArg = 0;
8069  int n, c;
8070  int rc = 0;
8071  char *azArg[52];
8072
8073#ifndef SQLITE_OMIT_VIRTUALTABLE
8074  if( p->expert.pExpert ){
8075    expertFinish(p, 1, 0);
8076  }
8077#endif
8078
8079  /* Parse the input line into tokens.
8080  */
8081  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8082    while( IsSpace(zLine[h]) ){ h++; }
8083    if( zLine[h]==0 ) break;
8084    if( zLine[h]=='\'' || zLine[h]=='"' ){
8085      int delim = zLine[h++];
8086      azArg[nArg++] = &zLine[h];
8087      while( zLine[h] && zLine[h]!=delim ){
8088        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8089        h++;
8090      }
8091      if( zLine[h]==delim ){
8092        zLine[h++] = 0;
8093      }
8094      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8095    }else{
8096      azArg[nArg++] = &zLine[h];
8097      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8098      if( zLine[h] ) zLine[h++] = 0;
8099      resolve_backslashes(azArg[nArg-1]);
8100    }
8101  }
8102  azArg[nArg] = 0;
8103
8104  /* Process the input line.
8105  */
8106  if( nArg==0 ) return 0; /* no tokens, no error */
8107  n = strlen30(azArg[0]);
8108  c = azArg[0][0];
8109  clearTempFile(p);
8110
8111#ifndef SQLITE_OMIT_AUTHORIZATION
8112  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8113    if( nArg!=2 ){
8114      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8115      rc = 1;
8116      goto meta_command_exit;
8117    }
8118    open_db(p, 0);
8119    if( booleanValue(azArg[1]) ){
8120      sqlite3_set_authorizer(p->db, shellAuth, p);
8121    }else if( p->bSafeModePersist ){
8122      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8123    }else{
8124      sqlite3_set_authorizer(p->db, 0, 0);
8125    }
8126  }else
8127#endif
8128
8129#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8130  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8131    open_db(p, 0);
8132    failIfSafeMode(p, "cannot run .archive in safe mode");
8133    rc = arDotCommand(p, 0, azArg, nArg);
8134  }else
8135#endif
8136
8137  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8138   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8139  ){
8140    const char *zDestFile = 0;
8141    const char *zDb = 0;
8142    sqlite3 *pDest;
8143    sqlite3_backup *pBackup;
8144    int j;
8145    int bAsync = 0;
8146    const char *zVfs = 0;
8147    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8148    for(j=1; j<nArg; j++){
8149      const char *z = azArg[j];
8150      if( z[0]=='-' ){
8151        if( z[1]=='-' ) z++;
8152        if( strcmp(z, "-append")==0 ){
8153          zVfs = "apndvfs";
8154        }else
8155        if( strcmp(z, "-async")==0 ){
8156          bAsync = 1;
8157        }else
8158        {
8159          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8160          return 1;
8161        }
8162      }else if( zDestFile==0 ){
8163        zDestFile = azArg[j];
8164      }else if( zDb==0 ){
8165        zDb = zDestFile;
8166        zDestFile = azArg[j];
8167      }else{
8168        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8169        return 1;
8170      }
8171    }
8172    if( zDestFile==0 ){
8173      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8174      return 1;
8175    }
8176    if( zDb==0 ) zDb = "main";
8177    rc = sqlite3_open_v2(zDestFile, &pDest,
8178                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8179    if( rc!=SQLITE_OK ){
8180      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8181      close_db(pDest);
8182      return 1;
8183    }
8184    if( bAsync ){
8185      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8186                   0, 0, 0);
8187    }
8188    open_db(p, 0);
8189    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8190    if( pBackup==0 ){
8191      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8192      close_db(pDest);
8193      return 1;
8194    }
8195    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8196    sqlite3_backup_finish(pBackup);
8197    if( rc==SQLITE_DONE ){
8198      rc = 0;
8199    }else{
8200      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8201      rc = 1;
8202    }
8203    close_db(pDest);
8204  }else
8205
8206  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8207    if( nArg==2 ){
8208      bail_on_error = booleanValue(azArg[1]);
8209    }else{
8210      raw_printf(stderr, "Usage: .bail on|off\n");
8211      rc = 1;
8212    }
8213  }else
8214
8215  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8216    if( nArg==2 ){
8217      if( booleanValue(azArg[1]) ){
8218        setBinaryMode(p->out, 1);
8219      }else{
8220        setTextMode(p->out, 1);
8221      }
8222    }else{
8223      raw_printf(stderr, "Usage: .binary on|off\n");
8224      rc = 1;
8225    }
8226  }else
8227
8228  /* The undocumented ".breakpoint" command causes a call to the no-op
8229  ** routine named test_breakpoint().
8230  */
8231  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8232    test_breakpoint();
8233  }else
8234
8235  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8236    failIfSafeMode(p, "cannot run .cd in safe mode");
8237    if( nArg==2 ){
8238#if defined(_WIN32) || defined(WIN32)
8239      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8240      rc = !SetCurrentDirectoryW(z);
8241      sqlite3_free(z);
8242#else
8243      rc = chdir(azArg[1]);
8244#endif
8245      if( rc ){
8246        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8247        rc = 1;
8248      }
8249    }else{
8250      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8251      rc = 1;
8252    }
8253  }else
8254
8255  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8256    if( nArg==2 ){
8257      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8258    }else{
8259      raw_printf(stderr, "Usage: .changes on|off\n");
8260      rc = 1;
8261    }
8262  }else
8263
8264  /* Cancel output redirection, if it is currently set (by .testcase)
8265  ** Then read the content of the testcase-out.txt file and compare against
8266  ** azArg[1].  If there are differences, report an error and exit.
8267  */
8268  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8269    char *zRes = 0;
8270    output_reset(p);
8271    if( nArg!=2 ){
8272      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8273      rc = 2;
8274    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8275      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8276      rc = 2;
8277    }else if( testcase_glob(azArg[1],zRes)==0 ){
8278      utf8_printf(stderr,
8279                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8280                 p->zTestcase, azArg[1], zRes);
8281      rc = 1;
8282    }else{
8283      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8284      p->nCheck++;
8285    }
8286    sqlite3_free(zRes);
8287  }else
8288
8289  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8290    failIfSafeMode(p, "cannot run .clone in safe mode");
8291    if( nArg==2 ){
8292      tryToClone(p, azArg[1]);
8293    }else{
8294      raw_printf(stderr, "Usage: .clone FILENAME\n");
8295      rc = 1;
8296    }
8297  }else
8298
8299  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8300    if( nArg==1 ){
8301      /* List available connections */
8302      int i;
8303      for(i=0; i<ArraySize(p->aAuxDb); i++){
8304        const char *zFile = p->aAuxDb[i].zDbFilename;
8305        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8306          zFile = "(not open)";
8307        }else if( zFile==0 ){
8308          zFile = "(memory)";
8309        }else if( zFile[0]==0 ){
8310          zFile = "(temporary-file)";
8311        }
8312        if( p->pAuxDb == &p->aAuxDb[i] ){
8313          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8314        }else if( p->aAuxDb[i].db!=0 ){
8315          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8316        }
8317      }
8318    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8319      int i = azArg[1][0] - '0';
8320      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8321        p->pAuxDb->db = p->db;
8322        p->pAuxDb = &p->aAuxDb[i];
8323        globalDb = p->db = p->pAuxDb->db;
8324        p->pAuxDb->db = 0;
8325      }
8326    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8327           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8328      int i = azArg[2][0] - '0';
8329      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8330        /* No-op */
8331      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8332        raw_printf(stderr, "cannot close the active database connection\n");
8333        rc = 1;
8334      }else if( p->aAuxDb[i].db ){
8335        session_close_all(p, i);
8336        close_db(p->aAuxDb[i].db);
8337        p->aAuxDb[i].db = 0;
8338      }
8339    }else{
8340      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8341      rc = 1;
8342    }
8343  }else
8344
8345  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8346    char **azName = 0;
8347    int nName = 0;
8348    sqlite3_stmt *pStmt;
8349    int i;
8350    open_db(p, 0);
8351    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8352    if( rc ){
8353      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8354      rc = 1;
8355    }else{
8356      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8357        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8358        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8359        if( zSchema==0 || zFile==0 ) continue;
8360        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8361        shell_check_oom(azName);
8362        azName[nName*2] = strdup(zSchema);
8363        azName[nName*2+1] = strdup(zFile);
8364        nName++;
8365      }
8366    }
8367    sqlite3_finalize(pStmt);
8368    for(i=0; i<nName; i++){
8369      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8370      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8371      const char *z = azName[i*2+1];
8372      utf8_printf(p->out, "%s: %s %s%s\n",
8373         azName[i*2],
8374         z && z[0] ? z : "\"\"",
8375         bRdonly ? "r/o" : "r/w",
8376         eTxn==SQLITE_TXN_NONE ? "" :
8377            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8378      free(azName[i*2]);
8379      free(azName[i*2+1]);
8380    }
8381    sqlite3_free(azName);
8382  }else
8383
8384  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8385    static const struct DbConfigChoices {
8386      const char *zName;
8387      int op;
8388    } aDbConfig[] = {
8389        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8390        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8391        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8392        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8393        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8394        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8395        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8396        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8397        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8398        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8399        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8400        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8401        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8402        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8403        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8404        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8405    };
8406    int ii, v;
8407    open_db(p, 0);
8408    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8409      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8410      if( nArg>=3 ){
8411        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8412      }
8413      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8414      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8415      if( nArg>1 ) break;
8416    }
8417    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8418      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8419      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8420    }
8421  }else
8422
8423  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8424    rc = shell_dbinfo_command(p, nArg, azArg);
8425  }else
8426
8427#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8428  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8429    open_db(p, 0);
8430    rc = recoverDatabaseCmd(p, nArg, azArg);
8431  }else
8432#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8433
8434  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8435    char *zLike = 0;
8436    char *zSql;
8437    int i;
8438    int savedShowHeader = p->showHeader;
8439    int savedShellFlags = p->shellFlgs;
8440    ShellClearFlag(p,
8441       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8442       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8443    for(i=1; i<nArg; i++){
8444      if( azArg[i][0]=='-' ){
8445        const char *z = azArg[i]+1;
8446        if( z[0]=='-' ) z++;
8447        if( strcmp(z,"preserve-rowids")==0 ){
8448#ifdef SQLITE_OMIT_VIRTUALTABLE
8449          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8450                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8451          rc = 1;
8452          sqlite3_free(zLike);
8453          goto meta_command_exit;
8454#else
8455          ShellSetFlag(p, SHFLG_PreserveRowid);
8456#endif
8457        }else
8458        if( strcmp(z,"newlines")==0 ){
8459          ShellSetFlag(p, SHFLG_Newlines);
8460        }else
8461        if( strcmp(z,"data-only")==0 ){
8462          ShellSetFlag(p, SHFLG_DumpDataOnly);
8463        }else
8464        if( strcmp(z,"nosys")==0 ){
8465          ShellSetFlag(p, SHFLG_DumpNoSys);
8466        }else
8467        {
8468          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8469          rc = 1;
8470          sqlite3_free(zLike);
8471          goto meta_command_exit;
8472        }
8473      }else{
8474        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8475        ** only dump data for tables for which either the table name matches
8476        ** the LIKE pattern, or the table appears to be a shadow table of
8477        ** a virtual table for which the name matches the LIKE pattern.
8478        */
8479        char *zExpr = sqlite3_mprintf(
8480            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8481            "  SELECT 1 FROM sqlite_schema WHERE "
8482            "    name LIKE %Q ESCAPE '\\' AND"
8483            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8484            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8485            ")", azArg[i], azArg[i]
8486        );
8487
8488        if( zLike ){
8489          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8490        }else{
8491          zLike = zExpr;
8492        }
8493      }
8494    }
8495
8496    open_db(p, 0);
8497
8498    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8499      /* When playing back a "dump", the content might appear in an order
8500      ** which causes immediate foreign key constraints to be violated.
8501      ** So disable foreign-key constraint enforcement to prevent problems. */
8502      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8503      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8504    }
8505    p->writableSchema = 0;
8506    p->showHeader = 0;
8507    /* Set writable_schema=ON since doing so forces SQLite to initialize
8508    ** as much of the schema as it can even if the sqlite_schema table is
8509    ** corrupt. */
8510    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8511    p->nErr = 0;
8512    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8513    zSql = sqlite3_mprintf(
8514      "SELECT name, type, sql FROM sqlite_schema AS o "
8515      "WHERE (%s) AND type=='table'"
8516      "  AND sql NOT NULL"
8517      " ORDER BY tbl_name='sqlite_sequence', rowid",
8518      zLike
8519    );
8520    run_schema_dump_query(p,zSql);
8521    sqlite3_free(zSql);
8522    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8523      zSql = sqlite3_mprintf(
8524        "SELECT sql FROM sqlite_schema AS o "
8525        "WHERE (%s) AND sql NOT NULL"
8526        "  AND type IN ('index','trigger','view')",
8527        zLike
8528      );
8529      run_table_dump_query(p, zSql);
8530      sqlite3_free(zSql);
8531    }
8532    sqlite3_free(zLike);
8533    if( p->writableSchema ){
8534      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8535      p->writableSchema = 0;
8536    }
8537    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8538    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8539    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8540      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8541    }
8542    p->showHeader = savedShowHeader;
8543    p->shellFlgs = savedShellFlags;
8544  }else
8545
8546  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8547    if( nArg==2 ){
8548      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8549    }else{
8550      raw_printf(stderr, "Usage: .echo on|off\n");
8551      rc = 1;
8552    }
8553  }else
8554
8555  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8556    if( nArg==2 ){
8557      p->autoEQPtest = 0;
8558      if( p->autoEQPtrace ){
8559        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8560        p->autoEQPtrace = 0;
8561      }
8562      if( strcmp(azArg[1],"full")==0 ){
8563        p->autoEQP = AUTOEQP_full;
8564      }else if( strcmp(azArg[1],"trigger")==0 ){
8565        p->autoEQP = AUTOEQP_trigger;
8566#ifdef SQLITE_DEBUG
8567      }else if( strcmp(azArg[1],"test")==0 ){
8568        p->autoEQP = AUTOEQP_on;
8569        p->autoEQPtest = 1;
8570      }else if( strcmp(azArg[1],"trace")==0 ){
8571        p->autoEQP = AUTOEQP_full;
8572        p->autoEQPtrace = 1;
8573        open_db(p, 0);
8574        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8575        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8576#endif
8577      }else{
8578        p->autoEQP = (u8)booleanValue(azArg[1]);
8579      }
8580    }else{
8581      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8582      rc = 1;
8583    }
8584  }else
8585
8586  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8587    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8588    rc = 2;
8589  }else
8590
8591  /* The ".explain" command is automatic now.  It is largely pointless.  It
8592  ** retained purely for backwards compatibility */
8593  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8594    int val = 1;
8595    if( nArg>=2 ){
8596      if( strcmp(azArg[1],"auto")==0 ){
8597        val = 99;
8598      }else{
8599        val =  booleanValue(azArg[1]);
8600      }
8601    }
8602    if( val==1 && p->mode!=MODE_Explain ){
8603      p->normalMode = p->mode;
8604      p->mode = MODE_Explain;
8605      p->autoExplain = 0;
8606    }else if( val==0 ){
8607      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8608      p->autoExplain = 0;
8609    }else if( val==99 ){
8610      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8611      p->autoExplain = 1;
8612    }
8613  }else
8614
8615#ifndef SQLITE_OMIT_VIRTUALTABLE
8616  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8617    if( p->bSafeMode ){
8618      raw_printf(stderr,
8619        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8620        azArg[0]);
8621      rc = 1;
8622    }else{
8623      open_db(p, 0);
8624      expertDotCommand(p, azArg, nArg);
8625    }
8626  }else
8627#endif
8628
8629  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8630    static const struct {
8631       const char *zCtrlName;   /* Name of a test-control option */
8632       int ctrlCode;            /* Integer code for that option */
8633       const char *zUsage;      /* Usage notes */
8634    } aCtrl[] = {
8635      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8636      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8637      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8638      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8639      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8640   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8641      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8642      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8643      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8644      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8645   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8646    };
8647    int filectrl = -1;
8648    int iCtrl = -1;
8649    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8650    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8651    int n2, i;
8652    const char *zCmd = 0;
8653    const char *zSchema = 0;
8654
8655    open_db(p, 0);
8656    zCmd = nArg>=2 ? azArg[1] : "help";
8657
8658    if( zCmd[0]=='-'
8659     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8660     && nArg>=4
8661    ){
8662      zSchema = azArg[2];
8663      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8664      nArg -= 2;
8665      zCmd = azArg[1];
8666    }
8667
8668    /* The argument can optionally begin with "-" or "--" */
8669    if( zCmd[0]=='-' && zCmd[1] ){
8670      zCmd++;
8671      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8672    }
8673
8674    /* --help lists all file-controls */
8675    if( strcmp(zCmd,"help")==0 ){
8676      utf8_printf(p->out, "Available file-controls:\n");
8677      for(i=0; i<ArraySize(aCtrl); i++){
8678        utf8_printf(p->out, "  .filectrl %s %s\n",
8679                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8680      }
8681      rc = 1;
8682      goto meta_command_exit;
8683    }
8684
8685    /* convert filectrl text option to value. allow any unique prefix
8686    ** of the option name, or a numerical value. */
8687    n2 = strlen30(zCmd);
8688    for(i=0; i<ArraySize(aCtrl); i++){
8689      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8690        if( filectrl<0 ){
8691          filectrl = aCtrl[i].ctrlCode;
8692          iCtrl = i;
8693        }else{
8694          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8695                              "Use \".filectrl --help\" for help\n", zCmd);
8696          rc = 1;
8697          goto meta_command_exit;
8698        }
8699      }
8700    }
8701    if( filectrl<0 ){
8702      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8703                         "Use \".filectrl --help\" for help\n", zCmd);
8704    }else{
8705      switch(filectrl){
8706        case SQLITE_FCNTL_SIZE_LIMIT: {
8707          if( nArg!=2 && nArg!=3 ) break;
8708          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8709          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8710          isOk = 1;
8711          break;
8712        }
8713        case SQLITE_FCNTL_LOCK_TIMEOUT:
8714        case SQLITE_FCNTL_CHUNK_SIZE: {
8715          int x;
8716          if( nArg!=3 ) break;
8717          x = (int)integerValue(azArg[2]);
8718          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8719          isOk = 2;
8720          break;
8721        }
8722        case SQLITE_FCNTL_PERSIST_WAL:
8723        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8724          int x;
8725          if( nArg!=2 && nArg!=3 ) break;
8726          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8727          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8728          iRes = x;
8729          isOk = 1;
8730          break;
8731        }
8732        case SQLITE_FCNTL_DATA_VERSION:
8733        case SQLITE_FCNTL_HAS_MOVED: {
8734          int x;
8735          if( nArg!=2 ) break;
8736          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8737          iRes = x;
8738          isOk = 1;
8739          break;
8740        }
8741        case SQLITE_FCNTL_TEMPFILENAME: {
8742          char *z = 0;
8743          if( nArg!=2 ) break;
8744          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8745          if( z ){
8746            utf8_printf(p->out, "%s\n", z);
8747            sqlite3_free(z);
8748          }
8749          isOk = 2;
8750          break;
8751        }
8752        case SQLITE_FCNTL_RESERVE_BYTES: {
8753          int x;
8754          if( nArg>=3 ){
8755            x = atoi(azArg[2]);
8756            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8757          }
8758          x = -1;
8759          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8760          utf8_printf(p->out,"%d\n", x);
8761          isOk = 2;
8762          break;
8763        }
8764      }
8765    }
8766    if( isOk==0 && iCtrl>=0 ){
8767      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8768      rc = 1;
8769    }else if( isOk==1 ){
8770      char zBuf[100];
8771      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8772      raw_printf(p->out, "%s\n", zBuf);
8773    }
8774  }else
8775
8776  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8777    ShellState data;
8778    int doStats = 0;
8779    memcpy(&data, p, sizeof(data));
8780    data.showHeader = 0;
8781    data.cMode = data.mode = MODE_Semi;
8782    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8783      data.cMode = data.mode = MODE_Pretty;
8784      nArg = 1;
8785    }
8786    if( nArg!=1 ){
8787      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8788      rc = 1;
8789      goto meta_command_exit;
8790    }
8791    open_db(p, 0);
8792    rc = sqlite3_exec(p->db,
8793       "SELECT sql FROM"
8794       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8795       "     FROM sqlite_schema UNION ALL"
8796       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8797       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8798       "ORDER BY x",
8799       callback, &data, 0
8800    );
8801    if( rc==SQLITE_OK ){
8802      sqlite3_stmt *pStmt;
8803      rc = sqlite3_prepare_v2(p->db,
8804               "SELECT rowid FROM sqlite_schema"
8805               " WHERE name GLOB 'sqlite_stat[134]'",
8806               -1, &pStmt, 0);
8807      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8808      sqlite3_finalize(pStmt);
8809    }
8810    if( doStats==0 ){
8811      raw_printf(p->out, "/* No STAT tables available */\n");
8812    }else{
8813      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8814      data.cMode = data.mode = MODE_Insert;
8815      data.zDestTable = "sqlite_stat1";
8816      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8817      data.zDestTable = "sqlite_stat4";
8818      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8819      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8820    }
8821  }else
8822
8823  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8824    if( nArg==2 ){
8825      p->showHeader = booleanValue(azArg[1]);
8826      p->shellFlgs |= SHFLG_HeaderSet;
8827    }else{
8828      raw_printf(stderr, "Usage: .headers on|off\n");
8829      rc = 1;
8830    }
8831  }else
8832
8833  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8834    if( nArg>=2 ){
8835      n = showHelp(p->out, azArg[1]);
8836      if( n==0 ){
8837        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8838      }
8839    }else{
8840      showHelp(p->out, 0);
8841    }
8842  }else
8843
8844  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8845    char *zTable = 0;           /* Insert data into this table */
8846    char *zSchema = 0;          /* within this schema (may default to "main") */
8847    char *zFile = 0;            /* Name of file to extra content from */
8848    sqlite3_stmt *pStmt = NULL; /* A statement */
8849    int nCol;                   /* Number of columns in the table */
8850    int nByte;                  /* Number of bytes in an SQL string */
8851    int i, j;                   /* Loop counters */
8852    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8853    int nSep;                   /* Number of bytes in p->colSeparator[] */
8854    char *zSql;                 /* An SQL statement */
8855    char *zFullTabName;         /* Table name with schema if applicable */
8856    ImportCtx sCtx;             /* Reader context */
8857    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8858    int eVerbose = 0;           /* Larger for more console output */
8859    int nSkip = 0;              /* Initial lines to skip */
8860    int useOutputMode = 1;      /* Use output mode to determine separators */
8861    char *zCreate = 0;          /* CREATE TABLE statement text */
8862
8863    failIfSafeMode(p, "cannot run .import in safe mode");
8864    memset(&sCtx, 0, sizeof(sCtx));
8865    sCtx.z = sqlite3_malloc64(120);
8866    if( sCtx.z==0 ){
8867      import_cleanup(&sCtx);
8868      shell_out_of_memory();
8869    }
8870    if( p->mode==MODE_Ascii ){
8871      xRead = ascii_read_one_field;
8872    }else{
8873      xRead = csv_read_one_field;
8874    }
8875    for(i=1; i<nArg; i++){
8876      char *z = azArg[i];
8877      if( z[0]=='-' && z[1]=='-' ) z++;
8878      if( z[0]!='-' ){
8879        if( zFile==0 ){
8880          zFile = z;
8881        }else if( zTable==0 ){
8882          zTable = z;
8883        }else{
8884          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8885          showHelp(p->out, "import");
8886          rc = 1;
8887          goto meta_command_exit;
8888        }
8889      }else if( strcmp(z,"-v")==0 ){
8890        eVerbose++;
8891      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8892        zSchema = azArg[++i];
8893      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8894        nSkip = integerValue(azArg[++i]);
8895      }else if( strcmp(z,"-ascii")==0 ){
8896        sCtx.cColSep = SEP_Unit[0];
8897        sCtx.cRowSep = SEP_Record[0];
8898        xRead = ascii_read_one_field;
8899        useOutputMode = 0;
8900      }else if( strcmp(z,"-csv")==0 ){
8901        sCtx.cColSep = ',';
8902        sCtx.cRowSep = '\n';
8903        xRead = csv_read_one_field;
8904        useOutputMode = 0;
8905      }else{
8906        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8907        showHelp(p->out, "import");
8908        rc = 1;
8909        goto meta_command_exit;
8910      }
8911    }
8912    if( zTable==0 ){
8913      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8914                  zFile==0 ? "FILE" : "TABLE");
8915      showHelp(p->out, "import");
8916      rc = 1;
8917      goto meta_command_exit;
8918    }
8919    seenInterrupt = 0;
8920    open_db(p, 0);
8921    if( useOutputMode ){
8922      /* If neither the --csv or --ascii options are specified, then set
8923      ** the column and row separator characters from the output mode. */
8924      nSep = strlen30(p->colSeparator);
8925      if( nSep==0 ){
8926        raw_printf(stderr,
8927                   "Error: non-null column separator required for import\n");
8928        rc = 1;
8929        goto meta_command_exit;
8930      }
8931      if( nSep>1 ){
8932        raw_printf(stderr,
8933              "Error: multi-character column separators not allowed"
8934              " for import\n");
8935        rc = 1;
8936        goto meta_command_exit;
8937      }
8938      nSep = strlen30(p->rowSeparator);
8939      if( nSep==0 ){
8940        raw_printf(stderr,
8941            "Error: non-null row separator required for import\n");
8942        rc = 1;
8943        goto meta_command_exit;
8944      }
8945      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8946        /* When importing CSV (only), if the row separator is set to the
8947        ** default output row separator, change it to the default input
8948        ** row separator.  This avoids having to maintain different input
8949        ** and output row separators. */
8950        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8951        nSep = strlen30(p->rowSeparator);
8952      }
8953      if( nSep>1 ){
8954        raw_printf(stderr, "Error: multi-character row separators not allowed"
8955                           " for import\n");
8956        rc = 1;
8957        goto meta_command_exit;
8958      }
8959      sCtx.cColSep = p->colSeparator[0];
8960      sCtx.cRowSep = p->rowSeparator[0];
8961    }
8962    sCtx.zFile = zFile;
8963    sCtx.nLine = 1;
8964    if( sCtx.zFile[0]=='|' ){
8965#ifdef SQLITE_OMIT_POPEN
8966      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8967      rc = 1;
8968      goto meta_command_exit;
8969#else
8970      sCtx.in = popen(sCtx.zFile+1, "r");
8971      sCtx.zFile = "<pipe>";
8972      sCtx.xCloser = pclose;
8973#endif
8974    }else{
8975      sCtx.in = fopen(sCtx.zFile, "rb");
8976      sCtx.xCloser = fclose;
8977    }
8978    if( sCtx.in==0 ){
8979      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8980      rc = 1;
8981      import_cleanup(&sCtx);
8982      goto meta_command_exit;
8983    }
8984    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8985      char zSep[2];
8986      zSep[1] = 0;
8987      zSep[0] = sCtx.cColSep;
8988      utf8_printf(p->out, "Column separator ");
8989      output_c_string(p->out, zSep);
8990      utf8_printf(p->out, ", row separator ");
8991      zSep[0] = sCtx.cRowSep;
8992      output_c_string(p->out, zSep);
8993      utf8_printf(p->out, "\n");
8994    }
8995    /* Below, resources must be freed before exit. */
8996    while( (nSkip--)>0 ){
8997      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8998    }
8999    if( zSchema!=0 ){
9000      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9001    }else{
9002      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9003    }
9004    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9005    if( zSql==0 || zFullTabName==0 ){
9006      import_cleanup(&sCtx);
9007      shell_out_of_memory();
9008    }
9009    nByte = strlen30(zSql);
9010    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9011    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9012    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9013      sqlite3 *dbCols = 0;
9014      char *zRenames = 0;
9015      char *zColDefs;
9016      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9017      while( xRead(&sCtx) ){
9018        zAutoColumn(sCtx.z, &dbCols, 0);
9019        if( sCtx.cTerm!=sCtx.cColSep ) break;
9020      }
9021      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9022      if( zRenames!=0 ){
9023        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9024                    "Columns renamed during .import %s due to duplicates:\n"
9025                    "%s\n", sCtx.zFile, zRenames);
9026        sqlite3_free(zRenames);
9027      }
9028      assert(dbCols==0);
9029      if( zColDefs==0 ){
9030        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9031      import_fail:
9032        sqlite3_free(zCreate);
9033        sqlite3_free(zSql);
9034        sqlite3_free(zFullTabName);
9035        import_cleanup(&sCtx);
9036        rc = 1;
9037        goto meta_command_exit;
9038      }
9039      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9040      if( eVerbose>=1 ){
9041        utf8_printf(p->out, "%s\n", zCreate);
9042      }
9043      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9044      if( rc ){
9045        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9046        goto import_fail;
9047      }
9048      sqlite3_free(zCreate);
9049      zCreate = 0;
9050      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9051    }
9052    if( rc ){
9053      if (pStmt) sqlite3_finalize(pStmt);
9054      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9055      goto import_fail;
9056    }
9057    sqlite3_free(zSql);
9058    nCol = sqlite3_column_count(pStmt);
9059    sqlite3_finalize(pStmt);
9060    pStmt = 0;
9061    if( nCol==0 ) return 0; /* no columns, no error */
9062    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9063    if( zSql==0 ){
9064      import_cleanup(&sCtx);
9065      shell_out_of_memory();
9066    }
9067    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9068    j = strlen30(zSql);
9069    for(i=1; i<nCol; i++){
9070      zSql[j++] = ',';
9071      zSql[j++] = '?';
9072    }
9073    zSql[j++] = ')';
9074    zSql[j] = 0;
9075    if( eVerbose>=2 ){
9076      utf8_printf(p->out, "Insert using: %s\n", zSql);
9077    }
9078    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9079    if( rc ){
9080      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9081      if (pStmt) sqlite3_finalize(pStmt);
9082      goto import_fail;
9083    }
9084    sqlite3_free(zSql);
9085    sqlite3_free(zFullTabName);
9086    needCommit = sqlite3_get_autocommit(p->db);
9087    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9088    do{
9089      int startLine = sCtx.nLine;
9090      for(i=0; i<nCol; i++){
9091        char *z = xRead(&sCtx);
9092        /*
9093        ** Did we reach end-of-file before finding any columns?
9094        ** If so, stop instead of NULL filling the remaining columns.
9095        */
9096        if( z==0 && i==0 ) break;
9097        /*
9098        ** Did we reach end-of-file OR end-of-line before finding any
9099        ** columns in ASCII mode?  If so, stop instead of NULL filling
9100        ** the remaining columns.
9101        */
9102        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9103        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9104        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9105          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9106                          "filling the rest with NULL\n",
9107                          sCtx.zFile, startLine, nCol, i+1);
9108          i += 2;
9109          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9110        }
9111      }
9112      if( sCtx.cTerm==sCtx.cColSep ){
9113        do{
9114          xRead(&sCtx);
9115          i++;
9116        }while( sCtx.cTerm==sCtx.cColSep );
9117        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9118                        "extras ignored\n",
9119                        sCtx.zFile, startLine, nCol, i);
9120      }
9121      if( i>=nCol ){
9122        sqlite3_step(pStmt);
9123        rc = sqlite3_reset(pStmt);
9124        if( rc!=SQLITE_OK ){
9125          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9126                      startLine, sqlite3_errmsg(p->db));
9127          sCtx.nErr++;
9128        }else{
9129          sCtx.nRow++;
9130        }
9131      }
9132    }while( sCtx.cTerm!=EOF );
9133
9134    import_cleanup(&sCtx);
9135    sqlite3_finalize(pStmt);
9136    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9137    if( eVerbose>0 ){
9138      utf8_printf(p->out,
9139          "Added %d rows with %d errors using %d lines of input\n",
9140          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9141    }
9142  }else
9143
9144#ifndef SQLITE_UNTESTABLE
9145  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9146    char *zSql;
9147    char *zCollist = 0;
9148    sqlite3_stmt *pStmt;
9149    int tnum = 0;
9150    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9151    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9152    int i;
9153    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9154      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9155                          "       .imposter off\n");
9156      /* Also allowed, but not documented:
9157      **
9158      **    .imposter TABLE IMPOSTER
9159      **
9160      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9161      ** imposter is another WITHOUT ROWID table with the columns in
9162      ** storage order. */
9163      rc = 1;
9164      goto meta_command_exit;
9165    }
9166    open_db(p, 0);
9167    if( nArg==2 ){
9168      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9169      goto meta_command_exit;
9170    }
9171    zSql = sqlite3_mprintf(
9172      "SELECT rootpage, 0 FROM sqlite_schema"
9173      " WHERE name='%q' AND type='index'"
9174      "UNION ALL "
9175      "SELECT rootpage, 1 FROM sqlite_schema"
9176      " WHERE name='%q' AND type='table'"
9177      "   AND sql LIKE '%%without%%rowid%%'",
9178      azArg[1], azArg[1]
9179    );
9180    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9181    sqlite3_free(zSql);
9182    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9183      tnum = sqlite3_column_int(pStmt, 0);
9184      isWO = sqlite3_column_int(pStmt, 1);
9185    }
9186    sqlite3_finalize(pStmt);
9187    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9188    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9189    sqlite3_free(zSql);
9190    i = 0;
9191    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9192      char zLabel[20];
9193      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9194      i++;
9195      if( zCol==0 ){
9196        if( sqlite3_column_int(pStmt,1)==-1 ){
9197          zCol = "_ROWID_";
9198        }else{
9199          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9200          zCol = zLabel;
9201        }
9202      }
9203      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9204        lenPK = (int)strlen(zCollist);
9205      }
9206      if( zCollist==0 ){
9207        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9208      }else{
9209        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9210      }
9211    }
9212    sqlite3_finalize(pStmt);
9213    if( i==0 || tnum==0 ){
9214      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9215      rc = 1;
9216      sqlite3_free(zCollist);
9217      goto meta_command_exit;
9218    }
9219    if( lenPK==0 ) lenPK = 100000;
9220    zSql = sqlite3_mprintf(
9221          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9222          azArg[2], zCollist, lenPK, zCollist);
9223    sqlite3_free(zCollist);
9224    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9225    if( rc==SQLITE_OK ){
9226      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9227      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9228      if( rc ){
9229        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9230      }else{
9231        utf8_printf(stdout, "%s;\n", zSql);
9232        raw_printf(stdout,
9233          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9234          azArg[1], isWO ? "table" : "index"
9235        );
9236      }
9237    }else{
9238      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9239      rc = 1;
9240    }
9241    sqlite3_free(zSql);
9242  }else
9243#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9244
9245#ifdef SQLITE_ENABLE_IOTRACE
9246  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9247    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9248    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9249    iotrace = 0;
9250    if( nArg<2 ){
9251      sqlite3IoTrace = 0;
9252    }else if( strcmp(azArg[1], "-")==0 ){
9253      sqlite3IoTrace = iotracePrintf;
9254      iotrace = stdout;
9255    }else{
9256      iotrace = fopen(azArg[1], "w");
9257      if( iotrace==0 ){
9258        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9259        sqlite3IoTrace = 0;
9260        rc = 1;
9261      }else{
9262        sqlite3IoTrace = iotracePrintf;
9263      }
9264    }
9265  }else
9266#endif
9267
9268  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9269    static const struct {
9270       const char *zLimitName;   /* Name of a limit */
9271       int limitCode;            /* Integer code for that limit */
9272    } aLimit[] = {
9273      { "length",                SQLITE_LIMIT_LENGTH                    },
9274      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9275      { "column",                SQLITE_LIMIT_COLUMN                    },
9276      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9277      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9278      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9279      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9280      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9281      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9282      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9283      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9284      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9285    };
9286    int i, n2;
9287    open_db(p, 0);
9288    if( nArg==1 ){
9289      for(i=0; i<ArraySize(aLimit); i++){
9290        printf("%20s %d\n", aLimit[i].zLimitName,
9291               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9292      }
9293    }else if( nArg>3 ){
9294      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9295      rc = 1;
9296      goto meta_command_exit;
9297    }else{
9298      int iLimit = -1;
9299      n2 = strlen30(azArg[1]);
9300      for(i=0; i<ArraySize(aLimit); i++){
9301        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9302          if( iLimit<0 ){
9303            iLimit = i;
9304          }else{
9305            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9306            rc = 1;
9307            goto meta_command_exit;
9308          }
9309        }
9310      }
9311      if( iLimit<0 ){
9312        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9313                        "enter \".limits\" with no arguments for a list.\n",
9314                         azArg[1]);
9315        rc = 1;
9316        goto meta_command_exit;
9317      }
9318      if( nArg==3 ){
9319        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9320                      (int)integerValue(azArg[2]));
9321      }
9322      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9323             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9324    }
9325  }else
9326
9327  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9328    open_db(p, 0);
9329    lintDotCommand(p, azArg, nArg);
9330  }else
9331
9332#ifndef SQLITE_OMIT_LOAD_EXTENSION
9333  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9334    const char *zFile, *zProc;
9335    char *zErrMsg = 0;
9336    failIfSafeMode(p, "cannot run .load in safe mode");
9337    if( nArg<2 ){
9338      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9339      rc = 1;
9340      goto meta_command_exit;
9341    }
9342    zFile = azArg[1];
9343    zProc = nArg>=3 ? azArg[2] : 0;
9344    open_db(p, 0);
9345    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9346    if( rc!=SQLITE_OK ){
9347      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9348      sqlite3_free(zErrMsg);
9349      rc = 1;
9350    }
9351  }else
9352#endif
9353
9354  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9355    failIfSafeMode(p, "cannot run .log in safe mode");
9356    if( nArg!=2 ){
9357      raw_printf(stderr, "Usage: .log FILENAME\n");
9358      rc = 1;
9359    }else{
9360      const char *zFile = azArg[1];
9361      output_file_close(p->pLog);
9362      p->pLog = output_file_open(zFile, 0);
9363    }
9364  }else
9365
9366  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9367    const char *zMode = 0;
9368    const char *zTabname = 0;
9369    int i, n2;
9370    ColModeOpts cmOpts = ColModeOpts_default;
9371    for(i=1; i<nArg; i++){
9372      const char *z = azArg[i];
9373      if( optionMatch(z,"wrap") && i+1<nArg ){
9374        cmOpts.iWrap = integerValue(azArg[++i]);
9375      }else if( optionMatch(z,"ww") ){
9376        cmOpts.bWordWrap = 1;
9377      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9378        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9379      }else if( optionMatch(z,"quote") ){
9380        cmOpts.bQuote = 1;
9381      }else if( optionMatch(z,"noquote") ){
9382        cmOpts.bQuote = 0;
9383      }else if( zMode==0 ){
9384        zMode = z;
9385        /* Apply defaults for qbox pseudo-mods. If that
9386         * overwrites already-set values, user was informed of this.
9387         */
9388        if( strcmp(z, "qbox")==0 ){
9389          ColModeOpts cmo = ColModeOpts_default_qbox;
9390          zMode = "box";
9391          cmOpts = cmo;
9392        }
9393      }else if( zTabname==0 ){
9394        zTabname = z;
9395      }else if( z[0]=='-' ){
9396        utf8_printf(stderr, "unknown option: %s\n", z);
9397        utf8_printf(stderr, "options:\n"
9398                            "  --noquote\n"
9399                            "  --quote\n"
9400                            "  --wordwrap on/off\n"
9401                            "  --wrap N\n"
9402                            "  --ww\n");
9403        rc = 1;
9404        goto meta_command_exit;
9405      }else{
9406        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9407        rc = 1;
9408        goto meta_command_exit;
9409      }
9410    }
9411    if( zMode==0 ){
9412      if( p->mode==MODE_Column
9413       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9414      ){
9415        raw_printf
9416          (p->out,
9417           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9418           modeDescr[p->mode], p->cmOpts.iWrap,
9419           p->cmOpts.bWordWrap ? "on" : "off",
9420           p->cmOpts.bQuote ? "" : "no");
9421      }else{
9422        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9423      }
9424      zMode = modeDescr[p->mode];
9425    }
9426    n2 = strlen30(zMode);
9427    if( strncmp(zMode,"lines",n2)==0 ){
9428      p->mode = MODE_Line;
9429      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9430    }else if( strncmp(zMode,"columns",n2)==0 ){
9431      p->mode = MODE_Column;
9432      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9433        p->showHeader = 1;
9434      }
9435      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9436      p->cmOpts = cmOpts;
9437    }else if( strncmp(zMode,"list",n2)==0 ){
9438      p->mode = MODE_List;
9439      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9440      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9441    }else if( strncmp(zMode,"html",n2)==0 ){
9442      p->mode = MODE_Html;
9443    }else if( strncmp(zMode,"tcl",n2)==0 ){
9444      p->mode = MODE_Tcl;
9445      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9446      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9447    }else if( strncmp(zMode,"csv",n2)==0 ){
9448      p->mode = MODE_Csv;
9449      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9450      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9451    }else if( strncmp(zMode,"tabs",n2)==0 ){
9452      p->mode = MODE_List;
9453      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9454    }else if( strncmp(zMode,"insert",n2)==0 ){
9455      p->mode = MODE_Insert;
9456      set_table_name(p, zTabname ? zTabname : "table");
9457    }else if( strncmp(zMode,"quote",n2)==0 ){
9458      p->mode = MODE_Quote;
9459      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9460      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9461    }else if( strncmp(zMode,"ascii",n2)==0 ){
9462      p->mode = MODE_Ascii;
9463      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9464      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9465    }else if( strncmp(zMode,"markdown",n2)==0 ){
9466      p->mode = MODE_Markdown;
9467      p->cmOpts = cmOpts;
9468    }else if( strncmp(zMode,"table",n2)==0 ){
9469      p->mode = MODE_Table;
9470      p->cmOpts = cmOpts;
9471    }else if( strncmp(zMode,"box",n2)==0 ){
9472      p->mode = MODE_Box;
9473      p->cmOpts = cmOpts;
9474    }else if( strncmp(zMode,"count",n2)==0 ){
9475      p->mode = MODE_Count;
9476    }else if( strncmp(zMode,"off",n2)==0 ){
9477      p->mode = MODE_Off;
9478    }else if( strncmp(zMode,"json",n2)==0 ){
9479      p->mode = MODE_Json;
9480    }else{
9481      raw_printf(stderr, "Error: mode should be one of: "
9482         "ascii box column csv html insert json line list markdown "
9483         "qbox quote table tabs tcl\n");
9484      rc = 1;
9485    }
9486    p->cMode = p->mode;
9487  }else
9488
9489  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9490    if( nArg!=2 ){
9491      raw_printf(stderr, "Usage: .nonce NONCE\n");
9492      rc = 1;
9493    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9494      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9495                 p->lineno, azArg[1]);
9496      exit(1);
9497    }else{
9498      p->bSafeMode = 0;
9499      return 0;  /* Return immediately to bypass the safe mode reset
9500                 ** at the end of this procedure */
9501    }
9502  }else
9503
9504  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9505    if( nArg==2 ){
9506      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9507                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9508    }else{
9509      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9510      rc = 1;
9511    }
9512  }else
9513
9514  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9515    const char *zFN = 0;     /* Pointer to constant filename */
9516    char *zNewFilename = 0;  /* Name of the database file to open */
9517    int iName = 1;           /* Index in azArg[] of the filename */
9518    int newFlag = 0;         /* True to delete file before opening */
9519    int openMode = SHELL_OPEN_UNSPEC;
9520
9521    /* Check for command-line arguments */
9522    for(iName=1; iName<nArg; iName++){
9523      const char *z = azArg[iName];
9524      if( optionMatch(z,"new") ){
9525        newFlag = 1;
9526#ifdef SQLITE_HAVE_ZLIB
9527      }else if( optionMatch(z, "zip") ){
9528        openMode = SHELL_OPEN_ZIPFILE;
9529#endif
9530      }else if( optionMatch(z, "append") ){
9531        openMode = SHELL_OPEN_APPENDVFS;
9532      }else if( optionMatch(z, "readonly") ){
9533        openMode = SHELL_OPEN_READONLY;
9534      }else if( optionMatch(z, "nofollow") ){
9535        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9536#ifndef SQLITE_OMIT_DESERIALIZE
9537      }else if( optionMatch(z, "deserialize") ){
9538        openMode = SHELL_OPEN_DESERIALIZE;
9539      }else if( optionMatch(z, "hexdb") ){
9540        openMode = SHELL_OPEN_HEXDB;
9541      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9542        p->szMax = integerValue(azArg[++iName]);
9543#endif /* SQLITE_OMIT_DESERIALIZE */
9544      }else if( z[0]=='-' ){
9545        utf8_printf(stderr, "unknown option: %s\n", z);
9546        rc = 1;
9547        goto meta_command_exit;
9548      }else if( zFN ){
9549        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9550        rc = 1;
9551        goto meta_command_exit;
9552      }else{
9553        zFN = z;
9554      }
9555    }
9556
9557    /* Close the existing database */
9558    session_close_all(p, -1);
9559    close_db(p->db);
9560    p->db = 0;
9561    p->pAuxDb->zDbFilename = 0;
9562    sqlite3_free(p->pAuxDb->zFreeOnClose);
9563    p->pAuxDb->zFreeOnClose = 0;
9564    p->openMode = openMode;
9565    p->openFlags = 0;
9566    p->szMax = 0;
9567
9568    /* If a filename is specified, try to open it first */
9569    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9570      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9571      if( p->bSafeMode
9572       && p->openMode!=SHELL_OPEN_HEXDB
9573       && zFN
9574       && strcmp(zFN,":memory:")!=0
9575      ){
9576        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9577      }
9578      if( zFN ){
9579        zNewFilename = sqlite3_mprintf("%s", zFN);
9580        shell_check_oom(zNewFilename);
9581      }else{
9582        zNewFilename = 0;
9583      }
9584      p->pAuxDb->zDbFilename = zNewFilename;
9585      open_db(p, OPEN_DB_KEEPALIVE);
9586      if( p->db==0 ){
9587        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9588        sqlite3_free(zNewFilename);
9589      }else{
9590        p->pAuxDb->zFreeOnClose = zNewFilename;
9591      }
9592    }
9593    if( p->db==0 ){
9594      /* As a fall-back open a TEMP database */
9595      p->pAuxDb->zDbFilename = 0;
9596      open_db(p, 0);
9597    }
9598  }else
9599
9600  if( (c=='o'
9601        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9602   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9603  ){
9604    char *zFile = 0;
9605    int bTxtMode = 0;
9606    int i;
9607    int eMode = 0;
9608    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9609    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9610
9611    zBOM[0] = 0;
9612    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9613    if( c=='e' ){
9614      eMode = 'x';
9615      bOnce = 2;
9616    }else if( strncmp(azArg[0],"once",n)==0 ){
9617      bOnce = 1;
9618    }
9619    for(i=1; i<nArg; i++){
9620      char *z = azArg[i];
9621      if( z[0]=='-' ){
9622        if( z[1]=='-' ) z++;
9623        if( strcmp(z,"-bom")==0 ){
9624          zBOM[0] = 0xef;
9625          zBOM[1] = 0xbb;
9626          zBOM[2] = 0xbf;
9627          zBOM[3] = 0;
9628        }else if( c!='e' && strcmp(z,"-x")==0 ){
9629          eMode = 'x';  /* spreadsheet */
9630        }else if( c!='e' && strcmp(z,"-e")==0 ){
9631          eMode = 'e';  /* text editor */
9632        }else{
9633          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9634                      azArg[i]);
9635          showHelp(p->out, azArg[0]);
9636          rc = 1;
9637          goto meta_command_exit;
9638        }
9639      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9640        zFile = sqlite3_mprintf("%s", z);
9641        if( zFile && zFile[0]=='|' ){
9642          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9643          break;
9644        }
9645      }else{
9646        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9647                    azArg[i]);
9648        showHelp(p->out, azArg[0]);
9649        rc = 1;
9650        sqlite3_free(zFile);
9651        goto meta_command_exit;
9652      }
9653    }
9654    if( zFile==0 ){
9655      zFile = sqlite3_mprintf("stdout");
9656    }
9657    if( bOnce ){
9658      p->outCount = 2;
9659    }else{
9660      p->outCount = 0;
9661    }
9662    output_reset(p);
9663#ifndef SQLITE_NOHAVE_SYSTEM
9664    if( eMode=='e' || eMode=='x' ){
9665      p->doXdgOpen = 1;
9666      outputModePush(p);
9667      if( eMode=='x' ){
9668        /* spreadsheet mode.  Output as CSV. */
9669        newTempFile(p, "csv");
9670        ShellClearFlag(p, SHFLG_Echo);
9671        p->mode = MODE_Csv;
9672        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9673        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9674      }else{
9675        /* text editor mode */
9676        newTempFile(p, "txt");
9677        bTxtMode = 1;
9678      }
9679      sqlite3_free(zFile);
9680      zFile = sqlite3_mprintf("%s", p->zTempFile);
9681    }
9682#endif /* SQLITE_NOHAVE_SYSTEM */
9683    shell_check_oom(zFile);
9684    if( zFile[0]=='|' ){
9685#ifdef SQLITE_OMIT_POPEN
9686      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9687      rc = 1;
9688      p->out = stdout;
9689#else
9690      p->out = popen(zFile + 1, "w");
9691      if( p->out==0 ){
9692        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9693        p->out = stdout;
9694        rc = 1;
9695      }else{
9696        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9697        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9698      }
9699#endif
9700    }else{
9701      p->out = output_file_open(zFile, bTxtMode);
9702      if( p->out==0 ){
9703        if( strcmp(zFile,"off")!=0 ){
9704          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9705        }
9706        p->out = stdout;
9707        rc = 1;
9708      } else {
9709        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9710        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9711      }
9712    }
9713    sqlite3_free(zFile);
9714  }else
9715
9716  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9717    open_db(p,0);
9718    if( nArg<=1 ) goto parameter_syntax_error;
9719
9720    /* .parameter clear
9721    ** Clear all bind parameters by dropping the TEMP table that holds them.
9722    */
9723    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9724      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9725                   0, 0, 0);
9726    }else
9727
9728    /* .parameter list
9729    ** List all bind parameters.
9730    */
9731    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9732      sqlite3_stmt *pStmt = 0;
9733      int rx;
9734      int len = 0;
9735      rx = sqlite3_prepare_v2(p->db,
9736             "SELECT max(length(key)) "
9737             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9738      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9739        len = sqlite3_column_int(pStmt, 0);
9740        if( len>40 ) len = 40;
9741      }
9742      sqlite3_finalize(pStmt);
9743      pStmt = 0;
9744      if( len ){
9745        rx = sqlite3_prepare_v2(p->db,
9746             "SELECT key, quote(value) "
9747             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9748        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9749          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9750                      sqlite3_column_text(pStmt,1));
9751        }
9752        sqlite3_finalize(pStmt);
9753      }
9754    }else
9755
9756    /* .parameter init
9757    ** Make sure the TEMP table used to hold bind parameters exists.
9758    ** Create it if necessary.
9759    */
9760    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9761      bind_table_init(p);
9762    }else
9763
9764    /* .parameter set NAME VALUE
9765    ** Set or reset a bind parameter.  NAME should be the full parameter
9766    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9767    ** VALUE can be in either SQL literal notation, or if not it will be
9768    ** understood to be a text string.
9769    */
9770    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9771      int rx;
9772      char *zSql;
9773      sqlite3_stmt *pStmt;
9774      const char *zKey = azArg[2];
9775      const char *zValue = azArg[3];
9776      bind_table_init(p);
9777      zSql = sqlite3_mprintf(
9778                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9779                  "VALUES(%Q,%s);", zKey, zValue);
9780      shell_check_oom(zSql);
9781      pStmt = 0;
9782      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9783      sqlite3_free(zSql);
9784      if( rx!=SQLITE_OK ){
9785        sqlite3_finalize(pStmt);
9786        pStmt = 0;
9787        zSql = sqlite3_mprintf(
9788                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9789                   "VALUES(%Q,%Q);", zKey, zValue);
9790        shell_check_oom(zSql);
9791        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9792        sqlite3_free(zSql);
9793        if( rx!=SQLITE_OK ){
9794          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9795          sqlite3_finalize(pStmt);
9796          pStmt = 0;
9797          rc = 1;
9798        }
9799      }
9800      sqlite3_step(pStmt);
9801      sqlite3_finalize(pStmt);
9802    }else
9803
9804    /* .parameter unset NAME
9805    ** Remove the NAME binding from the parameter binding table, if it
9806    ** exists.
9807    */
9808    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9809      char *zSql = sqlite3_mprintf(
9810          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9811      shell_check_oom(zSql);
9812      sqlite3_exec(p->db, zSql, 0, 0, 0);
9813      sqlite3_free(zSql);
9814    }else
9815    /* If no command name matches, show a syntax error */
9816    parameter_syntax_error:
9817    showHelp(p->out, "parameter");
9818  }else
9819
9820  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9821    int i;
9822    for(i=1; i<nArg; i++){
9823      if( i>1 ) raw_printf(p->out, " ");
9824      utf8_printf(p->out, "%s", azArg[i]);
9825    }
9826    raw_printf(p->out, "\n");
9827  }else
9828
9829#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9830  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9831    int i;
9832    int nn = 0;
9833    p->flgProgress = 0;
9834    p->mxProgress = 0;
9835    p->nProgress = 0;
9836    for(i=1; i<nArg; i++){
9837      const char *z = azArg[i];
9838      if( z[0]=='-' ){
9839        z++;
9840        if( z[0]=='-' ) z++;
9841        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9842          p->flgProgress |= SHELL_PROGRESS_QUIET;
9843          continue;
9844        }
9845        if( strcmp(z,"reset")==0 ){
9846          p->flgProgress |= SHELL_PROGRESS_RESET;
9847          continue;
9848        }
9849        if( strcmp(z,"once")==0 ){
9850          p->flgProgress |= SHELL_PROGRESS_ONCE;
9851          continue;
9852        }
9853        if( strcmp(z,"limit")==0 ){
9854          if( i+1>=nArg ){
9855            utf8_printf(stderr, "Error: missing argument on --limit\n");
9856            rc = 1;
9857            goto meta_command_exit;
9858          }else{
9859            p->mxProgress = (int)integerValue(azArg[++i]);
9860          }
9861          continue;
9862        }
9863        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9864        rc = 1;
9865        goto meta_command_exit;
9866      }else{
9867        nn = (int)integerValue(z);
9868      }
9869    }
9870    open_db(p, 0);
9871    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9872  }else
9873#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9874
9875  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9876    if( nArg >= 2) {
9877      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9878    }
9879    if( nArg >= 3) {
9880      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9881    }
9882  }else
9883
9884  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9885    rc = 2;
9886  }else
9887
9888  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9889    FILE *inSaved = p->in;
9890    int savedLineno = p->lineno;
9891    failIfSafeMode(p, "cannot run .read in safe mode");
9892    if( nArg!=2 ){
9893      raw_printf(stderr, "Usage: .read FILE\n");
9894      rc = 1;
9895      goto meta_command_exit;
9896    }
9897    if( azArg[1][0]=='|' ){
9898#ifdef SQLITE_OMIT_POPEN
9899      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9900      rc = 1;
9901      p->out = stdout;
9902#else
9903      p->in = popen(azArg[1]+1, "r");
9904      if( p->in==0 ){
9905        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9906        rc = 1;
9907      }else{
9908        rc = process_input(p);
9909        pclose(p->in);
9910      }
9911#endif
9912    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9913      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9914      rc = 1;
9915    }else{
9916      rc = process_input(p);
9917      fclose(p->in);
9918    }
9919    p->in = inSaved;
9920    p->lineno = savedLineno;
9921  }else
9922
9923  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9924    const char *zSrcFile;
9925    const char *zDb;
9926    sqlite3 *pSrc;
9927    sqlite3_backup *pBackup;
9928    int nTimeout = 0;
9929
9930    failIfSafeMode(p, "cannot run .restore in safe mode");
9931    if( nArg==2 ){
9932      zSrcFile = azArg[1];
9933      zDb = "main";
9934    }else if( nArg==3 ){
9935      zSrcFile = azArg[2];
9936      zDb = azArg[1];
9937    }else{
9938      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9939      rc = 1;
9940      goto meta_command_exit;
9941    }
9942    rc = sqlite3_open(zSrcFile, &pSrc);
9943    if( rc!=SQLITE_OK ){
9944      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9945      close_db(pSrc);
9946      return 1;
9947    }
9948    open_db(p, 0);
9949    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9950    if( pBackup==0 ){
9951      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9952      close_db(pSrc);
9953      return 1;
9954    }
9955    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9956          || rc==SQLITE_BUSY  ){
9957      if( rc==SQLITE_BUSY ){
9958        if( nTimeout++ >= 3 ) break;
9959        sqlite3_sleep(100);
9960      }
9961    }
9962    sqlite3_backup_finish(pBackup);
9963    if( rc==SQLITE_DONE ){
9964      rc = 0;
9965    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9966      raw_printf(stderr, "Error: source database is busy\n");
9967      rc = 1;
9968    }else{
9969      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9970      rc = 1;
9971    }
9972    close_db(pSrc);
9973  }else
9974
9975  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9976    if( nArg==2 ){
9977      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9978#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9979      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9980#endif
9981    }else{
9982      raw_printf(stderr, "Usage: .scanstats on|off\n");
9983      rc = 1;
9984    }
9985  }else
9986
9987  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9988    ShellText sSelect;
9989    ShellState data;
9990    char *zErrMsg = 0;
9991    const char *zDiv = "(";
9992    const char *zName = 0;
9993    int iSchema = 0;
9994    int bDebug = 0;
9995    int bNoSystemTabs = 0;
9996    int ii;
9997
9998    open_db(p, 0);
9999    memcpy(&data, p, sizeof(data));
10000    data.showHeader = 0;
10001    data.cMode = data.mode = MODE_Semi;
10002    initText(&sSelect);
10003    for(ii=1; ii<nArg; ii++){
10004      if( optionMatch(azArg[ii],"indent") ){
10005        data.cMode = data.mode = MODE_Pretty;
10006      }else if( optionMatch(azArg[ii],"debug") ){
10007        bDebug = 1;
10008      }else if( optionMatch(azArg[ii],"nosys") ){
10009        bNoSystemTabs = 1;
10010      }else if( azArg[ii][0]=='-' ){
10011        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10012        rc = 1;
10013        goto meta_command_exit;
10014      }else if( zName==0 ){
10015        zName = azArg[ii];
10016      }else{
10017        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10018        rc = 1;
10019        goto meta_command_exit;
10020      }
10021    }
10022    if( zName!=0 ){
10023      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10024                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10025                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10026                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10027      if( isSchema ){
10028        char *new_argv[2], *new_colv[2];
10029        new_argv[0] = sqlite3_mprintf(
10030                      "CREATE TABLE %s (\n"
10031                      "  type text,\n"
10032                      "  name text,\n"
10033                      "  tbl_name text,\n"
10034                      "  rootpage integer,\n"
10035                      "  sql text\n"
10036                      ")", zName);
10037        shell_check_oom(new_argv[0]);
10038        new_argv[1] = 0;
10039        new_colv[0] = "sql";
10040        new_colv[1] = 0;
10041        callback(&data, 1, new_argv, new_colv);
10042        sqlite3_free(new_argv[0]);
10043      }
10044    }
10045    if( zDiv ){
10046      sqlite3_stmt *pStmt = 0;
10047      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10048                              -1, &pStmt, 0);
10049      if( rc ){
10050        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10051        sqlite3_finalize(pStmt);
10052        rc = 1;
10053        goto meta_command_exit;
10054      }
10055      appendText(&sSelect, "SELECT sql FROM", 0);
10056      iSchema = 0;
10057      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10058        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10059        char zScNum[30];
10060        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10061        appendText(&sSelect, zDiv, 0);
10062        zDiv = " UNION ALL ";
10063        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10064        if( sqlite3_stricmp(zDb, "main")!=0 ){
10065          appendText(&sSelect, zDb, '\'');
10066        }else{
10067          appendText(&sSelect, "NULL", 0);
10068        }
10069        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10070        appendText(&sSelect, zScNum, 0);
10071        appendText(&sSelect, " AS snum, ", 0);
10072        appendText(&sSelect, zDb, '\'');
10073        appendText(&sSelect, " AS sname FROM ", 0);
10074        appendText(&sSelect, zDb, quoteChar(zDb));
10075        appendText(&sSelect, ".sqlite_schema", 0);
10076      }
10077      sqlite3_finalize(pStmt);
10078#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10079      if( zName ){
10080        appendText(&sSelect,
10081           " UNION ALL SELECT shell_module_schema(name),"
10082           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10083        0);
10084      }
10085#endif
10086      appendText(&sSelect, ") WHERE ", 0);
10087      if( zName ){
10088        char *zQarg = sqlite3_mprintf("%Q", zName);
10089        int bGlob;
10090        shell_check_oom(zQarg);
10091        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10092                strchr(zName, '[') != 0;
10093        if( strchr(zName, '.') ){
10094          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10095        }else{
10096          appendText(&sSelect, "lower(tbl_name)", 0);
10097        }
10098        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10099        appendText(&sSelect, zQarg, 0);
10100        if( !bGlob ){
10101          appendText(&sSelect, " ESCAPE '\\' ", 0);
10102        }
10103        appendText(&sSelect, " AND ", 0);
10104        sqlite3_free(zQarg);
10105      }
10106      if( bNoSystemTabs ){
10107        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10108      }
10109      appendText(&sSelect, "sql IS NOT NULL"
10110                           " ORDER BY snum, rowid", 0);
10111      if( bDebug ){
10112        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10113      }else{
10114        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10115      }
10116      freeText(&sSelect);
10117    }
10118    if( zErrMsg ){
10119      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10120      sqlite3_free(zErrMsg);
10121      rc = 1;
10122    }else if( rc != SQLITE_OK ){
10123      raw_printf(stderr,"Error: querying schema information\n");
10124      rc = 1;
10125    }else{
10126      rc = 0;
10127    }
10128  }else
10129
10130  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10131   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10132  ){
10133    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10134    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10135  }else
10136
10137#if defined(SQLITE_ENABLE_SESSION)
10138  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10139    struct AuxDb *pAuxDb = p->pAuxDb;
10140    OpenSession *pSession = &pAuxDb->aSession[0];
10141    char **azCmd = &azArg[1];
10142    int iSes = 0;
10143    int nCmd = nArg - 1;
10144    int i;
10145    if( nArg<=1 ) goto session_syntax_error;
10146    open_db(p, 0);
10147    if( nArg>=3 ){
10148      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10149        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10150      }
10151      if( iSes<pAuxDb->nSession ){
10152        pSession = &pAuxDb->aSession[iSes];
10153        azCmd++;
10154        nCmd--;
10155      }else{
10156        pSession = &pAuxDb->aSession[0];
10157        iSes = 0;
10158      }
10159    }
10160
10161    /* .session attach TABLE
10162    ** Invoke the sqlite3session_attach() interface to attach a particular
10163    ** table so that it is never filtered.
10164    */
10165    if( strcmp(azCmd[0],"attach")==0 ){
10166      if( nCmd!=2 ) goto session_syntax_error;
10167      if( pSession->p==0 ){
10168        session_not_open:
10169        raw_printf(stderr, "ERROR: No sessions are open\n");
10170      }else{
10171        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10172        if( rc ){
10173          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10174          rc = 0;
10175        }
10176      }
10177    }else
10178
10179    /* .session changeset FILE
10180    ** .session patchset FILE
10181    ** Write a changeset or patchset into a file.  The file is overwritten.
10182    */
10183    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10184      FILE *out = 0;
10185      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10186      if( nCmd!=2 ) goto session_syntax_error;
10187      if( pSession->p==0 ) goto session_not_open;
10188      out = fopen(azCmd[1], "wb");
10189      if( out==0 ){
10190        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10191                    azCmd[1]);
10192      }else{
10193        int szChng;
10194        void *pChng;
10195        if( azCmd[0][0]=='c' ){
10196          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10197        }else{
10198          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10199        }
10200        if( rc ){
10201          printf("Error: error code %d\n", rc);
10202          rc = 0;
10203        }
10204        if( pChng
10205          && fwrite(pChng, szChng, 1, out)!=1 ){
10206          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10207                  szChng);
10208        }
10209        sqlite3_free(pChng);
10210        fclose(out);
10211      }
10212    }else
10213
10214    /* .session close
10215    ** Close the identified session
10216    */
10217    if( strcmp(azCmd[0], "close")==0 ){
10218      if( nCmd!=1 ) goto session_syntax_error;
10219      if( pAuxDb->nSession ){
10220        session_close(pSession);
10221        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10222      }
10223    }else
10224
10225    /* .session enable ?BOOLEAN?
10226    ** Query or set the enable flag
10227    */
10228    if( strcmp(azCmd[0], "enable")==0 ){
10229      int ii;
10230      if( nCmd>2 ) goto session_syntax_error;
10231      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10232      if( pAuxDb->nSession ){
10233        ii = sqlite3session_enable(pSession->p, ii);
10234        utf8_printf(p->out, "session %s enable flag = %d\n",
10235                    pSession->zName, ii);
10236      }
10237    }else
10238
10239    /* .session filter GLOB ....
10240    ** Set a list of GLOB patterns of table names to be excluded.
10241    */
10242    if( strcmp(azCmd[0], "filter")==0 ){
10243      int ii, nByte;
10244      if( nCmd<2 ) goto session_syntax_error;
10245      if( pAuxDb->nSession ){
10246        for(ii=0; ii<pSession->nFilter; ii++){
10247          sqlite3_free(pSession->azFilter[ii]);
10248        }
10249        sqlite3_free(pSession->azFilter);
10250        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10251        pSession->azFilter = sqlite3_malloc( nByte );
10252        if( pSession->azFilter==0 ){
10253          raw_printf(stderr, "Error: out or memory\n");
10254          exit(1);
10255        }
10256        for(ii=1; ii<nCmd; ii++){
10257          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10258          shell_check_oom(x);
10259        }
10260        pSession->nFilter = ii-1;
10261      }
10262    }else
10263
10264    /* .session indirect ?BOOLEAN?
10265    ** Query or set the indirect flag
10266    */
10267    if( strcmp(azCmd[0], "indirect")==0 ){
10268      int ii;
10269      if( nCmd>2 ) goto session_syntax_error;
10270      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10271      if( pAuxDb->nSession ){
10272        ii = sqlite3session_indirect(pSession->p, ii);
10273        utf8_printf(p->out, "session %s indirect flag = %d\n",
10274                    pSession->zName, ii);
10275      }
10276    }else
10277
10278    /* .session isempty
10279    ** Determine if the session is empty
10280    */
10281    if( strcmp(azCmd[0], "isempty")==0 ){
10282      int ii;
10283      if( nCmd!=1 ) goto session_syntax_error;
10284      if( pAuxDb->nSession ){
10285        ii = sqlite3session_isempty(pSession->p);
10286        utf8_printf(p->out, "session %s isempty flag = %d\n",
10287                    pSession->zName, ii);
10288      }
10289    }else
10290
10291    /* .session list
10292    ** List all currently open sessions
10293    */
10294    if( strcmp(azCmd[0],"list")==0 ){
10295      for(i=0; i<pAuxDb->nSession; i++){
10296        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10297      }
10298    }else
10299
10300    /* .session open DB NAME
10301    ** Open a new session called NAME on the attached database DB.
10302    ** DB is normally "main".
10303    */
10304    if( strcmp(azCmd[0],"open")==0 ){
10305      char *zName;
10306      if( nCmd!=3 ) goto session_syntax_error;
10307      zName = azCmd[2];
10308      if( zName[0]==0 ) goto session_syntax_error;
10309      for(i=0; i<pAuxDb->nSession; i++){
10310        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10311          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10312          goto meta_command_exit;
10313        }
10314      }
10315      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10316        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10317        goto meta_command_exit;
10318      }
10319      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10320      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10321      if( rc ){
10322        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10323        rc = 0;
10324        goto meta_command_exit;
10325      }
10326      pSession->nFilter = 0;
10327      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10328      pAuxDb->nSession++;
10329      pSession->zName = sqlite3_mprintf("%s", zName);
10330      shell_check_oom(pSession->zName);
10331    }else
10332    /* If no command name matches, show a syntax error */
10333    session_syntax_error:
10334    showHelp(p->out, "session");
10335  }else
10336#endif
10337
10338#ifdef SQLITE_DEBUG
10339  /* Undocumented commands for internal testing.  Subject to change
10340  ** without notice. */
10341  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10342    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10343      int i, v;
10344      for(i=1; i<nArg; i++){
10345        v = booleanValue(azArg[i]);
10346        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10347      }
10348    }
10349    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10350      int i; sqlite3_int64 v;
10351      for(i=1; i<nArg; i++){
10352        char zBuf[200];
10353        v = integerValue(azArg[i]);
10354        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10355        utf8_printf(p->out, "%s", zBuf);
10356      }
10357    }
10358  }else
10359#endif
10360
10361  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10362    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10363    int bVerbose = 0;        /* Verbose output */
10364    int bSelftestExists;     /* True if SELFTEST already exists */
10365    int i, k;                /* Loop counters */
10366    int nTest = 0;           /* Number of tests runs */
10367    int nErr = 0;            /* Number of errors seen */
10368    ShellText str;           /* Answer for a query */
10369    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10370
10371    open_db(p,0);
10372    for(i=1; i<nArg; i++){
10373      const char *z = azArg[i];
10374      if( z[0]=='-' && z[1]=='-' ) z++;
10375      if( strcmp(z,"-init")==0 ){
10376        bIsInit = 1;
10377      }else
10378      if( strcmp(z,"-v")==0 ){
10379        bVerbose++;
10380      }else
10381      {
10382        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10383                    azArg[i], azArg[0]);
10384        raw_printf(stderr, "Should be one of: --init -v\n");
10385        rc = 1;
10386        goto meta_command_exit;
10387      }
10388    }
10389    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10390           != SQLITE_OK ){
10391      bSelftestExists = 0;
10392    }else{
10393      bSelftestExists = 1;
10394    }
10395    if( bIsInit ){
10396      createSelftestTable(p);
10397      bSelftestExists = 1;
10398    }
10399    initText(&str);
10400    appendText(&str, "x", 0);
10401    for(k=bSelftestExists; k>=0; k--){
10402      if( k==1 ){
10403        rc = sqlite3_prepare_v2(p->db,
10404            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10405            -1, &pStmt, 0);
10406      }else{
10407        rc = sqlite3_prepare_v2(p->db,
10408          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10409          "      (1,'run','PRAGMA integrity_check','ok')",
10410          -1, &pStmt, 0);
10411      }
10412      if( rc ){
10413        raw_printf(stderr, "Error querying the selftest table\n");
10414        rc = 1;
10415        sqlite3_finalize(pStmt);
10416        goto meta_command_exit;
10417      }
10418      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10419        int tno = sqlite3_column_int(pStmt, 0);
10420        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10421        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10422        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10423
10424        if( zOp==0 ) continue;
10425        if( zSql==0 ) continue;
10426        if( zAns==0 ) continue;
10427        k = 0;
10428        if( bVerbose>0 ){
10429          printf("%d: %s %s\n", tno, zOp, zSql);
10430        }
10431        if( strcmp(zOp,"memo")==0 ){
10432          utf8_printf(p->out, "%s\n", zSql);
10433        }else
10434        if( strcmp(zOp,"run")==0 ){
10435          char *zErrMsg = 0;
10436          str.n = 0;
10437          str.z[0] = 0;
10438          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10439          nTest++;
10440          if( bVerbose ){
10441            utf8_printf(p->out, "Result: %s\n", str.z);
10442          }
10443          if( rc || zErrMsg ){
10444            nErr++;
10445            rc = 1;
10446            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10447            sqlite3_free(zErrMsg);
10448          }else if( strcmp(zAns,str.z)!=0 ){
10449            nErr++;
10450            rc = 1;
10451            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10452            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10453          }
10454        }else
10455        {
10456          utf8_printf(stderr,
10457            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10458          rc = 1;
10459          break;
10460        }
10461      } /* End loop over rows of content from SELFTEST */
10462      sqlite3_finalize(pStmt);
10463    } /* End loop over k */
10464    freeText(&str);
10465    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10466  }else
10467
10468  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10469    if( nArg<2 || nArg>3 ){
10470      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10471      rc = 1;
10472    }
10473    if( nArg>=2 ){
10474      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10475                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10476    }
10477    if( nArg>=3 ){
10478      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10479                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10480    }
10481  }else
10482
10483  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10484    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10485    int i;                   /* Loop counter */
10486    int bSchema = 0;         /* Also hash the schema */
10487    int bSeparate = 0;       /* Hash each table separately */
10488    int iSize = 224;         /* Hash algorithm to use */
10489    int bDebug = 0;          /* Only show the query that would have run */
10490    sqlite3_stmt *pStmt;     /* For querying tables names */
10491    char *zSql;              /* SQL to be run */
10492    char *zSep;              /* Separator */
10493    ShellText sSql;          /* Complete SQL for the query to run the hash */
10494    ShellText sQuery;        /* Set of queries used to read all content */
10495    open_db(p, 0);
10496    for(i=1; i<nArg; i++){
10497      const char *z = azArg[i];
10498      if( z[0]=='-' ){
10499        z++;
10500        if( z[0]=='-' ) z++;
10501        if( strcmp(z,"schema")==0 ){
10502          bSchema = 1;
10503        }else
10504        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10505         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10506        ){
10507          iSize = atoi(&z[5]);
10508        }else
10509        if( strcmp(z,"debug")==0 ){
10510          bDebug = 1;
10511        }else
10512        {
10513          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10514                      azArg[i], azArg[0]);
10515          showHelp(p->out, azArg[0]);
10516          rc = 1;
10517          goto meta_command_exit;
10518        }
10519      }else if( zLike ){
10520        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10521        rc = 1;
10522        goto meta_command_exit;
10523      }else{
10524        zLike = z;
10525        bSeparate = 1;
10526        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10527      }
10528    }
10529    if( bSchema ){
10530      zSql = "SELECT lower(name) FROM sqlite_schema"
10531             " WHERE type='table' AND coalesce(rootpage,0)>1"
10532             " UNION ALL SELECT 'sqlite_schema'"
10533             " ORDER BY 1 collate nocase";
10534    }else{
10535      zSql = "SELECT lower(name) FROM sqlite_schema"
10536             " WHERE type='table' AND coalesce(rootpage,0)>1"
10537             " AND name NOT LIKE 'sqlite_%'"
10538             " ORDER BY 1 collate nocase";
10539    }
10540    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10541    initText(&sQuery);
10542    initText(&sSql);
10543    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10544    zSep = "VALUES(";
10545    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10546      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10547      if( zTab==0 ) continue;
10548      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10549      if( strncmp(zTab, "sqlite_",7)!=0 ){
10550        appendText(&sQuery,"SELECT * FROM ", 0);
10551        appendText(&sQuery,zTab,'"');
10552        appendText(&sQuery," NOT INDEXED;", 0);
10553      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10554        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10555                           " ORDER BY name;", 0);
10556      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10557        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10558                           " ORDER BY name;", 0);
10559      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10560        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10561                           " ORDER BY tbl,idx;", 0);
10562      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10563        appendText(&sQuery, "SELECT * FROM ", 0);
10564        appendText(&sQuery, zTab, 0);
10565        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10566      }
10567      appendText(&sSql, zSep, 0);
10568      appendText(&sSql, sQuery.z, '\'');
10569      sQuery.n = 0;
10570      appendText(&sSql, ",", 0);
10571      appendText(&sSql, zTab, '\'');
10572      zSep = "),(";
10573    }
10574    sqlite3_finalize(pStmt);
10575    if( bSeparate ){
10576      zSql = sqlite3_mprintf(
10577          "%s))"
10578          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10579          "   FROM [sha3sum$query]",
10580          sSql.z, iSize);
10581    }else{
10582      zSql = sqlite3_mprintf(
10583          "%s))"
10584          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10585          "   FROM [sha3sum$query]",
10586          sSql.z, iSize);
10587    }
10588    shell_check_oom(zSql);
10589    freeText(&sQuery);
10590    freeText(&sSql);
10591    if( bDebug ){
10592      utf8_printf(p->out, "%s\n", zSql);
10593    }else{
10594      shell_exec(p, zSql, 0);
10595    }
10596    sqlite3_free(zSql);
10597  }else
10598
10599#ifndef SQLITE_NOHAVE_SYSTEM
10600  if( c=='s'
10601   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10602  ){
10603    char *zCmd;
10604    int i, x;
10605    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10606    if( nArg<2 ){
10607      raw_printf(stderr, "Usage: .system COMMAND\n");
10608      rc = 1;
10609      goto meta_command_exit;
10610    }
10611    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10612    for(i=2; i<nArg && zCmd!=0; i++){
10613      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10614                             zCmd, azArg[i]);
10615    }
10616    x = zCmd!=0 ? system(zCmd) : 1;
10617    sqlite3_free(zCmd);
10618    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10619  }else
10620#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10621
10622  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10623    static const char *azBool[] = { "off", "on", "trigger", "full"};
10624    const char *zOut;
10625    int i;
10626    if( nArg!=1 ){
10627      raw_printf(stderr, "Usage: .show\n");
10628      rc = 1;
10629      goto meta_command_exit;
10630    }
10631    utf8_printf(p->out, "%12.12s: %s\n","echo",
10632                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10633    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10634    utf8_printf(p->out, "%12.12s: %s\n","explain",
10635         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10636    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10637    if( p->mode==MODE_Column
10638     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10639    ){
10640      utf8_printf
10641        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10642         modeDescr[p->mode], p->cmOpts.iWrap,
10643         p->cmOpts.bWordWrap ? "on" : "off",
10644         p->cmOpts.bQuote ? "" : "no");
10645    }else{
10646      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10647    }
10648    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10649      output_c_string(p->out, p->nullValue);
10650      raw_printf(p->out, "\n");
10651    utf8_printf(p->out,"%12.12s: %s\n","output",
10652            strlen30(p->outfile) ? p->outfile : "stdout");
10653    utf8_printf(p->out,"%12.12s: ", "colseparator");
10654      output_c_string(p->out, p->colSeparator);
10655      raw_printf(p->out, "\n");
10656    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10657      output_c_string(p->out, p->rowSeparator);
10658      raw_printf(p->out, "\n");
10659    switch( p->statsOn ){
10660      case 0:  zOut = "off";     break;
10661      default: zOut = "on";      break;
10662      case 2:  zOut = "stmt";    break;
10663      case 3:  zOut = "vmstep";  break;
10664    }
10665    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10666    utf8_printf(p->out, "%12.12s: ", "width");
10667    for (i=0;i<p->nWidth;i++) {
10668      raw_printf(p->out, "%d ", p->colWidth[i]);
10669    }
10670    raw_printf(p->out, "\n");
10671    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10672                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10673  }else
10674
10675  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10676    if( nArg==2 ){
10677      if( strcmp(azArg[1],"stmt")==0 ){
10678        p->statsOn = 2;
10679      }else if( strcmp(azArg[1],"vmstep")==0 ){
10680        p->statsOn = 3;
10681      }else{
10682        p->statsOn = (u8)booleanValue(azArg[1]);
10683      }
10684    }else if( nArg==1 ){
10685      display_stats(p->db, p, 0);
10686    }else{
10687      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10688      rc = 1;
10689    }
10690  }else
10691
10692  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10693   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10694                 || strncmp(azArg[0], "indexes", n)==0) )
10695  ){
10696    sqlite3_stmt *pStmt;
10697    char **azResult;
10698    int nRow, nAlloc;
10699    int ii;
10700    ShellText s;
10701    initText(&s);
10702    open_db(p, 0);
10703    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10704    if( rc ){
10705      sqlite3_finalize(pStmt);
10706      return shellDatabaseError(p->db);
10707    }
10708
10709    if( nArg>2 && c=='i' ){
10710      /* It is an historical accident that the .indexes command shows an error
10711      ** when called with the wrong number of arguments whereas the .tables
10712      ** command does not. */
10713      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10714      rc = 1;
10715      sqlite3_finalize(pStmt);
10716      goto meta_command_exit;
10717    }
10718    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10719      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10720      if( zDbName==0 ) continue;
10721      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10722      if( sqlite3_stricmp(zDbName, "main")==0 ){
10723        appendText(&s, "SELECT name FROM ", 0);
10724      }else{
10725        appendText(&s, "SELECT ", 0);
10726        appendText(&s, zDbName, '\'');
10727        appendText(&s, "||'.'||name FROM ", 0);
10728      }
10729      appendText(&s, zDbName, '"');
10730      appendText(&s, ".sqlite_schema ", 0);
10731      if( c=='t' ){
10732        appendText(&s," WHERE type IN ('table','view')"
10733                      "   AND name NOT LIKE 'sqlite_%'"
10734                      "   AND name LIKE ?1", 0);
10735      }else{
10736        appendText(&s," WHERE type='index'"
10737                      "   AND tbl_name LIKE ?1", 0);
10738      }
10739    }
10740    rc = sqlite3_finalize(pStmt);
10741    if( rc==SQLITE_OK ){
10742      appendText(&s, " ORDER BY 1", 0);
10743      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10744    }
10745    freeText(&s);
10746    if( rc ) return shellDatabaseError(p->db);
10747
10748    /* Run the SQL statement prepared by the above block. Store the results
10749    ** as an array of nul-terminated strings in azResult[].  */
10750    nRow = nAlloc = 0;
10751    azResult = 0;
10752    if( nArg>1 ){
10753      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10754    }else{
10755      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10756    }
10757    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10758      if( nRow>=nAlloc ){
10759        char **azNew;
10760        int n2 = nAlloc*2 + 10;
10761        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10762        shell_check_oom(azNew);
10763        nAlloc = n2;
10764        azResult = azNew;
10765      }
10766      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10767      shell_check_oom(azResult[nRow]);
10768      nRow++;
10769    }
10770    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10771      rc = shellDatabaseError(p->db);
10772    }
10773
10774    /* Pretty-print the contents of array azResult[] to the output */
10775    if( rc==0 && nRow>0 ){
10776      int len, maxlen = 0;
10777      int i, j;
10778      int nPrintCol, nPrintRow;
10779      for(i=0; i<nRow; i++){
10780        len = strlen30(azResult[i]);
10781        if( len>maxlen ) maxlen = len;
10782      }
10783      nPrintCol = 80/(maxlen+2);
10784      if( nPrintCol<1 ) nPrintCol = 1;
10785      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10786      for(i=0; i<nPrintRow; i++){
10787        for(j=i; j<nRow; j+=nPrintRow){
10788          char *zSp = j<nPrintRow ? "" : "  ";
10789          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10790                      azResult[j] ? azResult[j]:"");
10791        }
10792        raw_printf(p->out, "\n");
10793      }
10794    }
10795
10796    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10797    sqlite3_free(azResult);
10798  }else
10799
10800  /* Begin redirecting output to the file "testcase-out.txt" */
10801  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10802    output_reset(p);
10803    p->out = output_file_open("testcase-out.txt", 0);
10804    if( p->out==0 ){
10805      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10806    }
10807    if( nArg>=2 ){
10808      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10809    }else{
10810      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10811    }
10812  }else
10813
10814#ifndef SQLITE_UNTESTABLE
10815  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10816    static const struct {
10817       const char *zCtrlName;   /* Name of a test-control option */
10818       int ctrlCode;            /* Integer code for that option */
10819       int unSafe;              /* Not valid for --safe mode */
10820       const char *zUsage;      /* Usage notes */
10821    } aCtrl[] = {
10822      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10823      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10824    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10825    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10826      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10827      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10828    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10829      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10830      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10831      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10832      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10833      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10834#ifdef YYCOVERAGE
10835      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10836#endif
10837      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10838      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10839      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10840      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10841      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10842      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10843      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10844    };
10845    int testctrl = -1;
10846    int iCtrl = -1;
10847    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10848    int isOk = 0;
10849    int i, n2;
10850    const char *zCmd = 0;
10851
10852    open_db(p, 0);
10853    zCmd = nArg>=2 ? azArg[1] : "help";
10854
10855    /* The argument can optionally begin with "-" or "--" */
10856    if( zCmd[0]=='-' && zCmd[1] ){
10857      zCmd++;
10858      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10859    }
10860
10861    /* --help lists all test-controls */
10862    if( strcmp(zCmd,"help")==0 ){
10863      utf8_printf(p->out, "Available test-controls:\n");
10864      for(i=0; i<ArraySize(aCtrl); i++){
10865        utf8_printf(p->out, "  .testctrl %s %s\n",
10866                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10867      }
10868      rc = 1;
10869      goto meta_command_exit;
10870    }
10871
10872    /* convert testctrl text option to value. allow any unique prefix
10873    ** of the option name, or a numerical value. */
10874    n2 = strlen30(zCmd);
10875    for(i=0; i<ArraySize(aCtrl); i++){
10876      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10877        if( testctrl<0 ){
10878          testctrl = aCtrl[i].ctrlCode;
10879          iCtrl = i;
10880        }else{
10881          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10882                              "Use \".testctrl --help\" for help\n", zCmd);
10883          rc = 1;
10884          goto meta_command_exit;
10885        }
10886      }
10887    }
10888    if( testctrl<0 ){
10889      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10890                         "Use \".testctrl --help\" for help\n", zCmd);
10891    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10892      utf8_printf(stderr,
10893         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10894         p->lineno, aCtrl[iCtrl].zCtrlName);
10895      exit(1);
10896    }else{
10897      switch(testctrl){
10898
10899        /* sqlite3_test_control(int, db, int) */
10900        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10901          if( nArg==3 ){
10902            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10903            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10904            isOk = 3;
10905          }
10906          break;
10907
10908        /* sqlite3_test_control(int) */
10909        case SQLITE_TESTCTRL_PRNG_SAVE:
10910        case SQLITE_TESTCTRL_PRNG_RESTORE:
10911        case SQLITE_TESTCTRL_BYTEORDER:
10912          if( nArg==2 ){
10913            rc2 = sqlite3_test_control(testctrl);
10914            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10915          }
10916          break;
10917
10918        /* sqlite3_test_control(int, uint) */
10919        case SQLITE_TESTCTRL_PENDING_BYTE:
10920          if( nArg==3 ){
10921            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10922            rc2 = sqlite3_test_control(testctrl, opt);
10923            isOk = 3;
10924          }
10925          break;
10926
10927        /* sqlite3_test_control(int, int, sqlite3*) */
10928        case SQLITE_TESTCTRL_PRNG_SEED:
10929          if( nArg==3 || nArg==4 ){
10930            int ii = (int)integerValue(azArg[2]);
10931            sqlite3 *db;
10932            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10933              sqlite3_randomness(sizeof(ii),&ii);
10934              printf("-- random seed: %d\n", ii);
10935            }
10936            if( nArg==3 ){
10937              db = 0;
10938            }else{
10939              db = p->db;
10940              /* Make sure the schema has been loaded */
10941              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10942            }
10943            rc2 = sqlite3_test_control(testctrl, ii, db);
10944            isOk = 3;
10945          }
10946          break;
10947
10948        /* sqlite3_test_control(int, int) */
10949        case SQLITE_TESTCTRL_ASSERT:
10950        case SQLITE_TESTCTRL_ALWAYS:
10951          if( nArg==3 ){
10952            int opt = booleanValue(azArg[2]);
10953            rc2 = sqlite3_test_control(testctrl, opt);
10954            isOk = 1;
10955          }
10956          break;
10957
10958        /* sqlite3_test_control(int, int) */
10959        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10960        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10961          if( nArg==3 ){
10962            int opt = booleanValue(azArg[2]);
10963            rc2 = sqlite3_test_control(testctrl, opt);
10964            isOk = 3;
10965          }
10966          break;
10967
10968        /* sqlite3_test_control(sqlite3*) */
10969        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10970          rc2 = sqlite3_test_control(testctrl, p->db);
10971          isOk = 3;
10972          break;
10973
10974        case SQLITE_TESTCTRL_IMPOSTER:
10975          if( nArg==5 ){
10976            rc2 = sqlite3_test_control(testctrl, p->db,
10977                          azArg[2],
10978                          integerValue(azArg[3]),
10979                          integerValue(azArg[4]));
10980            isOk = 3;
10981          }
10982          break;
10983
10984        case SQLITE_TESTCTRL_SEEK_COUNT: {
10985          u64 x = 0;
10986          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10987          utf8_printf(p->out, "%llu\n", x);
10988          isOk = 3;
10989          break;
10990        }
10991
10992#ifdef YYCOVERAGE
10993        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10994          if( nArg==2 ){
10995            sqlite3_test_control(testctrl, p->out);
10996            isOk = 3;
10997          }
10998          break;
10999        }
11000#endif
11001#ifdef SQLITE_DEBUG
11002        case SQLITE_TESTCTRL_TUNE: {
11003          if( nArg==4 ){
11004            int id = (int)integerValue(azArg[2]);
11005            int val = (int)integerValue(azArg[3]);
11006            sqlite3_test_control(testctrl, id, &val);
11007            isOk = 3;
11008          }else if( nArg==3 ){
11009            int id = (int)integerValue(azArg[2]);
11010            sqlite3_test_control(testctrl, -id, &rc2);
11011            isOk = 1;
11012          }else if( nArg==2 ){
11013            int id = 1;
11014            while(1){
11015              int val = 0;
11016              rc2 = sqlite3_test_control(testctrl, -id, &val);
11017              if( rc2!=SQLITE_OK ) break;
11018              if( id>1 ) utf8_printf(p->out, "  ");
11019              utf8_printf(p->out, "%d: %d", id, val);
11020              id++;
11021            }
11022            if( id>1 ) utf8_printf(p->out, "\n");
11023            isOk = 3;
11024          }
11025          break;
11026        }
11027#endif
11028        case SQLITE_TESTCTRL_SORTER_MMAP:
11029          if( nArg==3 ){
11030            int opt = (unsigned int)integerValue(azArg[2]);
11031            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11032            isOk = 3;
11033          }
11034          break;
11035      }
11036    }
11037    if( isOk==0 && iCtrl>=0 ){
11038      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11039      rc = 1;
11040    }else if( isOk==1 ){
11041      raw_printf(p->out, "%d\n", rc2);
11042    }else if( isOk==2 ){
11043      raw_printf(p->out, "0x%08x\n", rc2);
11044    }
11045  }else
11046#endif /* !defined(SQLITE_UNTESTABLE) */
11047
11048  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11049    open_db(p, 0);
11050    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11051  }else
11052
11053  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11054    if( nArg==2 ){
11055      enableTimer = booleanValue(azArg[1]);
11056      if( enableTimer && !HAS_TIMER ){
11057        raw_printf(stderr, "Error: timer not available on this system.\n");
11058        enableTimer = 0;
11059      }
11060    }else{
11061      raw_printf(stderr, "Usage: .timer on|off\n");
11062      rc = 1;
11063    }
11064  }else
11065
11066#ifndef SQLITE_OMIT_TRACE
11067  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11068    int mType = 0;
11069    int jj;
11070    open_db(p, 0);
11071    for(jj=1; jj<nArg; jj++){
11072      const char *z = azArg[jj];
11073      if( z[0]=='-' ){
11074        if( optionMatch(z, "expanded") ){
11075          p->eTraceType = SHELL_TRACE_EXPANDED;
11076        }
11077#ifdef SQLITE_ENABLE_NORMALIZE
11078        else if( optionMatch(z, "normalized") ){
11079          p->eTraceType = SHELL_TRACE_NORMALIZED;
11080        }
11081#endif
11082        else if( optionMatch(z, "plain") ){
11083          p->eTraceType = SHELL_TRACE_PLAIN;
11084        }
11085        else if( optionMatch(z, "profile") ){
11086          mType |= SQLITE_TRACE_PROFILE;
11087        }
11088        else if( optionMatch(z, "row") ){
11089          mType |= SQLITE_TRACE_ROW;
11090        }
11091        else if( optionMatch(z, "stmt") ){
11092          mType |= SQLITE_TRACE_STMT;
11093        }
11094        else if( optionMatch(z, "close") ){
11095          mType |= SQLITE_TRACE_CLOSE;
11096        }
11097        else {
11098          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11099          rc = 1;
11100          goto meta_command_exit;
11101        }
11102      }else{
11103        output_file_close(p->traceOut);
11104        p->traceOut = output_file_open(azArg[1], 0);
11105      }
11106    }
11107    if( p->traceOut==0 ){
11108      sqlite3_trace_v2(p->db, 0, 0, 0);
11109    }else{
11110      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11111      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11112    }
11113  }else
11114#endif /* !defined(SQLITE_OMIT_TRACE) */
11115
11116#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11117  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11118    int ii;
11119    int lenOpt;
11120    char *zOpt;
11121    if( nArg<2 ){
11122      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11123      rc = 1;
11124      goto meta_command_exit;
11125    }
11126    open_db(p, 0);
11127    zOpt = azArg[1];
11128    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11129    lenOpt = (int)strlen(zOpt);
11130    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11131      assert( azArg[nArg]==0 );
11132      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11133    }else{
11134      for(ii=1; ii<nArg; ii++){
11135        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11136      }
11137    }
11138  }else
11139#endif
11140
11141#if SQLITE_USER_AUTHENTICATION
11142  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11143    if( nArg<2 ){
11144      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11145      rc = 1;
11146      goto meta_command_exit;
11147    }
11148    open_db(p, 0);
11149    if( strcmp(azArg[1],"login")==0 ){
11150      if( nArg!=4 ){
11151        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11152        rc = 1;
11153        goto meta_command_exit;
11154      }
11155      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11156                                     strlen30(azArg[3]));
11157      if( rc ){
11158        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11159        rc = 1;
11160      }
11161    }else if( strcmp(azArg[1],"add")==0 ){
11162      if( nArg!=5 ){
11163        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11164        rc = 1;
11165        goto meta_command_exit;
11166      }
11167      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11168                            booleanValue(azArg[4]));
11169      if( rc ){
11170        raw_printf(stderr, "User-Add failed: %d\n", rc);
11171        rc = 1;
11172      }
11173    }else if( strcmp(azArg[1],"edit")==0 ){
11174      if( nArg!=5 ){
11175        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11176        rc = 1;
11177        goto meta_command_exit;
11178      }
11179      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11180                              booleanValue(azArg[4]));
11181      if( rc ){
11182        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11183        rc = 1;
11184      }
11185    }else if( strcmp(azArg[1],"delete")==0 ){
11186      if( nArg!=3 ){
11187        raw_printf(stderr, "Usage: .user delete USER\n");
11188        rc = 1;
11189        goto meta_command_exit;
11190      }
11191      rc = sqlite3_user_delete(p->db, azArg[2]);
11192      if( rc ){
11193        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11194        rc = 1;
11195      }
11196    }else{
11197      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11198      rc = 1;
11199      goto meta_command_exit;
11200    }
11201  }else
11202#endif /* SQLITE_USER_AUTHENTICATION */
11203
11204  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11205    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11206        sqlite3_libversion(), sqlite3_sourceid());
11207#if SQLITE_HAVE_ZLIB
11208    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11209#endif
11210#define CTIMEOPT_VAL_(opt) #opt
11211#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11212#if defined(__clang__) && defined(__clang_major__)
11213    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11214                    CTIMEOPT_VAL(__clang_minor__) "."
11215                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11216#elif defined(_MSC_VER)
11217    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11218#elif defined(__GNUC__) && defined(__VERSION__)
11219    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11220#endif
11221  }else
11222
11223  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11224    const char *zDbName = nArg==2 ? azArg[1] : "main";
11225    sqlite3_vfs *pVfs = 0;
11226    if( p->db ){
11227      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11228      if( pVfs ){
11229        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11230        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11231        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11232        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11233      }
11234    }
11235  }else
11236
11237  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11238    sqlite3_vfs *pVfs;
11239    sqlite3_vfs *pCurrent = 0;
11240    if( p->db ){
11241      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11242    }
11243    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11244      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11245           pVfs==pCurrent ? "  <--- CURRENT" : "");
11246      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11247      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11248      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11249      if( pVfs->pNext ){
11250        raw_printf(p->out, "-----------------------------------\n");
11251      }
11252    }
11253  }else
11254
11255  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11256    const char *zDbName = nArg==2 ? azArg[1] : "main";
11257    char *zVfsName = 0;
11258    if( p->db ){
11259      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11260      if( zVfsName ){
11261        utf8_printf(p->out, "%s\n", zVfsName);
11262        sqlite3_free(zVfsName);
11263      }
11264    }
11265  }else
11266
11267  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11268    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11269    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11270  }else
11271
11272  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11273    int j;
11274    assert( nArg<=ArraySize(azArg) );
11275    p->nWidth = nArg-1;
11276    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11277    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11278    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11279    for(j=1; j<nArg; j++){
11280      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11281    }
11282  }else
11283
11284  {
11285    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11286      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11287    rc = 1;
11288  }
11289
11290meta_command_exit:
11291  if( p->outCount ){
11292    p->outCount--;
11293    if( p->outCount==0 ) output_reset(p);
11294  }
11295  p->bSafeMode = p->bSafeModePersist;
11296  return rc;
11297}
11298
11299/* Line scan result and intermediate states (supporting scan resumption)
11300*/
11301#ifndef CHAR_BIT
11302# define CHAR_BIT 8
11303#endif
11304typedef enum {
11305  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11306  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11307  QSS_Start = 0
11308} QuickScanState;
11309#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11310#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11311#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11312#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11313#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11314
11315/*
11316** Scan line for classification to guide shell's handling.
11317** The scan is resumable for subsequent lines when prior
11318** return values are passed as the 2nd argument.
11319*/
11320static QuickScanState quickscan(char *zLine, QuickScanState qss){
11321  char cin;
11322  char cWait = (char)qss; /* intentional narrowing loss */
11323  if( cWait==0 ){
11324  PlainScan:
11325    assert( cWait==0 );
11326    while( (cin = *zLine++)!=0 ){
11327      if( IsSpace(cin) )
11328        continue;
11329      switch (cin){
11330      case '-':
11331        if( *zLine!='-' )
11332          break;
11333        while((cin = *++zLine)!=0 )
11334          if( cin=='\n')
11335            goto PlainScan;
11336        return qss;
11337      case ';':
11338        qss |= QSS_EndingSemi;
11339        continue;
11340      case '/':
11341        if( *zLine=='*' ){
11342          ++zLine;
11343          cWait = '*';
11344          qss = QSS_SETV(qss, cWait);
11345          goto TermScan;
11346        }
11347        break;
11348      case '[':
11349        cin = ']';
11350        /* fall thru */
11351      case '`': case '\'': case '"':
11352        cWait = cin;
11353        qss = QSS_HasDark | cWait;
11354        goto TermScan;
11355      default:
11356        break;
11357      }
11358      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11359    }
11360  }else{
11361  TermScan:
11362    while( (cin = *zLine++)!=0 ){
11363      if( cin==cWait ){
11364        switch( cWait ){
11365        case '*':
11366          if( *zLine != '/' )
11367            continue;
11368          ++zLine;
11369          cWait = 0;
11370          qss = QSS_SETV(qss, 0);
11371          goto PlainScan;
11372        case '`': case '\'': case '"':
11373          if(*zLine==cWait){
11374            ++zLine;
11375            continue;
11376          }
11377          /* fall thru */
11378        case ']':
11379          cWait = 0;
11380          qss = QSS_SETV(qss, 0);
11381          goto PlainScan;
11382        default: assert(0);
11383        }
11384      }
11385    }
11386  }
11387  return qss;
11388}
11389
11390/*
11391** Return TRUE if the line typed in is an SQL command terminator other
11392** than a semi-colon.  The SQL Server style "go" command is understood
11393** as is the Oracle "/".
11394*/
11395static int line_is_command_terminator(char *zLine){
11396  while( IsSpace(zLine[0]) ){ zLine++; };
11397  if( zLine[0]=='/' )
11398    zLine += 1; /* Oracle */
11399  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11400    zLine += 2; /* SQL Server */
11401  else
11402    return 0;
11403  return quickscan(zLine,QSS_Start)==QSS_Start;
11404}
11405
11406/*
11407** We need a default sqlite3_complete() implementation to use in case
11408** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11409** any arbitrary text is a complete SQL statement.  This is not very
11410** user-friendly, but it does seem to work.
11411*/
11412#ifdef SQLITE_OMIT_COMPLETE
11413#define sqlite3_complete(x) 1
11414#endif
11415
11416/*
11417** Return true if zSql is a complete SQL statement.  Return false if it
11418** ends in the middle of a string literal or C-style comment.
11419*/
11420static int line_is_complete(char *zSql, int nSql){
11421  int rc;
11422  if( zSql==0 ) return 1;
11423  zSql[nSql] = ';';
11424  zSql[nSql+1] = 0;
11425  rc = sqlite3_complete(zSql);
11426  zSql[nSql] = 0;
11427  return rc;
11428}
11429
11430/*
11431** Run a single line of SQL.  Return the number of errors.
11432*/
11433static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11434  int rc;
11435  char *zErrMsg = 0;
11436
11437  open_db(p, 0);
11438  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11439  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11440  BEGIN_TIMER;
11441  rc = shell_exec(p, zSql, &zErrMsg);
11442  END_TIMER;
11443  if( rc || zErrMsg ){
11444    char zPrefix[100];
11445    const char *zErrorTail;
11446    const char *zErrorType;
11447    if( zErrMsg==0 ){
11448      zErrorType = "Error";
11449      zErrorTail = sqlite3_errmsg(p->db);
11450    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11451      zErrorType = "Parse error";
11452      zErrorTail = &zErrMsg[12];
11453    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11454      zErrorType = "Runtime error";
11455      zErrorTail = &zErrMsg[10];
11456    }else{
11457      zErrorType = "Error";
11458      zErrorTail = zErrMsg;
11459    }
11460    if( in!=0 || !stdin_is_interactive ){
11461      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11462                       "%s near line %d:", zErrorType, startline);
11463    }else{
11464      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11465    }
11466    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11467    sqlite3_free(zErrMsg);
11468    zErrMsg = 0;
11469    return 1;
11470  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11471    char zLineBuf[2000];
11472    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11473            "changes: %lld   total_changes: %lld",
11474            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11475    raw_printf(p->out, "%s\n", zLineBuf);
11476  }
11477  return 0;
11478}
11479
11480
11481/*
11482** Read input from *in and process it.  If *in==0 then input
11483** is interactive - the user is typing it it.  Otherwise, input
11484** is coming from a file or device.  A prompt is issued and history
11485** is saved only if input is interactive.  An interrupt signal will
11486** cause this routine to exit immediately, unless input is interactive.
11487**
11488** Return the number of errors.
11489*/
11490static int process_input(ShellState *p){
11491  char *zLine = 0;          /* A single input line */
11492  char *zSql = 0;           /* Accumulated SQL text */
11493  int nLine;                /* Length of current line */
11494  int nSql = 0;             /* Bytes of zSql[] used */
11495  int nAlloc = 0;           /* Allocated zSql[] space */
11496  int rc;                   /* Error code */
11497  int errCnt = 0;           /* Number of errors seen */
11498  int startline = 0;        /* Line number for start of current input */
11499  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11500
11501  if( p->inputNesting==MAX_INPUT_NESTING ){
11502    /* This will be more informative in a later version. */
11503    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11504                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11505    return 1;
11506  }
11507  ++p->inputNesting;
11508  p->lineno = 0;
11509  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11510    fflush(p->out);
11511    zLine = one_input_line(p->in, zLine, nSql>0);
11512    if( zLine==0 ){
11513      /* End of input */
11514      if( p->in==0 && stdin_is_interactive ) printf("\n");
11515      break;
11516    }
11517    if( seenInterrupt ){
11518      if( p->in!=0 ) break;
11519      seenInterrupt = 0;
11520    }
11521    p->lineno++;
11522    if( QSS_INPLAIN(qss)
11523        && line_is_command_terminator(zLine)
11524        && line_is_complete(zSql, nSql) ){
11525      memcpy(zLine,";",2);
11526    }
11527    qss = quickscan(zLine, qss);
11528    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11529      if( ShellHasFlag(p, SHFLG_Echo) )
11530        printf("%s\n", zLine);
11531      /* Just swallow single-line whitespace */
11532      qss = QSS_Start;
11533      continue;
11534    }
11535    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11536      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
11537      if( zLine[0]=='.' ){
11538        rc = do_meta_command(zLine, p);
11539        if( rc==2 ){ /* exit requested */
11540          break;
11541        }else if( rc ){
11542          errCnt++;
11543        }
11544      }
11545      qss = QSS_Start;
11546      continue;
11547    }
11548    /* No single-line dispositions remain; accumulate line(s). */
11549    nLine = strlen30(zLine);
11550    if( nSql+nLine+2>=nAlloc ){
11551      /* Grow buffer by half-again increments when big. */
11552      nAlloc = nSql+(nSql>>1)+nLine+100;
11553      zSql = realloc(zSql, nAlloc);
11554      shell_check_oom(zSql);
11555    }
11556    if( nSql==0 ){
11557      int i;
11558      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11559      assert( nAlloc>0 && zSql!=0 );
11560      memcpy(zSql, zLine+i, nLine+1-i);
11561      startline = p->lineno;
11562      nSql = nLine-i;
11563    }else{
11564      zSql[nSql++] = '\n';
11565      memcpy(zSql+nSql, zLine, nLine+1);
11566      nSql += nLine;
11567    }
11568    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11569      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11570      nSql = 0;
11571      if( p->outCount ){
11572        output_reset(p);
11573        p->outCount = 0;
11574      }else{
11575        clearTempFile(p);
11576      }
11577      p->bSafeMode = p->bSafeModePersist;
11578      qss = QSS_Start;
11579    }else if( nSql && QSS_PLAINWHITE(qss) ){
11580      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
11581      nSql = 0;
11582      qss = QSS_Start;
11583    }
11584  }
11585  if( nSql ){
11586    /* This may be incomplete. Let the SQL parser deal with that. */
11587    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11588  }
11589  free(zSql);
11590  free(zLine);
11591  --p->inputNesting;
11592  return errCnt>0;
11593}
11594
11595/*
11596** Return a pathname which is the user's home directory.  A
11597** 0 return indicates an error of some kind.
11598*/
11599static char *find_home_dir(int clearFlag){
11600  static char *home_dir = NULL;
11601  if( clearFlag ){
11602    free(home_dir);
11603    home_dir = 0;
11604    return 0;
11605  }
11606  if( home_dir ) return home_dir;
11607
11608#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11609     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11610  {
11611    struct passwd *pwent;
11612    uid_t uid = getuid();
11613    if( (pwent=getpwuid(uid)) != NULL) {
11614      home_dir = pwent->pw_dir;
11615    }
11616  }
11617#endif
11618
11619#if defined(_WIN32_WCE)
11620  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11621   */
11622  home_dir = "/";
11623#else
11624
11625#if defined(_WIN32) || defined(WIN32)
11626  if (!home_dir) {
11627    home_dir = getenv("USERPROFILE");
11628  }
11629#endif
11630
11631  if (!home_dir) {
11632    home_dir = getenv("HOME");
11633  }
11634
11635#if defined(_WIN32) || defined(WIN32)
11636  if (!home_dir) {
11637    char *zDrive, *zPath;
11638    int n;
11639    zDrive = getenv("HOMEDRIVE");
11640    zPath = getenv("HOMEPATH");
11641    if( zDrive && zPath ){
11642      n = strlen30(zDrive) + strlen30(zPath) + 1;
11643      home_dir = malloc( n );
11644      if( home_dir==0 ) return 0;
11645      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11646      return home_dir;
11647    }
11648    home_dir = "c:\\";
11649  }
11650#endif
11651
11652#endif /* !_WIN32_WCE */
11653
11654  if( home_dir ){
11655    int n = strlen30(home_dir) + 1;
11656    char *z = malloc( n );
11657    if( z ) memcpy(z, home_dir, n);
11658    home_dir = z;
11659  }
11660
11661  return home_dir;
11662}
11663
11664/*
11665** Read input from the file given by sqliterc_override.  Or if that
11666** parameter is NULL, take input from ~/.sqliterc
11667**
11668** Returns the number of errors.
11669*/
11670static void process_sqliterc(
11671  ShellState *p,                  /* Configuration data */
11672  const char *sqliterc_override   /* Name of config file. NULL to use default */
11673){
11674  char *home_dir = NULL;
11675  const char *sqliterc = sqliterc_override;
11676  char *zBuf = 0;
11677  FILE *inSaved = p->in;
11678  int savedLineno = p->lineno;
11679
11680  if (sqliterc == NULL) {
11681    home_dir = find_home_dir(0);
11682    if( home_dir==0 ){
11683      raw_printf(stderr, "-- warning: cannot find home directory;"
11684                      " cannot read ~/.sqliterc\n");
11685      return;
11686    }
11687    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11688    shell_check_oom(zBuf);
11689    sqliterc = zBuf;
11690  }
11691  p->in = fopen(sqliterc,"rb");
11692  if( p->in ){
11693    if( stdin_is_interactive ){
11694      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11695    }
11696    if( process_input(p) && bail_on_error ) exit(1);
11697    fclose(p->in);
11698  }else if( sqliterc_override!=0 ){
11699    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11700    if( bail_on_error ) exit(1);
11701  }
11702  p->in = inSaved;
11703  p->lineno = savedLineno;
11704  sqlite3_free(zBuf);
11705}
11706
11707/*
11708** Show available command line options
11709*/
11710static const char zOptions[] =
11711#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11712  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11713#endif
11714  "   -append              append the database to the end of the file\n"
11715  "   -ascii               set output mode to 'ascii'\n"
11716  "   -bail                stop after hitting an error\n"
11717  "   -batch               force batch I/O\n"
11718  "   -box                 set output mode to 'box'\n"
11719  "   -column              set output mode to 'column'\n"
11720  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11721  "   -csv                 set output mode to 'csv'\n"
11722#if !defined(SQLITE_OMIT_DESERIALIZE)
11723  "   -deserialize         open the database using sqlite3_deserialize()\n"
11724#endif
11725  "   -echo                print commands before execution\n"
11726  "   -init FILENAME       read/process named file\n"
11727  "   -[no]header          turn headers on or off\n"
11728#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11729  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11730#endif
11731  "   -help                show this message\n"
11732  "   -html                set output mode to HTML\n"
11733  "   -interactive         force interactive I/O\n"
11734  "   -json                set output mode to 'json'\n"
11735  "   -line                set output mode to 'line'\n"
11736  "   -list                set output mode to 'list'\n"
11737  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11738  "   -markdown            set output mode to 'markdown'\n"
11739#if !defined(SQLITE_OMIT_DESERIALIZE)
11740  "   -maxsize N           maximum size for a --deserialize database\n"
11741#endif
11742  "   -memtrace            trace all memory allocations and deallocations\n"
11743  "   -mmap N              default mmap size set to N\n"
11744#ifdef SQLITE_ENABLE_MULTIPLEX
11745  "   -multiplex           enable the multiplexor VFS\n"
11746#endif
11747  "   -newline SEP         set output row separator. Default: '\\n'\n"
11748  "   -nofollow            refuse to open symbolic links to database files\n"
11749  "   -nonce STRING        set the safe-mode escape nonce\n"
11750  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11751  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11752  "   -quote               set output mode to 'quote'\n"
11753  "   -readonly            open the database read-only\n"
11754  "   -safe                enable safe-mode\n"
11755  "   -separator SEP       set output column separator. Default: '|'\n"
11756#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11757  "   -sorterref SIZE      sorter references threshold size\n"
11758#endif
11759  "   -stats               print memory stats before each finalize\n"
11760  "   -table               set output mode to 'table'\n"
11761  "   -tabs                set output mode to 'tabs'\n"
11762  "   -version             show SQLite version\n"
11763  "   -vfs NAME            use NAME as the default VFS\n"
11764#ifdef SQLITE_ENABLE_VFSTRACE
11765  "   -vfstrace            enable tracing of all VFS calls\n"
11766#endif
11767#ifdef SQLITE_HAVE_ZLIB
11768  "   -zip                 open the file as a ZIP Archive\n"
11769#endif
11770;
11771static void usage(int showDetail){
11772  utf8_printf(stderr,
11773      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11774      "FILENAME is the name of an SQLite database. A new database is created\n"
11775      "if the file does not previously exist.\n", Argv0);
11776  if( showDetail ){
11777    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11778  }else{
11779    raw_printf(stderr, "Use the -help option for additional information\n");
11780  }
11781  exit(1);
11782}
11783
11784/*
11785** Internal check:  Verify that the SQLite is uninitialized.  Print a
11786** error message if it is initialized.
11787*/
11788static void verify_uninitialized(void){
11789  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11790    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11791                        " initialization.\n");
11792  }
11793}
11794
11795/*
11796** Initialize the state information in data
11797*/
11798static void main_init(ShellState *data) {
11799  memset(data, 0, sizeof(*data));
11800  data->normalMode = data->cMode = data->mode = MODE_List;
11801  data->autoExplain = 1;
11802  data->pAuxDb = &data->aAuxDb[0];
11803  memcpy(data->colSeparator,SEP_Column, 2);
11804  memcpy(data->rowSeparator,SEP_Row, 2);
11805  data->showHeader = 0;
11806  data->shellFlgs = SHFLG_Lookaside;
11807  verify_uninitialized();
11808  sqlite3_config(SQLITE_CONFIG_URI, 1);
11809  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11810  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11811  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11812  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11813}
11814
11815/*
11816** Output text to the console in a font that attracts extra attention.
11817*/
11818#ifdef _WIN32
11819static void printBold(const char *zText){
11820#if !SQLITE_OS_WINRT
11821  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11822  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11823  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11824  SetConsoleTextAttribute(out,
11825         FOREGROUND_RED|FOREGROUND_INTENSITY
11826  );
11827#endif
11828  printf("%s", zText);
11829#if !SQLITE_OS_WINRT
11830  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11831#endif
11832}
11833#else
11834static void printBold(const char *zText){
11835  printf("\033[1m%s\033[0m", zText);
11836}
11837#endif
11838
11839/*
11840** Get the argument to an --option.  Throw an error and die if no argument
11841** is available.
11842*/
11843static char *cmdline_option_value(int argc, char **argv, int i){
11844  if( i==argc ){
11845    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11846            argv[0], argv[argc-1]);
11847    exit(1);
11848  }
11849  return argv[i];
11850}
11851
11852#ifndef SQLITE_SHELL_IS_UTF8
11853#  if (defined(_WIN32) || defined(WIN32)) \
11854   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11855#    define SQLITE_SHELL_IS_UTF8          (0)
11856#  else
11857#    define SQLITE_SHELL_IS_UTF8          (1)
11858#  endif
11859#endif
11860
11861#if SQLITE_SHELL_IS_UTF8
11862int SQLITE_CDECL main(int argc, char **argv){
11863#else
11864int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11865  char **argv;
11866#endif
11867  char *zErrMsg = 0;
11868  ShellState data;
11869  const char *zInitFile = 0;
11870  int i;
11871  int rc = 0;
11872  int warnInmemoryDb = 0;
11873  int readStdin = 1;
11874  int nCmd = 0;
11875  char **azCmd = 0;
11876  const char *zVfs = 0;           /* Value of -vfs command-line option */
11877#if !SQLITE_SHELL_IS_UTF8
11878  char **argvToFree = 0;
11879  int argcToFree = 0;
11880#endif
11881
11882  setBinaryMode(stdin, 0);
11883  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11884  stdin_is_interactive = isatty(0);
11885  stdout_is_console = isatty(1);
11886
11887#if !defined(_WIN32_WCE)
11888  if( getenv("SQLITE_DEBUG_BREAK") ){
11889    if( isatty(0) && isatty(2) ){
11890      fprintf(stderr,
11891          "attach debugger to process %d and press any key to continue.\n",
11892          GETPID());
11893      fgetc(stdin);
11894    }else{
11895#if defined(_WIN32) || defined(WIN32)
11896#if SQLITE_OS_WINRT
11897      __debugbreak();
11898#else
11899      DebugBreak();
11900#endif
11901#elif defined(SIGTRAP)
11902      raise(SIGTRAP);
11903#endif
11904    }
11905  }
11906#endif
11907
11908#if USE_SYSTEM_SQLITE+0!=1
11909  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11910    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11911            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11912    exit(1);
11913  }
11914#endif
11915  main_init(&data);
11916
11917  /* On Windows, we must translate command-line arguments into UTF-8.
11918  ** The SQLite memory allocator subsystem has to be enabled in order to
11919  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11920  ** subsequent sqlite3_config() calls will work.  So copy all results into
11921  ** memory that does not come from the SQLite memory allocator.
11922  */
11923#if !SQLITE_SHELL_IS_UTF8
11924  sqlite3_initialize();
11925  argvToFree = malloc(sizeof(argv[0])*argc*2);
11926  shell_check_oom(argvToFree);
11927  argcToFree = argc;
11928  argv = argvToFree + argc;
11929  for(i=0; i<argc; i++){
11930    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11931    int n;
11932    shell_check_oom(z);
11933    n = (int)strlen(z);
11934    argv[i] = malloc( n+1 );
11935    shell_check_oom(argv[i]);
11936    memcpy(argv[i], z, n+1);
11937    argvToFree[i] = argv[i];
11938    sqlite3_free(z);
11939  }
11940  sqlite3_shutdown();
11941#endif
11942
11943  assert( argc>=1 && argv && argv[0] );
11944  Argv0 = argv[0];
11945
11946  /* Make sure we have a valid signal handler early, before anything
11947  ** else is done.
11948  */
11949#ifdef SIGINT
11950  signal(SIGINT, interrupt_handler);
11951#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11952  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11953#endif
11954
11955#ifdef SQLITE_SHELL_DBNAME_PROC
11956  {
11957    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11958    ** of a C-function that will provide the name of the database file.  Use
11959    ** this compile-time option to embed this shell program in larger
11960    ** applications. */
11961    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11962    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11963    warnInmemoryDb = 0;
11964  }
11965#endif
11966
11967  /* Do an initial pass through the command-line argument to locate
11968  ** the name of the database file, the name of the initialization file,
11969  ** the size of the alternative malloc heap,
11970  ** and the first command to execute.
11971  */
11972  verify_uninitialized();
11973  for(i=1; i<argc; i++){
11974    char *z;
11975    z = argv[i];
11976    if( z[0]!='-' ){
11977      if( data.aAuxDb->zDbFilename==0 ){
11978        data.aAuxDb->zDbFilename = z;
11979      }else{
11980        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11981        ** mean that nothing is read from stdin */
11982        readStdin = 0;
11983        nCmd++;
11984        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11985        shell_check_oom(azCmd);
11986        azCmd[nCmd-1] = z;
11987      }
11988    }
11989    if( z[1]=='-' ) z++;
11990    if( strcmp(z,"-separator")==0
11991     || strcmp(z,"-nullvalue")==0
11992     || strcmp(z,"-newline")==0
11993     || strcmp(z,"-cmd")==0
11994    ){
11995      (void)cmdline_option_value(argc, argv, ++i);
11996    }else if( strcmp(z,"-init")==0 ){
11997      zInitFile = cmdline_option_value(argc, argv, ++i);
11998    }else if( strcmp(z,"-batch")==0 ){
11999      /* Need to check for batch mode here to so we can avoid printing
12000      ** informational messages (like from process_sqliterc) before
12001      ** we do the actual processing of arguments later in a second pass.
12002      */
12003      stdin_is_interactive = 0;
12004    }else if( strcmp(z,"-heap")==0 ){
12005#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12006      const char *zSize;
12007      sqlite3_int64 szHeap;
12008
12009      zSize = cmdline_option_value(argc, argv, ++i);
12010      szHeap = integerValue(zSize);
12011      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12012      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12013#else
12014      (void)cmdline_option_value(argc, argv, ++i);
12015#endif
12016    }else if( strcmp(z,"-pagecache")==0 ){
12017      sqlite3_int64 n, sz;
12018      sz = integerValue(cmdline_option_value(argc,argv,++i));
12019      if( sz>70000 ) sz = 70000;
12020      if( sz<0 ) sz = 0;
12021      n = integerValue(cmdline_option_value(argc,argv,++i));
12022      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12023        n = 0xffffffffffffLL/sz;
12024      }
12025      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12026                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12027      data.shellFlgs |= SHFLG_Pagecache;
12028    }else if( strcmp(z,"-lookaside")==0 ){
12029      int n, sz;
12030      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12031      if( sz<0 ) sz = 0;
12032      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12033      if( n<0 ) n = 0;
12034      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12035      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12036    }else if( strcmp(z,"-threadsafe")==0 ){
12037      int n;
12038      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12039      switch( n ){
12040         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12041         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12042         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12043      }
12044#ifdef SQLITE_ENABLE_VFSTRACE
12045    }else if( strcmp(z,"-vfstrace")==0 ){
12046      extern int vfstrace_register(
12047         const char *zTraceName,
12048         const char *zOldVfsName,
12049         int (*xOut)(const char*,void*),
12050         void *pOutArg,
12051         int makeDefault
12052      );
12053      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12054#endif
12055#ifdef SQLITE_ENABLE_MULTIPLEX
12056    }else if( strcmp(z,"-multiplex")==0 ){
12057      extern int sqlite3_multiple_initialize(const char*,int);
12058      sqlite3_multiplex_initialize(0, 1);
12059#endif
12060    }else if( strcmp(z,"-mmap")==0 ){
12061      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12062      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12063#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12064    }else if( strcmp(z,"-sorterref")==0 ){
12065      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12066      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12067#endif
12068    }else if( strcmp(z,"-vfs")==0 ){
12069      zVfs = cmdline_option_value(argc, argv, ++i);
12070#ifdef SQLITE_HAVE_ZLIB
12071    }else if( strcmp(z,"-zip")==0 ){
12072      data.openMode = SHELL_OPEN_ZIPFILE;
12073#endif
12074    }else if( strcmp(z,"-append")==0 ){
12075      data.openMode = SHELL_OPEN_APPENDVFS;
12076#ifndef SQLITE_OMIT_DESERIALIZE
12077    }else if( strcmp(z,"-deserialize")==0 ){
12078      data.openMode = SHELL_OPEN_DESERIALIZE;
12079    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12080      data.szMax = integerValue(argv[++i]);
12081#endif
12082    }else if( strcmp(z,"-readonly")==0 ){
12083      data.openMode = SHELL_OPEN_READONLY;
12084    }else if( strcmp(z,"-nofollow")==0 ){
12085      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12086#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12087    }else if( strncmp(z, "-A",2)==0 ){
12088      /* All remaining command-line arguments are passed to the ".archive"
12089      ** command, so ignore them */
12090      break;
12091#endif
12092    }else if( strcmp(z, "-memtrace")==0 ){
12093      sqlite3MemTraceActivate(stderr);
12094    }else if( strcmp(z,"-bail")==0 ){
12095      bail_on_error = 1;
12096    }else if( strcmp(z,"-nonce")==0 ){
12097      free(data.zNonce);
12098      data.zNonce = strdup(argv[++i]);
12099    }else if( strcmp(z,"-safe")==0 ){
12100      /* no-op - catch this on the second pass */
12101    }
12102  }
12103  verify_uninitialized();
12104
12105
12106#ifdef SQLITE_SHELL_INIT_PROC
12107  {
12108    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12109    ** of a C-function that will perform initialization actions on SQLite that
12110    ** occur just before or after sqlite3_initialize(). Use this compile-time
12111    ** option to embed this shell program in larger applications. */
12112    extern void SQLITE_SHELL_INIT_PROC(void);
12113    SQLITE_SHELL_INIT_PROC();
12114  }
12115#else
12116  /* All the sqlite3_config() calls have now been made. So it is safe
12117  ** to call sqlite3_initialize() and process any command line -vfs option. */
12118  sqlite3_initialize();
12119#endif
12120
12121  if( zVfs ){
12122    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12123    if( pVfs ){
12124      sqlite3_vfs_register(pVfs, 1);
12125    }else{
12126      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12127      exit(1);
12128    }
12129  }
12130
12131  if( data.pAuxDb->zDbFilename==0 ){
12132#ifndef SQLITE_OMIT_MEMORYDB
12133    data.pAuxDb->zDbFilename = ":memory:";
12134    warnInmemoryDb = argc==1;
12135#else
12136    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12137    return 1;
12138#endif
12139  }
12140  data.out = stdout;
12141  sqlite3_appendvfs_init(0,0,0);
12142
12143  /* Go ahead and open the database file if it already exists.  If the
12144  ** file does not exist, delay opening it.  This prevents empty database
12145  ** files from being created if a user mistypes the database name argument
12146  ** to the sqlite command-line tool.
12147  */
12148  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12149    open_db(&data, 0);
12150  }
12151
12152  /* Process the initialization file if there is one.  If no -init option
12153  ** is given on the command line, look for a file named ~/.sqliterc and
12154  ** try to process it.
12155  */
12156  process_sqliterc(&data,zInitFile);
12157
12158  /* Make a second pass through the command-line argument and set
12159  ** options.  This second pass is delayed until after the initialization
12160  ** file is processed so that the command-line arguments will override
12161  ** settings in the initialization file.
12162  */
12163  for(i=1; i<argc; i++){
12164    char *z = argv[i];
12165    if( z[0]!='-' ) continue;
12166    if( z[1]=='-' ){ z++; }
12167    if( strcmp(z,"-init")==0 ){
12168      i++;
12169    }else if( strcmp(z,"-html")==0 ){
12170      data.mode = MODE_Html;
12171    }else if( strcmp(z,"-list")==0 ){
12172      data.mode = MODE_List;
12173    }else if( strcmp(z,"-quote")==0 ){
12174      data.mode = MODE_Quote;
12175      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12176      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12177    }else if( strcmp(z,"-line")==0 ){
12178      data.mode = MODE_Line;
12179    }else if( strcmp(z,"-column")==0 ){
12180      data.mode = MODE_Column;
12181    }else if( strcmp(z,"-json")==0 ){
12182      data.mode = MODE_Json;
12183    }else if( strcmp(z,"-markdown")==0 ){
12184      data.mode = MODE_Markdown;
12185    }else if( strcmp(z,"-table")==0 ){
12186      data.mode = MODE_Table;
12187    }else if( strcmp(z,"-box")==0 ){
12188      data.mode = MODE_Box;
12189    }else if( strcmp(z,"-csv")==0 ){
12190      data.mode = MODE_Csv;
12191      memcpy(data.colSeparator,",",2);
12192#ifdef SQLITE_HAVE_ZLIB
12193    }else if( strcmp(z,"-zip")==0 ){
12194      data.openMode = SHELL_OPEN_ZIPFILE;
12195#endif
12196    }else if( strcmp(z,"-append")==0 ){
12197      data.openMode = SHELL_OPEN_APPENDVFS;
12198#ifndef SQLITE_OMIT_DESERIALIZE
12199    }else if( strcmp(z,"-deserialize")==0 ){
12200      data.openMode = SHELL_OPEN_DESERIALIZE;
12201    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12202      data.szMax = integerValue(argv[++i]);
12203#endif
12204    }else if( strcmp(z,"-readonly")==0 ){
12205      data.openMode = SHELL_OPEN_READONLY;
12206    }else if( strcmp(z,"-nofollow")==0 ){
12207      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12208    }else if( strcmp(z,"-ascii")==0 ){
12209      data.mode = MODE_Ascii;
12210      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12211      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12212    }else if( strcmp(z,"-tabs")==0 ){
12213      data.mode = MODE_List;
12214      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12215      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12216    }else if( strcmp(z,"-separator")==0 ){
12217      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12218                       "%s",cmdline_option_value(argc,argv,++i));
12219    }else if( strcmp(z,"-newline")==0 ){
12220      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12221                       "%s",cmdline_option_value(argc,argv,++i));
12222    }else if( strcmp(z,"-nullvalue")==0 ){
12223      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12224                       "%s",cmdline_option_value(argc,argv,++i));
12225    }else if( strcmp(z,"-header")==0 ){
12226      data.showHeader = 1;
12227      ShellSetFlag(&data, SHFLG_HeaderSet);
12228     }else if( strcmp(z,"-noheader")==0 ){
12229      data.showHeader = 0;
12230      ShellSetFlag(&data, SHFLG_HeaderSet);
12231    }else if( strcmp(z,"-echo")==0 ){
12232      ShellSetFlag(&data, SHFLG_Echo);
12233    }else if( strcmp(z,"-eqp")==0 ){
12234      data.autoEQP = AUTOEQP_on;
12235    }else if( strcmp(z,"-eqpfull")==0 ){
12236      data.autoEQP = AUTOEQP_full;
12237    }else if( strcmp(z,"-stats")==0 ){
12238      data.statsOn = 1;
12239    }else if( strcmp(z,"-scanstats")==0 ){
12240      data.scanstatsOn = 1;
12241    }else if( strcmp(z,"-backslash")==0 ){
12242      /* Undocumented command-line option: -backslash
12243      ** Causes C-style backslash escapes to be evaluated in SQL statements
12244      ** prior to sending the SQL into SQLite.  Useful for injecting
12245      ** crazy bytes in the middle of SQL statements for testing and debugging.
12246      */
12247      ShellSetFlag(&data, SHFLG_Backslash);
12248    }else if( strcmp(z,"-bail")==0 ){
12249      /* No-op.  The bail_on_error flag should already be set. */
12250    }else if( strcmp(z,"-version")==0 ){
12251      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12252      return 0;
12253    }else if( strcmp(z,"-interactive")==0 ){
12254      stdin_is_interactive = 1;
12255    }else if( strcmp(z,"-batch")==0 ){
12256      stdin_is_interactive = 0;
12257    }else if( strcmp(z,"-heap")==0 ){
12258      i++;
12259    }else if( strcmp(z,"-pagecache")==0 ){
12260      i+=2;
12261    }else if( strcmp(z,"-lookaside")==0 ){
12262      i+=2;
12263    }else if( strcmp(z,"-threadsafe")==0 ){
12264      i+=2;
12265    }else if( strcmp(z,"-nonce")==0 ){
12266      i += 2;
12267    }else if( strcmp(z,"-mmap")==0 ){
12268      i++;
12269    }else if( strcmp(z,"-memtrace")==0 ){
12270      i++;
12271#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12272    }else if( strcmp(z,"-sorterref")==0 ){
12273      i++;
12274#endif
12275    }else if( strcmp(z,"-vfs")==0 ){
12276      i++;
12277#ifdef SQLITE_ENABLE_VFSTRACE
12278    }else if( strcmp(z,"-vfstrace")==0 ){
12279      i++;
12280#endif
12281#ifdef SQLITE_ENABLE_MULTIPLEX
12282    }else if( strcmp(z,"-multiplex")==0 ){
12283      i++;
12284#endif
12285    }else if( strcmp(z,"-help")==0 ){
12286      usage(1);
12287    }else if( strcmp(z,"-cmd")==0 ){
12288      /* Run commands that follow -cmd first and separately from commands
12289      ** that simply appear on the command-line.  This seems goofy.  It would
12290      ** be better if all commands ran in the order that they appear.  But
12291      ** we retain the goofy behavior for historical compatibility. */
12292      if( i==argc-1 ) break;
12293      z = cmdline_option_value(argc,argv,++i);
12294      if( z[0]=='.' ){
12295        rc = do_meta_command(z, &data);
12296        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12297      }else{
12298        open_db(&data, 0);
12299        rc = shell_exec(&data, z, &zErrMsg);
12300        if( zErrMsg!=0 ){
12301          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12302          if( bail_on_error ) return rc!=0 ? rc : 1;
12303        }else if( rc!=0 ){
12304          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12305          if( bail_on_error ) return rc;
12306        }
12307      }
12308#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12309    }else if( strncmp(z, "-A", 2)==0 ){
12310      if( nCmd>0 ){
12311        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12312                            " with \"%s\"\n", z);
12313        return 1;
12314      }
12315      open_db(&data, OPEN_DB_ZIPFILE);
12316      if( z[2] ){
12317        argv[i] = &z[2];
12318        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12319      }else{
12320        arDotCommand(&data, 1, argv+i, argc-i);
12321      }
12322      readStdin = 0;
12323      break;
12324#endif
12325    }else if( strcmp(z,"-safe")==0 ){
12326      data.bSafeMode = data.bSafeModePersist = 1;
12327    }else{
12328      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12329      raw_printf(stderr,"Use -help for a list of options.\n");
12330      return 1;
12331    }
12332    data.cMode = data.mode;
12333  }
12334
12335  if( !readStdin ){
12336    /* Run all arguments that do not begin with '-' as if they were separate
12337    ** command-line inputs, except for the argToSkip argument which contains
12338    ** the database filename.
12339    */
12340    for(i=0; i<nCmd; i++){
12341      if( azCmd[i][0]=='.' ){
12342        rc = do_meta_command(azCmd[i], &data);
12343        if( rc ){
12344          free(azCmd);
12345          return rc==2 ? 0 : rc;
12346        }
12347      }else{
12348        open_db(&data, 0);
12349        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12350        if( zErrMsg || rc ){
12351          if( zErrMsg!=0 ){
12352            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12353          }else{
12354            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12355          }
12356          sqlite3_free(zErrMsg);
12357          free(azCmd);
12358          return rc!=0 ? rc : 1;
12359        }
12360      }
12361    }
12362  }else{
12363    /* Run commands received from standard input
12364    */
12365    if( stdin_is_interactive ){
12366      char *zHome;
12367      char *zHistory;
12368      int nHistory;
12369      printf(
12370        "SQLite version %s %.19s\n" /*extra-version-info*/
12371        "Enter \".help\" for usage hints.\n",
12372        sqlite3_libversion(), sqlite3_sourceid()
12373      );
12374      if( warnInmemoryDb ){
12375        printf("Connected to a ");
12376        printBold("transient in-memory database");
12377        printf(".\nUse \".open FILENAME\" to reopen on a "
12378               "persistent database.\n");
12379      }
12380      zHistory = getenv("SQLITE_HISTORY");
12381      if( zHistory ){
12382        zHistory = strdup(zHistory);
12383      }else if( (zHome = find_home_dir(0))!=0 ){
12384        nHistory = strlen30(zHome) + 20;
12385        if( (zHistory = malloc(nHistory))!=0 ){
12386          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12387        }
12388      }
12389      if( zHistory ){ shell_read_history(zHistory); }
12390#if HAVE_READLINE || HAVE_EDITLINE
12391      rl_attempted_completion_function = readline_completion;
12392#elif HAVE_LINENOISE
12393      linenoiseSetCompletionCallback(linenoise_completion);
12394#endif
12395      data.in = 0;
12396      rc = process_input(&data);
12397      if( zHistory ){
12398        shell_stifle_history(2000);
12399        shell_write_history(zHistory);
12400        free(zHistory);
12401      }
12402    }else{
12403      data.in = stdin;
12404      rc = process_input(&data);
12405    }
12406  }
12407  free(azCmd);
12408  set_table_name(&data, 0);
12409  if( data.db ){
12410    session_close_all(&data, -1);
12411    close_db(data.db);
12412  }
12413  for(i=0; i<ArraySize(data.aAuxDb); i++){
12414    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12415    if( data.aAuxDb[i].db ){
12416      session_close_all(&data, i);
12417      close_db(data.aAuxDb[i].db);
12418    }
12419  }
12420  find_home_dir(1);
12421  output_reset(&data);
12422  data.doXdgOpen = 0;
12423  clearTempFile(&data);
12424#if !SQLITE_SHELL_IS_UTF8
12425  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12426  free(argvToFree);
12427#endif
12428  free(data.colWidth);
12429  free(data.zNonce);
12430  /* Clear the global data structure so that valgrind will detect memory
12431  ** leaks */
12432  memset(&data, 0, sizeof(data));
12433  return rc;
12434}
12435