xref: /sqlite-3.40.0/src/shell.c.in (revision a6ca90c3)
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#ifdef SQLITE_CUSTOM_INCLUDE
27# define INC_STRINGIFY_(f) #f
28# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
29# include INC_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/*
1070** State information about the database connection is contained in an
1071** instance of the following structure.
1072*/
1073typedef struct ShellState ShellState;
1074struct ShellState {
1075  sqlite3 *db;           /* The database */
1076  u8 autoExplain;        /* Automatically turn on .explain mode */
1077  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1078  u8 autoEQPtest;        /* autoEQP is in test mode */
1079  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1080  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1081  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1082  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1083  u8 nEqpLevel;          /* Depth of the EQP output graph */
1084  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1085  u8 bSafeMode;          /* True to prohibit unsafe operations */
1086  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1087  unsigned statsOn;      /* True to display memory stats before each finalize */
1088  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1089  int outCount;          /* Revert to stdout when reaching zero */
1090  int cnt;               /* Number of records displayed so far */
1091  int lineno;            /* Line number of last line read from in */
1092  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1093  FILE *in;              /* Read commands from this stream */
1094  FILE *out;             /* Write results here */
1095  FILE *traceOut;        /* Output for sqlite3_trace() */
1096  int nErr;              /* Number of errors seen */
1097  int mode;              /* An output mode setting */
1098  int modePrior;         /* Saved mode */
1099  int cMode;             /* temporary output mode for the current query */
1100  int normalMode;        /* Output mode before ".explain on" */
1101  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1102  int showHeader;        /* True to show column names in List or Column mode */
1103  int nCheck;            /* Number of ".check" commands run */
1104  unsigned nProgress;    /* Number of progress callbacks encountered */
1105  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1106  unsigned flgProgress;  /* Flags for the progress callback */
1107  unsigned shellFlgs;    /* Various flags */
1108  unsigned priorShFlgs;  /* Saved copy of flags */
1109  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1110  char *zDestTable;      /* Name of destination table when MODE_Insert */
1111  char *zTempFile;       /* Temporary file that might need deleting */
1112  char zTestcase[30];    /* Name of current test case */
1113  char colSeparator[20]; /* Column separator character for several modes */
1114  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1115  char colSepPrior[20];  /* Saved column separator */
1116  char rowSepPrior[20];  /* Saved row separator */
1117  int *colWidth;         /* Requested width of each column in columnar modes */
1118  int *actualWidth;      /* Actual width of each column */
1119  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1120  char nullValue[20];    /* The text to print when a NULL comes back from
1121                         ** the database */
1122  char outfile[FILENAME_MAX]; /* Filename for *out */
1123  sqlite3_stmt *pStmt;   /* Current statement if any. */
1124  FILE *pLog;            /* Write log output here */
1125  struct AuxDb {         /* Storage space for auxiliary database connections */
1126    sqlite3 *db;               /* Connection pointer */
1127    const char *zDbFilename;   /* Filename used to open the connection */
1128    char *zFreeOnClose;        /* Free this memory allocation on close */
1129#if defined(SQLITE_ENABLE_SESSION)
1130    int nSession;              /* Number of active sessions */
1131    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1132#endif
1133  } aAuxDb[5],           /* Array of all database connections */
1134    *pAuxDb;             /* Currently active database connection */
1135  int *aiIndent;         /* Array of indents used in MODE_Explain */
1136  int nIndent;           /* Size of array aiIndent[] */
1137  int iIndent;           /* Index of current op in aiIndent[] */
1138  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1139  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1140  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1141};
1142
1143
1144/* Allowed values for ShellState.autoEQP
1145*/
1146#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1147#define AUTOEQP_on       1           /* Automatic EQP is on */
1148#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1149#define AUTOEQP_full     3           /* Show full EXPLAIN */
1150
1151/* Allowed values for ShellState.openMode
1152*/
1153#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1154#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1155#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1156#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1157#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1158#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1159#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1160
1161/* Allowed values for ShellState.eTraceType
1162*/
1163#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1164#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1165#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1166
1167/* Bits in the ShellState.flgProgress variable */
1168#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1169#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1170                                   ** callback limit is reached, and for each
1171                                   ** top-level SQL statement */
1172#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1173
1174/*
1175** These are the allowed shellFlgs values
1176*/
1177#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1178#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1179#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1180#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1181#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1182#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1183#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1184#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1185#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1186#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1187
1188/*
1189** Macros for testing and setting shellFlgs
1190*/
1191#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1192#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1193#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1194
1195/*
1196** These are the allowed modes.
1197*/
1198#define MODE_Line     0  /* One column per line.  Blank line between records */
1199#define MODE_Column   1  /* One record per line in neat columns */
1200#define MODE_List     2  /* One record per line with a separator */
1201#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1202#define MODE_Html     4  /* Generate an XHTML table */
1203#define MODE_Insert   5  /* Generate SQL "insert" statements */
1204#define MODE_Quote    6  /* Quote values as for SQL */
1205#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1206#define MODE_Csv      8  /* Quote strings, numbers are plain */
1207#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1208#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1209#define MODE_Pretty  11  /* Pretty-print schemas */
1210#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1211#define MODE_Json    13  /* Output JSON */
1212#define MODE_Markdown 14 /* Markdown formatting */
1213#define MODE_Table   15  /* MySQL-style table formatting */
1214#define MODE_Box     16  /* Unicode box-drawing characters */
1215#define MODE_Count   17  /* Output only a count of the rows of output */
1216#define MODE_Off     18  /* No query output shown */
1217
1218static const char *modeDescr[] = {
1219  "line",
1220  "column",
1221  "list",
1222  "semi",
1223  "html",
1224  "insert",
1225  "quote",
1226  "tcl",
1227  "csv",
1228  "explain",
1229  "ascii",
1230  "prettyprint",
1231  "eqp",
1232  "json",
1233  "markdown",
1234  "table",
1235  "box",
1236  "count",
1237  "off"
1238};
1239
1240/*
1241** These are the column/row/line separators used by the various
1242** import/export modes.
1243*/
1244#define SEP_Column    "|"
1245#define SEP_Row       "\n"
1246#define SEP_Tab       "\t"
1247#define SEP_Space     " "
1248#define SEP_Comma     ","
1249#define SEP_CrLf      "\r\n"
1250#define SEP_Unit      "\x1F"
1251#define SEP_Record    "\x1E"
1252
1253/*
1254** A callback for the sqlite3_log() interface.
1255*/
1256static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1257  ShellState *p = (ShellState*)pArg;
1258  if( p->pLog==0 ) return;
1259  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1260  fflush(p->pLog);
1261}
1262
1263/*
1264** SQL function:  shell_putsnl(X)
1265**
1266** Write the text X to the screen (or whatever output is being directed)
1267** adding a newline at the end, and then return X.
1268*/
1269static void shellPutsFunc(
1270  sqlite3_context *pCtx,
1271  int nVal,
1272  sqlite3_value **apVal
1273){
1274  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1275  (void)nVal;
1276  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1277  sqlite3_result_value(pCtx, apVal[0]);
1278}
1279
1280/*
1281** If in safe mode, print an error message described by the arguments
1282** and exit immediately.
1283*/
1284static void failIfSafeMode(
1285  ShellState *p,
1286  const char *zErrMsg,
1287  ...
1288){
1289  if( p->bSafeMode ){
1290    va_list ap;
1291    char *zMsg;
1292    va_start(ap, zErrMsg);
1293    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1294    va_end(ap);
1295    raw_printf(stderr, "line %d: ", p->lineno);
1296    utf8_printf(stderr, "%s\n", zMsg);
1297    exit(1);
1298  }
1299}
1300
1301/*
1302** SQL function:   edit(VALUE)
1303**                 edit(VALUE,EDITOR)
1304**
1305** These steps:
1306**
1307**     (1) Write VALUE into a temporary file.
1308**     (2) Run program EDITOR on that temporary file.
1309**     (3) Read the temporary file back and return its content as the result.
1310**     (4) Delete the temporary file
1311**
1312** If the EDITOR argument is omitted, use the value in the VISUAL
1313** environment variable.  If still there is no EDITOR, through an error.
1314**
1315** Also throw an error if the EDITOR program returns a non-zero exit code.
1316*/
1317#ifndef SQLITE_NOHAVE_SYSTEM
1318static void editFunc(
1319  sqlite3_context *context,
1320  int argc,
1321  sqlite3_value **argv
1322){
1323  const char *zEditor;
1324  char *zTempFile = 0;
1325  sqlite3 *db;
1326  char *zCmd = 0;
1327  int bBin;
1328  int rc;
1329  int hasCRNL = 0;
1330  FILE *f = 0;
1331  sqlite3_int64 sz;
1332  sqlite3_int64 x;
1333  unsigned char *p = 0;
1334
1335  if( argc==2 ){
1336    zEditor = (const char*)sqlite3_value_text(argv[1]);
1337  }else{
1338    zEditor = getenv("VISUAL");
1339  }
1340  if( zEditor==0 ){
1341    sqlite3_result_error(context, "no editor for edit()", -1);
1342    return;
1343  }
1344  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1345    sqlite3_result_error(context, "NULL input to edit()", -1);
1346    return;
1347  }
1348  db = sqlite3_context_db_handle(context);
1349  zTempFile = 0;
1350  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1351  if( zTempFile==0 ){
1352    sqlite3_uint64 r = 0;
1353    sqlite3_randomness(sizeof(r), &r);
1354    zTempFile = sqlite3_mprintf("temp%llx", r);
1355    if( zTempFile==0 ){
1356      sqlite3_result_error_nomem(context);
1357      return;
1358    }
1359  }
1360  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1361  /* When writing the file to be edited, do \n to \r\n conversions on systems
1362  ** that want \r\n line endings */
1363  f = fopen(zTempFile, bBin ? "wb" : "w");
1364  if( f==0 ){
1365    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1366    goto edit_func_end;
1367  }
1368  sz = sqlite3_value_bytes(argv[0]);
1369  if( bBin ){
1370    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1371  }else{
1372    const char *z = (const char*)sqlite3_value_text(argv[0]);
1373    /* Remember whether or not the value originally contained \r\n */
1374    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1375    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1376  }
1377  fclose(f);
1378  f = 0;
1379  if( x!=sz ){
1380    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1381    goto edit_func_end;
1382  }
1383  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1384  if( zCmd==0 ){
1385    sqlite3_result_error_nomem(context);
1386    goto edit_func_end;
1387  }
1388  rc = system(zCmd);
1389  sqlite3_free(zCmd);
1390  if( rc ){
1391    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1392    goto edit_func_end;
1393  }
1394  f = fopen(zTempFile, "rb");
1395  if( f==0 ){
1396    sqlite3_result_error(context,
1397      "edit() cannot reopen temp file after edit", -1);
1398    goto edit_func_end;
1399  }
1400  fseek(f, 0, SEEK_END);
1401  sz = ftell(f);
1402  rewind(f);
1403  p = sqlite3_malloc64( sz+1 );
1404  if( p==0 ){
1405    sqlite3_result_error_nomem(context);
1406    goto edit_func_end;
1407  }
1408  x = fread(p, 1, (size_t)sz, f);
1409  fclose(f);
1410  f = 0;
1411  if( x!=sz ){
1412    sqlite3_result_error(context, "could not read back the whole file", -1);
1413    goto edit_func_end;
1414  }
1415  if( bBin ){
1416    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1417  }else{
1418    sqlite3_int64 i, j;
1419    if( hasCRNL ){
1420      /* If the original contains \r\n then do no conversions back to \n */
1421    }else{
1422      /* If the file did not originally contain \r\n then convert any new
1423      ** \r\n back into \n */
1424      for(i=j=0; i<sz; i++){
1425        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1426        p[j++] = p[i];
1427      }
1428      sz = j;
1429      p[sz] = 0;
1430    }
1431    sqlite3_result_text64(context, (const char*)p, sz,
1432                          sqlite3_free, SQLITE_UTF8);
1433  }
1434  p = 0;
1435
1436edit_func_end:
1437  if( f ) fclose(f);
1438  unlink(zTempFile);
1439  sqlite3_free(zTempFile);
1440  sqlite3_free(p);
1441}
1442#endif /* SQLITE_NOHAVE_SYSTEM */
1443
1444/*
1445** Save or restore the current output mode
1446*/
1447static void outputModePush(ShellState *p){
1448  p->modePrior = p->mode;
1449  p->priorShFlgs = p->shellFlgs;
1450  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1451  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1452}
1453static void outputModePop(ShellState *p){
1454  p->mode = p->modePrior;
1455  p->shellFlgs = p->priorShFlgs;
1456  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1457  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1458}
1459
1460/*
1461** Output the given string as a hex-encoded blob (eg. X'1234' )
1462*/
1463static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1464  int i;
1465  char *zBlob = (char *)pBlob;
1466  raw_printf(out,"X'");
1467  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1468  raw_printf(out,"'");
1469}
1470
1471/*
1472** Find a string that is not found anywhere in z[].  Return a pointer
1473** to that string.
1474**
1475** Try to use zA and zB first.  If both of those are already found in z[]
1476** then make up some string and store it in the buffer zBuf.
1477*/
1478static const char *unused_string(
1479  const char *z,                    /* Result must not appear anywhere in z */
1480  const char *zA, const char *zB,   /* Try these first */
1481  char *zBuf                        /* Space to store a generated string */
1482){
1483  unsigned i = 0;
1484  if( strstr(z, zA)==0 ) return zA;
1485  if( strstr(z, zB)==0 ) return zB;
1486  do{
1487    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1488  }while( strstr(z,zBuf)!=0 );
1489  return zBuf;
1490}
1491
1492/*
1493** Output the given string as a quoted string using SQL quoting conventions.
1494**
1495** See also: output_quoted_escaped_string()
1496*/
1497static void output_quoted_string(FILE *out, const char *z){
1498  int i;
1499  char c;
1500  setBinaryMode(out, 1);
1501  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1502  if( c==0 ){
1503    utf8_printf(out,"'%s'",z);
1504  }else{
1505    raw_printf(out, "'");
1506    while( *z ){
1507      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1508      if( c=='\'' ) i++;
1509      if( i ){
1510        utf8_printf(out, "%.*s", i, z);
1511        z += i;
1512      }
1513      if( c=='\'' ){
1514        raw_printf(out, "'");
1515        continue;
1516      }
1517      if( c==0 ){
1518        break;
1519      }
1520      z++;
1521    }
1522    raw_printf(out, "'");
1523  }
1524  setTextMode(out, 1);
1525}
1526
1527/*
1528** Output the given string as a quoted string using SQL quoting conventions.
1529** Additionallly , escape the "\n" and "\r" characters so that they do not
1530** get corrupted by end-of-line translation facilities in some operating
1531** systems.
1532**
1533** This is like output_quoted_string() but with the addition of the \r\n
1534** escape mechanism.
1535*/
1536static void output_quoted_escaped_string(FILE *out, const char *z){
1537  int i;
1538  char c;
1539  setBinaryMode(out, 1);
1540  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1541  if( c==0 ){
1542    utf8_printf(out,"'%s'",z);
1543  }else{
1544    const char *zNL = 0;
1545    const char *zCR = 0;
1546    int nNL = 0;
1547    int nCR = 0;
1548    char zBuf1[20], zBuf2[20];
1549    for(i=0; z[i]; i++){
1550      if( z[i]=='\n' ) nNL++;
1551      if( z[i]=='\r' ) nCR++;
1552    }
1553    if( nNL ){
1554      raw_printf(out, "replace(");
1555      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1556    }
1557    if( nCR ){
1558      raw_printf(out, "replace(");
1559      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1560    }
1561    raw_printf(out, "'");
1562    while( *z ){
1563      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1564      if( c=='\'' ) i++;
1565      if( i ){
1566        utf8_printf(out, "%.*s", i, z);
1567        z += i;
1568      }
1569      if( c=='\'' ){
1570        raw_printf(out, "'");
1571        continue;
1572      }
1573      if( c==0 ){
1574        break;
1575      }
1576      z++;
1577      if( c=='\n' ){
1578        raw_printf(out, "%s", zNL);
1579        continue;
1580      }
1581      raw_printf(out, "%s", zCR);
1582    }
1583    raw_printf(out, "'");
1584    if( nCR ){
1585      raw_printf(out, ",'%s',char(13))", zCR);
1586    }
1587    if( nNL ){
1588      raw_printf(out, ",'%s',char(10))", zNL);
1589    }
1590  }
1591  setTextMode(out, 1);
1592}
1593
1594/*
1595** Output the given string as a quoted according to C or TCL quoting rules.
1596*/
1597static void output_c_string(FILE *out, const char *z){
1598  unsigned int c;
1599  fputc('"', out);
1600  while( (c = *(z++))!=0 ){
1601    if( c=='\\' ){
1602      fputc(c, out);
1603      fputc(c, out);
1604    }else if( c=='"' ){
1605      fputc('\\', out);
1606      fputc('"', out);
1607    }else if( c=='\t' ){
1608      fputc('\\', out);
1609      fputc('t', out);
1610    }else if( c=='\n' ){
1611      fputc('\\', out);
1612      fputc('n', out);
1613    }else if( c=='\r' ){
1614      fputc('\\', out);
1615      fputc('r', out);
1616    }else if( !isprint(c&0xff) ){
1617      raw_printf(out, "\\%03o", c&0xff);
1618    }else{
1619      fputc(c, out);
1620    }
1621  }
1622  fputc('"', out);
1623}
1624
1625/*
1626** Output the given string as a quoted according to JSON quoting rules.
1627*/
1628static void output_json_string(FILE *out, const char *z, int n){
1629  unsigned int c;
1630  if( n<0 ) n = (int)strlen(z);
1631  fputc('"', out);
1632  while( n-- ){
1633    c = *(z++);
1634    if( c=='\\' || c=='"' ){
1635      fputc('\\', out);
1636      fputc(c, out);
1637    }else if( c<=0x1f ){
1638      fputc('\\', out);
1639      if( c=='\b' ){
1640        fputc('b', out);
1641      }else if( c=='\f' ){
1642        fputc('f', out);
1643      }else if( c=='\n' ){
1644        fputc('n', out);
1645      }else if( c=='\r' ){
1646        fputc('r', out);
1647      }else if( c=='\t' ){
1648        fputc('t', out);
1649      }else{
1650         raw_printf(out, "u%04x",c);
1651      }
1652    }else{
1653      fputc(c, out);
1654    }
1655  }
1656  fputc('"', out);
1657}
1658
1659/*
1660** Output the given string with characters that are special to
1661** HTML escaped.
1662*/
1663static void output_html_string(FILE *out, const char *z){
1664  int i;
1665  if( z==0 ) z = "";
1666  while( *z ){
1667    for(i=0;   z[i]
1668            && z[i]!='<'
1669            && z[i]!='&'
1670            && z[i]!='>'
1671            && z[i]!='\"'
1672            && z[i]!='\'';
1673        i++){}
1674    if( i>0 ){
1675      utf8_printf(out,"%.*s",i,z);
1676    }
1677    if( z[i]=='<' ){
1678      raw_printf(out,"&lt;");
1679    }else if( z[i]=='&' ){
1680      raw_printf(out,"&amp;");
1681    }else if( z[i]=='>' ){
1682      raw_printf(out,"&gt;");
1683    }else if( z[i]=='\"' ){
1684      raw_printf(out,"&quot;");
1685    }else if( z[i]=='\'' ){
1686      raw_printf(out,"&#39;");
1687    }else{
1688      break;
1689    }
1690    z += i + 1;
1691  }
1692}
1693
1694/*
1695** If a field contains any character identified by a 1 in the following
1696** array, then the string must be quoted for CSV.
1697*/
1698static const char needCsvQuote[] = {
1699  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1700  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1701  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1702  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1703  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1704  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1705  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1706  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1707  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1708  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1709  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1710  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1711  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1712  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1713  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1714  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1715};
1716
1717/*
1718** Output a single term of CSV.  Actually, p->colSeparator is used for
1719** the separator, which may or may not be a comma.  p->nullValue is
1720** the null value.  Strings are quoted if necessary.  The separator
1721** is only issued if bSep is true.
1722*/
1723static void output_csv(ShellState *p, const char *z, int bSep){
1724  FILE *out = p->out;
1725  if( z==0 ){
1726    utf8_printf(out,"%s",p->nullValue);
1727  }else{
1728    unsigned i;
1729    for(i=0; z[i]; i++){
1730      if( needCsvQuote[((unsigned char*)z)[i]] ){
1731        i = 0;
1732        break;
1733      }
1734    }
1735    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1736      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1737      shell_check_oom(zQuoted);
1738      utf8_printf(out, "%s", zQuoted);
1739      sqlite3_free(zQuoted);
1740    }else{
1741      utf8_printf(out, "%s", z);
1742    }
1743  }
1744  if( bSep ){
1745    utf8_printf(p->out, "%s", p->colSeparator);
1746  }
1747}
1748
1749/*
1750** This routine runs when the user presses Ctrl-C
1751*/
1752static void interrupt_handler(int NotUsed){
1753  UNUSED_PARAMETER(NotUsed);
1754  seenInterrupt++;
1755  if( seenInterrupt>2 ) exit(1);
1756  if( globalDb ) sqlite3_interrupt(globalDb);
1757}
1758
1759#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1760/*
1761** This routine runs for console events (e.g. Ctrl-C) on Win32
1762*/
1763static BOOL WINAPI ConsoleCtrlHandler(
1764  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1765){
1766  if( dwCtrlType==CTRL_C_EVENT ){
1767    interrupt_handler(0);
1768    return TRUE;
1769  }
1770  return FALSE;
1771}
1772#endif
1773
1774#ifndef SQLITE_OMIT_AUTHORIZATION
1775/*
1776** This authorizer runs in safe mode.
1777*/
1778static int safeModeAuth(
1779  void *pClientData,
1780  int op,
1781  const char *zA1,
1782  const char *zA2,
1783  const char *zA3,
1784  const char *zA4
1785){
1786  ShellState *p = (ShellState*)pClientData;
1787  static const char *azProhibitedFunctions[] = {
1788    "edit",
1789    "fts3_tokenizer",
1790    "load_extension",
1791    "readfile",
1792    "writefile",
1793    "zipfile",
1794    "zipfile_cds",
1795  };
1796  UNUSED_PARAMETER(zA2);
1797  UNUSED_PARAMETER(zA3);
1798  UNUSED_PARAMETER(zA4);
1799  switch( op ){
1800    case SQLITE_ATTACH: {
1801      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1802      break;
1803    }
1804    case SQLITE_FUNCTION: {
1805      int i;
1806      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1807        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1808          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1809                         azProhibitedFunctions[i]);
1810        }
1811      }
1812      break;
1813    }
1814  }
1815  return SQLITE_OK;
1816}
1817
1818/*
1819** When the ".auth ON" is set, the following authorizer callback is
1820** invoked.  It always returns SQLITE_OK.
1821*/
1822static int shellAuth(
1823  void *pClientData,
1824  int op,
1825  const char *zA1,
1826  const char *zA2,
1827  const char *zA3,
1828  const char *zA4
1829){
1830  ShellState *p = (ShellState*)pClientData;
1831  static const char *azAction[] = { 0,
1832     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1833     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1834     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1835     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1836     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1837     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1838     "PRAGMA",               "READ",                 "SELECT",
1839     "TRANSACTION",          "UPDATE",               "ATTACH",
1840     "DETACH",               "ALTER_TABLE",          "REINDEX",
1841     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1842     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1843  };
1844  int i;
1845  const char *az[4];
1846  az[0] = zA1;
1847  az[1] = zA2;
1848  az[2] = zA3;
1849  az[3] = zA4;
1850  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1851  for(i=0; i<4; i++){
1852    raw_printf(p->out, " ");
1853    if( az[i] ){
1854      output_c_string(p->out, az[i]);
1855    }else{
1856      raw_printf(p->out, "NULL");
1857    }
1858  }
1859  raw_printf(p->out, "\n");
1860  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1861  return SQLITE_OK;
1862}
1863#endif
1864
1865/*
1866** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1867**
1868** This routine converts some CREATE TABLE statements for shadow tables
1869** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1870*/
1871static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1872  if( z==0 ) return;
1873  if( zTail==0 ) return;
1874  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1875    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1876  }else{
1877    utf8_printf(out, "%s%s", z, zTail);
1878  }
1879}
1880static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1881  char c = z[n];
1882  z[n] = 0;
1883  printSchemaLine(out, z, zTail);
1884  z[n] = c;
1885}
1886
1887/*
1888** Return true if string z[] has nothing but whitespace and comments to the
1889** end of the first line.
1890*/
1891static int wsToEol(const char *z){
1892  int i;
1893  for(i=0; z[i]; i++){
1894    if( z[i]=='\n' ) return 1;
1895    if( IsSpace(z[i]) ) continue;
1896    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1897    return 0;
1898  }
1899  return 1;
1900}
1901
1902/*
1903** Add a new entry to the EXPLAIN QUERY PLAN data
1904*/
1905static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1906  EQPGraphRow *pNew;
1907  int nText = strlen30(zText);
1908  if( p->autoEQPtest ){
1909    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1910  }
1911  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1912  shell_check_oom(pNew);
1913  pNew->iEqpId = iEqpId;
1914  pNew->iParentId = p2;
1915  memcpy(pNew->zText, zText, nText+1);
1916  pNew->pNext = 0;
1917  if( p->sGraph.pLast ){
1918    p->sGraph.pLast->pNext = pNew;
1919  }else{
1920    p->sGraph.pRow = pNew;
1921  }
1922  p->sGraph.pLast = pNew;
1923}
1924
1925/*
1926** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1927** in p->sGraph.
1928*/
1929static void eqp_reset(ShellState *p){
1930  EQPGraphRow *pRow, *pNext;
1931  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1932    pNext = pRow->pNext;
1933    sqlite3_free(pRow);
1934  }
1935  memset(&p->sGraph, 0, sizeof(p->sGraph));
1936}
1937
1938/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1939** pOld, or return the first such line if pOld is NULL
1940*/
1941static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1942  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1943  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1944  return pRow;
1945}
1946
1947/* Render a single level of the graph that has iEqpId as its parent.  Called
1948** recursively to render sublevels.
1949*/
1950static void eqp_render_level(ShellState *p, int iEqpId){
1951  EQPGraphRow *pRow, *pNext;
1952  int n = strlen30(p->sGraph.zPrefix);
1953  char *z;
1954  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1955    pNext = eqp_next_row(p, iEqpId, pRow);
1956    z = pRow->zText;
1957    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1958                pNext ? "|--" : "`--", z);
1959    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1960      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1961      eqp_render_level(p, pRow->iEqpId);
1962      p->sGraph.zPrefix[n] = 0;
1963    }
1964  }
1965}
1966
1967/*
1968** Display and reset the EXPLAIN QUERY PLAN data
1969*/
1970static void eqp_render(ShellState *p){
1971  EQPGraphRow *pRow = p->sGraph.pRow;
1972  if( pRow ){
1973    if( pRow->zText[0]=='-' ){
1974      if( pRow->pNext==0 ){
1975        eqp_reset(p);
1976        return;
1977      }
1978      utf8_printf(p->out, "%s\n", pRow->zText+3);
1979      p->sGraph.pRow = pRow->pNext;
1980      sqlite3_free(pRow);
1981    }else{
1982      utf8_printf(p->out, "QUERY PLAN\n");
1983    }
1984    p->sGraph.zPrefix[0] = 0;
1985    eqp_render_level(p, 0);
1986    eqp_reset(p);
1987  }
1988}
1989
1990#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1991/*
1992** Progress handler callback.
1993*/
1994static int progress_handler(void *pClientData) {
1995  ShellState *p = (ShellState*)pClientData;
1996  p->nProgress++;
1997  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1998    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1999    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2000    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2001    return 1;
2002  }
2003  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2004    raw_printf(p->out, "Progress %u\n", p->nProgress);
2005  }
2006  return 0;
2007}
2008#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2009
2010/*
2011** Print N dashes
2012*/
2013static void print_dashes(FILE *out, int N){
2014  const char zDash[] = "--------------------------------------------------";
2015  const int nDash = sizeof(zDash) - 1;
2016  while( N>nDash ){
2017    fputs(zDash, out);
2018    N -= nDash;
2019  }
2020  raw_printf(out, "%.*s", N, zDash);
2021}
2022
2023/*
2024** Print a markdown or table-style row separator using ascii-art
2025*/
2026static void print_row_separator(
2027  ShellState *p,
2028  int nArg,
2029  const char *zSep
2030){
2031  int i;
2032  if( nArg>0 ){
2033    fputs(zSep, p->out);
2034    print_dashes(p->out, p->actualWidth[0]+2);
2035    for(i=1; i<nArg; i++){
2036      fputs(zSep, p->out);
2037      print_dashes(p->out, p->actualWidth[i]+2);
2038    }
2039    fputs(zSep, p->out);
2040  }
2041  fputs("\n", p->out);
2042}
2043
2044/*
2045** This is the callback routine that the shell
2046** invokes for each row of a query result.
2047*/
2048static int shell_callback(
2049  void *pArg,
2050  int nArg,        /* Number of result columns */
2051  char **azArg,    /* Text of each result column */
2052  char **azCol,    /* Column names */
2053  int *aiType      /* Column types.  Might be NULL */
2054){
2055  int i;
2056  ShellState *p = (ShellState*)pArg;
2057
2058  if( azArg==0 ) return 0;
2059  switch( p->cMode ){
2060    case MODE_Count:
2061    case MODE_Off: {
2062      break;
2063    }
2064    case MODE_Line: {
2065      int w = 5;
2066      if( azArg==0 ) break;
2067      for(i=0; i<nArg; i++){
2068        int len = strlen30(azCol[i] ? azCol[i] : "");
2069        if( len>w ) w = len;
2070      }
2071      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2072      for(i=0; i<nArg; i++){
2073        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2074                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2075      }
2076      break;
2077    }
2078    case MODE_Explain: {
2079      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2080      if( nArg>ArraySize(aExplainWidth) ){
2081        nArg = ArraySize(aExplainWidth);
2082      }
2083      if( p->cnt++==0 ){
2084        for(i=0; i<nArg; i++){
2085          int w = aExplainWidth[i];
2086          utf8_width_print(p->out, w, azCol[i]);
2087          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2088        }
2089        for(i=0; i<nArg; i++){
2090          int w = aExplainWidth[i];
2091          print_dashes(p->out, w);
2092          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2093        }
2094      }
2095      if( azArg==0 ) break;
2096      for(i=0; i<nArg; i++){
2097        int w = aExplainWidth[i];
2098        if( i==nArg-1 ) w = 0;
2099        if( azArg[i] && strlenChar(azArg[i])>w ){
2100          w = strlenChar(azArg[i]);
2101        }
2102        if( i==1 && p->aiIndent && p->pStmt ){
2103          if( p->iIndent<p->nIndent ){
2104            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2105          }
2106          p->iIndent++;
2107        }
2108        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2109        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2110      }
2111      break;
2112    }
2113    case MODE_Semi: {   /* .schema and .fullschema output */
2114      printSchemaLine(p->out, azArg[0], ";\n");
2115      break;
2116    }
2117    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2118      char *z;
2119      int j;
2120      int nParen = 0;
2121      char cEnd = 0;
2122      char c;
2123      int nLine = 0;
2124      assert( nArg==1 );
2125      if( azArg[0]==0 ) break;
2126      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2127       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2128      ){
2129        utf8_printf(p->out, "%s;\n", azArg[0]);
2130        break;
2131      }
2132      z = sqlite3_mprintf("%s", azArg[0]);
2133      shell_check_oom(z);
2134      j = 0;
2135      for(i=0; IsSpace(z[i]); i++){}
2136      for(; (c = z[i])!=0; i++){
2137        if( IsSpace(c) ){
2138          if( z[j-1]=='\r' ) z[j-1] = '\n';
2139          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2140        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2141          j--;
2142        }
2143        z[j++] = c;
2144      }
2145      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2146      z[j] = 0;
2147      if( strlen30(z)>=79 ){
2148        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2149          if( c==cEnd ){
2150            cEnd = 0;
2151          }else if( c=='"' || c=='\'' || c=='`' ){
2152            cEnd = c;
2153          }else if( c=='[' ){
2154            cEnd = ']';
2155          }else if( c=='-' && z[i+1]=='-' ){
2156            cEnd = '\n';
2157          }else if( c=='(' ){
2158            nParen++;
2159          }else if( c==')' ){
2160            nParen--;
2161            if( nLine>0 && nParen==0 && j>0 ){
2162              printSchemaLineN(p->out, z, j, "\n");
2163              j = 0;
2164            }
2165          }
2166          z[j++] = c;
2167          if( nParen==1 && cEnd==0
2168           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2169          ){
2170            if( c=='\n' ) j--;
2171            printSchemaLineN(p->out, z, j, "\n  ");
2172            j = 0;
2173            nLine++;
2174            while( IsSpace(z[i+1]) ){ i++; }
2175          }
2176        }
2177        z[j] = 0;
2178      }
2179      printSchemaLine(p->out, z, ";\n");
2180      sqlite3_free(z);
2181      break;
2182    }
2183    case MODE_List: {
2184      if( p->cnt++==0 && p->showHeader ){
2185        for(i=0; i<nArg; i++){
2186          utf8_printf(p->out,"%s%s",azCol[i],
2187                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2188        }
2189      }
2190      if( azArg==0 ) break;
2191      for(i=0; i<nArg; i++){
2192        char *z = azArg[i];
2193        if( z==0 ) z = p->nullValue;
2194        utf8_printf(p->out, "%s", z);
2195        if( i<nArg-1 ){
2196          utf8_printf(p->out, "%s", p->colSeparator);
2197        }else{
2198          utf8_printf(p->out, "%s", p->rowSeparator);
2199        }
2200      }
2201      break;
2202    }
2203    case MODE_Html: {
2204      if( p->cnt++==0 && p->showHeader ){
2205        raw_printf(p->out,"<TR>");
2206        for(i=0; i<nArg; i++){
2207          raw_printf(p->out,"<TH>");
2208          output_html_string(p->out, azCol[i]);
2209          raw_printf(p->out,"</TH>\n");
2210        }
2211        raw_printf(p->out,"</TR>\n");
2212      }
2213      if( azArg==0 ) break;
2214      raw_printf(p->out,"<TR>");
2215      for(i=0; i<nArg; i++){
2216        raw_printf(p->out,"<TD>");
2217        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2218        raw_printf(p->out,"</TD>\n");
2219      }
2220      raw_printf(p->out,"</TR>\n");
2221      break;
2222    }
2223    case MODE_Tcl: {
2224      if( p->cnt++==0 && p->showHeader ){
2225        for(i=0; i<nArg; i++){
2226          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2227          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2228        }
2229        utf8_printf(p->out, "%s", p->rowSeparator);
2230      }
2231      if( azArg==0 ) break;
2232      for(i=0; i<nArg; i++){
2233        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2234        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2235      }
2236      utf8_printf(p->out, "%s", p->rowSeparator);
2237      break;
2238    }
2239    case MODE_Csv: {
2240      setBinaryMode(p->out, 1);
2241      if( p->cnt++==0 && p->showHeader ){
2242        for(i=0; i<nArg; i++){
2243          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2244        }
2245        utf8_printf(p->out, "%s", p->rowSeparator);
2246      }
2247      if( nArg>0 ){
2248        for(i=0; i<nArg; i++){
2249          output_csv(p, azArg[i], i<nArg-1);
2250        }
2251        utf8_printf(p->out, "%s", p->rowSeparator);
2252      }
2253      setTextMode(p->out, 1);
2254      break;
2255    }
2256    case MODE_Insert: {
2257      if( azArg==0 ) break;
2258      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2259      if( p->showHeader ){
2260        raw_printf(p->out,"(");
2261        for(i=0; i<nArg; i++){
2262          if( i>0 ) raw_printf(p->out, ",");
2263          if( quoteChar(azCol[i]) ){
2264            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2265            shell_check_oom(z);
2266            utf8_printf(p->out, "%s", z);
2267            sqlite3_free(z);
2268          }else{
2269            raw_printf(p->out, "%s", azCol[i]);
2270          }
2271        }
2272        raw_printf(p->out,")");
2273      }
2274      p->cnt++;
2275      for(i=0; i<nArg; i++){
2276        raw_printf(p->out, i>0 ? "," : " VALUES(");
2277        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2278          utf8_printf(p->out,"NULL");
2279        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2280          if( ShellHasFlag(p, SHFLG_Newlines) ){
2281            output_quoted_string(p->out, azArg[i]);
2282          }else{
2283            output_quoted_escaped_string(p->out, azArg[i]);
2284          }
2285        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2286          utf8_printf(p->out,"%s", azArg[i]);
2287        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2288          char z[50];
2289          double r = sqlite3_column_double(p->pStmt, i);
2290          sqlite3_uint64 ur;
2291          memcpy(&ur,&r,sizeof(r));
2292          if( ur==0x7ff0000000000000LL ){
2293            raw_printf(p->out, "1e999");
2294          }else if( ur==0xfff0000000000000LL ){
2295            raw_printf(p->out, "-1e999");
2296          }else{
2297            sqlite3_snprintf(50,z,"%!.20g", r);
2298            raw_printf(p->out, "%s", z);
2299          }
2300        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2301          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2302          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2303          output_hex_blob(p->out, pBlob, nBlob);
2304        }else if( isNumber(azArg[i], 0) ){
2305          utf8_printf(p->out,"%s", azArg[i]);
2306        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2307          output_quoted_string(p->out, azArg[i]);
2308        }else{
2309          output_quoted_escaped_string(p->out, azArg[i]);
2310        }
2311      }
2312      raw_printf(p->out,");\n");
2313      break;
2314    }
2315    case MODE_Json: {
2316      if( azArg==0 ) break;
2317      if( p->cnt==0 ){
2318        fputs("[{", p->out);
2319      }else{
2320        fputs(",\n{", p->out);
2321      }
2322      p->cnt++;
2323      for(i=0; i<nArg; i++){
2324        output_json_string(p->out, azCol[i], -1);
2325        putc(':', p->out);
2326        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2327          fputs("null",p->out);
2328        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2329          char z[50];
2330          double r = sqlite3_column_double(p->pStmt, i);
2331          sqlite3_uint64 ur;
2332          memcpy(&ur,&r,sizeof(r));
2333          if( ur==0x7ff0000000000000LL ){
2334            raw_printf(p->out, "1e999");
2335          }else if( ur==0xfff0000000000000LL ){
2336            raw_printf(p->out, "-1e999");
2337          }else{
2338            sqlite3_snprintf(50,z,"%!.20g", r);
2339            raw_printf(p->out, "%s", z);
2340          }
2341        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2342          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2343          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2344          output_json_string(p->out, pBlob, nBlob);
2345        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2346          output_json_string(p->out, azArg[i], -1);
2347        }else{
2348          utf8_printf(p->out,"%s", azArg[i]);
2349        }
2350        if( i<nArg-1 ){
2351          putc(',', p->out);
2352        }
2353      }
2354      putc('}', p->out);
2355      break;
2356    }
2357    case MODE_Quote: {
2358      if( azArg==0 ) break;
2359      if( p->cnt==0 && p->showHeader ){
2360        for(i=0; i<nArg; i++){
2361          if( i>0 ) fputs(p->colSeparator, p->out);
2362          output_quoted_string(p->out, azCol[i]);
2363        }
2364        fputs(p->rowSeparator, p->out);
2365      }
2366      p->cnt++;
2367      for(i=0; i<nArg; i++){
2368        if( i>0 ) fputs(p->colSeparator, p->out);
2369        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2370          utf8_printf(p->out,"NULL");
2371        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2372          output_quoted_string(p->out, azArg[i]);
2373        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2374          utf8_printf(p->out,"%s", azArg[i]);
2375        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2376          char z[50];
2377          double r = sqlite3_column_double(p->pStmt, i);
2378          sqlite3_snprintf(50,z,"%!.20g", r);
2379          raw_printf(p->out, "%s", z);
2380        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2381          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2382          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2383          output_hex_blob(p->out, pBlob, nBlob);
2384        }else if( isNumber(azArg[i], 0) ){
2385          utf8_printf(p->out,"%s", azArg[i]);
2386        }else{
2387          output_quoted_string(p->out, azArg[i]);
2388        }
2389      }
2390      fputs(p->rowSeparator, p->out);
2391      break;
2392    }
2393    case MODE_Ascii: {
2394      if( p->cnt++==0 && p->showHeader ){
2395        for(i=0; i<nArg; i++){
2396          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2397          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2398        }
2399        utf8_printf(p->out, "%s", p->rowSeparator);
2400      }
2401      if( azArg==0 ) break;
2402      for(i=0; i<nArg; i++){
2403        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2404        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2405      }
2406      utf8_printf(p->out, "%s", p->rowSeparator);
2407      break;
2408    }
2409    case MODE_EQP: {
2410      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2411      break;
2412    }
2413  }
2414  return 0;
2415}
2416
2417/*
2418** This is the callback routine that the SQLite library
2419** invokes for each row of a query result.
2420*/
2421static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2422  /* since we don't have type info, call the shell_callback with a NULL value */
2423  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2424}
2425
2426/*
2427** This is the callback routine from sqlite3_exec() that appends all
2428** output onto the end of a ShellText object.
2429*/
2430static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2431  ShellText *p = (ShellText*)pArg;
2432  int i;
2433  UNUSED_PARAMETER(az);
2434  if( azArg==0 ) return 0;
2435  if( p->n ) appendText(p, "|", 0);
2436  for(i=0; i<nArg; i++){
2437    if( i ) appendText(p, ",", 0);
2438    if( azArg[i] ) appendText(p, azArg[i], 0);
2439  }
2440  return 0;
2441}
2442
2443/*
2444** Generate an appropriate SELFTEST table in the main database.
2445*/
2446static void createSelftestTable(ShellState *p){
2447  char *zErrMsg = 0;
2448  sqlite3_exec(p->db,
2449    "SAVEPOINT selftest_init;\n"
2450    "CREATE TABLE IF NOT EXISTS selftest(\n"
2451    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2452    "  op TEXT,\n"                   /* Operator:  memo run */
2453    "  cmd TEXT,\n"                  /* Command text */
2454    "  ans TEXT\n"                   /* Desired answer */
2455    ");"
2456    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2457    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2458    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2459    "         'memo','Tests generated by --init');\n"
2460    "INSERT INTO [_shell$self]\n"
2461    "  SELECT 'run',\n"
2462    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2463                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2464    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2465                          "FROM sqlite_schema ORDER BY 2',224));\n"
2466    "INSERT INTO [_shell$self]\n"
2467    "  SELECT 'run',"
2468    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2469    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2470    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2471    "  FROM (\n"
2472    "    SELECT name FROM sqlite_schema\n"
2473    "     WHERE type='table'\n"
2474    "       AND name<>'selftest'\n"
2475    "       AND coalesce(rootpage,0)>0\n"
2476    "  )\n"
2477    " ORDER BY name;\n"
2478    "INSERT INTO [_shell$self]\n"
2479    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2480    "INSERT INTO selftest(tno,op,cmd,ans)"
2481    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2482    "DROP TABLE [_shell$self];"
2483    ,0,0,&zErrMsg);
2484  if( zErrMsg ){
2485    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2486    sqlite3_free(zErrMsg);
2487  }
2488  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2489}
2490
2491
2492/*
2493** Set the destination table field of the ShellState structure to
2494** the name of the table given.  Escape any quote characters in the
2495** table name.
2496*/
2497static void set_table_name(ShellState *p, const char *zName){
2498  int i, n;
2499  char cQuote;
2500  char *z;
2501
2502  if( p->zDestTable ){
2503    free(p->zDestTable);
2504    p->zDestTable = 0;
2505  }
2506  if( zName==0 ) return;
2507  cQuote = quoteChar(zName);
2508  n = strlen30(zName);
2509  if( cQuote ) n += n+2;
2510  z = p->zDestTable = malloc( n+1 );
2511  shell_check_oom(z);
2512  n = 0;
2513  if( cQuote ) z[n++] = cQuote;
2514  for(i=0; zName[i]; i++){
2515    z[n++] = zName[i];
2516    if( zName[i]==cQuote ) z[n++] = cQuote;
2517  }
2518  if( cQuote ) z[n++] = cQuote;
2519  z[n] = 0;
2520}
2521
2522/*
2523** Maybe construct two lines of text that point out the position of a
2524** syntax error.  Return a pointer to the text, in memory obtained from
2525** sqlite3_malloc().  Or, if the most recent error does not involve a
2526** specific token that we can point to, return an empty string.
2527**
2528** In all cases, the memory returned is obtained from sqlite3_malloc64()
2529** and should be released by the caller invoking sqlite3_free().
2530*/
2531static char *shell_error_context(const char *zSql, sqlite3 *db){
2532  int iOffset;
2533  size_t len;
2534  char *zCode;
2535  char *zMsg;
2536  int i;
2537  if( db==0
2538   || zSql==0
2539   || (iOffset = sqlite3_error_offset(db))<0
2540  ){
2541    return sqlite3_mprintf("");
2542  }
2543  while( iOffset>50 ){
2544    iOffset--;
2545    zSql++;
2546    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2547  }
2548  len = strlen(zSql);
2549  if( len>78 ){
2550    len = 78;
2551    while( (zSql[len]&0xc0)==0x80 ) len--;
2552  }
2553  zCode = sqlite3_mprintf("%.*s", len, zSql);
2554  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2555  if( iOffset<25 ){
2556    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2557  }else{
2558    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2559  }
2560  return zMsg;
2561}
2562
2563
2564/*
2565** Execute a query statement that will generate SQL output.  Print
2566** the result columns, comma-separated, on a line and then add a
2567** semicolon terminator to the end of that line.
2568**
2569** If the number of columns is 1 and that column contains text "--"
2570** then write the semicolon on a separate line.  That way, if a
2571** "--" comment occurs at the end of the statement, the comment
2572** won't consume the semicolon terminator.
2573*/
2574static int run_table_dump_query(
2575  ShellState *p,           /* Query context */
2576  const char *zSelect      /* SELECT statement to extract content */
2577){
2578  sqlite3_stmt *pSelect;
2579  int rc;
2580  int nResult;
2581  int i;
2582  const char *z;
2583  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2584  if( rc!=SQLITE_OK || !pSelect ){
2585    char *zContext = shell_error_context(zSelect, p->db);
2586    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2587                sqlite3_errmsg(p->db), zContext);
2588    sqlite3_free(zContext);
2589    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2590    return rc;
2591  }
2592  rc = sqlite3_step(pSelect);
2593  nResult = sqlite3_column_count(pSelect);
2594  while( rc==SQLITE_ROW ){
2595    z = (const char*)sqlite3_column_text(pSelect, 0);
2596    utf8_printf(p->out, "%s", z);
2597    for(i=1; i<nResult; i++){
2598      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2599    }
2600    if( z==0 ) z = "";
2601    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2602    if( z[0] ){
2603      raw_printf(p->out, "\n;\n");
2604    }else{
2605      raw_printf(p->out, ";\n");
2606    }
2607    rc = sqlite3_step(pSelect);
2608  }
2609  rc = sqlite3_finalize(pSelect);
2610  if( rc!=SQLITE_OK ){
2611    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2612                sqlite3_errmsg(p->db));
2613    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2614  }
2615  return rc;
2616}
2617
2618/*
2619** Allocate space and save off string indicating current error.
2620*/
2621static char *save_err_msg(
2622  sqlite3 *db,           /* Database to query */
2623  const char *zWhen,     /* Qualifier (format) wrapper */
2624  int rc,                /* Error code returned from API */
2625  const char *zSql       /* SQL string, or NULL */
2626){
2627  char *zErr;
2628  char *zContext;
2629  if( zWhen==0 ) zWhen = "%s (%d)%s";
2630  zContext = shell_error_context(zSql, db);
2631  zErr = sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc, zContext);
2632  shell_check_oom(zErr);
2633  sqlite3_free(zContext);
2634  return zErr;
2635}
2636
2637#ifdef __linux__
2638/*
2639** Attempt to display I/O stats on Linux using /proc/PID/io
2640*/
2641static void displayLinuxIoStats(FILE *out){
2642  FILE *in;
2643  char z[200];
2644  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2645  in = fopen(z, "rb");
2646  if( in==0 ) return;
2647  while( fgets(z, sizeof(z), in)!=0 ){
2648    static const struct {
2649      const char *zPattern;
2650      const char *zDesc;
2651    } aTrans[] = {
2652      { "rchar: ",                  "Bytes received by read():" },
2653      { "wchar: ",                  "Bytes sent to write():"    },
2654      { "syscr: ",                  "Read() system calls:"      },
2655      { "syscw: ",                  "Write() system calls:"     },
2656      { "read_bytes: ",             "Bytes read from storage:"  },
2657      { "write_bytes: ",            "Bytes written to storage:" },
2658      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2659    };
2660    int i;
2661    for(i=0; i<ArraySize(aTrans); i++){
2662      int n = strlen30(aTrans[i].zPattern);
2663      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2664        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2665        break;
2666      }
2667    }
2668  }
2669  fclose(in);
2670}
2671#endif
2672
2673/*
2674** Display a single line of status using 64-bit values.
2675*/
2676static void displayStatLine(
2677  ShellState *p,            /* The shell context */
2678  char *zLabel,             /* Label for this one line */
2679  char *zFormat,            /* Format for the result */
2680  int iStatusCtrl,          /* Which status to display */
2681  int bReset                /* True to reset the stats */
2682){
2683  sqlite3_int64 iCur = -1;
2684  sqlite3_int64 iHiwtr = -1;
2685  int i, nPercent;
2686  char zLine[200];
2687  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2688  for(i=0, nPercent=0; zFormat[i]; i++){
2689    if( zFormat[i]=='%' ) nPercent++;
2690  }
2691  if( nPercent>1 ){
2692    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2693  }else{
2694    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2695  }
2696  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2697}
2698
2699/*
2700** Display memory stats.
2701*/
2702static int display_stats(
2703  sqlite3 *db,                /* Database to query */
2704  ShellState *pArg,           /* Pointer to ShellState */
2705  int bReset                  /* True to reset the stats */
2706){
2707  int iCur;
2708  int iHiwtr;
2709  FILE *out;
2710  if( pArg==0 || pArg->out==0 ) return 0;
2711  out = pArg->out;
2712
2713  if( pArg->pStmt && pArg->statsOn==2 ){
2714    int nCol, i, x;
2715    sqlite3_stmt *pStmt = pArg->pStmt;
2716    char z[100];
2717    nCol = sqlite3_column_count(pStmt);
2718    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2719    for(i=0; i<nCol; i++){
2720      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2721      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2722#ifndef SQLITE_OMIT_DECLTYPE
2723      sqlite3_snprintf(30, z+x, "declared type:");
2724      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2725#endif
2726#ifdef SQLITE_ENABLE_COLUMN_METADATA
2727      sqlite3_snprintf(30, z+x, "database name:");
2728      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2729      sqlite3_snprintf(30, z+x, "table name:");
2730      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2731      sqlite3_snprintf(30, z+x, "origin name:");
2732      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2733#endif
2734    }
2735  }
2736
2737  if( pArg->statsOn==3 ){
2738    if( pArg->pStmt ){
2739      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2740      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2741    }
2742    return 0;
2743  }
2744
2745  displayStatLine(pArg, "Memory Used:",
2746     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2747  displayStatLine(pArg, "Number of Outstanding Allocations:",
2748     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2749  if( pArg->shellFlgs & SHFLG_Pagecache ){
2750    displayStatLine(pArg, "Number of Pcache Pages Used:",
2751       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2752  }
2753  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2754     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2755  displayStatLine(pArg, "Largest Allocation:",
2756     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2757  displayStatLine(pArg, "Largest Pcache Allocation:",
2758     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2759#ifdef YYTRACKMAXSTACKDEPTH
2760  displayStatLine(pArg, "Deepest Parser Stack:",
2761     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2762#endif
2763
2764  if( db ){
2765    if( pArg->shellFlgs & SHFLG_Lookaside ){
2766      iHiwtr = iCur = -1;
2767      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2768                        &iCur, &iHiwtr, bReset);
2769      raw_printf(pArg->out,
2770              "Lookaside Slots Used:                %d (max %d)\n",
2771              iCur, iHiwtr);
2772      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2773                        &iCur, &iHiwtr, bReset);
2774      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2775              iHiwtr);
2776      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2777                        &iCur, &iHiwtr, bReset);
2778      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2779              iHiwtr);
2780      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2781                        &iCur, &iHiwtr, bReset);
2782      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2783              iHiwtr);
2784    }
2785    iHiwtr = iCur = -1;
2786    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2787    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2788            iCur);
2789    iHiwtr = iCur = -1;
2790    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2791    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2792    iHiwtr = iCur = -1;
2793    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2794    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2795    iHiwtr = iCur = -1;
2796    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2797    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2798    iHiwtr = iCur = -1;
2799    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2800    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2801    iHiwtr = iCur = -1;
2802    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2803    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2804            iCur);
2805    iHiwtr = iCur = -1;
2806    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2807    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2808            iCur);
2809  }
2810
2811  if( pArg->pStmt ){
2812    int iHit, iMiss;
2813    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2814                               bReset);
2815    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2816    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2817    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2818    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2819    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2820    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2821    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2822    if( iHit || iMiss ){
2823      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2824            iHit, iHit+iMiss);
2825    }
2826    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2827    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2828    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2829    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2830    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2831    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2832    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2833    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2834  }
2835
2836#ifdef __linux__
2837  displayLinuxIoStats(pArg->out);
2838#endif
2839
2840  /* Do not remove this machine readable comment: extra-stats-output-here */
2841
2842  return 0;
2843}
2844
2845/*
2846** Display scan stats.
2847*/
2848static void display_scanstats(
2849  sqlite3 *db,                    /* Database to query */
2850  ShellState *pArg                /* Pointer to ShellState */
2851){
2852#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2853  UNUSED_PARAMETER(db);
2854  UNUSED_PARAMETER(pArg);
2855#else
2856  int i, k, n, mx;
2857  raw_printf(pArg->out, "-------- scanstats --------\n");
2858  mx = 0;
2859  for(k=0; k<=mx; k++){
2860    double rEstLoop = 1.0;
2861    for(i=n=0; 1; i++){
2862      sqlite3_stmt *p = pArg->pStmt;
2863      sqlite3_int64 nLoop, nVisit;
2864      double rEst;
2865      int iSid;
2866      const char *zExplain;
2867      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2868        break;
2869      }
2870      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2871      if( iSid>mx ) mx = iSid;
2872      if( iSid!=k ) continue;
2873      if( n==0 ){
2874        rEstLoop = (double)nLoop;
2875        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2876      }
2877      n++;
2878      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2879      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2880      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2881      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2882      rEstLoop *= rEst;
2883      raw_printf(pArg->out,
2884          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2885          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2886      );
2887    }
2888  }
2889  raw_printf(pArg->out, "---------------------------\n");
2890#endif
2891}
2892
2893/*
2894** Parameter azArray points to a zero-terminated array of strings. zStr
2895** points to a single nul-terminated string. Return non-zero if zStr
2896** is equal, according to strcmp(), to any of the strings in the array.
2897** Otherwise, return zero.
2898*/
2899static int str_in_array(const char *zStr, const char **azArray){
2900  int i;
2901  for(i=0; azArray[i]; i++){
2902    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2903  }
2904  return 0;
2905}
2906
2907/*
2908** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2909** and populate the ShellState.aiIndent[] array with the number of
2910** spaces each opcode should be indented before it is output.
2911**
2912** The indenting rules are:
2913**
2914**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2915**       all opcodes that occur between the p2 jump destination and the opcode
2916**       itself by 2 spaces.
2917**
2918**     * For each "Goto", if the jump destination is earlier in the program
2919**       and ends on one of:
2920**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2921**       or if the P1 parameter is one instead of zero,
2922**       then indent all opcodes between the earlier instruction
2923**       and "Goto" by 2 spaces.
2924*/
2925static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2926  const char *zSql;               /* The text of the SQL statement */
2927  const char *z;                  /* Used to check if this is an EXPLAIN */
2928  int *abYield = 0;               /* True if op is an OP_Yield */
2929  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2930  int iOp;                        /* Index of operation in p->aiIndent[] */
2931
2932  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2933  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2934                            "Rewind", 0 };
2935  const char *azGoto[] = { "Goto", 0 };
2936
2937  /* Try to figure out if this is really an EXPLAIN statement. If this
2938  ** cannot be verified, return early.  */
2939  if( sqlite3_column_count(pSql)!=8 ){
2940    p->cMode = p->mode;
2941    return;
2942  }
2943  zSql = sqlite3_sql(pSql);
2944  if( zSql==0 ) return;
2945  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2946  if( sqlite3_strnicmp(z, "explain", 7) ){
2947    p->cMode = p->mode;
2948    return;
2949  }
2950
2951  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2952    int i;
2953    int iAddr = sqlite3_column_int(pSql, 0);
2954    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2955
2956    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2957    ** p2 is an instruction address, set variable p2op to the index of that
2958    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2959    ** the current instruction is part of a sub-program generated by an
2960    ** SQL trigger or foreign key.  */
2961    int p2 = sqlite3_column_int(pSql, 3);
2962    int p2op = (p2 + (iOp-iAddr));
2963
2964    /* Grow the p->aiIndent array as required */
2965    if( iOp>=nAlloc ){
2966      if( iOp==0 ){
2967        /* Do further verfication that this is explain output.  Abort if
2968        ** it is not */
2969        static const char *explainCols[] = {
2970           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2971        int jj;
2972        for(jj=0; jj<ArraySize(explainCols); jj++){
2973          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2974            p->cMode = p->mode;
2975            sqlite3_reset(pSql);
2976            return;
2977          }
2978        }
2979      }
2980      nAlloc += 100;
2981      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2982      shell_check_oom(p->aiIndent);
2983      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2984      shell_check_oom(abYield);
2985    }
2986    abYield[iOp] = str_in_array(zOp, azYield);
2987    p->aiIndent[iOp] = 0;
2988    p->nIndent = iOp+1;
2989
2990    if( str_in_array(zOp, azNext) ){
2991      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2992    }
2993    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2994     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2995    ){
2996      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2997    }
2998  }
2999
3000  p->iIndent = 0;
3001  sqlite3_free(abYield);
3002  sqlite3_reset(pSql);
3003}
3004
3005/*
3006** Free the array allocated by explain_data_prepare().
3007*/
3008static void explain_data_delete(ShellState *p){
3009  sqlite3_free(p->aiIndent);
3010  p->aiIndent = 0;
3011  p->nIndent = 0;
3012  p->iIndent = 0;
3013}
3014
3015/*
3016** Disable and restore .wheretrace and .selecttrace settings.
3017*/
3018static unsigned int savedSelectTrace;
3019static unsigned int savedWhereTrace;
3020static void disable_debug_trace_modes(void){
3021  unsigned int zero = 0;
3022  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3023  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3024  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3025  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3026}
3027static void restore_debug_trace_modes(void){
3028  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3029  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3030}
3031
3032/* Create the TEMP table used to store parameter bindings */
3033static void bind_table_init(ShellState *p){
3034  int wrSchema = 0;
3035  int defensiveMode = 0;
3036  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3037  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3038  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3039  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3040  sqlite3_exec(p->db,
3041    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3042    "  key TEXT PRIMARY KEY,\n"
3043    "  value\n"
3044    ") WITHOUT ROWID;",
3045    0, 0, 0);
3046  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3047  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3048}
3049
3050/*
3051** Bind parameters on a prepared statement.
3052**
3053** Parameter bindings are taken from a TEMP table of the form:
3054**
3055**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3056**    WITHOUT ROWID;
3057**
3058** No bindings occur if this table does not exist.  The name of the table
3059** begins with "sqlite_" so that it will not collide with ordinary application
3060** tables.  The table must be in the TEMP schema.
3061*/
3062static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3063  int nVar;
3064  int i;
3065  int rc;
3066  sqlite3_stmt *pQ = 0;
3067
3068  nVar = sqlite3_bind_parameter_count(pStmt);
3069  if( nVar==0 ) return;  /* Nothing to do */
3070  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3071                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3072    return; /* Parameter table does not exist */
3073  }
3074  rc = sqlite3_prepare_v2(pArg->db,
3075          "SELECT value FROM temp.sqlite_parameters"
3076          " WHERE key=?1", -1, &pQ, 0);
3077  if( rc || pQ==0 ) return;
3078  for(i=1; i<=nVar; i++){
3079    char zNum[30];
3080    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3081    if( zVar==0 ){
3082      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3083      zVar = zNum;
3084    }
3085    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3086    if( sqlite3_step(pQ)==SQLITE_ROW ){
3087      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3088    }else{
3089      sqlite3_bind_null(pStmt, i);
3090    }
3091    sqlite3_reset(pQ);
3092  }
3093  sqlite3_finalize(pQ);
3094}
3095
3096/*
3097** UTF8 box-drawing characters.  Imagine box lines like this:
3098**
3099**           1
3100**           |
3101**       4 --+-- 2
3102**           |
3103**           3
3104**
3105** Each box characters has between 2 and 4 of the lines leading from
3106** the center.  The characters are here identified by the numbers of
3107** their corresponding lines.
3108*/
3109#define BOX_24   "\342\224\200"  /* U+2500 --- */
3110#define BOX_13   "\342\224\202"  /* U+2502  |  */
3111#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3112#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3113#define BOX_12   "\342\224\224"  /* U+2514  '- */
3114#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3115#define BOX_123  "\342\224\234"  /* U+251c  |- */
3116#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3117#define BOX_234  "\342\224\254"  /* U+252c -,- */
3118#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3119#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3120
3121/* Draw horizontal line N characters long using unicode box
3122** characters
3123*/
3124static void print_box_line(FILE *out, int N){
3125  const char zDash[] =
3126      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3127      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3128  const int nDash = sizeof(zDash) - 1;
3129  N *= 3;
3130  while( N>nDash ){
3131    utf8_printf(out, zDash);
3132    N -= nDash;
3133  }
3134  utf8_printf(out, "%.*s", N, zDash);
3135}
3136
3137/*
3138** Draw a horizontal separator for a MODE_Box table.
3139*/
3140static void print_box_row_separator(
3141  ShellState *p,
3142  int nArg,
3143  const char *zSep1,
3144  const char *zSep2,
3145  const char *zSep3
3146){
3147  int i;
3148  if( nArg>0 ){
3149    utf8_printf(p->out, "%s", zSep1);
3150    print_box_line(p->out, p->actualWidth[0]+2);
3151    for(i=1; i<nArg; i++){
3152      utf8_printf(p->out, "%s", zSep2);
3153      print_box_line(p->out, p->actualWidth[i]+2);
3154    }
3155    utf8_printf(p->out, "%s", zSep3);
3156  }
3157  fputs("\n", p->out);
3158}
3159
3160
3161
3162/*
3163** Run a prepared statement and output the result in one of the
3164** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3165** or MODE_Box.
3166**
3167** This is different from ordinary exec_prepared_stmt() in that
3168** it has to run the entire query and gather the results into memory
3169** first, in order to determine column widths, before providing
3170** any output.
3171*/
3172static void exec_prepared_stmt_columnar(
3173  ShellState *p,                        /* Pointer to ShellState */
3174  sqlite3_stmt *pStmt                   /* Statment to run */
3175){
3176  sqlite3_int64 nRow = 0;
3177  int nColumn = 0;
3178  char **azData = 0;
3179  sqlite3_int64 nAlloc = 0;
3180  const char *z;
3181  int rc;
3182  sqlite3_int64 i, nData;
3183  int j, nTotal, w, n;
3184  const char *colSep = 0;
3185  const char *rowSep = 0;
3186
3187  rc = sqlite3_step(pStmt);
3188  if( rc!=SQLITE_ROW ) return;
3189  nColumn = sqlite3_column_count(pStmt);
3190  nAlloc = nColumn*4;
3191  if( nAlloc<=0 ) nAlloc = 1;
3192  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3193  shell_check_oom(azData);
3194  for(i=0; i<nColumn; i++){
3195    azData[i] = strdup(sqlite3_column_name(pStmt,i));
3196  }
3197  do{
3198    if( (nRow+2)*nColumn >= nAlloc ){
3199      nAlloc *= 2;
3200      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3201      shell_check_oom(azData);
3202    }
3203    nRow++;
3204    for(i=0; i<nColumn; i++){
3205      z = (const char*)sqlite3_column_text(pStmt,i);
3206      azData[nRow*nColumn + i] = z ? strdup(z) : 0;
3207    }
3208  }while( sqlite3_step(pStmt)==SQLITE_ROW );
3209  if( nColumn>p->nWidth ){
3210    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3211    shell_check_oom(p->colWidth);
3212    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3213    p->nWidth = nColumn;
3214    p->actualWidth = &p->colWidth[nColumn];
3215  }
3216  memset(p->actualWidth, 0, nColumn*sizeof(int));
3217  for(i=0; i<nColumn; i++){
3218    w = p->colWidth[i];
3219    if( w<0 ) w = -w;
3220    p->actualWidth[i] = w;
3221  }
3222  nTotal = nColumn*(nRow+1);
3223  for(i=0; i<nTotal; i++){
3224    z = azData[i];
3225    if( z==0 ) z = p->nullValue;
3226    n = strlenChar(z);
3227    j = i%nColumn;
3228    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3229  }
3230  if( seenInterrupt ) goto columnar_end;
3231  if( nColumn==0 ) goto columnar_end;
3232  switch( p->cMode ){
3233    case MODE_Column: {
3234      colSep = "  ";
3235      rowSep = "\n";
3236      if( p->showHeader ){
3237        for(i=0; i<nColumn; i++){
3238          w = p->actualWidth[i];
3239          if( p->colWidth[i]<0 ) w = -w;
3240          utf8_width_print(p->out, w, azData[i]);
3241          fputs(i==nColumn-1?"\n":"  ", p->out);
3242        }
3243        for(i=0; i<nColumn; i++){
3244          print_dashes(p->out, p->actualWidth[i]);
3245          fputs(i==nColumn-1?"\n":"  ", p->out);
3246        }
3247      }
3248      break;
3249    }
3250    case MODE_Table: {
3251      colSep = " | ";
3252      rowSep = " |\n";
3253      print_row_separator(p, nColumn, "+");
3254      fputs("| ", p->out);
3255      for(i=0; i<nColumn; i++){
3256        w = p->actualWidth[i];
3257        n = strlenChar(azData[i]);
3258        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3259        fputs(i==nColumn-1?" |\n":" | ", p->out);
3260      }
3261      print_row_separator(p, nColumn, "+");
3262      break;
3263    }
3264    case MODE_Markdown: {
3265      colSep = " | ";
3266      rowSep = " |\n";
3267      fputs("| ", p->out);
3268      for(i=0; i<nColumn; i++){
3269        w = p->actualWidth[i];
3270        n = strlenChar(azData[i]);
3271        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3272        fputs(i==nColumn-1?" |\n":" | ", p->out);
3273      }
3274      print_row_separator(p, nColumn, "|");
3275      break;
3276    }
3277    case MODE_Box: {
3278      colSep = " " BOX_13 " ";
3279      rowSep = " " BOX_13 "\n";
3280      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3281      utf8_printf(p->out, BOX_13 " ");
3282      for(i=0; i<nColumn; i++){
3283        w = p->actualWidth[i];
3284        n = strlenChar(azData[i]);
3285        utf8_printf(p->out, "%*s%s%*s%s",
3286            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3287            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3288      }
3289      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3290      break;
3291    }
3292  }
3293  for(i=nColumn, j=0; i<nTotal; i++, j++){
3294    if( j==0 && p->cMode!=MODE_Column ){
3295      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3296    }
3297    z = azData[i];
3298    if( z==0 ) z = p->nullValue;
3299    w = p->actualWidth[j];
3300    if( p->colWidth[j]<0 ) w = -w;
3301    utf8_width_print(p->out, w, z);
3302    if( j==nColumn-1 ){
3303      utf8_printf(p->out, "%s", rowSep);
3304      j = -1;
3305      if( seenInterrupt ) goto columnar_end;
3306    }else{
3307      utf8_printf(p->out, "%s", colSep);
3308    }
3309  }
3310  if( p->cMode==MODE_Table ){
3311    print_row_separator(p, nColumn, "+");
3312  }else if( p->cMode==MODE_Box ){
3313    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3314  }
3315columnar_end:
3316  if( seenInterrupt ){
3317    utf8_printf(p->out, "Interrupt\n");
3318  }
3319  nData = (nRow+1)*nColumn;
3320  for(i=0; i<nData; i++) free(azData[i]);
3321  sqlite3_free(azData);
3322}
3323
3324/*
3325** Run a prepared statement
3326*/
3327static void exec_prepared_stmt(
3328  ShellState *pArg,                                /* Pointer to ShellState */
3329  sqlite3_stmt *pStmt                              /* Statment to run */
3330){
3331  int rc;
3332  sqlite3_uint64 nRow = 0;
3333
3334  if( pArg->cMode==MODE_Column
3335   || pArg->cMode==MODE_Table
3336   || pArg->cMode==MODE_Box
3337   || pArg->cMode==MODE_Markdown
3338  ){
3339    exec_prepared_stmt_columnar(pArg, pStmt);
3340    return;
3341  }
3342
3343  /* perform the first step.  this will tell us if we
3344  ** have a result set or not and how wide it is.
3345  */
3346  rc = sqlite3_step(pStmt);
3347  /* if we have a result set... */
3348  if( SQLITE_ROW == rc ){
3349    /* allocate space for col name ptr, value ptr, and type */
3350    int nCol = sqlite3_column_count(pStmt);
3351    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3352    if( !pData ){
3353      shell_out_of_memory();
3354    }else{
3355      char **azCols = (char **)pData;      /* Names of result columns */
3356      char **azVals = &azCols[nCol];       /* Results */
3357      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3358      int i, x;
3359      assert(sizeof(int) <= sizeof(char *));
3360      /* save off ptrs to column names */
3361      for(i=0; i<nCol; i++){
3362        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3363      }
3364      do{
3365        nRow++;
3366        /* extract the data and data types */
3367        for(i=0; i<nCol; i++){
3368          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3369          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3370            azVals[i] = "";
3371          }else{
3372            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3373          }
3374          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3375            rc = SQLITE_NOMEM;
3376            break; /* from for */
3377          }
3378        } /* end for */
3379
3380        /* if data and types extracted successfully... */
3381        if( SQLITE_ROW == rc ){
3382          /* call the supplied callback with the result row data */
3383          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3384            rc = SQLITE_ABORT;
3385          }else{
3386            rc = sqlite3_step(pStmt);
3387          }
3388        }
3389      } while( SQLITE_ROW == rc );
3390      sqlite3_free(pData);
3391      if( pArg->cMode==MODE_Json ){
3392        fputs("]\n", pArg->out);
3393      }else if( pArg->cMode==MODE_Count ){
3394        char zBuf[200];
3395        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3396                         nRow, nRow!=1 ? "s" : "");
3397        printf("%s", zBuf);
3398      }
3399    }
3400  }
3401}
3402
3403#ifndef SQLITE_OMIT_VIRTUALTABLE
3404/*
3405** This function is called to process SQL if the previous shell command
3406** was ".expert". It passes the SQL in the second argument directly to
3407** the sqlite3expert object.
3408**
3409** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3410** code. In this case, (*pzErr) may be set to point to a buffer containing
3411** an English language error message. It is the responsibility of the
3412** caller to eventually free this buffer using sqlite3_free().
3413*/
3414static int expertHandleSQL(
3415  ShellState *pState,
3416  const char *zSql,
3417  char **pzErr
3418){
3419  assert( pState->expert.pExpert );
3420  assert( pzErr==0 || *pzErr==0 );
3421  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3422}
3423
3424/*
3425** This function is called either to silently clean up the object
3426** created by the ".expert" command (if bCancel==1), or to generate a
3427** report from it and then clean it up (if bCancel==0).
3428**
3429** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3430** code. In this case, (*pzErr) may be set to point to a buffer containing
3431** an English language error message. It is the responsibility of the
3432** caller to eventually free this buffer using sqlite3_free().
3433*/
3434static int expertFinish(
3435  ShellState *pState,
3436  int bCancel,
3437  char **pzErr
3438){
3439  int rc = SQLITE_OK;
3440  sqlite3expert *p = pState->expert.pExpert;
3441  assert( p );
3442  assert( bCancel || pzErr==0 || *pzErr==0 );
3443  if( bCancel==0 ){
3444    FILE *out = pState->out;
3445    int bVerbose = pState->expert.bVerbose;
3446
3447    rc = sqlite3_expert_analyze(p, pzErr);
3448    if( rc==SQLITE_OK ){
3449      int nQuery = sqlite3_expert_count(p);
3450      int i;
3451
3452      if( bVerbose ){
3453        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3454        raw_printf(out, "-- Candidates -----------------------------\n");
3455        raw_printf(out, "%s\n", zCand);
3456      }
3457      for(i=0; i<nQuery; i++){
3458        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3459        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3460        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3461        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3462        if( bVerbose ){
3463          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3464          raw_printf(out, "%s\n\n", zSql);
3465        }
3466        raw_printf(out, "%s\n", zIdx);
3467        raw_printf(out, "%s\n", zEQP);
3468      }
3469    }
3470  }
3471  sqlite3_expert_destroy(p);
3472  pState->expert.pExpert = 0;
3473  return rc;
3474}
3475
3476/*
3477** Implementation of ".expert" dot command.
3478*/
3479static int expertDotCommand(
3480  ShellState *pState,             /* Current shell tool state */
3481  char **azArg,                   /* Array of arguments passed to dot command */
3482  int nArg                        /* Number of entries in azArg[] */
3483){
3484  int rc = SQLITE_OK;
3485  char *zErr = 0;
3486  int i;
3487  int iSample = 0;
3488
3489  assert( pState->expert.pExpert==0 );
3490  memset(&pState->expert, 0, sizeof(ExpertInfo));
3491
3492  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3493    char *z = azArg[i];
3494    int n;
3495    if( z[0]=='-' && z[1]=='-' ) z++;
3496    n = strlen30(z);
3497    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3498      pState->expert.bVerbose = 1;
3499    }
3500    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3501      if( i==(nArg-1) ){
3502        raw_printf(stderr, "option requires an argument: %s\n", z);
3503        rc = SQLITE_ERROR;
3504      }else{
3505        iSample = (int)integerValue(azArg[++i]);
3506        if( iSample<0 || iSample>100 ){
3507          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3508          rc = SQLITE_ERROR;
3509        }
3510      }
3511    }
3512    else{
3513      raw_printf(stderr, "unknown option: %s\n", z);
3514      rc = SQLITE_ERROR;
3515    }
3516  }
3517
3518  if( rc==SQLITE_OK ){
3519    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3520    if( pState->expert.pExpert==0 ){
3521      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3522      rc = SQLITE_ERROR;
3523    }else{
3524      sqlite3_expert_config(
3525          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3526      );
3527    }
3528  }
3529  sqlite3_free(zErr);
3530
3531  return rc;
3532}
3533#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3534
3535/*
3536** Execute a statement or set of statements.  Print
3537** any result rows/columns depending on the current mode
3538** set via the supplied callback.
3539**
3540** This is very similar to SQLite's built-in sqlite3_exec()
3541** function except it takes a slightly different callback
3542** and callback data argument.
3543*/
3544static int shell_exec(
3545  ShellState *pArg,                         /* Pointer to ShellState */
3546  const char *zSql,                         /* SQL to be evaluated */
3547  char **pzErrMsg                           /* Error msg written here */
3548){
3549  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3550  int rc = SQLITE_OK;             /* Return Code */
3551  int rc2;
3552  const char *zLeftover;          /* Tail of unprocessed SQL */
3553  sqlite3 *db = pArg->db;
3554
3555  if( pzErrMsg ){
3556    *pzErrMsg = NULL;
3557  }
3558
3559#ifndef SQLITE_OMIT_VIRTUALTABLE
3560  if( pArg->expert.pExpert ){
3561    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3562    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3563  }
3564#endif
3565
3566  while( zSql[0] && (SQLITE_OK == rc) ){
3567    static const char *zStmtSql;
3568    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3569    if( SQLITE_OK != rc ){
3570      if( pzErrMsg ){
3571        *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)%s", rc, zSql);
3572      }
3573    }else{
3574      if( !pStmt ){
3575        /* this happens for a comment or white-space */
3576        zSql = zLeftover;
3577        while( IsSpace(zSql[0]) ) zSql++;
3578        continue;
3579      }
3580      zStmtSql = sqlite3_sql(pStmt);
3581      if( zStmtSql==0 ) zStmtSql = "";
3582      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3583
3584      /* save off the prepared statment handle and reset row count */
3585      if( pArg ){
3586        pArg->pStmt = pStmt;
3587        pArg->cnt = 0;
3588      }
3589
3590      /* echo the sql statement if echo on */
3591      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3592        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3593      }
3594
3595      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3596      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3597        sqlite3_stmt *pExplain;
3598        char *zEQP;
3599        int triggerEQP = 0;
3600        disable_debug_trace_modes();
3601        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3602        if( pArg->autoEQP>=AUTOEQP_trigger ){
3603          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3604        }
3605        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3606        shell_check_oom(zEQP);
3607        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3608        if( rc==SQLITE_OK ){
3609          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3610            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3611            int iEqpId = sqlite3_column_int(pExplain, 0);
3612            int iParentId = sqlite3_column_int(pExplain, 1);
3613            if( zEQPLine==0 ) zEQPLine = "";
3614            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3615            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3616          }
3617          eqp_render(pArg);
3618        }
3619        sqlite3_finalize(pExplain);
3620        sqlite3_free(zEQP);
3621        if( pArg->autoEQP>=AUTOEQP_full ){
3622          /* Also do an EXPLAIN for ".eqp full" mode */
3623          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3624          shell_check_oom(zEQP);
3625          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3626          if( rc==SQLITE_OK ){
3627            pArg->cMode = MODE_Explain;
3628            explain_data_prepare(pArg, pExplain);
3629            exec_prepared_stmt(pArg, pExplain);
3630            explain_data_delete(pArg);
3631          }
3632          sqlite3_finalize(pExplain);
3633          sqlite3_free(zEQP);
3634        }
3635        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3636          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3637          /* Reprepare pStmt before reactiving trace modes */
3638          sqlite3_finalize(pStmt);
3639          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3640          if( pArg ) pArg->pStmt = pStmt;
3641        }
3642        restore_debug_trace_modes();
3643      }
3644
3645      if( pArg ){
3646        pArg->cMode = pArg->mode;
3647        if( pArg->autoExplain ){
3648          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3649            pArg->cMode = MODE_Explain;
3650          }
3651          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3652            pArg->cMode = MODE_EQP;
3653          }
3654        }
3655
3656        /* If the shell is currently in ".explain" mode, gather the extra
3657        ** data required to add indents to the output.*/
3658        if( pArg->cMode==MODE_Explain ){
3659          explain_data_prepare(pArg, pStmt);
3660        }
3661      }
3662
3663      bind_prepared_stmt(pArg, pStmt);
3664      exec_prepared_stmt(pArg, pStmt);
3665      explain_data_delete(pArg);
3666      eqp_render(pArg);
3667
3668      /* print usage stats if stats on */
3669      if( pArg && pArg->statsOn ){
3670        display_stats(db, pArg, 0);
3671      }
3672
3673      /* print loop-counters if required */
3674      if( pArg && pArg->scanstatsOn ){
3675        display_scanstats(db, pArg);
3676      }
3677
3678      /* Finalize the statement just executed. If this fails, save a
3679      ** copy of the error message. Otherwise, set zSql to point to the
3680      ** next statement to execute. */
3681      rc2 = sqlite3_finalize(pStmt);
3682      if( rc!=SQLITE_NOMEM ) rc = rc2;
3683      if( rc==SQLITE_OK ){
3684        zSql = zLeftover;
3685        while( IsSpace(zSql[0]) ) zSql++;
3686      }else if( pzErrMsg ){
3687        *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc, 0);
3688      }
3689
3690      /* clear saved stmt handle */
3691      if( pArg ){
3692        pArg->pStmt = NULL;
3693      }
3694    }
3695  } /* end while */
3696
3697  return rc;
3698}
3699
3700/*
3701** Release memory previously allocated by tableColumnList().
3702*/
3703static void freeColumnList(char **azCol){
3704  int i;
3705  for(i=1; azCol[i]; i++){
3706    sqlite3_free(azCol[i]);
3707  }
3708  /* azCol[0] is a static string */
3709  sqlite3_free(azCol);
3710}
3711
3712/*
3713** Return a list of pointers to strings which are the names of all
3714** columns in table zTab.   The memory to hold the names is dynamically
3715** allocated and must be released by the caller using a subsequent call
3716** to freeColumnList().
3717**
3718** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3719** value that needs to be preserved, then azCol[0] is filled in with the
3720** name of the rowid column.
3721**
3722** The first regular column in the table is azCol[1].  The list is terminated
3723** by an entry with azCol[i]==0.
3724*/
3725static char **tableColumnList(ShellState *p, const char *zTab){
3726  char **azCol = 0;
3727  sqlite3_stmt *pStmt;
3728  char *zSql;
3729  int nCol = 0;
3730  int nAlloc = 0;
3731  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3732  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3733  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3734  int rc;
3735
3736  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3737  shell_check_oom(zSql);
3738  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3739  sqlite3_free(zSql);
3740  if( rc ) return 0;
3741  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3742    if( nCol>=nAlloc-2 ){
3743      nAlloc = nAlloc*2 + nCol + 10;
3744      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3745      shell_check_oom(azCol);
3746    }
3747    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3748    shell_check_oom(azCol[nCol]);
3749    if( sqlite3_column_int(pStmt, 5) ){
3750      nPK++;
3751      if( nPK==1
3752       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3753                          "INTEGER")==0
3754      ){
3755        isIPK = 1;
3756      }else{
3757        isIPK = 0;
3758      }
3759    }
3760  }
3761  sqlite3_finalize(pStmt);
3762  if( azCol==0 ) return 0;
3763  azCol[0] = 0;
3764  azCol[nCol+1] = 0;
3765
3766  /* The decision of whether or not a rowid really needs to be preserved
3767  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3768  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3769  ** rowids on tables where the rowid is inaccessible because there are other
3770  ** columns in the table named "rowid", "_rowid_", and "oid".
3771  */
3772  if( preserveRowid && isIPK ){
3773    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3774    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3775    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3776    ** ROWID aliases.  To distinguish these cases, check to see if
3777    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3778    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3779    */
3780    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3781                           " WHERE origin='pk'", zTab);
3782    shell_check_oom(zSql);
3783    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3784    sqlite3_free(zSql);
3785    if( rc ){
3786      freeColumnList(azCol);
3787      return 0;
3788    }
3789    rc = sqlite3_step(pStmt);
3790    sqlite3_finalize(pStmt);
3791    preserveRowid = rc==SQLITE_ROW;
3792  }
3793  if( preserveRowid ){
3794    /* Only preserve the rowid if we can find a name to use for the
3795    ** rowid */
3796    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3797    int i, j;
3798    for(j=0; j<3; j++){
3799      for(i=1; i<=nCol; i++){
3800        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3801      }
3802      if( i>nCol ){
3803        /* At this point, we know that azRowid[j] is not the name of any
3804        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3805        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3806        ** tables will fail this last check */
3807        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3808        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3809        break;
3810      }
3811    }
3812  }
3813  return azCol;
3814}
3815
3816/*
3817** Toggle the reverse_unordered_selects setting.
3818*/
3819static void toggleSelectOrder(sqlite3 *db){
3820  sqlite3_stmt *pStmt = 0;
3821  int iSetting = 0;
3822  char zStmt[100];
3823  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3824  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3825    iSetting = sqlite3_column_int(pStmt, 0);
3826  }
3827  sqlite3_finalize(pStmt);
3828  sqlite3_snprintf(sizeof(zStmt), zStmt,
3829       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3830  sqlite3_exec(db, zStmt, 0, 0, 0);
3831}
3832
3833/*
3834** This is a different callback routine used for dumping the database.
3835** Each row received by this callback consists of a table name,
3836** the table type ("index" or "table") and SQL to create the table.
3837** This routine should print text sufficient to recreate the table.
3838*/
3839static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3840  int rc;
3841  const char *zTable;
3842  const char *zType;
3843  const char *zSql;
3844  ShellState *p = (ShellState *)pArg;
3845  int dataOnly;
3846  int noSys;
3847
3848  UNUSED_PARAMETER(azNotUsed);
3849  if( nArg!=3 || azArg==0 ) return 0;
3850  zTable = azArg[0];
3851  zType = azArg[1];
3852  zSql = azArg[2];
3853  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
3854  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
3855
3856  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
3857    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3858  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
3859    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3860  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3861    return 0;
3862  }else if( dataOnly ){
3863    /* no-op */
3864  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3865    char *zIns;
3866    if( !p->writableSchema ){
3867      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3868      p->writableSchema = 1;
3869    }
3870    zIns = sqlite3_mprintf(
3871       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3872       "VALUES('table','%q','%q',0,'%q');",
3873       zTable, zTable, zSql);
3874    shell_check_oom(zIns);
3875    utf8_printf(p->out, "%s\n", zIns);
3876    sqlite3_free(zIns);
3877    return 0;
3878  }else{
3879    printSchemaLine(p->out, zSql, ";\n");
3880  }
3881
3882  if( strcmp(zType, "table")==0 ){
3883    ShellText sSelect;
3884    ShellText sTable;
3885    char **azCol;
3886    int i;
3887    char *savedDestTable;
3888    int savedMode;
3889
3890    azCol = tableColumnList(p, zTable);
3891    if( azCol==0 ){
3892      p->nErr++;
3893      return 0;
3894    }
3895
3896    /* Always quote the table name, even if it appears to be pure ascii,
3897    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3898    initText(&sTable);
3899    appendText(&sTable, zTable, quoteChar(zTable));
3900    /* If preserving the rowid, add a column list after the table name.
3901    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3902    ** instead of the usual "INSERT INTO tab VALUES(...)".
3903    */
3904    if( azCol[0] ){
3905      appendText(&sTable, "(", 0);
3906      appendText(&sTable, azCol[0], 0);
3907      for(i=1; azCol[i]; i++){
3908        appendText(&sTable, ",", 0);
3909        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3910      }
3911      appendText(&sTable, ")", 0);
3912    }
3913
3914    /* Build an appropriate SELECT statement */
3915    initText(&sSelect);
3916    appendText(&sSelect, "SELECT ", 0);
3917    if( azCol[0] ){
3918      appendText(&sSelect, azCol[0], 0);
3919      appendText(&sSelect, ",", 0);
3920    }
3921    for(i=1; azCol[i]; i++){
3922      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3923      if( azCol[i+1] ){
3924        appendText(&sSelect, ",", 0);
3925      }
3926    }
3927    freeColumnList(azCol);
3928    appendText(&sSelect, " FROM ", 0);
3929    appendText(&sSelect, zTable, quoteChar(zTable));
3930
3931    savedDestTable = p->zDestTable;
3932    savedMode = p->mode;
3933    p->zDestTable = sTable.z;
3934    p->mode = p->cMode = MODE_Insert;
3935    rc = shell_exec(p, sSelect.z, 0);
3936    if( (rc&0xff)==SQLITE_CORRUPT ){
3937      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3938      toggleSelectOrder(p->db);
3939      shell_exec(p, sSelect.z, 0);
3940      toggleSelectOrder(p->db);
3941    }
3942    p->zDestTable = savedDestTable;
3943    p->mode = savedMode;
3944    freeText(&sTable);
3945    freeText(&sSelect);
3946    if( rc ) p->nErr++;
3947  }
3948  return 0;
3949}
3950
3951/*
3952** Run zQuery.  Use dump_callback() as the callback routine so that
3953** the contents of the query are output as SQL statements.
3954**
3955** If we get a SQLITE_CORRUPT error, rerun the query after appending
3956** "ORDER BY rowid DESC" to the end.
3957*/
3958static int run_schema_dump_query(
3959  ShellState *p,
3960  const char *zQuery
3961){
3962  int rc;
3963  char *zErr = 0;
3964  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3965  if( rc==SQLITE_CORRUPT ){
3966    char *zQ2;
3967    int len = strlen30(zQuery);
3968    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3969    if( zErr ){
3970      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3971      sqlite3_free(zErr);
3972      zErr = 0;
3973    }
3974    zQ2 = malloc( len+100 );
3975    if( zQ2==0 ) return rc;
3976    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3977    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3978    if( rc ){
3979      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3980    }else{
3981      rc = SQLITE_CORRUPT;
3982    }
3983    sqlite3_free(zErr);
3984    free(zQ2);
3985  }
3986  return rc;
3987}
3988
3989/*
3990** Text of help messages.
3991**
3992** The help text for each individual command begins with a line that starts
3993** with ".".  Subsequent lines are supplimental information.
3994**
3995** There must be two or more spaces between the end of the command and the
3996** start of the description of what that command does.
3997*/
3998static const char *(azHelp[]) = {
3999#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
4000  ".archive ...             Manage SQL archives",
4001  "   Each command must have exactly one of the following options:",
4002  "     -c, --create               Create a new archive",
4003  "     -u, --update               Add or update files with changed mtime",
4004  "     -i, --insert               Like -u but always add even if unchanged",
4005  "     -r, --remove               Remove files from archive",
4006  "     -t, --list                 List contents of archive",
4007  "     -x, --extract              Extract files from archive",
4008  "   Optional arguments:",
4009  "     -v, --verbose              Print each filename as it is processed",
4010  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4011  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4012  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4013  "     -g, --glob                 Use glob matching for names in archive",
4014  "     -n, --dryrun               Show the SQL that would have occurred",
4015  "   Examples:",
4016  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4017  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4018  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4019  "   See also:",
4020  "      http://sqlite.org/cli.html#sqlite_archive_support",
4021#endif
4022#ifndef SQLITE_OMIT_AUTHORIZATION
4023  ".auth ON|OFF             Show authorizer callbacks",
4024#endif
4025  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4026  "       --append            Use the appendvfs",
4027  "       --async             Write to FILE without journal and fsync()",
4028  ".bail on|off             Stop after hitting an error.  Default OFF",
4029  ".binary on|off           Turn binary output on or off.  Default OFF",
4030  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4031  ".changes on|off          Show number of rows changed by SQL",
4032  ".check GLOB              Fail if output since .testcase does not match",
4033  ".clone NEWDB             Clone data into NEWDB from the existing database",
4034  ".connection [close] [#]  Open or close an auxiliary database connection",
4035  ".databases               List names and files of attached databases",
4036  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4037  ".dbinfo ?DB?             Show status information about the database",
4038  ".dump ?OBJECTS?          Render database content as SQL",
4039  "   Options:",
4040  "     --data-only            Output only INSERT statements",
4041  "     --newlines             Allow unescaped newline characters in output",
4042  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4043  "     --preserve-rowids      Include ROWID values in the output",
4044  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4045  "   Additional LIKE patterns can be given in subsequent arguments",
4046  ".echo on|off             Turn command echo on or off",
4047  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4048  "   Other Modes:",
4049#ifdef SQLITE_DEBUG
4050  "      test                  Show raw EXPLAIN QUERY PLAN output",
4051  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4052#endif
4053  "      trigger               Like \"full\" but also show trigger bytecode",
4054  ".excel                   Display the output of next command in spreadsheet",
4055  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4056  ".exit ?CODE?             Exit this program with return-code CODE",
4057  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4058  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4059  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4060  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4061  "   --help                  Show CMD details",
4062  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4063  ".headers on|off          Turn display of headers on or off",
4064  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4065  ".import FILE TABLE       Import data from FILE into TABLE",
4066  "   Options:",
4067  "     --ascii               Use \\037 and \\036 as column and row separators",
4068  "     --csv                 Use , and \\n as column and row separators",
4069  "     --skip N              Skip the first N rows of input",
4070  "     -v                    \"Verbose\" - increase auxiliary output",
4071  "   Notes:",
4072  "     *  If TABLE does not exist, it is created.  The first row of input",
4073  "        determines the column names.",
4074  "     *  If neither --csv or --ascii are used, the input mode is derived",
4075  "        from the \".mode\" output mode",
4076  "     *  If FILE begins with \"|\" then it is a command that generates the",
4077  "        input text.",
4078#ifndef SQLITE_OMIT_TEST_CONTROL
4079  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4080#endif
4081  ".indexes ?TABLE?         Show names of indexes",
4082  "                           If TABLE is specified, only show indexes for",
4083  "                           tables matching TABLE using the LIKE operator.",
4084#ifdef SQLITE_ENABLE_IOTRACE
4085  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4086#endif
4087  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4088  ".lint OPTIONS            Report potential schema issues.",
4089  "     Options:",
4090  "        fkey-indexes     Find missing foreign key indexes",
4091#ifndef SQLITE_OMIT_LOAD_EXTENSION
4092  ".load FILE ?ENTRY?       Load an extension library",
4093#endif
4094  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4095  ".mode MODE ?TABLE?       Set output mode",
4096  "   MODE is one of:",
4097  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
4098  "     box       Tables using unicode box-drawing characters",
4099  "     csv       Comma-separated values",
4100  "     column    Output in columns.  (See .width)",
4101  "     html      HTML <table> code",
4102  "     insert    SQL insert statements for TABLE",
4103  "     json      Results in a JSON array",
4104  "     line      One value per line",
4105  "     list      Values delimited by \"|\"",
4106  "     markdown  Markdown table format",
4107  "     quote     Escape answers as for SQL",
4108  "     table     ASCII-art table",
4109  "     tabs      Tab-separated values",
4110  "     tcl       TCL list elements",
4111  ".nonce STRING            Disable safe mode for one command if the nonce matches",
4112  ".nullvalue STRING        Use STRING in place of NULL values",
4113  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4114  "     If FILE begins with '|' then open as a pipe",
4115  "       --bom  Put a UTF8 byte-order mark at the beginning",
4116  "       -e     Send output to the system text editor",
4117  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4118  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4119  "     Options:",
4120  "        --append        Use appendvfs to append database to the end of FILE",
4121#ifndef SQLITE_OMIT_DESERIALIZE
4122  "        --deserialize   Load into memory using sqlite3_deserialize()",
4123  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4124  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4125#endif
4126  "        --new           Initialize FILE to an empty database",
4127  "        --nofollow      Do not follow symbolic links",
4128  "        --readonly      Open FILE readonly",
4129  "        --zip           FILE is a ZIP archive",
4130  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4131  "   If FILE begins with '|' then open it as a pipe.",
4132  "   Options:",
4133  "     --bom                 Prefix output with a UTF8 byte-order mark",
4134  "     -e                    Send output to the system text editor",
4135  "     -x                    Send output as CSV to a spreadsheet",
4136  ".parameter CMD ...       Manage SQL parameter bindings",
4137  "   clear                   Erase all bindings",
4138  "   init                    Initialize the TEMP table that holds bindings",
4139  "   list                    List the current parameter bindings",
4140  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4141  "                           PARAMETER should start with one of: $ : @ ?",
4142  "   unset PARAMETER         Remove PARAMETER from the binding table",
4143  ".print STRING...         Print literal STRING",
4144#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4145  ".progress N              Invoke progress handler after every N opcodes",
4146  "   --limit N                 Interrupt after N progress callbacks",
4147  "   --once                    Do no more than one progress interrupt",
4148  "   --quiet|-q                No output except at interrupts",
4149  "   --reset                   Reset the count for each input and interrupt",
4150#endif
4151  ".prompt MAIN CONTINUE    Replace the standard prompts",
4152  ".quit                    Exit this program",
4153  ".read FILE               Read input from FILE or command output",
4154  "    If FILE begins with \"|\", it is a command that generates the input.",
4155#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4156  ".recover                 Recover as much data as possible from corrupt db.",
4157  "   --freelist-corrupt       Assume the freelist is corrupt",
4158  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4159  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4160  "   --no-rowids              Do not attempt to recover rowid values",
4161  "                            that are not also INTEGER PRIMARY KEYs",
4162#endif
4163  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4164  ".save FILE               Write in-memory database into FILE",
4165  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4166  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4167  "   Options:",
4168  "      --indent             Try to pretty-print the schema",
4169  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4170  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4171  "    Options:",
4172  "       --init               Create a new SELFTEST table",
4173  "       -v                   Verbose output",
4174  ".separator COL ?ROW?     Change the column and row separators",
4175#if defined(SQLITE_ENABLE_SESSION)
4176  ".session ?NAME? CMD ...  Create or control sessions",
4177  "   Subcommands:",
4178  "     attach TABLE             Attach TABLE",
4179  "     changeset FILE           Write a changeset into FILE",
4180  "     close                    Close one session",
4181  "     enable ?BOOLEAN?         Set or query the enable bit",
4182  "     filter GLOB...           Reject tables matching GLOBs",
4183  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4184  "     isempty                  Query whether the session is empty",
4185  "     list                     List currently open session names",
4186  "     open DB NAME             Open a new session on DB",
4187  "     patchset FILE            Write a patchset into FILE",
4188  "   If ?NAME? is omitted, the first defined session is used.",
4189#endif
4190  ".sha3sum ...             Compute a SHA3 hash of database content",
4191  "    Options:",
4192  "      --schema              Also hash the sqlite_schema table",
4193  "      --sha3-224            Use the sha3-224 algorithm",
4194  "      --sha3-256            Use the sha3-256 algorithm (default)",
4195  "      --sha3-384            Use the sha3-384 algorithm",
4196  "      --sha3-512            Use the sha3-512 algorithm",
4197  "    Any other argument is a LIKE pattern for tables to hash",
4198#ifndef SQLITE_NOHAVE_SYSTEM
4199  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4200#endif
4201  ".show                    Show the current values for various settings",
4202  ".stats ?ARG?             Show stats or turn stats on or off",
4203  "   off                      Turn off automatic stat display",
4204  "   on                       Turn on automatic stat display",
4205  "   stmt                     Show statement stats",
4206  "   vmstep                   Show the virtual machine step count only",
4207#ifndef SQLITE_NOHAVE_SYSTEM
4208  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4209#endif
4210  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4211  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4212  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4213  "                           Run \".testctrl\" with no arguments for details",
4214  ".timeout MS              Try opening locked tables for MS milliseconds",
4215  ".timer on|off            Turn SQL timer on or off",
4216#ifndef SQLITE_OMIT_TRACE
4217  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4218  "    FILE                    Send output to FILE",
4219  "    stdout                  Send output to stdout",
4220  "    stderr                  Send output to stderr",
4221  "    off                     Disable tracing",
4222  "    --expanded              Expand query parameters",
4223#ifdef SQLITE_ENABLE_NORMALIZE
4224  "    --normalized            Normal the SQL statements",
4225#endif
4226  "    --plain                 Show SQL as it is input",
4227  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4228  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4229  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4230  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4231#endif /* SQLITE_OMIT_TRACE */
4232#ifdef SQLITE_DEBUG
4233  ".unmodule NAME ...       Unregister virtual table modules",
4234  "    --allexcept             Unregister everything except those named",
4235#endif
4236  ".vfsinfo ?AUX?           Information about the top-level VFS",
4237  ".vfslist                 List all available VFSes",
4238  ".vfsname ?AUX?           Print the name of the VFS stack",
4239  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4240  "     Negative values right-justify",
4241};
4242
4243/*
4244** Output help text.
4245**
4246** zPattern describes the set of commands for which help text is provided.
4247** If zPattern is NULL, then show all commands, but only give a one-line
4248** description of each.
4249**
4250** Return the number of matches.
4251*/
4252static int showHelp(FILE *out, const char *zPattern){
4253  int i = 0;
4254  int j = 0;
4255  int n = 0;
4256  char *zPat;
4257  if( zPattern==0
4258   || zPattern[0]=='0'
4259   || strcmp(zPattern,"-a")==0
4260   || strcmp(zPattern,"-all")==0
4261   || strcmp(zPattern,"--all")==0
4262  ){
4263    /* Show all commands, but only one line per command */
4264    if( zPattern==0 ) zPattern = "";
4265    for(i=0; i<ArraySize(azHelp); i++){
4266      if( azHelp[i][0]=='.' || zPattern[0] ){
4267        utf8_printf(out, "%s\n", azHelp[i]);
4268        n++;
4269      }
4270    }
4271  }else{
4272    /* Look for commands that for which zPattern is an exact prefix */
4273    zPat = sqlite3_mprintf(".%s*", zPattern);
4274    shell_check_oom(zPat);
4275    for(i=0; i<ArraySize(azHelp); i++){
4276      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4277        utf8_printf(out, "%s\n", azHelp[i]);
4278        j = i+1;
4279        n++;
4280      }
4281    }
4282    sqlite3_free(zPat);
4283    if( n ){
4284      if( n==1 ){
4285        /* when zPattern is a prefix of exactly one command, then include the
4286        ** details of that command, which should begin at offset j */
4287        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4288          utf8_printf(out, "%s\n", azHelp[j]);
4289          j++;
4290        }
4291      }
4292      return n;
4293    }
4294    /* Look for commands that contain zPattern anywhere.  Show the complete
4295    ** text of all commands that match. */
4296    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4297    shell_check_oom(zPat);
4298    for(i=0; i<ArraySize(azHelp); i++){
4299      if( azHelp[i][0]=='.' ) j = i;
4300      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4301        utf8_printf(out, "%s\n", azHelp[j]);
4302        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4303          j++;
4304          utf8_printf(out, "%s\n", azHelp[j]);
4305        }
4306        i = j;
4307        n++;
4308      }
4309    }
4310    sqlite3_free(zPat);
4311  }
4312  return n;
4313}
4314
4315/* Forward reference */
4316static int process_input(ShellState *p);
4317
4318/*
4319** Read the content of file zName into memory obtained from sqlite3_malloc64()
4320** and return a pointer to the buffer. The caller is responsible for freeing
4321** the memory.
4322**
4323** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4324** read.
4325**
4326** For convenience, a nul-terminator byte is always appended to the data read
4327** from the file before the buffer is returned. This byte is not included in
4328** the final value of (*pnByte), if applicable.
4329**
4330** NULL is returned if any error is encountered. The final value of *pnByte
4331** is undefined in this case.
4332*/
4333static char *readFile(const char *zName, int *pnByte){
4334  FILE *in = fopen(zName, "rb");
4335  long nIn;
4336  size_t nRead;
4337  char *pBuf;
4338  if( in==0 ) return 0;
4339  fseek(in, 0, SEEK_END);
4340  nIn = ftell(in);
4341  rewind(in);
4342  pBuf = sqlite3_malloc64( nIn+1 );
4343  if( pBuf==0 ){ fclose(in); return 0; }
4344  nRead = fread(pBuf, nIn, 1, in);
4345  fclose(in);
4346  if( nRead!=1 ){
4347    sqlite3_free(pBuf);
4348    return 0;
4349  }
4350  pBuf[nIn] = 0;
4351  if( pnByte ) *pnByte = nIn;
4352  return pBuf;
4353}
4354
4355#if defined(SQLITE_ENABLE_SESSION)
4356/*
4357** Close a single OpenSession object and release all of its associated
4358** resources.
4359*/
4360static void session_close(OpenSession *pSession){
4361  int i;
4362  sqlite3session_delete(pSession->p);
4363  sqlite3_free(pSession->zName);
4364  for(i=0; i<pSession->nFilter; i++){
4365    sqlite3_free(pSession->azFilter[i]);
4366  }
4367  sqlite3_free(pSession->azFilter);
4368  memset(pSession, 0, sizeof(OpenSession));
4369}
4370#endif
4371
4372/*
4373** Close all OpenSession objects and release all associated resources.
4374*/
4375#if defined(SQLITE_ENABLE_SESSION)
4376static void session_close_all(ShellState *p, int i){
4377  int j;
4378  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4379  for(j=0; j<pAuxDb->nSession; j++){
4380    session_close(&pAuxDb->aSession[j]);
4381  }
4382  pAuxDb->nSession = 0;
4383}
4384#else
4385# define session_close_all(X,Y)
4386#endif
4387
4388/*
4389** Implementation of the xFilter function for an open session.  Omit
4390** any tables named by ".session filter" but let all other table through.
4391*/
4392#if defined(SQLITE_ENABLE_SESSION)
4393static int session_filter(void *pCtx, const char *zTab){
4394  OpenSession *pSession = (OpenSession*)pCtx;
4395  int i;
4396  for(i=0; i<pSession->nFilter; i++){
4397    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4398  }
4399  return 1;
4400}
4401#endif
4402
4403/*
4404** Try to deduce the type of file for zName based on its content.  Return
4405** one of the SHELL_OPEN_* constants.
4406**
4407** If the file does not exist or is empty but its name looks like a ZIP
4408** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4409** Otherwise, assume an ordinary database regardless of the filename if
4410** the type cannot be determined from content.
4411*/
4412int deduceDatabaseType(const char *zName, int dfltZip){
4413  FILE *f = fopen(zName, "rb");
4414  size_t n;
4415  int rc = SHELL_OPEN_UNSPEC;
4416  char zBuf[100];
4417  if( f==0 ){
4418    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4419       return SHELL_OPEN_ZIPFILE;
4420    }else{
4421       return SHELL_OPEN_NORMAL;
4422    }
4423  }
4424  n = fread(zBuf, 16, 1, f);
4425  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4426    fclose(f);
4427    return SHELL_OPEN_NORMAL;
4428  }
4429  fseek(f, -25, SEEK_END);
4430  n = fread(zBuf, 25, 1, f);
4431  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4432    rc = SHELL_OPEN_APPENDVFS;
4433  }else{
4434    fseek(f, -22, SEEK_END);
4435    n = fread(zBuf, 22, 1, f);
4436    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4437       && zBuf[3]==0x06 ){
4438      rc = SHELL_OPEN_ZIPFILE;
4439    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4440      rc = SHELL_OPEN_ZIPFILE;
4441    }
4442  }
4443  fclose(f);
4444  return rc;
4445}
4446
4447#ifndef SQLITE_OMIT_DESERIALIZE
4448/*
4449** Reconstruct an in-memory database using the output from the "dbtotxt"
4450** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4451** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4452*/
4453static unsigned char *readHexDb(ShellState *p, int *pnData){
4454  unsigned char *a = 0;
4455  int nLine;
4456  int n = 0;
4457  int pgsz = 0;
4458  int iOffset = 0;
4459  int j, k;
4460  int rc;
4461  FILE *in;
4462  const char *zDbFilename = p->pAuxDb->zDbFilename;
4463  unsigned int x[16];
4464  char zLine[1000];
4465  if( zDbFilename ){
4466    in = fopen(zDbFilename, "r");
4467    if( in==0 ){
4468      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4469      return 0;
4470    }
4471    nLine = 0;
4472  }else{
4473    in = p->in;
4474    nLine = p->lineno;
4475    if( in==0 ) in = stdin;
4476  }
4477  *pnData = 0;
4478  nLine++;
4479  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4480  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4481  if( rc!=2 ) goto readHexDb_error;
4482  if( n<0 ) goto readHexDb_error;
4483  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4484  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4485  a = sqlite3_malloc( n ? n : 1 );
4486  shell_check_oom(a);
4487  memset(a, 0, n);
4488  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4489    utf8_printf(stderr, "invalid pagesize\n");
4490    goto readHexDb_error;
4491  }
4492  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4493    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4494    if( rc==2 ){
4495      iOffset = k;
4496      continue;
4497    }
4498    if( strncmp(zLine, "| end ", 6)==0 ){
4499      break;
4500    }
4501    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4502                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4503                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4504    if( rc==17 ){
4505      k = iOffset+j;
4506      if( k+16<=n && k>=0 ){
4507        int ii;
4508        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4509      }
4510    }
4511  }
4512  *pnData = n;
4513  if( in!=p->in ){
4514    fclose(in);
4515  }else{
4516    p->lineno = nLine;
4517  }
4518  return a;
4519
4520readHexDb_error:
4521  if( in!=p->in ){
4522    fclose(in);
4523  }else{
4524    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4525      nLine++;
4526      if(strncmp(zLine, "| end ", 6)==0 ) break;
4527    }
4528    p->lineno = nLine;
4529  }
4530  sqlite3_free(a);
4531  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4532  return 0;
4533}
4534#endif /* SQLITE_OMIT_DESERIALIZE */
4535
4536/*
4537** Scalar function "shell_int32". The first argument to this function
4538** must be a blob. The second a non-negative integer. This function
4539** reads and returns a 32-bit big-endian integer from byte
4540** offset (4*<arg2>) of the blob.
4541*/
4542static void shellInt32(
4543  sqlite3_context *context,
4544  int argc,
4545  sqlite3_value **argv
4546){
4547  const unsigned char *pBlob;
4548  int nBlob;
4549  int iInt;
4550
4551  UNUSED_PARAMETER(argc);
4552  nBlob = sqlite3_value_bytes(argv[0]);
4553  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4554  iInt = sqlite3_value_int(argv[1]);
4555
4556  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4557    const unsigned char *a = &pBlob[iInt*4];
4558    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4559                       + ((sqlite3_int64)a[1]<<16)
4560                       + ((sqlite3_int64)a[2]<< 8)
4561                       + ((sqlite3_int64)a[3]<< 0);
4562    sqlite3_result_int64(context, iVal);
4563  }
4564}
4565
4566/*
4567** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4568** using "..." with internal double-quote characters doubled.
4569*/
4570static void shellIdQuote(
4571  sqlite3_context *context,
4572  int argc,
4573  sqlite3_value **argv
4574){
4575  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4576  UNUSED_PARAMETER(argc);
4577  if( zName ){
4578    char *z = sqlite3_mprintf("\"%w\"", zName);
4579    sqlite3_result_text(context, z, -1, sqlite3_free);
4580  }
4581}
4582
4583/*
4584** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4585*/
4586static void shellUSleepFunc(
4587  sqlite3_context *context,
4588  int argcUnused,
4589  sqlite3_value **argv
4590){
4591  int sleep = sqlite3_value_int(argv[0]);
4592  (void)argcUnused;
4593  sqlite3_sleep(sleep/1000);
4594  sqlite3_result_int(context, sleep);
4595}
4596
4597/*
4598** Scalar function "shell_escape_crnl" used by the .recover command.
4599** The argument passed to this function is the output of built-in
4600** function quote(). If the first character of the input is "'",
4601** indicating that the value passed to quote() was a text value,
4602** then this function searches the input for "\n" and "\r" characters
4603** and adds a wrapper similar to the following:
4604**
4605**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4606**
4607** Or, if the first character of the input is not "'", then a copy
4608** of the input is returned.
4609*/
4610static void shellEscapeCrnl(
4611  sqlite3_context *context,
4612  int argc,
4613  sqlite3_value **argv
4614){
4615  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4616  UNUSED_PARAMETER(argc);
4617  if( zText && zText[0]=='\'' ){
4618    int nText = sqlite3_value_bytes(argv[0]);
4619    int i;
4620    char zBuf1[20];
4621    char zBuf2[20];
4622    const char *zNL = 0;
4623    const char *zCR = 0;
4624    int nCR = 0;
4625    int nNL = 0;
4626
4627    for(i=0; zText[i]; i++){
4628      if( zNL==0 && zText[i]=='\n' ){
4629        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4630        nNL = (int)strlen(zNL);
4631      }
4632      if( zCR==0 && zText[i]=='\r' ){
4633        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4634        nCR = (int)strlen(zCR);
4635      }
4636    }
4637
4638    if( zNL || zCR ){
4639      int iOut = 0;
4640      i64 nMax = (nNL > nCR) ? nNL : nCR;
4641      i64 nAlloc = nMax * nText + (nMax+64)*2;
4642      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4643      if( zOut==0 ){
4644        sqlite3_result_error_nomem(context);
4645        return;
4646      }
4647
4648      if( zNL && zCR ){
4649        memcpy(&zOut[iOut], "replace(replace(", 16);
4650        iOut += 16;
4651      }else{
4652        memcpy(&zOut[iOut], "replace(", 8);
4653        iOut += 8;
4654      }
4655      for(i=0; zText[i]; i++){
4656        if( zText[i]=='\n' ){
4657          memcpy(&zOut[iOut], zNL, nNL);
4658          iOut += nNL;
4659        }else if( zText[i]=='\r' ){
4660          memcpy(&zOut[iOut], zCR, nCR);
4661          iOut += nCR;
4662        }else{
4663          zOut[iOut] = zText[i];
4664          iOut++;
4665        }
4666      }
4667
4668      if( zNL ){
4669        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4670        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4671        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4672      }
4673      if( zCR ){
4674        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4675        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4676        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4677      }
4678
4679      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4680      sqlite3_free(zOut);
4681      return;
4682    }
4683  }
4684
4685  sqlite3_result_value(context, argv[0]);
4686}
4687
4688/* Flags for open_db().
4689**
4690** The default behavior of open_db() is to exit(1) if the database fails to
4691** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4692** but still returns without calling exit.
4693**
4694** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4695** ZIP archive if the file does not exist or is empty and its name matches
4696** the *.zip pattern.
4697*/
4698#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4699#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4700
4701/*
4702** Make sure the database is open.  If it is not, then open it.  If
4703** the database fails to open, print an error message and exit.
4704*/
4705static void open_db(ShellState *p, int openFlags){
4706  if( p->db==0 ){
4707    const char *zDbFilename = p->pAuxDb->zDbFilename;
4708    if( p->openMode==SHELL_OPEN_UNSPEC ){
4709      if( zDbFilename==0 || zDbFilename[0]==0 ){
4710        p->openMode = SHELL_OPEN_NORMAL;
4711      }else{
4712        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4713                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4714      }
4715    }
4716    switch( p->openMode ){
4717      case SHELL_OPEN_APPENDVFS: {
4718        sqlite3_open_v2(zDbFilename, &p->db,
4719           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4720        break;
4721      }
4722      case SHELL_OPEN_HEXDB:
4723      case SHELL_OPEN_DESERIALIZE: {
4724        sqlite3_open(0, &p->db);
4725        break;
4726      }
4727      case SHELL_OPEN_ZIPFILE: {
4728        sqlite3_open(":memory:", &p->db);
4729        break;
4730      }
4731      case SHELL_OPEN_READONLY: {
4732        sqlite3_open_v2(zDbFilename, &p->db,
4733            SQLITE_OPEN_READONLY|p->openFlags, 0);
4734        break;
4735      }
4736      case SHELL_OPEN_UNSPEC:
4737      case SHELL_OPEN_NORMAL: {
4738        sqlite3_open_v2(zDbFilename, &p->db,
4739           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4740        break;
4741      }
4742    }
4743    globalDb = p->db;
4744    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4745      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4746          zDbFilename, sqlite3_errmsg(p->db));
4747      if( openFlags & OPEN_DB_KEEPALIVE ){
4748        sqlite3_open(":memory:", &p->db);
4749        return;
4750      }
4751      exit(1);
4752    }
4753#ifndef SQLITE_OMIT_LOAD_EXTENSION
4754    sqlite3_enable_load_extension(p->db, 1);
4755#endif
4756    sqlite3_fileio_init(p->db, 0, 0);
4757    sqlite3_shathree_init(p->db, 0, 0);
4758    sqlite3_completion_init(p->db, 0, 0);
4759    sqlite3_uint_init(p->db, 0, 0);
4760    sqlite3_decimal_init(p->db, 0, 0);
4761    sqlite3_regexp_init(p->db, 0, 0);
4762    sqlite3_ieee_init(p->db, 0, 0);
4763    sqlite3_series_init(p->db, 0, 0);
4764#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4765    sqlite3_dbdata_init(p->db, 0, 0);
4766#endif
4767#ifdef SQLITE_HAVE_ZLIB
4768    sqlite3_zipfile_init(p->db, 0, 0);
4769    sqlite3_sqlar_init(p->db, 0, 0);
4770#endif
4771    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4772                            shellAddSchemaName, 0, 0);
4773    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4774                            shellModuleSchema, 0, 0);
4775    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4776                            shellPutsFunc, 0, 0);
4777    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4778                            shellEscapeCrnl, 0, 0);
4779    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4780                            shellInt32, 0, 0);
4781    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4782                            shellIdQuote, 0, 0);
4783    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
4784                            shellUSleepFunc, 0, 0);
4785#ifndef SQLITE_NOHAVE_SYSTEM
4786    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4787                            editFunc, 0, 0);
4788    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4789                            editFunc, 0, 0);
4790#endif
4791    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4792      char *zSql = sqlite3_mprintf(
4793         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
4794      shell_check_oom(zSql);
4795      sqlite3_exec(p->db, zSql, 0, 0, 0);
4796      sqlite3_free(zSql);
4797    }
4798#ifndef SQLITE_OMIT_DESERIALIZE
4799    else
4800    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4801      int rc;
4802      int nData = 0;
4803      unsigned char *aData;
4804      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4805        aData = (unsigned char*)readFile(zDbFilename, &nData);
4806      }else{
4807        aData = readHexDb(p, &nData);
4808        if( aData==0 ){
4809          return;
4810        }
4811      }
4812      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4813                   SQLITE_DESERIALIZE_RESIZEABLE |
4814                   SQLITE_DESERIALIZE_FREEONCLOSE);
4815      if( rc ){
4816        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4817      }
4818      if( p->szMax>0 ){
4819        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4820      }
4821    }
4822#endif
4823  }
4824  if( p->bSafeModePersist && p->db!=0 ){
4825    sqlite3_set_authorizer(p->db, safeModeAuth, p);
4826  }
4827}
4828
4829/*
4830** Attempt to close the databaes connection.  Report errors.
4831*/
4832void close_db(sqlite3 *db){
4833  int rc = sqlite3_close(db);
4834  if( rc ){
4835    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4836        rc, sqlite3_errmsg(db));
4837  }
4838}
4839
4840#if HAVE_READLINE || HAVE_EDITLINE
4841/*
4842** Readline completion callbacks
4843*/
4844static char *readline_completion_generator(const char *text, int state){
4845  static sqlite3_stmt *pStmt = 0;
4846  char *zRet;
4847  if( state==0 ){
4848    char *zSql;
4849    sqlite3_finalize(pStmt);
4850    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4851                           "  FROM completion(%Q) ORDER BY 1", text);
4852    shell_check_oom(zSql);
4853    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4854    sqlite3_free(zSql);
4855  }
4856  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4857    const char *z = (const char*)sqlite3_column_text(pStmt,0);
4858    zRet = z ? strdup(z) : 0;
4859  }else{
4860    sqlite3_finalize(pStmt);
4861    pStmt = 0;
4862    zRet = 0;
4863  }
4864  return zRet;
4865}
4866static char **readline_completion(const char *zText, int iStart, int iEnd){
4867  rl_attempted_completion_over = 1;
4868  return rl_completion_matches(zText, readline_completion_generator);
4869}
4870
4871#elif HAVE_LINENOISE
4872/*
4873** Linenoise completion callback
4874*/
4875static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4876  int nLine = strlen30(zLine);
4877  int i, iStart;
4878  sqlite3_stmt *pStmt = 0;
4879  char *zSql;
4880  char zBuf[1000];
4881
4882  if( nLine>sizeof(zBuf)-30 ) return;
4883  if( zLine[0]=='.' || zLine[0]=='#') return;
4884  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4885  if( i==nLine-1 ) return;
4886  iStart = i+1;
4887  memcpy(zBuf, zLine, iStart);
4888  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4889                         "  FROM completion(%Q,%Q) ORDER BY 1",
4890                         &zLine[iStart], zLine);
4891  shell_check_oom(zSql);
4892  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4893  sqlite3_free(zSql);
4894  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4895  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4896    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4897    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4898    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
4899      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4900      linenoiseAddCompletion(lc, zBuf);
4901    }
4902  }
4903  sqlite3_finalize(pStmt);
4904}
4905#endif
4906
4907/*
4908** Do C-language style dequoting.
4909**
4910**    \a    -> alarm
4911**    \b    -> backspace
4912**    \t    -> tab
4913**    \n    -> newline
4914**    \v    -> vertical tab
4915**    \f    -> form feed
4916**    \r    -> carriage return
4917**    \s    -> space
4918**    \"    -> "
4919**    \'    -> '
4920**    \\    -> backslash
4921**    \NNN  -> ascii character NNN in octal
4922*/
4923static void resolve_backslashes(char *z){
4924  int i, j;
4925  char c;
4926  while( *z && *z!='\\' ) z++;
4927  for(i=j=0; (c = z[i])!=0; i++, j++){
4928    if( c=='\\' && z[i+1]!=0 ){
4929      c = z[++i];
4930      if( c=='a' ){
4931        c = '\a';
4932      }else if( c=='b' ){
4933        c = '\b';
4934      }else if( c=='t' ){
4935        c = '\t';
4936      }else if( c=='n' ){
4937        c = '\n';
4938      }else if( c=='v' ){
4939        c = '\v';
4940      }else if( c=='f' ){
4941        c = '\f';
4942      }else if( c=='r' ){
4943        c = '\r';
4944      }else if( c=='"' ){
4945        c = '"';
4946      }else if( c=='\'' ){
4947        c = '\'';
4948      }else if( c=='\\' ){
4949        c = '\\';
4950      }else if( c>='0' && c<='7' ){
4951        c -= '0';
4952        if( z[i+1]>='0' && z[i+1]<='7' ){
4953          i++;
4954          c = (c<<3) + z[i] - '0';
4955          if( z[i+1]>='0' && z[i+1]<='7' ){
4956            i++;
4957            c = (c<<3) + z[i] - '0';
4958          }
4959        }
4960      }
4961    }
4962    z[j] = c;
4963  }
4964  if( j<i ) z[j] = 0;
4965}
4966
4967/*
4968** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4969** for TRUE and FALSE.  Return the integer value if appropriate.
4970*/
4971static int booleanValue(const char *zArg){
4972  int i;
4973  if( zArg[0]=='0' && zArg[1]=='x' ){
4974    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4975  }else{
4976    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4977  }
4978  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4979  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4980    return 1;
4981  }
4982  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4983    return 0;
4984  }
4985  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4986          zArg);
4987  return 0;
4988}
4989
4990/*
4991** Set or clear a shell flag according to a boolean value.
4992*/
4993static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4994  if( booleanValue(zArg) ){
4995    ShellSetFlag(p, mFlag);
4996  }else{
4997    ShellClearFlag(p, mFlag);
4998  }
4999}
5000
5001/*
5002** Close an output file, assuming it is not stderr or stdout
5003*/
5004static void output_file_close(FILE *f){
5005  if( f && f!=stdout && f!=stderr ) fclose(f);
5006}
5007
5008/*
5009** Try to open an output file.   The names "stdout" and "stderr" are
5010** recognized and do the right thing.  NULL is returned if the output
5011** filename is "off".
5012*/
5013static FILE *output_file_open(const char *zFile, int bTextMode){
5014  FILE *f;
5015  if( strcmp(zFile,"stdout")==0 ){
5016    f = stdout;
5017  }else if( strcmp(zFile, "stderr")==0 ){
5018    f = stderr;
5019  }else if( strcmp(zFile, "off")==0 ){
5020    f = 0;
5021  }else{
5022    f = fopen(zFile, bTextMode ? "w" : "wb");
5023    if( f==0 ){
5024      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5025    }
5026  }
5027  return f;
5028}
5029
5030#ifndef SQLITE_OMIT_TRACE
5031/*
5032** A routine for handling output from sqlite3_trace().
5033*/
5034static int sql_trace_callback(
5035  unsigned mType,         /* The trace type */
5036  void *pArg,             /* The ShellState pointer */
5037  void *pP,               /* Usually a pointer to sqlite_stmt */
5038  void *pX                /* Auxiliary output */
5039){
5040  ShellState *p = (ShellState*)pArg;
5041  sqlite3_stmt *pStmt;
5042  const char *zSql;
5043  int nSql;
5044  if( p->traceOut==0 ) return 0;
5045  if( mType==SQLITE_TRACE_CLOSE ){
5046    utf8_printf(p->traceOut, "-- closing database connection\n");
5047    return 0;
5048  }
5049  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5050    zSql = (const char*)pX;
5051  }else{
5052    pStmt = (sqlite3_stmt*)pP;
5053    switch( p->eTraceType ){
5054      case SHELL_TRACE_EXPANDED: {
5055        zSql = sqlite3_expanded_sql(pStmt);
5056        break;
5057      }
5058#ifdef SQLITE_ENABLE_NORMALIZE
5059      case SHELL_TRACE_NORMALIZED: {
5060        zSql = sqlite3_normalized_sql(pStmt);
5061        break;
5062      }
5063#endif
5064      default: {
5065        zSql = sqlite3_sql(pStmt);
5066        break;
5067      }
5068    }
5069  }
5070  if( zSql==0 ) return 0;
5071  nSql = strlen30(zSql);
5072  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5073  switch( mType ){
5074    case SQLITE_TRACE_ROW:
5075    case SQLITE_TRACE_STMT: {
5076      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5077      break;
5078    }
5079    case SQLITE_TRACE_PROFILE: {
5080      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5081      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5082      break;
5083    }
5084  }
5085  return 0;
5086}
5087#endif
5088
5089/*
5090** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5091** a useful spot to set a debugger breakpoint.
5092*/
5093static void test_breakpoint(void){
5094  static int nCall = 0;
5095  nCall++;
5096}
5097
5098/*
5099** An object used to read a CSV and other files for import.
5100*/
5101typedef struct ImportCtx ImportCtx;
5102struct ImportCtx {
5103  const char *zFile;  /* Name of the input file */
5104  FILE *in;           /* Read the CSV text from this input stream */
5105  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5106  char *z;            /* Accumulated text for a field */
5107  int n;              /* Number of bytes in z */
5108  int nAlloc;         /* Space allocated for z[] */
5109  int nLine;          /* Current line number */
5110  int nRow;           /* Number of rows imported */
5111  int nErr;           /* Number of errors encountered */
5112  int bNotFirst;      /* True if one or more bytes already read */
5113  int cTerm;          /* Character that terminated the most recent field */
5114  int cColSep;        /* The column separator character.  (Usually ",") */
5115  int cRowSep;        /* The row separator character.  (Usually "\n") */
5116};
5117
5118/* Clean up resourced used by an ImportCtx */
5119static void import_cleanup(ImportCtx *p){
5120  if( p->in!=0 && p->xCloser!=0 ){
5121    p->xCloser(p->in);
5122    p->in = 0;
5123  }
5124  sqlite3_free(p->z);
5125  p->z = 0;
5126}
5127
5128/* Append a single byte to z[] */
5129static void import_append_char(ImportCtx *p, int c){
5130  if( p->n+1>=p->nAlloc ){
5131    p->nAlloc += p->nAlloc + 100;
5132    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5133    shell_check_oom(p->z);
5134  }
5135  p->z[p->n++] = (char)c;
5136}
5137
5138/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5139** with the option of having a separator other than ",".
5140**
5141**   +  Input comes from p->in.
5142**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5143**      from sqlite3_malloc64().
5144**   +  Use p->cSep as the column separator.  The default is ",".
5145**   +  Use p->rSep as the row separator.  The default is "\n".
5146**   +  Keep track of the line number in p->nLine.
5147**   +  Store the character that terminates the field in p->cTerm.  Store
5148**      EOF on end-of-file.
5149**   +  Report syntax errors on stderr
5150*/
5151static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5152  int c;
5153  int cSep = p->cColSep;
5154  int rSep = p->cRowSep;
5155  p->n = 0;
5156  c = fgetc(p->in);
5157  if( c==EOF || seenInterrupt ){
5158    p->cTerm = EOF;
5159    return 0;
5160  }
5161  if( c=='"' ){
5162    int pc, ppc;
5163    int startLine = p->nLine;
5164    int cQuote = c;
5165    pc = ppc = 0;
5166    while( 1 ){
5167      c = fgetc(p->in);
5168      if( c==rSep ) p->nLine++;
5169      if( c==cQuote ){
5170        if( pc==cQuote ){
5171          pc = 0;
5172          continue;
5173        }
5174      }
5175      if( (c==cSep && pc==cQuote)
5176       || (c==rSep && pc==cQuote)
5177       || (c==rSep && pc=='\r' && ppc==cQuote)
5178       || (c==EOF && pc==cQuote)
5179      ){
5180        do{ p->n--; }while( p->z[p->n]!=cQuote );
5181        p->cTerm = c;
5182        break;
5183      }
5184      if( pc==cQuote && c!='\r' ){
5185        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5186                p->zFile, p->nLine, cQuote);
5187      }
5188      if( c==EOF ){
5189        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5190                p->zFile, startLine, cQuote);
5191        p->cTerm = c;
5192        break;
5193      }
5194      import_append_char(p, c);
5195      ppc = pc;
5196      pc = c;
5197    }
5198  }else{
5199    /* If this is the first field being parsed and it begins with the
5200    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5201    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5202      import_append_char(p, c);
5203      c = fgetc(p->in);
5204      if( (c&0xff)==0xbb ){
5205        import_append_char(p, c);
5206        c = fgetc(p->in);
5207        if( (c&0xff)==0xbf ){
5208          p->bNotFirst = 1;
5209          p->n = 0;
5210          return csv_read_one_field(p);
5211        }
5212      }
5213    }
5214    while( c!=EOF && c!=cSep && c!=rSep ){
5215      import_append_char(p, c);
5216      c = fgetc(p->in);
5217    }
5218    if( c==rSep ){
5219      p->nLine++;
5220      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5221    }
5222    p->cTerm = c;
5223  }
5224  if( p->z ) p->z[p->n] = 0;
5225  p->bNotFirst = 1;
5226  return p->z;
5227}
5228
5229/* Read a single field of ASCII delimited text.
5230**
5231**   +  Input comes from p->in.
5232**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5233**      from sqlite3_malloc64().
5234**   +  Use p->cSep as the column separator.  The default is "\x1F".
5235**   +  Use p->rSep as the row separator.  The default is "\x1E".
5236**   +  Keep track of the row number in p->nLine.
5237**   +  Store the character that terminates the field in p->cTerm.  Store
5238**      EOF on end-of-file.
5239**   +  Report syntax errors on stderr
5240*/
5241static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5242  int c;
5243  int cSep = p->cColSep;
5244  int rSep = p->cRowSep;
5245  p->n = 0;
5246  c = fgetc(p->in);
5247  if( c==EOF || seenInterrupt ){
5248    p->cTerm = EOF;
5249    return 0;
5250  }
5251  while( c!=EOF && c!=cSep && c!=rSep ){
5252    import_append_char(p, c);
5253    c = fgetc(p->in);
5254  }
5255  if( c==rSep ){
5256    p->nLine++;
5257  }
5258  p->cTerm = c;
5259  if( p->z ) p->z[p->n] = 0;
5260  return p->z;
5261}
5262
5263/*
5264** Try to transfer data for table zTable.  If an error is seen while
5265** moving forward, try to go backwards.  The backwards movement won't
5266** work for WITHOUT ROWID tables.
5267*/
5268static void tryToCloneData(
5269  ShellState *p,
5270  sqlite3 *newDb,
5271  const char *zTable
5272){
5273  sqlite3_stmt *pQuery = 0;
5274  sqlite3_stmt *pInsert = 0;
5275  char *zQuery = 0;
5276  char *zInsert = 0;
5277  int rc;
5278  int i, j, n;
5279  int nTable = strlen30(zTable);
5280  int k = 0;
5281  int cnt = 0;
5282  const int spinRate = 10000;
5283
5284  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5285  shell_check_oom(zQuery);
5286  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5287  if( rc ){
5288    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5289            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5290            zQuery);
5291    goto end_data_xfer;
5292  }
5293  n = sqlite3_column_count(pQuery);
5294  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5295  shell_check_oom(zInsert);
5296  sqlite3_snprintf(200+nTable,zInsert,
5297                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5298  i = strlen30(zInsert);
5299  for(j=1; j<n; j++){
5300    memcpy(zInsert+i, ",?", 2);
5301    i += 2;
5302  }
5303  memcpy(zInsert+i, ");", 3);
5304  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5305  if( rc ){
5306    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5307            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5308            zQuery);
5309    goto end_data_xfer;
5310  }
5311  for(k=0; k<2; k++){
5312    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5313      for(i=0; i<n; i++){
5314        switch( sqlite3_column_type(pQuery, i) ){
5315          case SQLITE_NULL: {
5316            sqlite3_bind_null(pInsert, i+1);
5317            break;
5318          }
5319          case SQLITE_INTEGER: {
5320            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5321            break;
5322          }
5323          case SQLITE_FLOAT: {
5324            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5325            break;
5326          }
5327          case SQLITE_TEXT: {
5328            sqlite3_bind_text(pInsert, i+1,
5329                             (const char*)sqlite3_column_text(pQuery,i),
5330                             -1, SQLITE_STATIC);
5331            break;
5332          }
5333          case SQLITE_BLOB: {
5334            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5335                                            sqlite3_column_bytes(pQuery,i),
5336                                            SQLITE_STATIC);
5337            break;
5338          }
5339        }
5340      } /* End for */
5341      rc = sqlite3_step(pInsert);
5342      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5343        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5344                        sqlite3_errmsg(newDb));
5345      }
5346      sqlite3_reset(pInsert);
5347      cnt++;
5348      if( (cnt%spinRate)==0 ){
5349        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5350        fflush(stdout);
5351      }
5352    } /* End while */
5353    if( rc==SQLITE_DONE ) break;
5354    sqlite3_finalize(pQuery);
5355    sqlite3_free(zQuery);
5356    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5357                             zTable);
5358    shell_check_oom(zQuery);
5359    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5360    if( rc ){
5361      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5362      break;
5363    }
5364  } /* End for(k=0...) */
5365
5366end_data_xfer:
5367  sqlite3_finalize(pQuery);
5368  sqlite3_finalize(pInsert);
5369  sqlite3_free(zQuery);
5370  sqlite3_free(zInsert);
5371}
5372
5373
5374/*
5375** Try to transfer all rows of the schema that match zWhere.  For
5376** each row, invoke xForEach() on the object defined by that row.
5377** If an error is encountered while moving forward through the
5378** sqlite_schema table, try again moving backwards.
5379*/
5380static void tryToCloneSchema(
5381  ShellState *p,
5382  sqlite3 *newDb,
5383  const char *zWhere,
5384  void (*xForEach)(ShellState*,sqlite3*,const char*)
5385){
5386  sqlite3_stmt *pQuery = 0;
5387  char *zQuery = 0;
5388  int rc;
5389  const unsigned char *zName;
5390  const unsigned char *zSql;
5391  char *zErrMsg = 0;
5392
5393  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5394                           " WHERE %s", zWhere);
5395  shell_check_oom(zQuery);
5396  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5397  if( rc ){
5398    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5399                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5400                    zQuery);
5401    goto end_schema_xfer;
5402  }
5403  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5404    zName = sqlite3_column_text(pQuery, 0);
5405    zSql = sqlite3_column_text(pQuery, 1);
5406    if( zName==0 || zSql==0 ) continue;
5407    printf("%s... ", zName); fflush(stdout);
5408    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5409    if( zErrMsg ){
5410      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5411      sqlite3_free(zErrMsg);
5412      zErrMsg = 0;
5413    }
5414    if( xForEach ){
5415      xForEach(p, newDb, (const char*)zName);
5416    }
5417    printf("done\n");
5418  }
5419  if( rc!=SQLITE_DONE ){
5420    sqlite3_finalize(pQuery);
5421    sqlite3_free(zQuery);
5422    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5423                             " WHERE %s ORDER BY rowid DESC", zWhere);
5424    shell_check_oom(zQuery);
5425    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5426    if( rc ){
5427      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5428                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5429                      zQuery);
5430      goto end_schema_xfer;
5431    }
5432    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5433      zName = sqlite3_column_text(pQuery, 0);
5434      zSql = sqlite3_column_text(pQuery, 1);
5435      if( zName==0 || zSql==0 ) continue;
5436      printf("%s... ", zName); fflush(stdout);
5437      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5438      if( zErrMsg ){
5439        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5440        sqlite3_free(zErrMsg);
5441        zErrMsg = 0;
5442      }
5443      if( xForEach ){
5444        xForEach(p, newDb, (const char*)zName);
5445      }
5446      printf("done\n");
5447    }
5448  }
5449end_schema_xfer:
5450  sqlite3_finalize(pQuery);
5451  sqlite3_free(zQuery);
5452}
5453
5454/*
5455** Open a new database file named "zNewDb".  Try to recover as much information
5456** as possible out of the main database (which might be corrupt) and write it
5457** into zNewDb.
5458*/
5459static void tryToClone(ShellState *p, const char *zNewDb){
5460  int rc;
5461  sqlite3 *newDb = 0;
5462  if( access(zNewDb,0)==0 ){
5463    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5464    return;
5465  }
5466  rc = sqlite3_open(zNewDb, &newDb);
5467  if( rc ){
5468    utf8_printf(stderr, "Cannot create output database: %s\n",
5469            sqlite3_errmsg(newDb));
5470  }else{
5471    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5472    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5473    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5474    tryToCloneSchema(p, newDb, "type!='table'", 0);
5475    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5476    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5477  }
5478  close_db(newDb);
5479}
5480
5481/*
5482** Change the output file back to stdout.
5483**
5484** If the p->doXdgOpen flag is set, that means the output was being
5485** redirected to a temporary file named by p->zTempFile.  In that case,
5486** launch start/open/xdg-open on that temporary file.
5487*/
5488static void output_reset(ShellState *p){
5489  if( p->outfile[0]=='|' ){
5490#ifndef SQLITE_OMIT_POPEN
5491    pclose(p->out);
5492#endif
5493  }else{
5494    output_file_close(p->out);
5495#ifndef SQLITE_NOHAVE_SYSTEM
5496    if( p->doXdgOpen ){
5497      const char *zXdgOpenCmd =
5498#if defined(_WIN32)
5499      "start";
5500#elif defined(__APPLE__)
5501      "open";
5502#else
5503      "xdg-open";
5504#endif
5505      char *zCmd;
5506      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5507      if( system(zCmd) ){
5508        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5509      }else{
5510        /* Give the start/open/xdg-open command some time to get
5511        ** going before we continue, and potential delete the
5512        ** p->zTempFile data file out from under it */
5513        sqlite3_sleep(2000);
5514      }
5515      sqlite3_free(zCmd);
5516      outputModePop(p);
5517      p->doXdgOpen = 0;
5518    }
5519#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5520  }
5521  p->outfile[0] = 0;
5522  p->out = stdout;
5523}
5524
5525/*
5526** Run an SQL command and return the single integer result.
5527*/
5528static int db_int(ShellState *p, const char *zSql){
5529  sqlite3_stmt *pStmt;
5530  int res = 0;
5531  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5532  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5533    res = sqlite3_column_int(pStmt,0);
5534  }
5535  sqlite3_finalize(pStmt);
5536  return res;
5537}
5538
5539/*
5540** Convert a 2-byte or 4-byte big-endian integer into a native integer
5541*/
5542static unsigned int get2byteInt(unsigned char *a){
5543  return (a[0]<<8) + a[1];
5544}
5545static unsigned int get4byteInt(unsigned char *a){
5546  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5547}
5548
5549/*
5550** Implementation of the ".dbinfo" command.
5551**
5552** Return 1 on error, 2 to exit, and 0 otherwise.
5553*/
5554static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5555  static const struct { const char *zName; int ofst; } aField[] = {
5556     { "file change counter:",  24  },
5557     { "database page count:",  28  },
5558     { "freelist page count:",  36  },
5559     { "schema cookie:",        40  },
5560     { "schema format:",        44  },
5561     { "default cache size:",   48  },
5562     { "autovacuum top root:",  52  },
5563     { "incremental vacuum:",   64  },
5564     { "text encoding:",        56  },
5565     { "user version:",         60  },
5566     { "application id:",       68  },
5567     { "software version:",     96  },
5568  };
5569  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5570     { "number of tables:",
5571       "SELECT count(*) FROM %s WHERE type='table'" },
5572     { "number of indexes:",
5573       "SELECT count(*) FROM %s WHERE type='index'" },
5574     { "number of triggers:",
5575       "SELECT count(*) FROM %s WHERE type='trigger'" },
5576     { "number of views:",
5577       "SELECT count(*) FROM %s WHERE type='view'" },
5578     { "schema size:",
5579       "SELECT total(length(sql)) FROM %s" },
5580  };
5581  int i, rc;
5582  unsigned iDataVersion;
5583  char *zSchemaTab;
5584  char *zDb = nArg>=2 ? azArg[1] : "main";
5585  sqlite3_stmt *pStmt = 0;
5586  unsigned char aHdr[100];
5587  open_db(p, 0);
5588  if( p->db==0 ) return 1;
5589  rc = sqlite3_prepare_v2(p->db,
5590             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5591             -1, &pStmt, 0);
5592  if( rc ){
5593    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5594    sqlite3_finalize(pStmt);
5595    return 1;
5596  }
5597  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5598  if( sqlite3_step(pStmt)==SQLITE_ROW
5599   && sqlite3_column_bytes(pStmt,0)>100
5600  ){
5601    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5602    sqlite3_finalize(pStmt);
5603  }else{
5604    raw_printf(stderr, "unable to read database header\n");
5605    sqlite3_finalize(pStmt);
5606    return 1;
5607  }
5608  i = get2byteInt(aHdr+16);
5609  if( i==1 ) i = 65536;
5610  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5611  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5612  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5613  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5614  for(i=0; i<ArraySize(aField); i++){
5615    int ofst = aField[i].ofst;
5616    unsigned int val = get4byteInt(aHdr + ofst);
5617    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5618    switch( ofst ){
5619      case 56: {
5620        if( val==1 ) raw_printf(p->out, " (utf8)");
5621        if( val==2 ) raw_printf(p->out, " (utf16le)");
5622        if( val==3 ) raw_printf(p->out, " (utf16be)");
5623      }
5624    }
5625    raw_printf(p->out, "\n");
5626  }
5627  if( zDb==0 ){
5628    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5629  }else if( strcmp(zDb,"temp")==0 ){
5630    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5631  }else{
5632    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5633  }
5634  for(i=0; i<ArraySize(aQuery); i++){
5635    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5636    int val = db_int(p, zSql);
5637    sqlite3_free(zSql);
5638    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5639  }
5640  sqlite3_free(zSchemaTab);
5641  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5642  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5643  return 0;
5644}
5645
5646/*
5647** Print the current sqlite3_errmsg() value to stderr and return 1.
5648*/
5649static int shellDatabaseError(sqlite3 *db){
5650  const char *zErr = sqlite3_errmsg(db);
5651  utf8_printf(stderr, "Error: %s\n", zErr);
5652  return 1;
5653}
5654
5655/*
5656** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5657** if they match and FALSE (0) if they do not match.
5658**
5659** Globbing rules:
5660**
5661**      '*'       Matches any sequence of zero or more characters.
5662**
5663**      '?'       Matches exactly one character.
5664**
5665**     [...]      Matches one character from the enclosed list of
5666**                characters.
5667**
5668**     [^...]     Matches one character not in the enclosed list.
5669**
5670**      '#'       Matches any sequence of one or more digits with an
5671**                optional + or - sign in front
5672**
5673**      ' '       Any span of whitespace matches any other span of
5674**                whitespace.
5675**
5676** Extra whitespace at the end of z[] is ignored.
5677*/
5678static int testcase_glob(const char *zGlob, const char *z){
5679  int c, c2;
5680  int invert;
5681  int seen;
5682
5683  while( (c = (*(zGlob++)))!=0 ){
5684    if( IsSpace(c) ){
5685      if( !IsSpace(*z) ) return 0;
5686      while( IsSpace(*zGlob) ) zGlob++;
5687      while( IsSpace(*z) ) z++;
5688    }else if( c=='*' ){
5689      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5690        if( c=='?' && (*(z++))==0 ) return 0;
5691      }
5692      if( c==0 ){
5693        return 1;
5694      }else if( c=='[' ){
5695        while( *z && testcase_glob(zGlob-1,z)==0 ){
5696          z++;
5697        }
5698        return (*z)!=0;
5699      }
5700      while( (c2 = (*(z++)))!=0 ){
5701        while( c2!=c ){
5702          c2 = *(z++);
5703          if( c2==0 ) return 0;
5704        }
5705        if( testcase_glob(zGlob,z) ) return 1;
5706      }
5707      return 0;
5708    }else if( c=='?' ){
5709      if( (*(z++))==0 ) return 0;
5710    }else if( c=='[' ){
5711      int prior_c = 0;
5712      seen = 0;
5713      invert = 0;
5714      c = *(z++);
5715      if( c==0 ) return 0;
5716      c2 = *(zGlob++);
5717      if( c2=='^' ){
5718        invert = 1;
5719        c2 = *(zGlob++);
5720      }
5721      if( c2==']' ){
5722        if( c==']' ) seen = 1;
5723        c2 = *(zGlob++);
5724      }
5725      while( c2 && c2!=']' ){
5726        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5727          c2 = *(zGlob++);
5728          if( c>=prior_c && c<=c2 ) seen = 1;
5729          prior_c = 0;
5730        }else{
5731          if( c==c2 ){
5732            seen = 1;
5733          }
5734          prior_c = c2;
5735        }
5736        c2 = *(zGlob++);
5737      }
5738      if( c2==0 || (seen ^ invert)==0 ) return 0;
5739    }else if( c=='#' ){
5740      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5741      if( !IsDigit(z[0]) ) return 0;
5742      z++;
5743      while( IsDigit(z[0]) ){ z++; }
5744    }else{
5745      if( c!=(*(z++)) ) return 0;
5746    }
5747  }
5748  while( IsSpace(*z) ){ z++; }
5749  return *z==0;
5750}
5751
5752
5753/*
5754** Compare the string as a command-line option with either one or two
5755** initial "-" characters.
5756*/
5757static int optionMatch(const char *zStr, const char *zOpt){
5758  if( zStr[0]!='-' ) return 0;
5759  zStr++;
5760  if( zStr[0]=='-' ) zStr++;
5761  return strcmp(zStr, zOpt)==0;
5762}
5763
5764/*
5765** Delete a file.
5766*/
5767int shellDeleteFile(const char *zFilename){
5768  int rc;
5769#ifdef _WIN32
5770  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5771  rc = _wunlink(z);
5772  sqlite3_free(z);
5773#else
5774  rc = unlink(zFilename);
5775#endif
5776  return rc;
5777}
5778
5779/*
5780** Try to delete the temporary file (if there is one) and free the
5781** memory used to hold the name of the temp file.
5782*/
5783static void clearTempFile(ShellState *p){
5784  if( p->zTempFile==0 ) return;
5785  if( p->doXdgOpen ) return;
5786  if( shellDeleteFile(p->zTempFile) ) return;
5787  sqlite3_free(p->zTempFile);
5788  p->zTempFile = 0;
5789}
5790
5791/*
5792** Create a new temp file name with the given suffix.
5793*/
5794static void newTempFile(ShellState *p, const char *zSuffix){
5795  clearTempFile(p);
5796  sqlite3_free(p->zTempFile);
5797  p->zTempFile = 0;
5798  if( p->db ){
5799    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5800  }
5801  if( p->zTempFile==0 ){
5802    /* If p->db is an in-memory database then the TEMPFILENAME file-control
5803    ** will not work and we will need to fallback to guessing */
5804    char *zTemp;
5805    sqlite3_uint64 r;
5806    sqlite3_randomness(sizeof(r), &r);
5807    zTemp = getenv("TEMP");
5808    if( zTemp==0 ) zTemp = getenv("TMP");
5809    if( zTemp==0 ){
5810#ifdef _WIN32
5811      zTemp = "\\tmp";
5812#else
5813      zTemp = "/tmp";
5814#endif
5815    }
5816    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5817  }else{
5818    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5819  }
5820  shell_check_oom(p->zTempFile);
5821}
5822
5823
5824/*
5825** The implementation of SQL scalar function fkey_collate_clause(), used
5826** by the ".lint fkey-indexes" command. This scalar function is always
5827** called with four arguments - the parent table name, the parent column name,
5828** the child table name and the child column name.
5829**
5830**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5831**
5832** If either of the named tables or columns do not exist, this function
5833** returns an empty string. An empty string is also returned if both tables
5834** and columns exist but have the same default collation sequence. Or,
5835** if both exist but the default collation sequences are different, this
5836** function returns the string " COLLATE <parent-collation>", where
5837** <parent-collation> is the default collation sequence of the parent column.
5838*/
5839static void shellFkeyCollateClause(
5840  sqlite3_context *pCtx,
5841  int nVal,
5842  sqlite3_value **apVal
5843){
5844  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5845  const char *zParent;
5846  const char *zParentCol;
5847  const char *zParentSeq;
5848  const char *zChild;
5849  const char *zChildCol;
5850  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5851  int rc;
5852
5853  assert( nVal==4 );
5854  zParent = (const char*)sqlite3_value_text(apVal[0]);
5855  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5856  zChild = (const char*)sqlite3_value_text(apVal[2]);
5857  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5858
5859  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5860  rc = sqlite3_table_column_metadata(
5861      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5862  );
5863  if( rc==SQLITE_OK ){
5864    rc = sqlite3_table_column_metadata(
5865        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5866    );
5867  }
5868
5869  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5870    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5871    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5872    sqlite3_free(z);
5873  }
5874}
5875
5876
5877/*
5878** The implementation of dot-command ".lint fkey-indexes".
5879*/
5880static int lintFkeyIndexes(
5881  ShellState *pState,             /* Current shell tool state */
5882  char **azArg,                   /* Array of arguments passed to dot command */
5883  int nArg                        /* Number of entries in azArg[] */
5884){
5885  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5886  FILE *out = pState->out;        /* Stream to write non-error output to */
5887  int bVerbose = 0;               /* If -verbose is present */
5888  int bGroupByParent = 0;         /* If -groupbyparent is present */
5889  int i;                          /* To iterate through azArg[] */
5890  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5891  int rc;                         /* Return code */
5892  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5893
5894  /*
5895  ** This SELECT statement returns one row for each foreign key constraint
5896  ** in the schema of the main database. The column values are:
5897  **
5898  ** 0. The text of an SQL statement similar to:
5899  **
5900  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5901  **
5902  **    This SELECT is similar to the one that the foreign keys implementation
5903  **    needs to run internally on child tables. If there is an index that can
5904  **    be used to optimize this query, then it can also be used by the FK
5905  **    implementation to optimize DELETE or UPDATE statements on the parent
5906  **    table.
5907  **
5908  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5909  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5910  **    contains an index that can be used to optimize the query.
5911  **
5912  ** 2. Human readable text that describes the child table and columns. e.g.
5913  **
5914  **       "child_table(child_key1, child_key2)"
5915  **
5916  ** 3. Human readable text that describes the parent table and columns. e.g.
5917  **
5918  **       "parent_table(parent_key1, parent_key2)"
5919  **
5920  ** 4. A full CREATE INDEX statement for an index that could be used to
5921  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5922  **
5923  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5924  **
5925  ** 5. The name of the parent table.
5926  **
5927  ** These six values are used by the C logic below to generate the report.
5928  */
5929  const char *zSql =
5930  "SELECT "
5931    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5932    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5933    "  || fkey_collate_clause("
5934    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5935    ", "
5936    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
5937    "  || group_concat('*=?', ' AND ') || ')'"
5938    ", "
5939    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5940    ", "
5941    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5942    ", "
5943    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5944    "  || ' ON ' || quote(s.name) || '('"
5945    "  || group_concat(quote(f.[from]) ||"
5946    "        fkey_collate_clause("
5947    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5948    "  || ');'"
5949    ", "
5950    "     f.[table] "
5951    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5952    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5953    "GROUP BY s.name, f.id "
5954    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5955  ;
5956  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
5957
5958  for(i=2; i<nArg; i++){
5959    int n = strlen30(azArg[i]);
5960    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5961      bVerbose = 1;
5962    }
5963    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5964      bGroupByParent = 1;
5965      zIndent = "    ";
5966    }
5967    else{
5968      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5969          azArg[0], azArg[1]
5970      );
5971      return SQLITE_ERROR;
5972    }
5973  }
5974
5975  /* Register the fkey_collate_clause() SQL function */
5976  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5977      0, shellFkeyCollateClause, 0, 0
5978  );
5979
5980
5981  if( rc==SQLITE_OK ){
5982    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5983  }
5984  if( rc==SQLITE_OK ){
5985    sqlite3_bind_int(pSql, 1, bGroupByParent);
5986  }
5987
5988  if( rc==SQLITE_OK ){
5989    int rc2;
5990    char *zPrev = 0;
5991    while( SQLITE_ROW==sqlite3_step(pSql) ){
5992      int res = -1;
5993      sqlite3_stmt *pExplain = 0;
5994      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5995      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5996      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5997      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5998      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5999      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6000
6001      if( zEQP==0 ) continue;
6002      if( zGlob==0 ) continue;
6003      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6004      if( rc!=SQLITE_OK ) break;
6005      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6006        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6007        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6008                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6009      }
6010      rc = sqlite3_finalize(pExplain);
6011      if( rc!=SQLITE_OK ) break;
6012
6013      if( res<0 ){
6014        raw_printf(stderr, "Error: internal error");
6015        break;
6016      }else{
6017        if( bGroupByParent
6018        && (bVerbose || res==0)
6019        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6020        ){
6021          raw_printf(out, "-- Parent table %s\n", zParent);
6022          sqlite3_free(zPrev);
6023          zPrev = sqlite3_mprintf("%s", zParent);
6024        }
6025
6026        if( res==0 ){
6027          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6028        }else if( bVerbose ){
6029          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6030              zIndent, zFrom, zTarget
6031          );
6032        }
6033      }
6034    }
6035    sqlite3_free(zPrev);
6036
6037    if( rc!=SQLITE_OK ){
6038      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6039    }
6040
6041    rc2 = sqlite3_finalize(pSql);
6042    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6043      rc = rc2;
6044      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6045    }
6046  }else{
6047    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6048  }
6049
6050  return rc;
6051}
6052
6053/*
6054** Implementation of ".lint" dot command.
6055*/
6056static int lintDotCommand(
6057  ShellState *pState,             /* Current shell tool state */
6058  char **azArg,                   /* Array of arguments passed to dot command */
6059  int nArg                        /* Number of entries in azArg[] */
6060){
6061  int n;
6062  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6063  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6064  return lintFkeyIndexes(pState, azArg, nArg);
6065
6066 usage:
6067  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6068  raw_printf(stderr, "Where sub-commands are:\n");
6069  raw_printf(stderr, "    fkey-indexes\n");
6070  return SQLITE_ERROR;
6071}
6072
6073#if !defined SQLITE_OMIT_VIRTUALTABLE
6074static void shellPrepare(
6075  sqlite3 *db,
6076  int *pRc,
6077  const char *zSql,
6078  sqlite3_stmt **ppStmt
6079){
6080  *ppStmt = 0;
6081  if( *pRc==SQLITE_OK ){
6082    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6083    if( rc!=SQLITE_OK ){
6084      raw_printf(stderr, "sql error: %s (%d)\n",
6085          sqlite3_errmsg(db), sqlite3_errcode(db)
6086      );
6087      *pRc = rc;
6088    }
6089  }
6090}
6091
6092/*
6093** Create a prepared statement using printf-style arguments for the SQL.
6094**
6095** This routine is could be marked "static".  But it is not always used,
6096** depending on compile-time options.  By omitting the "static", we avoid
6097** nuisance compiler warnings about "defined but not used".
6098*/
6099void shellPreparePrintf(
6100  sqlite3 *db,
6101  int *pRc,
6102  sqlite3_stmt **ppStmt,
6103  const char *zFmt,
6104  ...
6105){
6106  *ppStmt = 0;
6107  if( *pRc==SQLITE_OK ){
6108    va_list ap;
6109    char *z;
6110    va_start(ap, zFmt);
6111    z = sqlite3_vmprintf(zFmt, ap);
6112    va_end(ap);
6113    if( z==0 ){
6114      *pRc = SQLITE_NOMEM;
6115    }else{
6116      shellPrepare(db, pRc, z, ppStmt);
6117      sqlite3_free(z);
6118    }
6119  }
6120}
6121
6122/* Finalize the prepared statement created using shellPreparePrintf().
6123**
6124** This routine is could be marked "static".  But it is not always used,
6125** depending on compile-time options.  By omitting the "static", we avoid
6126** nuisance compiler warnings about "defined but not used".
6127*/
6128void shellFinalize(
6129  int *pRc,
6130  sqlite3_stmt *pStmt
6131){
6132  if( pStmt ){
6133    sqlite3 *db = sqlite3_db_handle(pStmt);
6134    int rc = sqlite3_finalize(pStmt);
6135    if( *pRc==SQLITE_OK ){
6136      if( rc!=SQLITE_OK ){
6137        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6138      }
6139      *pRc = rc;
6140    }
6141  }
6142}
6143
6144/* Reset the prepared statement created using shellPreparePrintf().
6145**
6146** This routine is could be marked "static".  But it is not always used,
6147** depending on compile-time options.  By omitting the "static", we avoid
6148** nuisance compiler warnings about "defined but not used".
6149*/
6150void shellReset(
6151  int *pRc,
6152  sqlite3_stmt *pStmt
6153){
6154  int rc = sqlite3_reset(pStmt);
6155  if( *pRc==SQLITE_OK ){
6156    if( rc!=SQLITE_OK ){
6157      sqlite3 *db = sqlite3_db_handle(pStmt);
6158      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6159    }
6160    *pRc = rc;
6161  }
6162}
6163#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6164
6165#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6166/******************************************************************************
6167** The ".archive" or ".ar" command.
6168*/
6169/*
6170** Structure representing a single ".ar" command.
6171*/
6172typedef struct ArCommand ArCommand;
6173struct ArCommand {
6174  u8 eCmd;                        /* An AR_CMD_* value */
6175  u8 bVerbose;                    /* True if --verbose */
6176  u8 bZip;                        /* True if the archive is a ZIP */
6177  u8 bDryRun;                     /* True if --dry-run */
6178  u8 bAppend;                     /* True if --append */
6179  u8 bGlob;                       /* True if --glob */
6180  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6181  int nArg;                       /* Number of command arguments */
6182  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6183  const char *zFile;              /* --file argument, or NULL */
6184  const char *zDir;               /* --directory argument, or NULL */
6185  char **azArg;                   /* Array of command arguments */
6186  ShellState *p;                  /* Shell state */
6187  sqlite3 *db;                    /* Database containing the archive */
6188};
6189
6190/*
6191** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6192*/
6193static int arUsage(FILE *f){
6194  showHelp(f,"archive");
6195  return SQLITE_ERROR;
6196}
6197
6198/*
6199** Print an error message for the .ar command to stderr and return
6200** SQLITE_ERROR.
6201*/
6202static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6203  va_list ap;
6204  char *z;
6205  va_start(ap, zFmt);
6206  z = sqlite3_vmprintf(zFmt, ap);
6207  va_end(ap);
6208  utf8_printf(stderr, "Error: %s\n", z);
6209  if( pAr->fromCmdLine ){
6210    utf8_printf(stderr, "Use \"-A\" for more help\n");
6211  }else{
6212    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6213  }
6214  sqlite3_free(z);
6215  return SQLITE_ERROR;
6216}
6217
6218/*
6219** Values for ArCommand.eCmd.
6220*/
6221#define AR_CMD_CREATE       1
6222#define AR_CMD_UPDATE       2
6223#define AR_CMD_INSERT       3
6224#define AR_CMD_EXTRACT      4
6225#define AR_CMD_LIST         5
6226#define AR_CMD_HELP         6
6227#define AR_CMD_REMOVE       7
6228
6229/*
6230** Other (non-command) switches.
6231*/
6232#define AR_SWITCH_VERBOSE     8
6233#define AR_SWITCH_FILE        9
6234#define AR_SWITCH_DIRECTORY  10
6235#define AR_SWITCH_APPEND     11
6236#define AR_SWITCH_DRYRUN     12
6237#define AR_SWITCH_GLOB       13
6238
6239static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6240  switch( eSwitch ){
6241    case AR_CMD_CREATE:
6242    case AR_CMD_EXTRACT:
6243    case AR_CMD_LIST:
6244    case AR_CMD_REMOVE:
6245    case AR_CMD_UPDATE:
6246    case AR_CMD_INSERT:
6247    case AR_CMD_HELP:
6248      if( pAr->eCmd ){
6249        return arErrorMsg(pAr, "multiple command options");
6250      }
6251      pAr->eCmd = eSwitch;
6252      break;
6253
6254    case AR_SWITCH_DRYRUN:
6255      pAr->bDryRun = 1;
6256      break;
6257    case AR_SWITCH_GLOB:
6258      pAr->bGlob = 1;
6259      break;
6260    case AR_SWITCH_VERBOSE:
6261      pAr->bVerbose = 1;
6262      break;
6263    case AR_SWITCH_APPEND:
6264      pAr->bAppend = 1;
6265      /* Fall thru into --file */
6266    case AR_SWITCH_FILE:
6267      pAr->zFile = zArg;
6268      break;
6269    case AR_SWITCH_DIRECTORY:
6270      pAr->zDir = zArg;
6271      break;
6272  }
6273
6274  return SQLITE_OK;
6275}
6276
6277/*
6278** Parse the command line for an ".ar" command. The results are written into
6279** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6280** successfully, otherwise an error message is written to stderr and
6281** SQLITE_ERROR returned.
6282*/
6283static int arParseCommand(
6284  char **azArg,                   /* Array of arguments passed to dot command */
6285  int nArg,                       /* Number of entries in azArg[] */
6286  ArCommand *pAr                  /* Populate this object */
6287){
6288  struct ArSwitch {
6289    const char *zLong;
6290    char cShort;
6291    u8 eSwitch;
6292    u8 bArg;
6293  } aSwitch[] = {
6294    { "create",    'c', AR_CMD_CREATE,       0 },
6295    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6296    { "insert",    'i', AR_CMD_INSERT,       0 },
6297    { "list",      't', AR_CMD_LIST,         0 },
6298    { "remove",    'r', AR_CMD_REMOVE,       0 },
6299    { "update",    'u', AR_CMD_UPDATE,       0 },
6300    { "help",      'h', AR_CMD_HELP,         0 },
6301    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6302    { "file",      'f', AR_SWITCH_FILE,      1 },
6303    { "append",    'a', AR_SWITCH_APPEND,    1 },
6304    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6305    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6306    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6307  };
6308  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6309  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6310
6311  if( nArg<=1 ){
6312    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6313    return arUsage(stderr);
6314  }else{
6315    char *z = azArg[1];
6316    if( z[0]!='-' ){
6317      /* Traditional style [tar] invocation */
6318      int i;
6319      int iArg = 2;
6320      for(i=0; z[i]; i++){
6321        const char *zArg = 0;
6322        struct ArSwitch *pOpt;
6323        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6324          if( z[i]==pOpt->cShort ) break;
6325        }
6326        if( pOpt==pEnd ){
6327          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6328        }
6329        if( pOpt->bArg ){
6330          if( iArg>=nArg ){
6331            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6332          }
6333          zArg = azArg[iArg++];
6334        }
6335        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6336      }
6337      pAr->nArg = nArg-iArg;
6338      if( pAr->nArg>0 ){
6339        pAr->azArg = &azArg[iArg];
6340      }
6341    }else{
6342      /* Non-traditional invocation */
6343      int iArg;
6344      for(iArg=1; iArg<nArg; iArg++){
6345        int n;
6346        z = azArg[iArg];
6347        if( z[0]!='-' ){
6348          /* All remaining command line words are command arguments. */
6349          pAr->azArg = &azArg[iArg];
6350          pAr->nArg = nArg-iArg;
6351          break;
6352        }
6353        n = strlen30(z);
6354
6355        if( z[1]!='-' ){
6356          int i;
6357          /* One or more short options */
6358          for(i=1; i<n; i++){
6359            const char *zArg = 0;
6360            struct ArSwitch *pOpt;
6361            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6362              if( z[i]==pOpt->cShort ) break;
6363            }
6364            if( pOpt==pEnd ){
6365              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6366            }
6367            if( pOpt->bArg ){
6368              if( i<(n-1) ){
6369                zArg = &z[i+1];
6370                i = n;
6371              }else{
6372                if( iArg>=(nArg-1) ){
6373                  return arErrorMsg(pAr, "option requires an argument: %c",
6374                                    z[i]);
6375                }
6376                zArg = azArg[++iArg];
6377              }
6378            }
6379            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6380          }
6381        }else if( z[2]=='\0' ){
6382          /* A -- option, indicating that all remaining command line words
6383          ** are command arguments.  */
6384          pAr->azArg = &azArg[iArg+1];
6385          pAr->nArg = nArg-iArg-1;
6386          break;
6387        }else{
6388          /* A long option */
6389          const char *zArg = 0;             /* Argument for option, if any */
6390          struct ArSwitch *pMatch = 0;      /* Matching option */
6391          struct ArSwitch *pOpt;            /* Iterator */
6392          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6393            const char *zLong = pOpt->zLong;
6394            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6395              if( pMatch ){
6396                return arErrorMsg(pAr, "ambiguous option: %s",z);
6397              }else{
6398                pMatch = pOpt;
6399              }
6400            }
6401          }
6402
6403          if( pMatch==0 ){
6404            return arErrorMsg(pAr, "unrecognized option: %s", z);
6405          }
6406          if( pMatch->bArg ){
6407            if( iArg>=(nArg-1) ){
6408              return arErrorMsg(pAr, "option requires an argument: %s", z);
6409            }
6410            zArg = azArg[++iArg];
6411          }
6412          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6413        }
6414      }
6415    }
6416  }
6417
6418  return SQLITE_OK;
6419}
6420
6421/*
6422** This function assumes that all arguments within the ArCommand.azArg[]
6423** array refer to archive members, as for the --extract, --list or --remove
6424** commands. It checks that each of them are "present". If any specified
6425** file is not present in the archive, an error is printed to stderr and an
6426** error code returned. Otherwise, if all specified arguments are present
6427** in the archive, SQLITE_OK is returned. Here, "present" means either an
6428** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6429** when pAr->bGlob is true.
6430**
6431** This function strips any trailing '/' characters from each argument.
6432** This is consistent with the way the [tar] command seems to work on
6433** Linux.
6434*/
6435static int arCheckEntries(ArCommand *pAr){
6436  int rc = SQLITE_OK;
6437  if( pAr->nArg ){
6438    int i, j;
6439    sqlite3_stmt *pTest = 0;
6440    const char *zSel = (pAr->bGlob)
6441      ? "SELECT name FROM %s WHERE glob($name,name)"
6442      : "SELECT name FROM %s WHERE name=$name";
6443
6444    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6445    j = sqlite3_bind_parameter_index(pTest, "$name");
6446    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6447      char *z = pAr->azArg[i];
6448      int n = strlen30(z);
6449      int bOk = 0;
6450      while( n>0 && z[n-1]=='/' ) n--;
6451      z[n] = '\0';
6452      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6453      if( SQLITE_ROW==sqlite3_step(pTest) ){
6454        bOk = 1;
6455      }
6456      shellReset(&rc, pTest);
6457      if( rc==SQLITE_OK && bOk==0 ){
6458        utf8_printf(stderr, "not found in archive: %s\n", z);
6459        rc = SQLITE_ERROR;
6460      }
6461    }
6462    shellFinalize(&rc, pTest);
6463  }
6464  return rc;
6465}
6466
6467/*
6468** Format a WHERE clause that can be used against the "sqlar" table to
6469** identify all archive members that match the command arguments held
6470** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6471** The caller is responsible for eventually calling sqlite3_free() on
6472** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6473** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6474*/
6475static void arWhereClause(
6476  int *pRc,
6477  ArCommand *pAr,
6478  char **pzWhere                  /* OUT: New WHERE clause */
6479){
6480  char *zWhere = 0;
6481  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6482  if( *pRc==SQLITE_OK ){
6483    if( pAr->nArg==0 ){
6484      zWhere = sqlite3_mprintf("1");
6485    }else{
6486      int i;
6487      const char *zSep = "";
6488      for(i=0; i<pAr->nArg; i++){
6489        const char *z = pAr->azArg[i];
6490        zWhere = sqlite3_mprintf(
6491          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6492          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6493        );
6494        if( zWhere==0 ){
6495          *pRc = SQLITE_NOMEM;
6496          break;
6497        }
6498        zSep = " OR ";
6499      }
6500    }
6501  }
6502  *pzWhere = zWhere;
6503}
6504
6505/*
6506** Implementation of .ar "lisT" command.
6507*/
6508static int arListCommand(ArCommand *pAr){
6509  const char *zSql = "SELECT %s FROM %s WHERE %s";
6510  const char *azCols[] = {
6511    "name",
6512    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6513  };
6514
6515  char *zWhere = 0;
6516  sqlite3_stmt *pSql = 0;
6517  int rc;
6518
6519  rc = arCheckEntries(pAr);
6520  arWhereClause(&rc, pAr, &zWhere);
6521
6522  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6523                     pAr->zSrcTable, zWhere);
6524  if( pAr->bDryRun ){
6525    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6526  }else{
6527    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6528      if( pAr->bVerbose ){
6529        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6530            sqlite3_column_text(pSql, 0),
6531            sqlite3_column_int(pSql, 1),
6532            sqlite3_column_text(pSql, 2),
6533            sqlite3_column_text(pSql, 3)
6534        );
6535      }else{
6536        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6537      }
6538    }
6539  }
6540  shellFinalize(&rc, pSql);
6541  sqlite3_free(zWhere);
6542  return rc;
6543}
6544
6545
6546/*
6547** Implementation of .ar "Remove" command.
6548*/
6549static int arRemoveCommand(ArCommand *pAr){
6550  int rc = 0;
6551  char *zSql = 0;
6552  char *zWhere = 0;
6553
6554  if( pAr->nArg ){
6555    /* Verify that args actually exist within the archive before proceeding.
6556    ** And formulate a WHERE clause to match them.  */
6557    rc = arCheckEntries(pAr);
6558    arWhereClause(&rc, pAr, &zWhere);
6559  }
6560  if( rc==SQLITE_OK ){
6561    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6562                           pAr->zSrcTable, zWhere);
6563    if( pAr->bDryRun ){
6564      utf8_printf(pAr->p->out, "%s\n", zSql);
6565    }else{
6566      char *zErr = 0;
6567      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6568      if( rc==SQLITE_OK ){
6569        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6570        if( rc!=SQLITE_OK ){
6571          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6572        }else{
6573          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6574        }
6575      }
6576      if( zErr ){
6577        utf8_printf(stdout, "ERROR: %s\n", zErr);
6578        sqlite3_free(zErr);
6579      }
6580    }
6581  }
6582  sqlite3_free(zWhere);
6583  sqlite3_free(zSql);
6584  return rc;
6585}
6586
6587/*
6588** Implementation of .ar "eXtract" command.
6589*/
6590static int arExtractCommand(ArCommand *pAr){
6591  const char *zSql1 =
6592    "SELECT "
6593    " ($dir || name),"
6594    " writefile(($dir || name), %s, mode, mtime) "
6595    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6596    " AND name NOT GLOB '*..[/\\]*'";
6597
6598  const char *azExtraArg[] = {
6599    "sqlar_uncompress(data, sz)",
6600    "data"
6601  };
6602
6603  sqlite3_stmt *pSql = 0;
6604  int rc = SQLITE_OK;
6605  char *zDir = 0;
6606  char *zWhere = 0;
6607  int i, j;
6608
6609  /* If arguments are specified, check that they actually exist within
6610  ** the archive before proceeding. And formulate a WHERE clause to
6611  ** match them.  */
6612  rc = arCheckEntries(pAr);
6613  arWhereClause(&rc, pAr, &zWhere);
6614
6615  if( rc==SQLITE_OK ){
6616    if( pAr->zDir ){
6617      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6618    }else{
6619      zDir = sqlite3_mprintf("");
6620    }
6621    if( zDir==0 ) rc = SQLITE_NOMEM;
6622  }
6623
6624  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6625      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6626  );
6627
6628  if( rc==SQLITE_OK ){
6629    j = sqlite3_bind_parameter_index(pSql, "$dir");
6630    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6631
6632    /* Run the SELECT statement twice. The first time, writefile() is called
6633    ** for all archive members that should be extracted. The second time,
6634    ** only for the directories. This is because the timestamps for
6635    ** extracted directories must be reset after they are populated (as
6636    ** populating them changes the timestamp).  */
6637    for(i=0; i<2; i++){
6638      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6639      sqlite3_bind_int(pSql, j, i);
6640      if( pAr->bDryRun ){
6641        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6642      }else{
6643        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6644          if( i==0 && pAr->bVerbose ){
6645            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6646          }
6647        }
6648      }
6649      shellReset(&rc, pSql);
6650    }
6651    shellFinalize(&rc, pSql);
6652  }
6653
6654  sqlite3_free(zDir);
6655  sqlite3_free(zWhere);
6656  return rc;
6657}
6658
6659/*
6660** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6661*/
6662static int arExecSql(ArCommand *pAr, const char *zSql){
6663  int rc;
6664  if( pAr->bDryRun ){
6665    utf8_printf(pAr->p->out, "%s\n", zSql);
6666    rc = SQLITE_OK;
6667  }else{
6668    char *zErr = 0;
6669    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6670    if( zErr ){
6671      utf8_printf(stdout, "ERROR: %s\n", zErr);
6672      sqlite3_free(zErr);
6673    }
6674  }
6675  return rc;
6676}
6677
6678
6679/*
6680** Implementation of .ar "create", "insert", and "update" commands.
6681**
6682**     create    ->     Create a new SQL archive
6683**     insert    ->     Insert or reinsert all files listed
6684**     update    ->     Insert files that have changed or that were not
6685**                      previously in the archive
6686**
6687** Create the "sqlar" table in the database if it does not already exist.
6688** Then add each file in the azFile[] array to the archive. Directories
6689** are added recursively. If argument bVerbose is non-zero, a message is
6690** printed on stdout for each file archived.
6691**
6692** The create command is the same as update, except that it drops
6693** any existing "sqlar" table before beginning.  The "insert" command
6694** always overwrites every file named on the command-line, where as
6695** "update" only overwrites if the size or mtime or mode has changed.
6696*/
6697static int arCreateOrUpdateCommand(
6698  ArCommand *pAr,                 /* Command arguments and options */
6699  int bUpdate,                    /* true for a --create. */
6700  int bOnlyIfChanged              /* Only update if file has changed */
6701){
6702  const char *zCreate =
6703      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6704      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6705      "  mode INT,               -- access permissions\n"
6706      "  mtime INT,              -- last modification time\n"
6707      "  sz INT,                 -- original file size\n"
6708      "  data BLOB               -- compressed content\n"
6709      ")";
6710  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6711  const char *zInsertFmt[2] = {
6712     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6713     "  SELECT\n"
6714     "    %s,\n"
6715     "    mode,\n"
6716     "    mtime,\n"
6717     "    CASE substr(lsmode(mode),1,1)\n"
6718     "      WHEN '-' THEN length(data)\n"
6719     "      WHEN 'd' THEN 0\n"
6720     "      ELSE -1 END,\n"
6721     "    sqlar_compress(data)\n"
6722     "  FROM fsdir(%Q,%Q) AS disk\n"
6723     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6724     ,
6725     "REPLACE INTO %s(name,mode,mtime,data)\n"
6726     "  SELECT\n"
6727     "    %s,\n"
6728     "    mode,\n"
6729     "    mtime,\n"
6730     "    data\n"
6731     "  FROM fsdir(%Q,%Q) AS disk\n"
6732     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6733  };
6734  int i;                          /* For iterating through azFile[] */
6735  int rc;                         /* Return code */
6736  const char *zTab = 0;           /* SQL table into which to insert */
6737  char *zSql;
6738  char zTemp[50];
6739  char *zExists = 0;
6740
6741  arExecSql(pAr, "PRAGMA page_size=512");
6742  rc = arExecSql(pAr, "SAVEPOINT ar;");
6743  if( rc!=SQLITE_OK ) return rc;
6744  zTemp[0] = 0;
6745  if( pAr->bZip ){
6746    /* Initialize the zipfile virtual table, if necessary */
6747    if( pAr->zFile ){
6748      sqlite3_uint64 r;
6749      sqlite3_randomness(sizeof(r),&r);
6750      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6751      zTab = zTemp;
6752      zSql = sqlite3_mprintf(
6753         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6754         zTab, pAr->zFile
6755      );
6756      rc = arExecSql(pAr, zSql);
6757      sqlite3_free(zSql);
6758    }else{
6759      zTab = "zip";
6760    }
6761  }else{
6762    /* Initialize the table for an SQLAR */
6763    zTab = "sqlar";
6764    if( bUpdate==0 ){
6765      rc = arExecSql(pAr, zDrop);
6766      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6767    }
6768    rc = arExecSql(pAr, zCreate);
6769  }
6770  if( bOnlyIfChanged ){
6771    zExists = sqlite3_mprintf(
6772      " AND NOT EXISTS("
6773          "SELECT 1 FROM %s AS mem"
6774          " WHERE mem.name=disk.name"
6775          " AND mem.mtime=disk.mtime"
6776          " AND mem.mode=disk.mode)", zTab);
6777  }else{
6778    zExists = sqlite3_mprintf("");
6779  }
6780  if( zExists==0 ) rc = SQLITE_NOMEM;
6781  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6782    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6783        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6784        pAr->azArg[i], pAr->zDir, zExists);
6785    rc = arExecSql(pAr, zSql2);
6786    sqlite3_free(zSql2);
6787  }
6788end_ar_transaction:
6789  if( rc!=SQLITE_OK ){
6790    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6791  }else{
6792    rc = arExecSql(pAr, "RELEASE ar;");
6793    if( pAr->bZip && pAr->zFile ){
6794      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6795      arExecSql(pAr, zSql);
6796      sqlite3_free(zSql);
6797    }
6798  }
6799  sqlite3_free(zExists);
6800  return rc;
6801}
6802
6803/*
6804** Implementation of ".ar" dot command.
6805*/
6806static int arDotCommand(
6807  ShellState *pState,          /* Current shell tool state */
6808  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
6809  char **azArg,                /* Array of arguments passed to dot command */
6810  int nArg                     /* Number of entries in azArg[] */
6811){
6812  ArCommand cmd;
6813  int rc;
6814  memset(&cmd, 0, sizeof(cmd));
6815  cmd.fromCmdLine = fromCmdLine;
6816  rc = arParseCommand(azArg, nArg, &cmd);
6817  if( rc==SQLITE_OK ){
6818    int eDbType = SHELL_OPEN_UNSPEC;
6819    cmd.p = pState;
6820    cmd.db = pState->db;
6821    if( cmd.zFile ){
6822      eDbType = deduceDatabaseType(cmd.zFile, 1);
6823    }else{
6824      eDbType = pState->openMode;
6825    }
6826    if( eDbType==SHELL_OPEN_ZIPFILE ){
6827      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6828        if( cmd.zFile==0 ){
6829          cmd.zSrcTable = sqlite3_mprintf("zip");
6830        }else{
6831          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6832        }
6833      }
6834      cmd.bZip = 1;
6835    }else if( cmd.zFile ){
6836      int flags;
6837      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6838      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6839           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
6840        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6841      }else{
6842        flags = SQLITE_OPEN_READONLY;
6843      }
6844      cmd.db = 0;
6845      if( cmd.bDryRun ){
6846        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6847             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6848      }
6849      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6850             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6851      if( rc!=SQLITE_OK ){
6852        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6853            cmd.zFile, sqlite3_errmsg(cmd.db)
6854        );
6855        goto end_ar_command;
6856      }
6857      sqlite3_fileio_init(cmd.db, 0, 0);
6858      sqlite3_sqlar_init(cmd.db, 0, 0);
6859      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6860                              shellPutsFunc, 0, 0);
6861
6862    }
6863    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6864      if( cmd.eCmd!=AR_CMD_CREATE
6865       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6866      ){
6867        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6868        rc = SQLITE_ERROR;
6869        goto end_ar_command;
6870      }
6871      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6872    }
6873
6874    switch( cmd.eCmd ){
6875      case AR_CMD_CREATE:
6876        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6877        break;
6878
6879      case AR_CMD_EXTRACT:
6880        rc = arExtractCommand(&cmd);
6881        break;
6882
6883      case AR_CMD_LIST:
6884        rc = arListCommand(&cmd);
6885        break;
6886
6887      case AR_CMD_HELP:
6888        arUsage(pState->out);
6889        break;
6890
6891      case AR_CMD_INSERT:
6892        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6893        break;
6894
6895      case AR_CMD_REMOVE:
6896        rc = arRemoveCommand(&cmd);
6897        break;
6898
6899      default:
6900        assert( cmd.eCmd==AR_CMD_UPDATE );
6901        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6902        break;
6903    }
6904  }
6905end_ar_command:
6906  if( cmd.db!=pState->db ){
6907    close_db(cmd.db);
6908  }
6909  sqlite3_free(cmd.zSrcTable);
6910
6911  return rc;
6912}
6913/* End of the ".archive" or ".ar" command logic
6914*******************************************************************************/
6915#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6916
6917#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6918/*
6919** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6920** Otherwise, the SQL statement or statements in zSql are executed using
6921** database connection db and the error code written to *pRc before
6922** this function returns.
6923*/
6924static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6925  int rc = *pRc;
6926  if( rc==SQLITE_OK ){
6927    char *zErr = 0;
6928    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6929    if( rc!=SQLITE_OK ){
6930      raw_printf(stderr, "SQL error: %s\n", zErr);
6931    }
6932    sqlite3_free(zErr);
6933    *pRc = rc;
6934  }
6935}
6936
6937/*
6938** Like shellExec(), except that zFmt is a printf() style format string.
6939*/
6940static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6941  char *z = 0;
6942  if( *pRc==SQLITE_OK ){
6943    va_list ap;
6944    va_start(ap, zFmt);
6945    z = sqlite3_vmprintf(zFmt, ap);
6946    va_end(ap);
6947    if( z==0 ){
6948      *pRc = SQLITE_NOMEM;
6949    }else{
6950      shellExec(db, pRc, z);
6951    }
6952    sqlite3_free(z);
6953  }
6954}
6955
6956/*
6957** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6958** Otherwise, an attempt is made to allocate, zero and return a pointer
6959** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6960** to SQLITE_NOMEM and NULL returned.
6961*/
6962static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6963  void *pRet = 0;
6964  if( *pRc==SQLITE_OK ){
6965    pRet = sqlite3_malloc64(nByte);
6966    if( pRet==0 ){
6967      *pRc = SQLITE_NOMEM;
6968    }else{
6969      memset(pRet, 0, nByte);
6970    }
6971  }
6972  return pRet;
6973}
6974
6975/*
6976** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6977** Otherwise, zFmt is treated as a printf() style string. The result of
6978** formatting it along with any trailing arguments is written into a
6979** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6980** It is the responsibility of the caller to eventually free this buffer
6981** using a call to sqlite3_free().
6982**
6983** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6984** pointer returned.
6985*/
6986static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6987  char *z = 0;
6988  if( *pRc==SQLITE_OK ){
6989    va_list ap;
6990    va_start(ap, zFmt);
6991    z = sqlite3_vmprintf(zFmt, ap);
6992    va_end(ap);
6993    if( z==0 ){
6994      *pRc = SQLITE_NOMEM;
6995    }
6996  }
6997  return z;
6998}
6999
7000/*
7001** When running the ".recover" command, each output table, and the special
7002** orphaned row table if it is required, is represented by an instance
7003** of the following struct.
7004*/
7005typedef struct RecoverTable RecoverTable;
7006struct RecoverTable {
7007  char *zQuoted;                  /* Quoted version of table name */
7008  int nCol;                       /* Number of columns in table */
7009  char **azlCol;                  /* Array of column lists */
7010  int iPk;                        /* Index of IPK column */
7011};
7012
7013/*
7014** Free a RecoverTable object allocated by recoverFindTable() or
7015** recoverOrphanTable().
7016*/
7017static void recoverFreeTable(RecoverTable *pTab){
7018  if( pTab ){
7019    sqlite3_free(pTab->zQuoted);
7020    if( pTab->azlCol ){
7021      int i;
7022      for(i=0; i<=pTab->nCol; i++){
7023        sqlite3_free(pTab->azlCol[i]);
7024      }
7025      sqlite3_free(pTab->azlCol);
7026    }
7027    sqlite3_free(pTab);
7028  }
7029}
7030
7031/*
7032** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7033** Otherwise, it allocates and returns a RecoverTable object based on the
7034** final four arguments passed to this function. It is the responsibility
7035** of the caller to eventually free the returned object using
7036** recoverFreeTable().
7037*/
7038static RecoverTable *recoverNewTable(
7039  int *pRc,                       /* IN/OUT: Error code */
7040  const char *zName,              /* Name of table */
7041  const char *zSql,               /* CREATE TABLE statement */
7042  int bIntkey,
7043  int nCol
7044){
7045  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7046  int rc = *pRc;
7047  RecoverTable *pTab = 0;
7048
7049  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7050  if( rc==SQLITE_OK ){
7051    int nSqlCol = 0;
7052    int bSqlIntkey = 0;
7053    sqlite3_stmt *pStmt = 0;
7054
7055    rc = sqlite3_open("", &dbtmp);
7056    if( rc==SQLITE_OK ){
7057      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7058                              shellIdQuote, 0, 0);
7059    }
7060    if( rc==SQLITE_OK ){
7061      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7062    }
7063    if( rc==SQLITE_OK ){
7064      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7065      if( rc==SQLITE_ERROR ){
7066        rc = SQLITE_OK;
7067        goto finished;
7068      }
7069    }
7070    shellPreparePrintf(dbtmp, &rc, &pStmt,
7071        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7072    );
7073    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7074      nSqlCol = sqlite3_column_int(pStmt, 0);
7075    }
7076    shellFinalize(&rc, pStmt);
7077
7078    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7079      goto finished;
7080    }
7081
7082    shellPreparePrintf(dbtmp, &rc, &pStmt,
7083      "SELECT ("
7084      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7085      ") FROM sqlite_schema WHERE name = %Q", zName
7086    );
7087    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7088      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7089    }
7090    shellFinalize(&rc, pStmt);
7091
7092    if( bIntkey==bSqlIntkey ){
7093      int i;
7094      const char *zPk = "_rowid_";
7095      sqlite3_stmt *pPkFinder = 0;
7096
7097      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7098      ** set zPk to the name of the PK column, and pTab->iPk to the index
7099      ** of the column, where columns are 0-numbered from left to right.
7100      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7101      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7102      pTab->iPk = -2;
7103      if( bIntkey ){
7104        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7105          "SELECT cid, name FROM pragma_table_info(%Q) "
7106          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7107          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7108          , zName, zName
7109        );
7110        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7111          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7112          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7113          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7114        }
7115      }
7116
7117      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7118      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7119      pTab->nCol = nSqlCol;
7120
7121      if( bIntkey ){
7122        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7123      }else{
7124        pTab->azlCol[0] = shellMPrintf(&rc, "");
7125      }
7126      i = 1;
7127      shellPreparePrintf(dbtmp, &rc, &pStmt,
7128          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7129          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7130          "FROM pragma_table_info(%Q)",
7131          bIntkey ? ", " : "", pTab->iPk,
7132          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7133          zName
7134      );
7135      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7136        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7137        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7138        i++;
7139      }
7140      shellFinalize(&rc, pStmt);
7141
7142      shellFinalize(&rc, pPkFinder);
7143    }
7144  }
7145
7146 finished:
7147  sqlite3_close(dbtmp);
7148  *pRc = rc;
7149  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7150    recoverFreeTable(pTab);
7151    pTab = 0;
7152  }
7153  return pTab;
7154}
7155
7156/*
7157** This function is called to search the schema recovered from the
7158** sqlite_schema table of the (possibly) corrupt database as part
7159** of a ".recover" command. Specifically, for a table with root page
7160** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7161** table must be a WITHOUT ROWID table, or if non-zero, not one of
7162** those.
7163**
7164** If a table is found, a (RecoverTable*) object is returned. Or, if
7165** no such table is found, but bIntkey is false and iRoot is the
7166** root page of an index in the recovered schema, then (*pbNoop) is
7167** set to true and NULL returned. Or, if there is no such table or
7168** index, NULL is returned and (*pbNoop) set to 0, indicating that
7169** the caller should write data to the orphans table.
7170*/
7171static RecoverTable *recoverFindTable(
7172  ShellState *pState,             /* Shell state object */
7173  int *pRc,                       /* IN/OUT: Error code */
7174  int iRoot,                      /* Root page of table */
7175  int bIntkey,                    /* True for an intkey table */
7176  int nCol,                       /* Number of columns in table */
7177  int *pbNoop                     /* OUT: True if iRoot is root of index */
7178){
7179  sqlite3_stmt *pStmt = 0;
7180  RecoverTable *pRet = 0;
7181  int bNoop = 0;
7182  const char *zSql = 0;
7183  const char *zName = 0;
7184
7185  /* Search the recovered schema for an object with root page iRoot. */
7186  shellPreparePrintf(pState->db, pRc, &pStmt,
7187      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7188  );
7189  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7190    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7191    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7192      bNoop = 1;
7193      break;
7194    }
7195    if( sqlite3_stricmp(zType, "table")==0 ){
7196      zName = (const char*)sqlite3_column_text(pStmt, 1);
7197      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7198      if( zName!=0 && zSql!=0 ){
7199        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7200        break;
7201      }
7202    }
7203  }
7204
7205  shellFinalize(pRc, pStmt);
7206  *pbNoop = bNoop;
7207  return pRet;
7208}
7209
7210/*
7211** Return a RecoverTable object representing the orphans table.
7212*/
7213static RecoverTable *recoverOrphanTable(
7214  ShellState *pState,             /* Shell state object */
7215  int *pRc,                       /* IN/OUT: Error code */
7216  const char *zLostAndFound,      /* Base name for orphans table */
7217  int nCol                        /* Number of user data columns */
7218){
7219  RecoverTable *pTab = 0;
7220  if( nCol>=0 && *pRc==SQLITE_OK ){
7221    int i;
7222
7223    /* This block determines the name of the orphan table. The prefered
7224    ** name is zLostAndFound. But if that clashes with another name
7225    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7226    ** and so on until a non-clashing name is found.  */
7227    int iTab = 0;
7228    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7229    sqlite3_stmt *pTest = 0;
7230    shellPrepare(pState->db, pRc,
7231        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7232    );
7233    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7234    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7235      shellReset(pRc, pTest);
7236      sqlite3_free(zTab);
7237      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7238      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7239    }
7240    shellFinalize(pRc, pTest);
7241
7242    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7243    if( pTab ){
7244      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7245      pTab->nCol = nCol;
7246      pTab->iPk = -2;
7247      if( nCol>0 ){
7248        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7249        if( pTab->azlCol ){
7250          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7251          for(i=nCol-1; i>=0; i--){
7252            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7253          }
7254        }
7255      }
7256
7257      if( *pRc!=SQLITE_OK ){
7258        recoverFreeTable(pTab);
7259        pTab = 0;
7260      }else{
7261        raw_printf(pState->out,
7262            "CREATE TABLE %s(rootpgno INTEGER, "
7263            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7264        );
7265        for(i=0; i<nCol; i++){
7266          raw_printf(pState->out, ", c%d", i);
7267        }
7268        raw_printf(pState->out, ");\n");
7269      }
7270    }
7271    sqlite3_free(zTab);
7272  }
7273  return pTab;
7274}
7275
7276/*
7277** This function is called to recover data from the database. A script
7278** to construct a new database containing all recovered data is output
7279** on stream pState->out.
7280*/
7281static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7282  int rc = SQLITE_OK;
7283  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7284  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7285  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7286  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7287  const char *zLostAndFound = "lost_and_found";
7288  int i;
7289  int nOrphan = -1;
7290  RecoverTable *pOrphan = 0;
7291
7292  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7293  int bRowids = 1;                /* 0 if --no-rowids */
7294  for(i=1; i<nArg; i++){
7295    char *z = azArg[i];
7296    int n;
7297    if( z[0]=='-' && z[1]=='-' ) z++;
7298    n = strlen30(z);
7299    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7300      bFreelist = 0;
7301    }else
7302    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7303      i++;
7304      zRecoveryDb = azArg[i];
7305    }else
7306    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7307      i++;
7308      zLostAndFound = azArg[i];
7309    }else
7310    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7311      bRowids = 0;
7312    }
7313    else{
7314      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7315      showHelp(pState->out, azArg[0]);
7316      return 1;
7317    }
7318  }
7319
7320  shellExecPrintf(pState->db, &rc,
7321    /* Attach an in-memory database named 'recovery'. Create an indexed
7322    ** cache of the sqlite_dbptr virtual table. */
7323    "PRAGMA writable_schema = on;"
7324    "ATTACH %Q AS recovery;"
7325    "DROP TABLE IF EXISTS recovery.dbptr;"
7326    "DROP TABLE IF EXISTS recovery.freelist;"
7327    "DROP TABLE IF EXISTS recovery.map;"
7328    "DROP TABLE IF EXISTS recovery.schema;"
7329    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7330  );
7331
7332  if( bFreelist ){
7333    shellExec(pState->db, &rc,
7334      "WITH trunk(pgno) AS ("
7335      "  SELECT shell_int32("
7336      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7337      "      WHERE x>0"
7338      "    UNION"
7339      "  SELECT shell_int32("
7340      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7341      "      FROM trunk WHERE x>0"
7342      "),"
7343      "freelist(data, n, freepgno) AS ("
7344      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7345      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7346      "    UNION ALL"
7347      "  SELECT data, n-1, shell_int32(data, 2+n) "
7348      "      FROM freelist WHERE n>=0"
7349      ")"
7350      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7351    );
7352  }
7353
7354  /* If this is an auto-vacuum database, add all pointer-map pages to
7355  ** the freelist table. Do this regardless of whether or not
7356  ** --freelist-corrupt was specified.  */
7357  shellExec(pState->db, &rc,
7358    "WITH ptrmap(pgno) AS ("
7359    "  SELECT 2 WHERE shell_int32("
7360    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7361    "  )"
7362    "    UNION ALL "
7363    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7364    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7365    ")"
7366    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7367  );
7368
7369  shellExec(pState->db, &rc,
7370    "CREATE TABLE recovery.dbptr("
7371    "      pgno, child, PRIMARY KEY(child, pgno)"
7372    ") WITHOUT ROWID;"
7373    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7374    "    SELECT * FROM sqlite_dbptr"
7375    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7376
7377    /* Delete any pointer to page 1. This ensures that page 1 is considered
7378    ** a root page, regardless of how corrupt the db is. */
7379    "DELETE FROM recovery.dbptr WHERE child = 1;"
7380
7381    /* Delete all pointers to any pages that have more than one pointer
7382    ** to them. Such pages will be treated as root pages when recovering
7383    ** data.  */
7384    "DELETE FROM recovery.dbptr WHERE child IN ("
7385    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7386    ");"
7387
7388    /* Create the "map" table that will (eventually) contain instructions
7389    ** for dealing with each page in the db that contains one or more
7390    ** records. */
7391    "CREATE TABLE recovery.map("
7392      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7393    ");"
7394
7395    /* Populate table [map]. If there are circular loops of pages in the
7396    ** database, the following adds all pages in such a loop to the map
7397    ** as individual root pages. This could be handled better.  */
7398    "WITH pages(i, maxlen) AS ("
7399    "  SELECT page_count, ("
7400    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7401    "  ) FROM pragma_page_count WHERE page_count>0"
7402    "    UNION ALL"
7403    "  SELECT i-1, ("
7404    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7405    "  ) FROM pages WHERE i>=2"
7406    ")"
7407    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7408    "  SELECT i, maxlen, NULL, ("
7409    "    WITH p(orig, pgno, parent) AS ("
7410    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7411    "        UNION "
7412    "      SELECT i, p.parent, "
7413    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7414    "    )"
7415    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7416    ") "
7417    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7418    "UPDATE recovery.map AS o SET intkey = ("
7419    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7420    ");"
7421
7422    /* Extract data from page 1 and any linked pages into table
7423    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7424    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7425    "INSERT INTO recovery.schema SELECT "
7426    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7427    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7428    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7429    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7430    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7431    "FROM sqlite_dbdata WHERE pgno IN ("
7432    "  SELECT pgno FROM recovery.map WHERE root=1"
7433    ")"
7434    "GROUP BY pgno, cell;"
7435    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7436  );
7437
7438  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7439  ** CREATE TABLE statements that extracted from the existing schema.  */
7440  if( rc==SQLITE_OK ){
7441    sqlite3_stmt *pStmt = 0;
7442    /* ".recover" might output content in an order which causes immediate
7443    ** foreign key constraints to be violated. So disable foreign-key
7444    ** constraint enforcement to prevent problems when running the output
7445    ** script. */
7446    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7447    raw_printf(pState->out, "BEGIN;\n");
7448    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7449    shellPrepare(pState->db, &rc,
7450        "SELECT sql FROM recovery.schema "
7451        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7452    );
7453    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7454      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7455      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7456          &zCreateTable[12]
7457      );
7458    }
7459    shellFinalize(&rc, pStmt);
7460  }
7461
7462  /* Figure out if an orphan table will be required. And if so, how many
7463  ** user columns it should contain */
7464  shellPrepare(pState->db, &rc,
7465      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7466      , &pLoop
7467  );
7468  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7469    nOrphan = sqlite3_column_int(pLoop, 0);
7470  }
7471  shellFinalize(&rc, pLoop);
7472  pLoop = 0;
7473
7474  shellPrepare(pState->db, &rc,
7475      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7476  );
7477
7478  shellPrepare(pState->db, &rc,
7479      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7480      "(case when (? AND field<0) then NULL else value end)"
7481      "), ', ')"
7482      ", min(field) "
7483      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7484      "GROUP BY cell", &pCells
7485  );
7486
7487  /* Loop through each root page. */
7488  shellPrepare(pState->db, &rc,
7489      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7490      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7491      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7492      ")", &pLoop
7493  );
7494  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7495    int iRoot = sqlite3_column_int(pLoop, 0);
7496    int bIntkey = sqlite3_column_int(pLoop, 1);
7497    int nCol = sqlite3_column_int(pLoop, 2);
7498    int bNoop = 0;
7499    RecoverTable *pTab;
7500
7501    assert( bIntkey==0 || bIntkey==1 );
7502    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7503    if( bNoop || rc ) continue;
7504    if( pTab==0 ){
7505      if( pOrphan==0 ){
7506        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7507      }
7508      pTab = pOrphan;
7509      if( pTab==0 ) break;
7510    }
7511
7512    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7513      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7514    }
7515    sqlite3_bind_int(pPages, 1, iRoot);
7516    if( bRowids==0 && pTab->iPk<0 ){
7517      sqlite3_bind_int(pCells, 1, 1);
7518    }else{
7519      sqlite3_bind_int(pCells, 1, 0);
7520    }
7521    sqlite3_bind_int(pCells, 3, pTab->iPk);
7522
7523    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7524      int iPgno = sqlite3_column_int(pPages, 0);
7525      sqlite3_bind_int(pCells, 2, iPgno);
7526      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7527        int nField = sqlite3_column_int(pCells, 0);
7528        int iMin = sqlite3_column_int(pCells, 2);
7529        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7530
7531        RecoverTable *pTab2 = pTab;
7532        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7533          if( pOrphan==0 ){
7534            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7535          }
7536          pTab2 = pOrphan;
7537          if( pTab2==0 ) break;
7538        }
7539
7540        nField = nField+1;
7541        if( pTab2==pOrphan ){
7542          raw_printf(pState->out,
7543              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7544              pTab2->zQuoted, iRoot, iPgno, nField,
7545              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7546          );
7547        }else{
7548          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7549              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7550          );
7551        }
7552      }
7553      shellReset(&rc, pCells);
7554    }
7555    shellReset(&rc, pPages);
7556    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7557  }
7558  shellFinalize(&rc, pLoop);
7559  shellFinalize(&rc, pPages);
7560  shellFinalize(&rc, pCells);
7561  recoverFreeTable(pOrphan);
7562
7563  /* The rest of the schema */
7564  if( rc==SQLITE_OK ){
7565    sqlite3_stmt *pStmt = 0;
7566    shellPrepare(pState->db, &rc,
7567        "SELECT sql, name FROM recovery.schema "
7568        "WHERE sql NOT LIKE 'create table%'", &pStmt
7569    );
7570    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7571      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7572      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7573        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7574        char *zPrint = shellMPrintf(&rc,
7575          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7576          zName, zName, zSql
7577        );
7578        raw_printf(pState->out, "%s;\n", zPrint);
7579        sqlite3_free(zPrint);
7580      }else{
7581        raw_printf(pState->out, "%s;\n", zSql);
7582      }
7583    }
7584    shellFinalize(&rc, pStmt);
7585  }
7586
7587  if( rc==SQLITE_OK ){
7588    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7589    raw_printf(pState->out, "COMMIT;\n");
7590  }
7591  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7592  return rc;
7593}
7594#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7595
7596/*
7597** If an input line begins with "." then invoke this routine to
7598** process that line.
7599**
7600** Return 1 on error, 2 to exit, and 0 otherwise.
7601*/
7602static int do_meta_command(char *zLine, ShellState *p){
7603  int h = 1;
7604  int nArg = 0;
7605  int n, c;
7606  int rc = 0;
7607  char *azArg[52];
7608
7609#ifndef SQLITE_OMIT_VIRTUALTABLE
7610  if( p->expert.pExpert ){
7611    expertFinish(p, 1, 0);
7612  }
7613#endif
7614
7615  /* Parse the input line into tokens.
7616  */
7617  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7618    while( IsSpace(zLine[h]) ){ h++; }
7619    if( zLine[h]==0 ) break;
7620    if( zLine[h]=='\'' || zLine[h]=='"' ){
7621      int delim = zLine[h++];
7622      azArg[nArg++] = &zLine[h];
7623      while( zLine[h] && zLine[h]!=delim ){
7624        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7625        h++;
7626      }
7627      if( zLine[h]==delim ){
7628        zLine[h++] = 0;
7629      }
7630      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7631    }else{
7632      azArg[nArg++] = &zLine[h];
7633      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7634      if( zLine[h] ) zLine[h++] = 0;
7635      resolve_backslashes(azArg[nArg-1]);
7636    }
7637  }
7638  azArg[nArg] = 0;
7639
7640  /* Process the input line.
7641  */
7642  if( nArg==0 ) return 0; /* no tokens, no error */
7643  n = strlen30(azArg[0]);
7644  c = azArg[0][0];
7645  clearTempFile(p);
7646
7647#ifndef SQLITE_OMIT_AUTHORIZATION
7648  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7649    if( nArg!=2 ){
7650      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7651      rc = 1;
7652      goto meta_command_exit;
7653    }
7654    open_db(p, 0);
7655    if( booleanValue(azArg[1]) ){
7656      sqlite3_set_authorizer(p->db, shellAuth, p);
7657    }else if( p->bSafeModePersist ){
7658      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7659    }else{
7660      sqlite3_set_authorizer(p->db, 0, 0);
7661    }
7662  }else
7663#endif
7664
7665#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7666  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7667    open_db(p, 0);
7668    failIfSafeMode(p, "cannot run .archive in safe mode");
7669    rc = arDotCommand(p, 0, azArg, nArg);
7670  }else
7671#endif
7672
7673  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7674   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7675  ){
7676    const char *zDestFile = 0;
7677    const char *zDb = 0;
7678    sqlite3 *pDest;
7679    sqlite3_backup *pBackup;
7680    int j;
7681    int bAsync = 0;
7682    const char *zVfs = 0;
7683    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7684    for(j=1; j<nArg; j++){
7685      const char *z = azArg[j];
7686      if( z[0]=='-' ){
7687        if( z[1]=='-' ) z++;
7688        if( strcmp(z, "-append")==0 ){
7689          zVfs = "apndvfs";
7690        }else
7691        if( strcmp(z, "-async")==0 ){
7692          bAsync = 1;
7693        }else
7694        {
7695          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7696          return 1;
7697        }
7698      }else if( zDestFile==0 ){
7699        zDestFile = azArg[j];
7700      }else if( zDb==0 ){
7701        zDb = zDestFile;
7702        zDestFile = azArg[j];
7703      }else{
7704        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7705        return 1;
7706      }
7707    }
7708    if( zDestFile==0 ){
7709      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7710      return 1;
7711    }
7712    if( zDb==0 ) zDb = "main";
7713    rc = sqlite3_open_v2(zDestFile, &pDest,
7714                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7715    if( rc!=SQLITE_OK ){
7716      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7717      close_db(pDest);
7718      return 1;
7719    }
7720    if( bAsync ){
7721      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7722                   0, 0, 0);
7723    }
7724    open_db(p, 0);
7725    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7726    if( pBackup==0 ){
7727      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7728      close_db(pDest);
7729      return 1;
7730    }
7731    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7732    sqlite3_backup_finish(pBackup);
7733    if( rc==SQLITE_DONE ){
7734      rc = 0;
7735    }else{
7736      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7737      rc = 1;
7738    }
7739    close_db(pDest);
7740  }else
7741
7742  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7743    if( nArg==2 ){
7744      bail_on_error = booleanValue(azArg[1]);
7745    }else{
7746      raw_printf(stderr, "Usage: .bail on|off\n");
7747      rc = 1;
7748    }
7749  }else
7750
7751  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7752    if( nArg==2 ){
7753      if( booleanValue(azArg[1]) ){
7754        setBinaryMode(p->out, 1);
7755      }else{
7756        setTextMode(p->out, 1);
7757      }
7758    }else{
7759      raw_printf(stderr, "Usage: .binary on|off\n");
7760      rc = 1;
7761    }
7762  }else
7763
7764  /* The undocumented ".breakpoint" command causes a call to the no-op
7765  ** routine named test_breakpoint().
7766  */
7767  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7768    test_breakpoint();
7769  }else
7770
7771  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7772    failIfSafeMode(p, "cannot run .cd in safe mode");
7773    if( nArg==2 ){
7774#if defined(_WIN32) || defined(WIN32)
7775      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7776      rc = !SetCurrentDirectoryW(z);
7777      sqlite3_free(z);
7778#else
7779      rc = chdir(azArg[1]);
7780#endif
7781      if( rc ){
7782        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7783        rc = 1;
7784      }
7785    }else{
7786      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7787      rc = 1;
7788    }
7789  }else
7790
7791  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7792    if( nArg==2 ){
7793      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7794    }else{
7795      raw_printf(stderr, "Usage: .changes on|off\n");
7796      rc = 1;
7797    }
7798  }else
7799
7800  /* Cancel output redirection, if it is currently set (by .testcase)
7801  ** Then read the content of the testcase-out.txt file and compare against
7802  ** azArg[1].  If there are differences, report an error and exit.
7803  */
7804  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7805    char *zRes = 0;
7806    output_reset(p);
7807    if( nArg!=2 ){
7808      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7809      rc = 2;
7810    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7811      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7812      rc = 2;
7813    }else if( testcase_glob(azArg[1],zRes)==0 ){
7814      utf8_printf(stderr,
7815                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7816                 p->zTestcase, azArg[1], zRes);
7817      rc = 1;
7818    }else{
7819      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7820      p->nCheck++;
7821    }
7822    sqlite3_free(zRes);
7823  }else
7824
7825  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7826    failIfSafeMode(p, "cannot run .clone in safe mode");
7827    if( nArg==2 ){
7828      tryToClone(p, azArg[1]);
7829    }else{
7830      raw_printf(stderr, "Usage: .clone FILENAME\n");
7831      rc = 1;
7832    }
7833  }else
7834
7835  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
7836    if( nArg==1 ){
7837      /* List available connections */
7838      int i;
7839      for(i=0; i<ArraySize(p->aAuxDb); i++){
7840        const char *zFile = p->aAuxDb[i].zDbFilename;
7841        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7842          zFile = "(not open)";
7843        }else if( zFile==0 ){
7844          zFile = "(memory)";
7845        }else if( zFile[0]==0 ){
7846          zFile = "(temporary-file)";
7847        }
7848        if( p->pAuxDb == &p->aAuxDb[i] ){
7849          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7850        }else if( p->aAuxDb[i].db!=0 ){
7851          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7852        }
7853      }
7854    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7855      int i = azArg[1][0] - '0';
7856      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7857        p->pAuxDb->db = p->db;
7858        p->pAuxDb = &p->aAuxDb[i];
7859        globalDb = p->db = p->pAuxDb->db;
7860        p->pAuxDb->db = 0;
7861      }
7862    }else if( nArg==3 && strcmp(azArg[1], "close")==0
7863           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7864      int i = azArg[2][0] - '0';
7865      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7866        /* No-op */
7867      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7868        raw_printf(stderr, "cannot close the active database connection\n");
7869        rc = 1;
7870      }else if( p->aAuxDb[i].db ){
7871        session_close_all(p, i);
7872        close_db(p->aAuxDb[i].db);
7873        p->aAuxDb[i].db = 0;
7874      }
7875    }else{
7876      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7877      rc = 1;
7878    }
7879  }else
7880
7881  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7882    char **azName = 0;
7883    int nName = 0;
7884    sqlite3_stmt *pStmt;
7885    int i;
7886    open_db(p, 0);
7887    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7888    if( rc ){
7889      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7890      rc = 1;
7891    }else{
7892      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7893        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7894        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7895        if( zSchema==0 || zFile==0 ) continue;
7896        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7897        shell_check_oom(azName);
7898        azName[nName*2] = strdup(zSchema);
7899        azName[nName*2+1] = strdup(zFile);
7900        nName++;
7901      }
7902    }
7903    sqlite3_finalize(pStmt);
7904    for(i=0; i<nName; i++){
7905      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7906      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7907      const char *z = azName[i*2+1];
7908      utf8_printf(p->out, "%s: %s %s%s\n",
7909         azName[i*2],
7910         z && z[0] ? z : "\"\"",
7911         bRdonly ? "r/o" : "r/w",
7912         eTxn==SQLITE_TXN_NONE ? "" :
7913            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7914      free(azName[i*2]);
7915      free(azName[i*2+1]);
7916    }
7917    sqlite3_free(azName);
7918  }else
7919
7920  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7921    static const struct DbConfigChoices {
7922      const char *zName;
7923      int op;
7924    } aDbConfig[] = {
7925        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7926        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7927        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7928        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7929        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7930        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7931        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7932        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7933        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7934        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7935        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7936        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7937        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7938        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7939        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7940        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7941    };
7942    int ii, v;
7943    open_db(p, 0);
7944    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7945      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7946      if( nArg>=3 ){
7947        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7948      }
7949      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7950      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7951      if( nArg>1 ) break;
7952    }
7953    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7954      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7955      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7956    }
7957  }else
7958
7959  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7960    rc = shell_dbinfo_command(p, nArg, azArg);
7961  }else
7962
7963#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7964  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7965    open_db(p, 0);
7966    rc = recoverDatabaseCmd(p, nArg, azArg);
7967  }else
7968#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7969
7970  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7971    char *zLike = 0;
7972    char *zSql;
7973    int i;
7974    int savedShowHeader = p->showHeader;
7975    int savedShellFlags = p->shellFlgs;
7976    ShellClearFlag(p,
7977       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7978       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7979    for(i=1; i<nArg; i++){
7980      if( azArg[i][0]=='-' ){
7981        const char *z = azArg[i]+1;
7982        if( z[0]=='-' ) z++;
7983        if( strcmp(z,"preserve-rowids")==0 ){
7984#ifdef SQLITE_OMIT_VIRTUALTABLE
7985          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7986                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7987          rc = 1;
7988          sqlite3_free(zLike);
7989          goto meta_command_exit;
7990#else
7991          ShellSetFlag(p, SHFLG_PreserveRowid);
7992#endif
7993        }else
7994        if( strcmp(z,"newlines")==0 ){
7995          ShellSetFlag(p, SHFLG_Newlines);
7996        }else
7997        if( strcmp(z,"data-only")==0 ){
7998          ShellSetFlag(p, SHFLG_DumpDataOnly);
7999        }else
8000        if( strcmp(z,"nosys")==0 ){
8001          ShellSetFlag(p, SHFLG_DumpNoSys);
8002        }else
8003        {
8004          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8005          rc = 1;
8006          sqlite3_free(zLike);
8007          goto meta_command_exit;
8008        }
8009      }else{
8010        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8011        ** only dump data for tables for which either the table name matches
8012        ** the LIKE pattern, or the table appears to be a shadow table of
8013        ** a virtual table for which the name matches the LIKE pattern.
8014        */
8015        char *zExpr = sqlite3_mprintf(
8016            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8017            "  SELECT 1 FROM sqlite_schema WHERE "
8018            "    name LIKE %Q ESCAPE '\\' AND"
8019            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8020            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8021            ")", azArg[i], azArg[i]
8022        );
8023
8024        if( zLike ){
8025          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8026        }else{
8027          zLike = zExpr;
8028        }
8029      }
8030    }
8031
8032    open_db(p, 0);
8033
8034    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8035      /* When playing back a "dump", the content might appear in an order
8036      ** which causes immediate foreign key constraints to be violated.
8037      ** So disable foreign-key constraint enforcement to prevent problems. */
8038      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8039      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8040    }
8041    p->writableSchema = 0;
8042    p->showHeader = 0;
8043    /* Set writable_schema=ON since doing so forces SQLite to initialize
8044    ** as much of the schema as it can even if the sqlite_schema table is
8045    ** corrupt. */
8046    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8047    p->nErr = 0;
8048    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8049    zSql = sqlite3_mprintf(
8050      "SELECT name, type, sql FROM sqlite_schema AS o "
8051      "WHERE (%s) AND type=='table'"
8052      "  AND sql NOT NULL"
8053      " ORDER BY tbl_name='sqlite_sequence', rowid",
8054      zLike
8055    );
8056    run_schema_dump_query(p,zSql);
8057    sqlite3_free(zSql);
8058    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8059      zSql = sqlite3_mprintf(
8060        "SELECT sql FROM sqlite_schema AS o "
8061        "WHERE (%s) AND sql NOT NULL"
8062        "  AND type IN ('index','trigger','view')",
8063        zLike
8064      );
8065      run_table_dump_query(p, zSql);
8066      sqlite3_free(zSql);
8067    }
8068    sqlite3_free(zLike);
8069    if( p->writableSchema ){
8070      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8071      p->writableSchema = 0;
8072    }
8073    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8074    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8075    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8076      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8077    }
8078    p->showHeader = savedShowHeader;
8079    p->shellFlgs = savedShellFlags;
8080  }else
8081
8082  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8083    if( nArg==2 ){
8084      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8085    }else{
8086      raw_printf(stderr, "Usage: .echo on|off\n");
8087      rc = 1;
8088    }
8089  }else
8090
8091  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8092    if( nArg==2 ){
8093      p->autoEQPtest = 0;
8094      if( p->autoEQPtrace ){
8095        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8096        p->autoEQPtrace = 0;
8097      }
8098      if( strcmp(azArg[1],"full")==0 ){
8099        p->autoEQP = AUTOEQP_full;
8100      }else if( strcmp(azArg[1],"trigger")==0 ){
8101        p->autoEQP = AUTOEQP_trigger;
8102#ifdef SQLITE_DEBUG
8103      }else if( strcmp(azArg[1],"test")==0 ){
8104        p->autoEQP = AUTOEQP_on;
8105        p->autoEQPtest = 1;
8106      }else if( strcmp(azArg[1],"trace")==0 ){
8107        p->autoEQP = AUTOEQP_full;
8108        p->autoEQPtrace = 1;
8109        open_db(p, 0);
8110        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8111        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8112#endif
8113      }else{
8114        p->autoEQP = (u8)booleanValue(azArg[1]);
8115      }
8116    }else{
8117      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8118      rc = 1;
8119    }
8120  }else
8121
8122  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8123    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8124    rc = 2;
8125  }else
8126
8127  /* The ".explain" command is automatic now.  It is largely pointless.  It
8128  ** retained purely for backwards compatibility */
8129  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8130    int val = 1;
8131    if( nArg>=2 ){
8132      if( strcmp(azArg[1],"auto")==0 ){
8133        val = 99;
8134      }else{
8135        val =  booleanValue(azArg[1]);
8136      }
8137    }
8138    if( val==1 && p->mode!=MODE_Explain ){
8139      p->normalMode = p->mode;
8140      p->mode = MODE_Explain;
8141      p->autoExplain = 0;
8142    }else if( val==0 ){
8143      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8144      p->autoExplain = 0;
8145    }else if( val==99 ){
8146      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8147      p->autoExplain = 1;
8148    }
8149  }else
8150
8151#ifndef SQLITE_OMIT_VIRTUALTABLE
8152  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8153    if( p->bSafeMode ){
8154      raw_printf(stderr,
8155        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8156        azArg[0]);
8157      rc = 1;
8158    }else{
8159      open_db(p, 0);
8160      expertDotCommand(p, azArg, nArg);
8161    }
8162  }else
8163#endif
8164
8165  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8166    static const struct {
8167       const char *zCtrlName;   /* Name of a test-control option */
8168       int ctrlCode;            /* Integer code for that option */
8169       const char *zUsage;      /* Usage notes */
8170    } aCtrl[] = {
8171      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8172      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8173      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8174      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8175      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8176   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8177      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8178      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8179      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8180      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8181   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8182    };
8183    int filectrl = -1;
8184    int iCtrl = -1;
8185    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8186    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8187    int n2, i;
8188    const char *zCmd = 0;
8189    const char *zSchema = 0;
8190
8191    open_db(p, 0);
8192    zCmd = nArg>=2 ? azArg[1] : "help";
8193
8194    if( zCmd[0]=='-'
8195     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8196     && nArg>=4
8197    ){
8198      zSchema = azArg[2];
8199      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8200      nArg -= 2;
8201      zCmd = azArg[1];
8202    }
8203
8204    /* The argument can optionally begin with "-" or "--" */
8205    if( zCmd[0]=='-' && zCmd[1] ){
8206      zCmd++;
8207      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8208    }
8209
8210    /* --help lists all file-controls */
8211    if( strcmp(zCmd,"help")==0 ){
8212      utf8_printf(p->out, "Available file-controls:\n");
8213      for(i=0; i<ArraySize(aCtrl); i++){
8214        utf8_printf(p->out, "  .filectrl %s %s\n",
8215                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8216      }
8217      rc = 1;
8218      goto meta_command_exit;
8219    }
8220
8221    /* convert filectrl text option to value. allow any unique prefix
8222    ** of the option name, or a numerical value. */
8223    n2 = strlen30(zCmd);
8224    for(i=0; i<ArraySize(aCtrl); i++){
8225      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8226        if( filectrl<0 ){
8227          filectrl = aCtrl[i].ctrlCode;
8228          iCtrl = i;
8229        }else{
8230          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8231                              "Use \".filectrl --help\" for help\n", zCmd);
8232          rc = 1;
8233          goto meta_command_exit;
8234        }
8235      }
8236    }
8237    if( filectrl<0 ){
8238      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8239                         "Use \".filectrl --help\" for help\n", zCmd);
8240    }else{
8241      switch(filectrl){
8242        case SQLITE_FCNTL_SIZE_LIMIT: {
8243          if( nArg!=2 && nArg!=3 ) break;
8244          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8245          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8246          isOk = 1;
8247          break;
8248        }
8249        case SQLITE_FCNTL_LOCK_TIMEOUT:
8250        case SQLITE_FCNTL_CHUNK_SIZE: {
8251          int x;
8252          if( nArg!=3 ) break;
8253          x = (int)integerValue(azArg[2]);
8254          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8255          isOk = 2;
8256          break;
8257        }
8258        case SQLITE_FCNTL_PERSIST_WAL:
8259        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8260          int x;
8261          if( nArg!=2 && nArg!=3 ) break;
8262          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8263          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8264          iRes = x;
8265          isOk = 1;
8266          break;
8267        }
8268        case SQLITE_FCNTL_DATA_VERSION:
8269        case SQLITE_FCNTL_HAS_MOVED: {
8270          int x;
8271          if( nArg!=2 ) break;
8272          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8273          iRes = x;
8274          isOk = 1;
8275          break;
8276        }
8277        case SQLITE_FCNTL_TEMPFILENAME: {
8278          char *z = 0;
8279          if( nArg!=2 ) break;
8280          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8281          if( z ){
8282            utf8_printf(p->out, "%s\n", z);
8283            sqlite3_free(z);
8284          }
8285          isOk = 2;
8286          break;
8287        }
8288        case SQLITE_FCNTL_RESERVE_BYTES: {
8289          int x;
8290          if( nArg>=3 ){
8291            x = atoi(azArg[2]);
8292            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8293          }
8294          x = -1;
8295          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8296          utf8_printf(p->out,"%d\n", x);
8297          isOk = 2;
8298          break;
8299        }
8300      }
8301    }
8302    if( isOk==0 && iCtrl>=0 ){
8303      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8304      rc = 1;
8305    }else if( isOk==1 ){
8306      char zBuf[100];
8307      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8308      raw_printf(p->out, "%s\n", zBuf);
8309    }
8310  }else
8311
8312  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8313    ShellState data;
8314    int doStats = 0;
8315    memcpy(&data, p, sizeof(data));
8316    data.showHeader = 0;
8317    data.cMode = data.mode = MODE_Semi;
8318    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8319      data.cMode = data.mode = MODE_Pretty;
8320      nArg = 1;
8321    }
8322    if( nArg!=1 ){
8323      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8324      rc = 1;
8325      goto meta_command_exit;
8326    }
8327    open_db(p, 0);
8328    rc = sqlite3_exec(p->db,
8329       "SELECT sql FROM"
8330       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8331       "     FROM sqlite_schema UNION ALL"
8332       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8333       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8334       "ORDER BY x",
8335       callback, &data, 0
8336    );
8337    if( rc==SQLITE_OK ){
8338      sqlite3_stmt *pStmt;
8339      rc = sqlite3_prepare_v2(p->db,
8340               "SELECT rowid FROM sqlite_schema"
8341               " WHERE name GLOB 'sqlite_stat[134]'",
8342               -1, &pStmt, 0);
8343      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8344      sqlite3_finalize(pStmt);
8345    }
8346    if( doStats==0 ){
8347      raw_printf(p->out, "/* No STAT tables available */\n");
8348    }else{
8349      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8350      data.cMode = data.mode = MODE_Insert;
8351      data.zDestTable = "sqlite_stat1";
8352      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8353      data.zDestTable = "sqlite_stat4";
8354      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8355      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8356    }
8357  }else
8358
8359  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8360    if( nArg==2 ){
8361      p->showHeader = booleanValue(azArg[1]);
8362      p->shellFlgs |= SHFLG_HeaderSet;
8363    }else{
8364      raw_printf(stderr, "Usage: .headers on|off\n");
8365      rc = 1;
8366    }
8367  }else
8368
8369  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8370    if( nArg>=2 ){
8371      n = showHelp(p->out, azArg[1]);
8372      if( n==0 ){
8373        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8374      }
8375    }else{
8376      showHelp(p->out, 0);
8377    }
8378  }else
8379
8380  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8381    char *zTable = 0;           /* Insert data into this table */
8382    char *zFile = 0;            /* Name of file to extra content from */
8383    sqlite3_stmt *pStmt = NULL; /* A statement */
8384    int nCol;                   /* Number of columns in the table */
8385    int nByte;                  /* Number of bytes in an SQL string */
8386    int i, j;                   /* Loop counters */
8387    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8388    int nSep;                   /* Number of bytes in p->colSeparator[] */
8389    char *zSql;                 /* An SQL statement */
8390    ImportCtx sCtx;             /* Reader context */
8391    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8392    int eVerbose = 0;           /* Larger for more console output */
8393    int nSkip = 0;              /* Initial lines to skip */
8394    int useOutputMode = 1;      /* Use output mode to determine separators */
8395
8396    failIfSafeMode(p, "cannot run .import in safe mode");
8397    memset(&sCtx, 0, sizeof(sCtx));
8398    sCtx.z = sqlite3_malloc64(120);
8399    if( sCtx.z==0 ){
8400      import_cleanup(&sCtx);
8401      shell_out_of_memory();
8402    }
8403    if( p->mode==MODE_Ascii ){
8404      xRead = ascii_read_one_field;
8405    }else{
8406      xRead = csv_read_one_field;
8407    }
8408    for(i=1; i<nArg; i++){
8409      char *z = azArg[i];
8410      if( z[0]=='-' && z[1]=='-' ) z++;
8411      if( z[0]!='-' ){
8412        if( zFile==0 ){
8413          zFile = z;
8414        }else if( zTable==0 ){
8415          zTable = z;
8416        }else{
8417          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8418          showHelp(p->out, "import");
8419          rc = 1;
8420          goto meta_command_exit;
8421        }
8422      }else if( strcmp(z,"-v")==0 ){
8423        eVerbose++;
8424      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8425        nSkip = integerValue(azArg[++i]);
8426      }else if( strcmp(z,"-ascii")==0 ){
8427        sCtx.cColSep = SEP_Unit[0];
8428        sCtx.cRowSep = SEP_Record[0];
8429        xRead = ascii_read_one_field;
8430        useOutputMode = 0;
8431      }else if( strcmp(z,"-csv")==0 ){
8432        sCtx.cColSep = ',';
8433        sCtx.cRowSep = '\n';
8434        xRead = csv_read_one_field;
8435        useOutputMode = 0;
8436      }else{
8437        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8438        showHelp(p->out, "import");
8439        rc = 1;
8440        goto meta_command_exit;
8441      }
8442    }
8443    if( zTable==0 ){
8444      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8445                  zFile==0 ? "FILE" : "TABLE");
8446      showHelp(p->out, "import");
8447      rc = 1;
8448      goto meta_command_exit;
8449    }
8450    seenInterrupt = 0;
8451    open_db(p, 0);
8452    if( useOutputMode ){
8453      /* If neither the --csv or --ascii options are specified, then set
8454      ** the column and row separator characters from the output mode. */
8455      nSep = strlen30(p->colSeparator);
8456      if( nSep==0 ){
8457        raw_printf(stderr,
8458                   "Error: non-null column separator required for import\n");
8459        rc = 1;
8460        goto meta_command_exit;
8461      }
8462      if( nSep>1 ){
8463        raw_printf(stderr,
8464              "Error: multi-character column separators not allowed"
8465              " for import\n");
8466        rc = 1;
8467        goto meta_command_exit;
8468      }
8469      nSep = strlen30(p->rowSeparator);
8470      if( nSep==0 ){
8471        raw_printf(stderr,
8472            "Error: non-null row separator required for import\n");
8473        rc = 1;
8474        goto meta_command_exit;
8475      }
8476      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8477        /* When importing CSV (only), if the row separator is set to the
8478        ** default output row separator, change it to the default input
8479        ** row separator.  This avoids having to maintain different input
8480        ** and output row separators. */
8481        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8482        nSep = strlen30(p->rowSeparator);
8483      }
8484      if( nSep>1 ){
8485        raw_printf(stderr, "Error: multi-character row separators not allowed"
8486                           " for import\n");
8487        rc = 1;
8488        goto meta_command_exit;
8489      }
8490      sCtx.cColSep = p->colSeparator[0];
8491      sCtx.cRowSep = p->rowSeparator[0];
8492    }
8493    sCtx.zFile = zFile;
8494    sCtx.nLine = 1;
8495    if( sCtx.zFile[0]=='|' ){
8496#ifdef SQLITE_OMIT_POPEN
8497      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8498      rc = 1;
8499      goto meta_command_exit;
8500#else
8501      sCtx.in = popen(sCtx.zFile+1, "r");
8502      sCtx.zFile = "<pipe>";
8503      sCtx.xCloser = pclose;
8504#endif
8505    }else{
8506      sCtx.in = fopen(sCtx.zFile, "rb");
8507      sCtx.xCloser = fclose;
8508    }
8509    if( sCtx.in==0 ){
8510      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8511      rc = 1;
8512      import_cleanup(&sCtx);
8513      goto meta_command_exit;
8514    }
8515    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8516      char zSep[2];
8517      zSep[1] = 0;
8518      zSep[0] = sCtx.cColSep;
8519      utf8_printf(p->out, "Column separator ");
8520      output_c_string(p->out, zSep);
8521      utf8_printf(p->out, ", row separator ");
8522      zSep[0] = sCtx.cRowSep;
8523      output_c_string(p->out, zSep);
8524      utf8_printf(p->out, "\n");
8525    }
8526    while( (nSkip--)>0 ){
8527      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8528    }
8529    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
8530    if( zSql==0 ){
8531      import_cleanup(&sCtx);
8532      shell_out_of_memory();
8533    }
8534    nByte = strlen30(zSql);
8535    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8536    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8537    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8538      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
8539      char cSep = '(';
8540      while( xRead(&sCtx) ){
8541        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
8542        cSep = ',';
8543        if( sCtx.cTerm!=sCtx.cColSep ) break;
8544      }
8545      if( cSep=='(' ){
8546        sqlite3_free(zCreate);
8547        import_cleanup(&sCtx);
8548        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8549        rc = 1;
8550        goto meta_command_exit;
8551      }
8552      zCreate = sqlite3_mprintf("%z\n)", zCreate);
8553      if( eVerbose>=1 ){
8554        utf8_printf(p->out, "%s\n", zCreate);
8555      }
8556      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8557      sqlite3_free(zCreate);
8558      if( rc ){
8559        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
8560                sqlite3_errmsg(p->db));
8561        import_cleanup(&sCtx);
8562        rc = 1;
8563        goto meta_command_exit;
8564      }
8565      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8566    }
8567    sqlite3_free(zSql);
8568    if( rc ){
8569      if (pStmt) sqlite3_finalize(pStmt);
8570      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8571      import_cleanup(&sCtx);
8572      rc = 1;
8573      goto meta_command_exit;
8574    }
8575    nCol = sqlite3_column_count(pStmt);
8576    sqlite3_finalize(pStmt);
8577    pStmt = 0;
8578    if( nCol==0 ) return 0; /* no columns, no error */
8579    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8580    if( zSql==0 ){
8581      import_cleanup(&sCtx);
8582      shell_out_of_memory();
8583    }
8584    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8585    j = strlen30(zSql);
8586    for(i=1; i<nCol; i++){
8587      zSql[j++] = ',';
8588      zSql[j++] = '?';
8589    }
8590    zSql[j++] = ')';
8591    zSql[j] = 0;
8592    if( eVerbose>=2 ){
8593      utf8_printf(p->out, "Insert using: %s\n", zSql);
8594    }
8595    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8596    sqlite3_free(zSql);
8597    if( rc ){
8598      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8599      if (pStmt) sqlite3_finalize(pStmt);
8600      import_cleanup(&sCtx);
8601      rc = 1;
8602      goto meta_command_exit;
8603    }
8604    needCommit = sqlite3_get_autocommit(p->db);
8605    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8606    do{
8607      int startLine = sCtx.nLine;
8608      for(i=0; i<nCol; i++){
8609        char *z = xRead(&sCtx);
8610        /*
8611        ** Did we reach end-of-file before finding any columns?
8612        ** If so, stop instead of NULL filling the remaining columns.
8613        */
8614        if( z==0 && i==0 ) break;
8615        /*
8616        ** Did we reach end-of-file OR end-of-line before finding any
8617        ** columns in ASCII mode?  If so, stop instead of NULL filling
8618        ** the remaining columns.
8619        */
8620        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8621        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8622        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8623          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8624                          "filling the rest with NULL\n",
8625                          sCtx.zFile, startLine, nCol, i+1);
8626          i += 2;
8627          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8628        }
8629      }
8630      if( sCtx.cTerm==sCtx.cColSep ){
8631        do{
8632          xRead(&sCtx);
8633          i++;
8634        }while( sCtx.cTerm==sCtx.cColSep );
8635        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8636                        "extras ignored\n",
8637                        sCtx.zFile, startLine, nCol, i);
8638      }
8639      if( i>=nCol ){
8640        sqlite3_step(pStmt);
8641        rc = sqlite3_reset(pStmt);
8642        if( rc!=SQLITE_OK ){
8643          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8644                      startLine, sqlite3_errmsg(p->db));
8645          sCtx.nErr++;
8646        }else{
8647          sCtx.nRow++;
8648        }
8649      }
8650    }while( sCtx.cTerm!=EOF );
8651
8652    import_cleanup(&sCtx);
8653    sqlite3_finalize(pStmt);
8654    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8655    if( eVerbose>0 ){
8656      utf8_printf(p->out,
8657          "Added %d rows with %d errors using %d lines of input\n",
8658          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8659    }
8660  }else
8661
8662#ifndef SQLITE_UNTESTABLE
8663  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8664    char *zSql;
8665    char *zCollist = 0;
8666    sqlite3_stmt *pStmt;
8667    int tnum = 0;
8668    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8669    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8670    int i;
8671    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8672      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8673                          "       .imposter off\n");
8674      /* Also allowed, but not documented:
8675      **
8676      **    .imposter TABLE IMPOSTER
8677      **
8678      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8679      ** imposter is another WITHOUT ROWID table with the columns in
8680      ** storage order. */
8681      rc = 1;
8682      goto meta_command_exit;
8683    }
8684    open_db(p, 0);
8685    if( nArg==2 ){
8686      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8687      goto meta_command_exit;
8688    }
8689    zSql = sqlite3_mprintf(
8690      "SELECT rootpage, 0 FROM sqlite_schema"
8691      " WHERE name='%q' AND type='index'"
8692      "UNION ALL "
8693      "SELECT rootpage, 1 FROM sqlite_schema"
8694      " WHERE name='%q' AND type='table'"
8695      "   AND sql LIKE '%%without%%rowid%%'",
8696      azArg[1], azArg[1]
8697    );
8698    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8699    sqlite3_free(zSql);
8700    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8701      tnum = sqlite3_column_int(pStmt, 0);
8702      isWO = sqlite3_column_int(pStmt, 1);
8703    }
8704    sqlite3_finalize(pStmt);
8705    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8706    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8707    sqlite3_free(zSql);
8708    i = 0;
8709    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8710      char zLabel[20];
8711      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8712      i++;
8713      if( zCol==0 ){
8714        if( sqlite3_column_int(pStmt,1)==-1 ){
8715          zCol = "_ROWID_";
8716        }else{
8717          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8718          zCol = zLabel;
8719        }
8720      }
8721      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8722        lenPK = (int)strlen(zCollist);
8723      }
8724      if( zCollist==0 ){
8725        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8726      }else{
8727        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8728      }
8729    }
8730    sqlite3_finalize(pStmt);
8731    if( i==0 || tnum==0 ){
8732      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8733      rc = 1;
8734      sqlite3_free(zCollist);
8735      goto meta_command_exit;
8736    }
8737    if( lenPK==0 ) lenPK = 100000;
8738    zSql = sqlite3_mprintf(
8739          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8740          azArg[2], zCollist, lenPK, zCollist);
8741    sqlite3_free(zCollist);
8742    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8743    if( rc==SQLITE_OK ){
8744      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8745      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8746      if( rc ){
8747        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8748      }else{
8749        utf8_printf(stdout, "%s;\n", zSql);
8750        raw_printf(stdout,
8751          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8752          azArg[1], isWO ? "table" : "index"
8753        );
8754      }
8755    }else{
8756      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8757      rc = 1;
8758    }
8759    sqlite3_free(zSql);
8760  }else
8761#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8762
8763#ifdef SQLITE_ENABLE_IOTRACE
8764  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8765    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8766    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8767    iotrace = 0;
8768    if( nArg<2 ){
8769      sqlite3IoTrace = 0;
8770    }else if( strcmp(azArg[1], "-")==0 ){
8771      sqlite3IoTrace = iotracePrintf;
8772      iotrace = stdout;
8773    }else{
8774      iotrace = fopen(azArg[1], "w");
8775      if( iotrace==0 ){
8776        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8777        sqlite3IoTrace = 0;
8778        rc = 1;
8779      }else{
8780        sqlite3IoTrace = iotracePrintf;
8781      }
8782    }
8783  }else
8784#endif
8785
8786  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8787    static const struct {
8788       const char *zLimitName;   /* Name of a limit */
8789       int limitCode;            /* Integer code for that limit */
8790    } aLimit[] = {
8791      { "length",                SQLITE_LIMIT_LENGTH                    },
8792      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8793      { "column",                SQLITE_LIMIT_COLUMN                    },
8794      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8795      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8796      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8797      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8798      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8799      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8800      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8801      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8802      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8803    };
8804    int i, n2;
8805    open_db(p, 0);
8806    if( nArg==1 ){
8807      for(i=0; i<ArraySize(aLimit); i++){
8808        printf("%20s %d\n", aLimit[i].zLimitName,
8809               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8810      }
8811    }else if( nArg>3 ){
8812      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8813      rc = 1;
8814      goto meta_command_exit;
8815    }else{
8816      int iLimit = -1;
8817      n2 = strlen30(azArg[1]);
8818      for(i=0; i<ArraySize(aLimit); i++){
8819        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8820          if( iLimit<0 ){
8821            iLimit = i;
8822          }else{
8823            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8824            rc = 1;
8825            goto meta_command_exit;
8826          }
8827        }
8828      }
8829      if( iLimit<0 ){
8830        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8831                        "enter \".limits\" with no arguments for a list.\n",
8832                         azArg[1]);
8833        rc = 1;
8834        goto meta_command_exit;
8835      }
8836      if( nArg==3 ){
8837        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8838                      (int)integerValue(azArg[2]));
8839      }
8840      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8841             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8842    }
8843  }else
8844
8845  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8846    open_db(p, 0);
8847    lintDotCommand(p, azArg, nArg);
8848  }else
8849
8850#ifndef SQLITE_OMIT_LOAD_EXTENSION
8851  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8852    const char *zFile, *zProc;
8853    char *zErrMsg = 0;
8854    failIfSafeMode(p, "cannot run .load in safe mode");
8855    if( nArg<2 ){
8856      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8857      rc = 1;
8858      goto meta_command_exit;
8859    }
8860    zFile = azArg[1];
8861    zProc = nArg>=3 ? azArg[2] : 0;
8862    open_db(p, 0);
8863    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8864    if( rc!=SQLITE_OK ){
8865      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8866      sqlite3_free(zErrMsg);
8867      rc = 1;
8868    }
8869  }else
8870#endif
8871
8872  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8873    failIfSafeMode(p, "cannot run .log in safe mode");
8874    if( nArg!=2 ){
8875      raw_printf(stderr, "Usage: .log FILENAME\n");
8876      rc = 1;
8877    }else{
8878      const char *zFile = azArg[1];
8879      output_file_close(p->pLog);
8880      p->pLog = output_file_open(zFile, 0);
8881    }
8882  }else
8883
8884  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8885    const char *zMode = nArg>=2 ? azArg[1] : "";
8886    int n2 = strlen30(zMode);
8887    int c2 = zMode[0];
8888    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8889      p->mode = MODE_Line;
8890      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8891    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8892      p->mode = MODE_Column;
8893      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8894        p->showHeader = 1;
8895      }
8896      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8897    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8898      p->mode = MODE_List;
8899      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8900      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8901    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8902      p->mode = MODE_Html;
8903    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8904      p->mode = MODE_Tcl;
8905      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8906      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8907    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8908      p->mode = MODE_Csv;
8909      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8910      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8911    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8912      p->mode = MODE_List;
8913      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8914    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8915      p->mode = MODE_Insert;
8916      set_table_name(p, nArg>=3 ? azArg[2] : "table");
8917    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8918      p->mode = MODE_Quote;
8919      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8920      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8921    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8922      p->mode = MODE_Ascii;
8923      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8924      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8925    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8926      p->mode = MODE_Markdown;
8927    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8928      p->mode = MODE_Table;
8929    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8930      p->mode = MODE_Box;
8931    }else if( c2=='c' && strncmp(azArg[1],"count",n2)==0 ){
8932      p->mode = MODE_Count;
8933    }else if( c2=='o' && strncmp(azArg[1],"off",n2)==0 ){
8934      p->mode = MODE_Off;
8935    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8936      p->mode = MODE_Json;
8937    }else if( nArg==1 ){
8938      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8939    }else{
8940      raw_printf(stderr, "Error: mode should be one of: "
8941         "ascii box column csv html insert json line list markdown "
8942         "quote table tabs tcl\n");
8943      rc = 1;
8944    }
8945    p->cMode = p->mode;
8946  }else
8947
8948  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
8949    if( nArg!=2 ){
8950      raw_printf(stderr, "Usage: .nonce NONCE\n");
8951      rc = 1;
8952    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
8953      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
8954                 p->lineno, azArg[1]);
8955      exit(1);
8956    }else{
8957      p->bSafeMode = 0;
8958      return 0;  /* Return immediately to bypass the safe mode reset
8959                 ** at the end of this procedure */
8960    }
8961  }else
8962
8963  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8964    if( nArg==2 ){
8965      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8966                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8967    }else{
8968      raw_printf(stderr, "Usage: .nullvalue STRING\n");
8969      rc = 1;
8970    }
8971  }else
8972
8973  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8974    const char *zFN = 0;     /* Pointer to constant filename */
8975    char *zNewFilename = 0;  /* Name of the database file to open */
8976    int iName = 1;           /* Index in azArg[] of the filename */
8977    int newFlag = 0;         /* True to delete file before opening */
8978    int openMode = SHELL_OPEN_UNSPEC;
8979
8980    /* Check for command-line arguments */
8981    for(iName=1; iName<nArg; iName++){
8982      const char *z = azArg[iName];
8983      if( optionMatch(z,"new") ){
8984        newFlag = 1;
8985#ifdef SQLITE_HAVE_ZLIB
8986      }else if( optionMatch(z, "zip") ){
8987        openMode = SHELL_OPEN_ZIPFILE;
8988#endif
8989      }else if( optionMatch(z, "append") ){
8990        openMode = SHELL_OPEN_APPENDVFS;
8991      }else if( optionMatch(z, "readonly") ){
8992        openMode = SHELL_OPEN_READONLY;
8993      }else if( optionMatch(z, "nofollow") ){
8994        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8995#ifndef SQLITE_OMIT_DESERIALIZE
8996      }else if( optionMatch(z, "deserialize") ){
8997        openMode = SHELL_OPEN_DESERIALIZE;
8998      }else if( optionMatch(z, "hexdb") ){
8999        openMode = SHELL_OPEN_HEXDB;
9000      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9001        p->szMax = integerValue(azArg[++iName]);
9002#endif /* SQLITE_OMIT_DESERIALIZE */
9003      }else if( z[0]=='-' ){
9004        utf8_printf(stderr, "unknown option: %s\n", z);
9005        rc = 1;
9006        goto meta_command_exit;
9007      }else if( zFN ){
9008        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9009        rc = 1;
9010        goto meta_command_exit;
9011      }else{
9012        zFN = z;
9013      }
9014    }
9015
9016    /* Close the existing database */
9017    session_close_all(p, -1);
9018    close_db(p->db);
9019    p->db = 0;
9020    p->pAuxDb->zDbFilename = 0;
9021    sqlite3_free(p->pAuxDb->zFreeOnClose);
9022    p->pAuxDb->zFreeOnClose = 0;
9023    p->openMode = openMode;
9024    p->openFlags = 0;
9025    p->szMax = 0;
9026
9027    /* If a filename is specified, try to open it first */
9028    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9029      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9030      if( p->bSafeMode
9031       && p->openMode!=SHELL_OPEN_HEXDB
9032       && zFN
9033       && strcmp(zFN,":memory:")!=0
9034      ){
9035        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9036      }
9037      if( zFN ){
9038        zNewFilename = sqlite3_mprintf("%s", zFN);
9039        shell_check_oom(zNewFilename);
9040      }else{
9041        zNewFilename = 0;
9042      }
9043      p->pAuxDb->zDbFilename = zNewFilename;
9044      open_db(p, OPEN_DB_KEEPALIVE);
9045      if( p->db==0 ){
9046        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9047        sqlite3_free(zNewFilename);
9048      }else{
9049        p->pAuxDb->zFreeOnClose = zNewFilename;
9050      }
9051    }
9052    if( p->db==0 ){
9053      /* As a fall-back open a TEMP database */
9054      p->pAuxDb->zDbFilename = 0;
9055      open_db(p, 0);
9056    }
9057  }else
9058
9059  if( (c=='o'
9060        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9061   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9062  ){
9063    char *zFile = 0;
9064    int bTxtMode = 0;
9065    int i;
9066    int eMode = 0;
9067    int bBOM = 0;
9068    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
9069
9070    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9071    if( c=='e' ){
9072      eMode = 'x';
9073      bOnce = 2;
9074    }else if( strncmp(azArg[0],"once",n)==0 ){
9075      bOnce = 1;
9076    }
9077    for(i=1; i<nArg; i++){
9078      char *z = azArg[i];
9079      if( z[0]=='-' ){
9080        if( z[1]=='-' ) z++;
9081        if( strcmp(z,"-bom")==0 ){
9082          bBOM = 1;
9083        }else if( c!='e' && strcmp(z,"-x")==0 ){
9084          eMode = 'x';  /* spreadsheet */
9085        }else if( c!='e' && strcmp(z,"-e")==0 ){
9086          eMode = 'e';  /* text editor */
9087        }else{
9088          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9089                      azArg[i]);
9090          showHelp(p->out, azArg[0]);
9091          rc = 1;
9092          goto meta_command_exit;
9093        }
9094      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9095        zFile = sqlite3_mprintf("%s", z);
9096        if( zFile && zFile[0]=='|' ){
9097          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9098          break;
9099        }
9100      }else{
9101        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9102                    azArg[i]);
9103        showHelp(p->out, azArg[0]);
9104        rc = 1;
9105        sqlite3_free(zFile);
9106        goto meta_command_exit;
9107      }
9108    }
9109    if( zFile==0 ){
9110      zFile = sqlite3_mprintf("stdout");
9111    }
9112    if( bOnce ){
9113      p->outCount = 2;
9114    }else{
9115      p->outCount = 0;
9116    }
9117    output_reset(p);
9118#ifndef SQLITE_NOHAVE_SYSTEM
9119    if( eMode=='e' || eMode=='x' ){
9120      p->doXdgOpen = 1;
9121      outputModePush(p);
9122      if( eMode=='x' ){
9123        /* spreadsheet mode.  Output as CSV. */
9124        newTempFile(p, "csv");
9125        ShellClearFlag(p, SHFLG_Echo);
9126        p->mode = MODE_Csv;
9127        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9128        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9129      }else{
9130        /* text editor mode */
9131        newTempFile(p, "txt");
9132        bTxtMode = 1;
9133      }
9134      sqlite3_free(zFile);
9135      zFile = sqlite3_mprintf("%s", p->zTempFile);
9136    }
9137#endif /* SQLITE_NOHAVE_SYSTEM */
9138    shell_check_oom(zFile);
9139    if( zFile[0]=='|' ){
9140#ifdef SQLITE_OMIT_POPEN
9141      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9142      rc = 1;
9143      p->out = stdout;
9144#else
9145      p->out = popen(zFile + 1, "w");
9146      if( p->out==0 ){
9147        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9148        p->out = stdout;
9149        rc = 1;
9150      }else{
9151        if( bBOM ) fprintf(p->out,"\357\273\277");
9152        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9153      }
9154#endif
9155    }else{
9156      p->out = output_file_open(zFile, bTxtMode);
9157      if( p->out==0 ){
9158        if( strcmp(zFile,"off")!=0 ){
9159          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9160        }
9161        p->out = stdout;
9162        rc = 1;
9163      } else {
9164        if( bBOM ) fprintf(p->out,"\357\273\277");
9165        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9166      }
9167    }
9168    sqlite3_free(zFile);
9169  }else
9170
9171  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9172    open_db(p,0);
9173    if( nArg<=1 ) goto parameter_syntax_error;
9174
9175    /* .parameter clear
9176    ** Clear all bind parameters by dropping the TEMP table that holds them.
9177    */
9178    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9179      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9180                   0, 0, 0);
9181    }else
9182
9183    /* .parameter list
9184    ** List all bind parameters.
9185    */
9186    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9187      sqlite3_stmt *pStmt = 0;
9188      int rx;
9189      int len = 0;
9190      rx = sqlite3_prepare_v2(p->db,
9191             "SELECT max(length(key)) "
9192             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9193      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9194        len = sqlite3_column_int(pStmt, 0);
9195        if( len>40 ) len = 40;
9196      }
9197      sqlite3_finalize(pStmt);
9198      pStmt = 0;
9199      if( len ){
9200        rx = sqlite3_prepare_v2(p->db,
9201             "SELECT key, quote(value) "
9202             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9203        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9204          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9205                      sqlite3_column_text(pStmt,1));
9206        }
9207        sqlite3_finalize(pStmt);
9208      }
9209    }else
9210
9211    /* .parameter init
9212    ** Make sure the TEMP table used to hold bind parameters exists.
9213    ** Create it if necessary.
9214    */
9215    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9216      bind_table_init(p);
9217    }else
9218
9219    /* .parameter set NAME VALUE
9220    ** Set or reset a bind parameter.  NAME should be the full parameter
9221    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9222    ** VALUE can be in either SQL literal notation, or if not it will be
9223    ** understood to be a text string.
9224    */
9225    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9226      int rx;
9227      char *zSql;
9228      sqlite3_stmt *pStmt;
9229      const char *zKey = azArg[2];
9230      const char *zValue = azArg[3];
9231      bind_table_init(p);
9232      zSql = sqlite3_mprintf(
9233                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9234                  "VALUES(%Q,%s);", zKey, zValue);
9235      shell_check_oom(zSql);
9236      pStmt = 0;
9237      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9238      sqlite3_free(zSql);
9239      if( rx!=SQLITE_OK ){
9240        sqlite3_finalize(pStmt);
9241        pStmt = 0;
9242        zSql = sqlite3_mprintf(
9243                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9244                   "VALUES(%Q,%Q);", zKey, zValue);
9245        shell_check_oom(zSql);
9246        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9247        sqlite3_free(zSql);
9248        if( rx!=SQLITE_OK ){
9249          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9250          sqlite3_finalize(pStmt);
9251          pStmt = 0;
9252          rc = 1;
9253        }
9254      }
9255      sqlite3_step(pStmt);
9256      sqlite3_finalize(pStmt);
9257    }else
9258
9259    /* .parameter unset NAME
9260    ** Remove the NAME binding from the parameter binding table, if it
9261    ** exists.
9262    */
9263    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9264      char *zSql = sqlite3_mprintf(
9265          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9266      shell_check_oom(zSql);
9267      sqlite3_exec(p->db, zSql, 0, 0, 0);
9268      sqlite3_free(zSql);
9269    }else
9270    /* If no command name matches, show a syntax error */
9271    parameter_syntax_error:
9272    showHelp(p->out, "parameter");
9273  }else
9274
9275  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9276    int i;
9277    for(i=1; i<nArg; i++){
9278      if( i>1 ) raw_printf(p->out, " ");
9279      utf8_printf(p->out, "%s", azArg[i]);
9280    }
9281    raw_printf(p->out, "\n");
9282  }else
9283
9284#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9285  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9286    int i;
9287    int nn = 0;
9288    p->flgProgress = 0;
9289    p->mxProgress = 0;
9290    p->nProgress = 0;
9291    for(i=1; i<nArg; i++){
9292      const char *z = azArg[i];
9293      if( z[0]=='-' ){
9294        z++;
9295        if( z[0]=='-' ) z++;
9296        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9297          p->flgProgress |= SHELL_PROGRESS_QUIET;
9298          continue;
9299        }
9300        if( strcmp(z,"reset")==0 ){
9301          p->flgProgress |= SHELL_PROGRESS_RESET;
9302          continue;
9303        }
9304        if( strcmp(z,"once")==0 ){
9305          p->flgProgress |= SHELL_PROGRESS_ONCE;
9306          continue;
9307        }
9308        if( strcmp(z,"limit")==0 ){
9309          if( i+1>=nArg ){
9310            utf8_printf(stderr, "Error: missing argument on --limit\n");
9311            rc = 1;
9312            goto meta_command_exit;
9313          }else{
9314            p->mxProgress = (int)integerValue(azArg[++i]);
9315          }
9316          continue;
9317        }
9318        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9319        rc = 1;
9320        goto meta_command_exit;
9321      }else{
9322        nn = (int)integerValue(z);
9323      }
9324    }
9325    open_db(p, 0);
9326    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9327  }else
9328#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9329
9330  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9331    if( nArg >= 2) {
9332      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9333    }
9334    if( nArg >= 3) {
9335      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9336    }
9337  }else
9338
9339  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9340    rc = 2;
9341  }else
9342
9343  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9344    FILE *inSaved = p->in;
9345    int savedLineno = p->lineno;
9346    failIfSafeMode(p, "cannot run .read in safe mode");
9347    if( nArg!=2 ){
9348      raw_printf(stderr, "Usage: .read FILE\n");
9349      rc = 1;
9350      goto meta_command_exit;
9351    }
9352    if( azArg[1][0]=='|' ){
9353#ifdef SQLITE_OMIT_POPEN
9354      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9355      rc = 1;
9356      p->out = stdout;
9357#else
9358      p->in = popen(azArg[1]+1, "r");
9359      if( p->in==0 ){
9360        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9361        rc = 1;
9362      }else{
9363        rc = process_input(p);
9364        pclose(p->in);
9365      }
9366#endif
9367    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9368      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9369      rc = 1;
9370    }else{
9371      rc = process_input(p);
9372      fclose(p->in);
9373    }
9374    p->in = inSaved;
9375    p->lineno = savedLineno;
9376  }else
9377
9378  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9379    const char *zSrcFile;
9380    const char *zDb;
9381    sqlite3 *pSrc;
9382    sqlite3_backup *pBackup;
9383    int nTimeout = 0;
9384
9385    failIfSafeMode(p, "cannot run .restore in safe mode");
9386    if( nArg==2 ){
9387      zSrcFile = azArg[1];
9388      zDb = "main";
9389    }else if( nArg==3 ){
9390      zSrcFile = azArg[2];
9391      zDb = azArg[1];
9392    }else{
9393      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9394      rc = 1;
9395      goto meta_command_exit;
9396    }
9397    rc = sqlite3_open(zSrcFile, &pSrc);
9398    if( rc!=SQLITE_OK ){
9399      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9400      close_db(pSrc);
9401      return 1;
9402    }
9403    open_db(p, 0);
9404    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9405    if( pBackup==0 ){
9406      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9407      close_db(pSrc);
9408      return 1;
9409    }
9410    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9411          || rc==SQLITE_BUSY  ){
9412      if( rc==SQLITE_BUSY ){
9413        if( nTimeout++ >= 3 ) break;
9414        sqlite3_sleep(100);
9415      }
9416    }
9417    sqlite3_backup_finish(pBackup);
9418    if( rc==SQLITE_DONE ){
9419      rc = 0;
9420    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9421      raw_printf(stderr, "Error: source database is busy\n");
9422      rc = 1;
9423    }else{
9424      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9425      rc = 1;
9426    }
9427    close_db(pSrc);
9428  }else
9429
9430  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9431    if( nArg==2 ){
9432      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9433#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9434      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9435#endif
9436    }else{
9437      raw_printf(stderr, "Usage: .scanstats on|off\n");
9438      rc = 1;
9439    }
9440  }else
9441
9442  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9443    ShellText sSelect;
9444    ShellState data;
9445    char *zErrMsg = 0;
9446    const char *zDiv = "(";
9447    const char *zName = 0;
9448    int iSchema = 0;
9449    int bDebug = 0;
9450    int bNoSystemTabs = 0;
9451    int ii;
9452
9453    open_db(p, 0);
9454    memcpy(&data, p, sizeof(data));
9455    data.showHeader = 0;
9456    data.cMode = data.mode = MODE_Semi;
9457    initText(&sSelect);
9458    for(ii=1; ii<nArg; ii++){
9459      if( optionMatch(azArg[ii],"indent") ){
9460        data.cMode = data.mode = MODE_Pretty;
9461      }else if( optionMatch(azArg[ii],"debug") ){
9462        bDebug = 1;
9463      }else if( optionMatch(azArg[ii],"nosys") ){
9464        bNoSystemTabs = 1;
9465      }else if( azArg[ii][0]=='-' ){
9466        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9467        rc = 1;
9468        goto meta_command_exit;
9469      }else if( zName==0 ){
9470        zName = azArg[ii];
9471      }else{
9472        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9473        rc = 1;
9474        goto meta_command_exit;
9475      }
9476    }
9477    if( zName!=0 ){
9478      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9479                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9480                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9481                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9482      if( isSchema ){
9483        char *new_argv[2], *new_colv[2];
9484        new_argv[0] = sqlite3_mprintf(
9485                      "CREATE TABLE %s (\n"
9486                      "  type text,\n"
9487                      "  name text,\n"
9488                      "  tbl_name text,\n"
9489                      "  rootpage integer,\n"
9490                      "  sql text\n"
9491                      ")", zName);
9492        shell_check_oom(new_argv[0]);
9493        new_argv[1] = 0;
9494        new_colv[0] = "sql";
9495        new_colv[1] = 0;
9496        callback(&data, 1, new_argv, new_colv);
9497        sqlite3_free(new_argv[0]);
9498      }
9499    }
9500    if( zDiv ){
9501      sqlite3_stmt *pStmt = 0;
9502      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9503                              -1, &pStmt, 0);
9504      if( rc ){
9505        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9506        sqlite3_finalize(pStmt);
9507        rc = 1;
9508        goto meta_command_exit;
9509      }
9510      appendText(&sSelect, "SELECT sql FROM", 0);
9511      iSchema = 0;
9512      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9513        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9514        char zScNum[30];
9515        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9516        appendText(&sSelect, zDiv, 0);
9517        zDiv = " UNION ALL ";
9518        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9519        if( sqlite3_stricmp(zDb, "main")!=0 ){
9520          appendText(&sSelect, zDb, '\'');
9521        }else{
9522          appendText(&sSelect, "NULL", 0);
9523        }
9524        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9525        appendText(&sSelect, zScNum, 0);
9526        appendText(&sSelect, " AS snum, ", 0);
9527        appendText(&sSelect, zDb, '\'');
9528        appendText(&sSelect, " AS sname FROM ", 0);
9529        appendText(&sSelect, zDb, quoteChar(zDb));
9530        appendText(&sSelect, ".sqlite_schema", 0);
9531      }
9532      sqlite3_finalize(pStmt);
9533#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9534      if( zName ){
9535        appendText(&sSelect,
9536           " UNION ALL SELECT shell_module_schema(name),"
9537           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9538        0);
9539      }
9540#endif
9541      appendText(&sSelect, ") WHERE ", 0);
9542      if( zName ){
9543        char *zQarg = sqlite3_mprintf("%Q", zName);
9544        int bGlob;
9545        shell_check_oom(zQarg);
9546        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9547                strchr(zName, '[') != 0;
9548        if( strchr(zName, '.') ){
9549          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9550        }else{
9551          appendText(&sSelect, "lower(tbl_name)", 0);
9552        }
9553        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9554        appendText(&sSelect, zQarg, 0);
9555        if( !bGlob ){
9556          appendText(&sSelect, " ESCAPE '\\' ", 0);
9557        }
9558        appendText(&sSelect, " AND ", 0);
9559        sqlite3_free(zQarg);
9560      }
9561      if( bNoSystemTabs ){
9562        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9563      }
9564      appendText(&sSelect, "sql IS NOT NULL"
9565                           " ORDER BY snum, rowid", 0);
9566      if( bDebug ){
9567        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9568      }else{
9569        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9570      }
9571      freeText(&sSelect);
9572    }
9573    if( zErrMsg ){
9574      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9575      sqlite3_free(zErrMsg);
9576      rc = 1;
9577    }else if( rc != SQLITE_OK ){
9578      raw_printf(stderr,"Error: querying schema information\n");
9579      rc = 1;
9580    }else{
9581      rc = 0;
9582    }
9583  }else
9584
9585  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9586    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9587    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9588  }else
9589
9590#if defined(SQLITE_ENABLE_SESSION)
9591  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9592    struct AuxDb *pAuxDb = p->pAuxDb;
9593    OpenSession *pSession = &pAuxDb->aSession[0];
9594    char **azCmd = &azArg[1];
9595    int iSes = 0;
9596    int nCmd = nArg - 1;
9597    int i;
9598    if( nArg<=1 ) goto session_syntax_error;
9599    open_db(p, 0);
9600    if( nArg>=3 ){
9601      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9602        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9603      }
9604      if( iSes<pAuxDb->nSession ){
9605        pSession = &pAuxDb->aSession[iSes];
9606        azCmd++;
9607        nCmd--;
9608      }else{
9609        pSession = &pAuxDb->aSession[0];
9610        iSes = 0;
9611      }
9612    }
9613
9614    /* .session attach TABLE
9615    ** Invoke the sqlite3session_attach() interface to attach a particular
9616    ** table so that it is never filtered.
9617    */
9618    if( strcmp(azCmd[0],"attach")==0 ){
9619      if( nCmd!=2 ) goto session_syntax_error;
9620      if( pSession->p==0 ){
9621        session_not_open:
9622        raw_printf(stderr, "ERROR: No sessions are open\n");
9623      }else{
9624        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9625        if( rc ){
9626          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9627          rc = 0;
9628        }
9629      }
9630    }else
9631
9632    /* .session changeset FILE
9633    ** .session patchset FILE
9634    ** Write a changeset or patchset into a file.  The file is overwritten.
9635    */
9636    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9637      FILE *out = 0;
9638      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9639      if( nCmd!=2 ) goto session_syntax_error;
9640      if( pSession->p==0 ) goto session_not_open;
9641      out = fopen(azCmd[1], "wb");
9642      if( out==0 ){
9643        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9644                    azCmd[1]);
9645      }else{
9646        int szChng;
9647        void *pChng;
9648        if( azCmd[0][0]=='c' ){
9649          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9650        }else{
9651          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9652        }
9653        if( rc ){
9654          printf("Error: error code %d\n", rc);
9655          rc = 0;
9656        }
9657        if( pChng
9658          && fwrite(pChng, szChng, 1, out)!=1 ){
9659          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9660                  szChng);
9661        }
9662        sqlite3_free(pChng);
9663        fclose(out);
9664      }
9665    }else
9666
9667    /* .session close
9668    ** Close the identified session
9669    */
9670    if( strcmp(azCmd[0], "close")==0 ){
9671      if( nCmd!=1 ) goto session_syntax_error;
9672      if( pAuxDb->nSession ){
9673        session_close(pSession);
9674        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9675      }
9676    }else
9677
9678    /* .session enable ?BOOLEAN?
9679    ** Query or set the enable flag
9680    */
9681    if( strcmp(azCmd[0], "enable")==0 ){
9682      int ii;
9683      if( nCmd>2 ) goto session_syntax_error;
9684      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9685      if( pAuxDb->nSession ){
9686        ii = sqlite3session_enable(pSession->p, ii);
9687        utf8_printf(p->out, "session %s enable flag = %d\n",
9688                    pSession->zName, ii);
9689      }
9690    }else
9691
9692    /* .session filter GLOB ....
9693    ** Set a list of GLOB patterns of table names to be excluded.
9694    */
9695    if( strcmp(azCmd[0], "filter")==0 ){
9696      int ii, nByte;
9697      if( nCmd<2 ) goto session_syntax_error;
9698      if( pAuxDb->nSession ){
9699        for(ii=0; ii<pSession->nFilter; ii++){
9700          sqlite3_free(pSession->azFilter[ii]);
9701        }
9702        sqlite3_free(pSession->azFilter);
9703        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9704        pSession->azFilter = sqlite3_malloc( nByte );
9705        if( pSession->azFilter==0 ){
9706          raw_printf(stderr, "Error: out or memory\n");
9707          exit(1);
9708        }
9709        for(ii=1; ii<nCmd; ii++){
9710          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9711          shell_check_oom(x);
9712        }
9713        pSession->nFilter = ii-1;
9714      }
9715    }else
9716
9717    /* .session indirect ?BOOLEAN?
9718    ** Query or set the indirect flag
9719    */
9720    if( strcmp(azCmd[0], "indirect")==0 ){
9721      int ii;
9722      if( nCmd>2 ) goto session_syntax_error;
9723      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9724      if( pAuxDb->nSession ){
9725        ii = sqlite3session_indirect(pSession->p, ii);
9726        utf8_printf(p->out, "session %s indirect flag = %d\n",
9727                    pSession->zName, ii);
9728      }
9729    }else
9730
9731    /* .session isempty
9732    ** Determine if the session is empty
9733    */
9734    if( strcmp(azCmd[0], "isempty")==0 ){
9735      int ii;
9736      if( nCmd!=1 ) goto session_syntax_error;
9737      if( pAuxDb->nSession ){
9738        ii = sqlite3session_isempty(pSession->p);
9739        utf8_printf(p->out, "session %s isempty flag = %d\n",
9740                    pSession->zName, ii);
9741      }
9742    }else
9743
9744    /* .session list
9745    ** List all currently open sessions
9746    */
9747    if( strcmp(azCmd[0],"list")==0 ){
9748      for(i=0; i<pAuxDb->nSession; i++){
9749        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9750      }
9751    }else
9752
9753    /* .session open DB NAME
9754    ** Open a new session called NAME on the attached database DB.
9755    ** DB is normally "main".
9756    */
9757    if( strcmp(azCmd[0],"open")==0 ){
9758      char *zName;
9759      if( nCmd!=3 ) goto session_syntax_error;
9760      zName = azCmd[2];
9761      if( zName[0]==0 ) goto session_syntax_error;
9762      for(i=0; i<pAuxDb->nSession; i++){
9763        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9764          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9765          goto meta_command_exit;
9766        }
9767      }
9768      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9769        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9770        goto meta_command_exit;
9771      }
9772      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9773      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9774      if( rc ){
9775        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9776        rc = 0;
9777        goto meta_command_exit;
9778      }
9779      pSession->nFilter = 0;
9780      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9781      pAuxDb->nSession++;
9782      pSession->zName = sqlite3_mprintf("%s", zName);
9783      shell_check_oom(pSession->zName);
9784    }else
9785    /* If no command name matches, show a syntax error */
9786    session_syntax_error:
9787    showHelp(p->out, "session");
9788  }else
9789#endif
9790
9791#ifdef SQLITE_DEBUG
9792  /* Undocumented commands for internal testing.  Subject to change
9793  ** without notice. */
9794  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9795    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9796      int i, v;
9797      for(i=1; i<nArg; i++){
9798        v = booleanValue(azArg[i]);
9799        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9800      }
9801    }
9802    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9803      int i; sqlite3_int64 v;
9804      for(i=1; i<nArg; i++){
9805        char zBuf[200];
9806        v = integerValue(azArg[i]);
9807        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9808        utf8_printf(p->out, "%s", zBuf);
9809      }
9810    }
9811  }else
9812#endif
9813
9814  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9815    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9816    int bVerbose = 0;        /* Verbose output */
9817    int bSelftestExists;     /* True if SELFTEST already exists */
9818    int i, k;                /* Loop counters */
9819    int nTest = 0;           /* Number of tests runs */
9820    int nErr = 0;            /* Number of errors seen */
9821    ShellText str;           /* Answer for a query */
9822    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9823
9824    open_db(p,0);
9825    for(i=1; i<nArg; i++){
9826      const char *z = azArg[i];
9827      if( z[0]=='-' && z[1]=='-' ) z++;
9828      if( strcmp(z,"-init")==0 ){
9829        bIsInit = 1;
9830      }else
9831      if( strcmp(z,"-v")==0 ){
9832        bVerbose++;
9833      }else
9834      {
9835        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9836                    azArg[i], azArg[0]);
9837        raw_printf(stderr, "Should be one of: --init -v\n");
9838        rc = 1;
9839        goto meta_command_exit;
9840      }
9841    }
9842    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9843           != SQLITE_OK ){
9844      bSelftestExists = 0;
9845    }else{
9846      bSelftestExists = 1;
9847    }
9848    if( bIsInit ){
9849      createSelftestTable(p);
9850      bSelftestExists = 1;
9851    }
9852    initText(&str);
9853    appendText(&str, "x", 0);
9854    for(k=bSelftestExists; k>=0; k--){
9855      if( k==1 ){
9856        rc = sqlite3_prepare_v2(p->db,
9857            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9858            -1, &pStmt, 0);
9859      }else{
9860        rc = sqlite3_prepare_v2(p->db,
9861          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9862          "      (1,'run','PRAGMA integrity_check','ok')",
9863          -1, &pStmt, 0);
9864      }
9865      if( rc ){
9866        raw_printf(stderr, "Error querying the selftest table\n");
9867        rc = 1;
9868        sqlite3_finalize(pStmt);
9869        goto meta_command_exit;
9870      }
9871      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9872        int tno = sqlite3_column_int(pStmt, 0);
9873        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9874        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9875        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9876
9877        if( zOp==0 ) continue;
9878        if( zSql==0 ) continue;
9879        if( zAns==0 ) continue;
9880        k = 0;
9881        if( bVerbose>0 ){
9882          printf("%d: %s %s\n", tno, zOp, zSql);
9883        }
9884        if( strcmp(zOp,"memo")==0 ){
9885          utf8_printf(p->out, "%s\n", zSql);
9886        }else
9887        if( strcmp(zOp,"run")==0 ){
9888          char *zErrMsg = 0;
9889          str.n = 0;
9890          str.z[0] = 0;
9891          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9892          nTest++;
9893          if( bVerbose ){
9894            utf8_printf(p->out, "Result: %s\n", str.z);
9895          }
9896          if( rc || zErrMsg ){
9897            nErr++;
9898            rc = 1;
9899            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9900            sqlite3_free(zErrMsg);
9901          }else if( strcmp(zAns,str.z)!=0 ){
9902            nErr++;
9903            rc = 1;
9904            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9905            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9906          }
9907        }else
9908        {
9909          utf8_printf(stderr,
9910            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9911          rc = 1;
9912          break;
9913        }
9914      } /* End loop over rows of content from SELFTEST */
9915      sqlite3_finalize(pStmt);
9916    } /* End loop over k */
9917    freeText(&str);
9918    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9919  }else
9920
9921  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9922    if( nArg<2 || nArg>3 ){
9923      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9924      rc = 1;
9925    }
9926    if( nArg>=2 ){
9927      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9928                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9929    }
9930    if( nArg>=3 ){
9931      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9932                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9933    }
9934  }else
9935
9936  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9937    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
9938    int i;                   /* Loop counter */
9939    int bSchema = 0;         /* Also hash the schema */
9940    int bSeparate = 0;       /* Hash each table separately */
9941    int iSize = 224;         /* Hash algorithm to use */
9942    int bDebug = 0;          /* Only show the query that would have run */
9943    sqlite3_stmt *pStmt;     /* For querying tables names */
9944    char *zSql;              /* SQL to be run */
9945    char *zSep;              /* Separator */
9946    ShellText sSql;          /* Complete SQL for the query to run the hash */
9947    ShellText sQuery;        /* Set of queries used to read all content */
9948    open_db(p, 0);
9949    for(i=1; i<nArg; i++){
9950      const char *z = azArg[i];
9951      if( z[0]=='-' ){
9952        z++;
9953        if( z[0]=='-' ) z++;
9954        if( strcmp(z,"schema")==0 ){
9955          bSchema = 1;
9956        }else
9957        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9958         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9959        ){
9960          iSize = atoi(&z[5]);
9961        }else
9962        if( strcmp(z,"debug")==0 ){
9963          bDebug = 1;
9964        }else
9965        {
9966          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9967                      azArg[i], azArg[0]);
9968          showHelp(p->out, azArg[0]);
9969          rc = 1;
9970          goto meta_command_exit;
9971        }
9972      }else if( zLike ){
9973        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9974        rc = 1;
9975        goto meta_command_exit;
9976      }else{
9977        zLike = z;
9978        bSeparate = 1;
9979        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9980      }
9981    }
9982    if( bSchema ){
9983      zSql = "SELECT lower(name) FROM sqlite_schema"
9984             " WHERE type='table' AND coalesce(rootpage,0)>1"
9985             " UNION ALL SELECT 'sqlite_schema'"
9986             " ORDER BY 1 collate nocase";
9987    }else{
9988      zSql = "SELECT lower(name) FROM sqlite_schema"
9989             " WHERE type='table' AND coalesce(rootpage,0)>1"
9990             " AND name NOT LIKE 'sqlite_%'"
9991             " ORDER BY 1 collate nocase";
9992    }
9993    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9994    initText(&sQuery);
9995    initText(&sSql);
9996    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9997    zSep = "VALUES(";
9998    while( SQLITE_ROW==sqlite3_step(pStmt) ){
9999      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10000      if( zTab==0 ) continue;
10001      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10002      if( strncmp(zTab, "sqlite_",7)!=0 ){
10003        appendText(&sQuery,"SELECT * FROM ", 0);
10004        appendText(&sQuery,zTab,'"');
10005        appendText(&sQuery," NOT INDEXED;", 0);
10006      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10007        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10008                           " ORDER BY name;", 0);
10009      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10010        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10011                           " ORDER BY name;", 0);
10012      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10013        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10014                           " ORDER BY tbl,idx;", 0);
10015      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10016        appendText(&sQuery, "SELECT * FROM ", 0);
10017        appendText(&sQuery, zTab, 0);
10018        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10019      }
10020      appendText(&sSql, zSep, 0);
10021      appendText(&sSql, sQuery.z, '\'');
10022      sQuery.n = 0;
10023      appendText(&sSql, ",", 0);
10024      appendText(&sSql, zTab, '\'');
10025      zSep = "),(";
10026    }
10027    sqlite3_finalize(pStmt);
10028    if( bSeparate ){
10029      zSql = sqlite3_mprintf(
10030          "%s))"
10031          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10032          "   FROM [sha3sum$query]",
10033          sSql.z, iSize);
10034    }else{
10035      zSql = sqlite3_mprintf(
10036          "%s))"
10037          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10038          "   FROM [sha3sum$query]",
10039          sSql.z, iSize);
10040    }
10041    shell_check_oom(zSql);
10042    freeText(&sQuery);
10043    freeText(&sSql);
10044    if( bDebug ){
10045      utf8_printf(p->out, "%s\n", zSql);
10046    }else{
10047      shell_exec(p, zSql, 0);
10048    }
10049    sqlite3_free(zSql);
10050  }else
10051
10052#ifndef SQLITE_NOHAVE_SYSTEM
10053  if( c=='s'
10054   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10055  ){
10056    char *zCmd;
10057    int i, x;
10058    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10059    if( nArg<2 ){
10060      raw_printf(stderr, "Usage: .system COMMAND\n");
10061      rc = 1;
10062      goto meta_command_exit;
10063    }
10064    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10065    for(i=2; i<nArg && zCmd!=0; i++){
10066      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10067                             zCmd, azArg[i]);
10068    }
10069    x = zCmd!=0 ? system(zCmd) : 1;
10070    sqlite3_free(zCmd);
10071    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10072  }else
10073#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10074
10075  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10076    static const char *azBool[] = { "off", "on", "trigger", "full"};
10077    const char *zOut;
10078    int i;
10079    if( nArg!=1 ){
10080      raw_printf(stderr, "Usage: .show\n");
10081      rc = 1;
10082      goto meta_command_exit;
10083    }
10084    utf8_printf(p->out, "%12.12s: %s\n","echo",
10085                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10086    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10087    utf8_printf(p->out, "%12.12s: %s\n","explain",
10088         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10089    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10090    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10091    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10092      output_c_string(p->out, p->nullValue);
10093      raw_printf(p->out, "\n");
10094    utf8_printf(p->out,"%12.12s: %s\n","output",
10095            strlen30(p->outfile) ? p->outfile : "stdout");
10096    utf8_printf(p->out,"%12.12s: ", "colseparator");
10097      output_c_string(p->out, p->colSeparator);
10098      raw_printf(p->out, "\n");
10099    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10100      output_c_string(p->out, p->rowSeparator);
10101      raw_printf(p->out, "\n");
10102    switch( p->statsOn ){
10103      case 0:  zOut = "off";     break;
10104      default: zOut = "on";      break;
10105      case 2:  zOut = "stmt";    break;
10106      case 3:  zOut = "vmstep";  break;
10107    }
10108    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10109    utf8_printf(p->out, "%12.12s: ", "width");
10110    for (i=0;i<p->nWidth;i++) {
10111      raw_printf(p->out, "%d ", p->colWidth[i]);
10112    }
10113    raw_printf(p->out, "\n");
10114    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10115                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10116  }else
10117
10118  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10119    if( nArg==2 ){
10120      if( strcmp(azArg[1],"stmt")==0 ){
10121        p->statsOn = 2;
10122      }else if( strcmp(azArg[1],"vmstep")==0 ){
10123        p->statsOn = 3;
10124      }else{
10125        p->statsOn = (u8)booleanValue(azArg[1]);
10126      }
10127    }else if( nArg==1 ){
10128      display_stats(p->db, p, 0);
10129    }else{
10130      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10131      rc = 1;
10132    }
10133  }else
10134
10135  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10136   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10137                 || strncmp(azArg[0], "indexes", n)==0) )
10138  ){
10139    sqlite3_stmt *pStmt;
10140    char **azResult;
10141    int nRow, nAlloc;
10142    int ii;
10143    ShellText s;
10144    initText(&s);
10145    open_db(p, 0);
10146    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10147    if( rc ){
10148      sqlite3_finalize(pStmt);
10149      return shellDatabaseError(p->db);
10150    }
10151
10152    if( nArg>2 && c=='i' ){
10153      /* It is an historical accident that the .indexes command shows an error
10154      ** when called with the wrong number of arguments whereas the .tables
10155      ** command does not. */
10156      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10157      rc = 1;
10158      sqlite3_finalize(pStmt);
10159      goto meta_command_exit;
10160    }
10161    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10162      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10163      if( zDbName==0 ) continue;
10164      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10165      if( sqlite3_stricmp(zDbName, "main")==0 ){
10166        appendText(&s, "SELECT name FROM ", 0);
10167      }else{
10168        appendText(&s, "SELECT ", 0);
10169        appendText(&s, zDbName, '\'');
10170        appendText(&s, "||'.'||name FROM ", 0);
10171      }
10172      appendText(&s, zDbName, '"');
10173      appendText(&s, ".sqlite_schema ", 0);
10174      if( c=='t' ){
10175        appendText(&s," WHERE type IN ('table','view')"
10176                      "   AND name NOT LIKE 'sqlite_%'"
10177                      "   AND name LIKE ?1", 0);
10178      }else{
10179        appendText(&s," WHERE type='index'"
10180                      "   AND tbl_name LIKE ?1", 0);
10181      }
10182    }
10183    rc = sqlite3_finalize(pStmt);
10184    if( rc==SQLITE_OK ){
10185      appendText(&s, " ORDER BY 1", 0);
10186      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10187    }
10188    freeText(&s);
10189    if( rc ) return shellDatabaseError(p->db);
10190
10191    /* Run the SQL statement prepared by the above block. Store the results
10192    ** as an array of nul-terminated strings in azResult[].  */
10193    nRow = nAlloc = 0;
10194    azResult = 0;
10195    if( nArg>1 ){
10196      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10197    }else{
10198      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10199    }
10200    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10201      if( nRow>=nAlloc ){
10202        char **azNew;
10203        int n2 = nAlloc*2 + 10;
10204        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10205        shell_check_oom(azNew);
10206        nAlloc = n2;
10207        azResult = azNew;
10208      }
10209      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10210      shell_check_oom(azResult[nRow]);
10211      nRow++;
10212    }
10213    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10214      rc = shellDatabaseError(p->db);
10215    }
10216
10217    /* Pretty-print the contents of array azResult[] to the output */
10218    if( rc==0 && nRow>0 ){
10219      int len, maxlen = 0;
10220      int i, j;
10221      int nPrintCol, nPrintRow;
10222      for(i=0; i<nRow; i++){
10223        len = strlen30(azResult[i]);
10224        if( len>maxlen ) maxlen = len;
10225      }
10226      nPrintCol = 80/(maxlen+2);
10227      if( nPrintCol<1 ) nPrintCol = 1;
10228      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10229      for(i=0; i<nPrintRow; i++){
10230        for(j=i; j<nRow; j+=nPrintRow){
10231          char *zSp = j<nPrintRow ? "" : "  ";
10232          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10233                      azResult[j] ? azResult[j]:"");
10234        }
10235        raw_printf(p->out, "\n");
10236      }
10237    }
10238
10239    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10240    sqlite3_free(azResult);
10241  }else
10242
10243  /* Begin redirecting output to the file "testcase-out.txt" */
10244  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10245    output_reset(p);
10246    p->out = output_file_open("testcase-out.txt", 0);
10247    if( p->out==0 ){
10248      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10249    }
10250    if( nArg>=2 ){
10251      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10252    }else{
10253      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10254    }
10255  }else
10256
10257#ifndef SQLITE_UNTESTABLE
10258  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10259    static const struct {
10260       const char *zCtrlName;   /* Name of a test-control option */
10261       int ctrlCode;            /* Integer code for that option */
10262       int unSafe;              /* Not valid for --safe mode */
10263       const char *zUsage;      /* Usage notes */
10264    } aCtrl[] = {
10265      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10266      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10267    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10268    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10269      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10270      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10271    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10272      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10273      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10274      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10275      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10276      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10277#ifdef YYCOVERAGE
10278      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10279#endif
10280      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10281      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10282      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10283      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10284      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10285      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10286      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10287    };
10288    int testctrl = -1;
10289    int iCtrl = -1;
10290    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10291    int isOk = 0;
10292    int i, n2;
10293    const char *zCmd = 0;
10294
10295    open_db(p, 0);
10296    zCmd = nArg>=2 ? azArg[1] : "help";
10297
10298    /* The argument can optionally begin with "-" or "--" */
10299    if( zCmd[0]=='-' && zCmd[1] ){
10300      zCmd++;
10301      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10302    }
10303
10304    /* --help lists all test-controls */
10305    if( strcmp(zCmd,"help")==0 ){
10306      utf8_printf(p->out, "Available test-controls:\n");
10307      for(i=0; i<ArraySize(aCtrl); i++){
10308        utf8_printf(p->out, "  .testctrl %s %s\n",
10309                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10310      }
10311      rc = 1;
10312      goto meta_command_exit;
10313    }
10314
10315    /* convert testctrl text option to value. allow any unique prefix
10316    ** of the option name, or a numerical value. */
10317    n2 = strlen30(zCmd);
10318    for(i=0; i<ArraySize(aCtrl); i++){
10319      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10320        if( testctrl<0 ){
10321          testctrl = aCtrl[i].ctrlCode;
10322          iCtrl = i;
10323        }else{
10324          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10325                              "Use \".testctrl --help\" for help\n", zCmd);
10326          rc = 1;
10327          goto meta_command_exit;
10328        }
10329      }
10330    }
10331    if( testctrl<0 ){
10332      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10333                         "Use \".testctrl --help\" for help\n", zCmd);
10334    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10335      utf8_printf(stderr,
10336         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10337         p->lineno, aCtrl[iCtrl].zCtrlName);
10338      exit(1);
10339    }else{
10340      switch(testctrl){
10341
10342        /* sqlite3_test_control(int, db, int) */
10343        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10344          if( nArg==3 ){
10345            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10346            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10347            isOk = 3;
10348          }
10349          break;
10350
10351        /* sqlite3_test_control(int) */
10352        case SQLITE_TESTCTRL_PRNG_SAVE:
10353        case SQLITE_TESTCTRL_PRNG_RESTORE:
10354        case SQLITE_TESTCTRL_BYTEORDER:
10355          if( nArg==2 ){
10356            rc2 = sqlite3_test_control(testctrl);
10357            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10358          }
10359          break;
10360
10361        /* sqlite3_test_control(int, uint) */
10362        case SQLITE_TESTCTRL_PENDING_BYTE:
10363          if( nArg==3 ){
10364            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10365            rc2 = sqlite3_test_control(testctrl, opt);
10366            isOk = 3;
10367          }
10368          break;
10369
10370        /* sqlite3_test_control(int, int, sqlite3*) */
10371        case SQLITE_TESTCTRL_PRNG_SEED:
10372          if( nArg==3 || nArg==4 ){
10373            int ii = (int)integerValue(azArg[2]);
10374            sqlite3 *db;
10375            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10376              sqlite3_randomness(sizeof(ii),&ii);
10377              printf("-- random seed: %d\n", ii);
10378            }
10379            if( nArg==3 ){
10380              db = 0;
10381            }else{
10382              db = p->db;
10383              /* Make sure the schema has been loaded */
10384              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10385            }
10386            rc2 = sqlite3_test_control(testctrl, ii, db);
10387            isOk = 3;
10388          }
10389          break;
10390
10391        /* sqlite3_test_control(int, int) */
10392        case SQLITE_TESTCTRL_ASSERT:
10393        case SQLITE_TESTCTRL_ALWAYS:
10394          if( nArg==3 ){
10395            int opt = booleanValue(azArg[2]);
10396            rc2 = sqlite3_test_control(testctrl, opt);
10397            isOk = 1;
10398          }
10399          break;
10400
10401        /* sqlite3_test_control(int, int) */
10402        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10403        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10404          if( nArg==3 ){
10405            int opt = booleanValue(azArg[2]);
10406            rc2 = sqlite3_test_control(testctrl, opt);
10407            isOk = 3;
10408          }
10409          break;
10410
10411        /* sqlite3_test_control(sqlite3*) */
10412        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10413          rc2 = sqlite3_test_control(testctrl, p->db);
10414          isOk = 3;
10415          break;
10416
10417        case SQLITE_TESTCTRL_IMPOSTER:
10418          if( nArg==5 ){
10419            rc2 = sqlite3_test_control(testctrl, p->db,
10420                          azArg[2],
10421                          integerValue(azArg[3]),
10422                          integerValue(azArg[4]));
10423            isOk = 3;
10424          }
10425          break;
10426
10427        case SQLITE_TESTCTRL_SEEK_COUNT: {
10428          u64 x = 0;
10429          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10430          utf8_printf(p->out, "%llu\n", x);
10431          isOk = 3;
10432          break;
10433        }
10434
10435#ifdef YYCOVERAGE
10436        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10437          if( nArg==2 ){
10438            sqlite3_test_control(testctrl, p->out);
10439            isOk = 3;
10440          }
10441          break;
10442        }
10443#endif
10444#ifdef SQLITE_DEBUG
10445        case SQLITE_TESTCTRL_TUNE: {
10446          if( nArg==4 ){
10447            int id = (int)integerValue(azArg[2]);
10448            int val = (int)integerValue(azArg[3]);
10449            sqlite3_test_control(testctrl, id, &val);
10450            isOk = 3;
10451          }else if( nArg==3 ){
10452            int id = (int)integerValue(azArg[2]);
10453            sqlite3_test_control(testctrl, -id, &rc2);
10454            isOk = 1;
10455          }else if( nArg==2 ){
10456            int id = 1;
10457            while(1){
10458              int val = 0;
10459              rc2 = sqlite3_test_control(testctrl, -id, &val);
10460              if( rc2!=SQLITE_OK ) break;
10461              if( id>1 ) utf8_printf(p->out, "  ");
10462              utf8_printf(p->out, "%d: %d", id, val);
10463              id++;
10464            }
10465            if( id>1 ) utf8_printf(p->out, "\n");
10466            isOk = 3;
10467          }
10468          break;
10469        }
10470#endif
10471        case SQLITE_TESTCTRL_SORTER_MMAP:
10472          if( nArg==3 ){
10473            int opt = (unsigned int)integerValue(azArg[2]);
10474            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10475            isOk = 3;
10476          }
10477          break;
10478      }
10479    }
10480    if( isOk==0 && iCtrl>=0 ){
10481      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10482      rc = 1;
10483    }else if( isOk==1 ){
10484      raw_printf(p->out, "%d\n", rc2);
10485    }else if( isOk==2 ){
10486      raw_printf(p->out, "0x%08x\n", rc2);
10487    }
10488  }else
10489#endif /* !defined(SQLITE_UNTESTABLE) */
10490
10491  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10492    open_db(p, 0);
10493    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10494  }else
10495
10496  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10497    if( nArg==2 ){
10498      enableTimer = booleanValue(azArg[1]);
10499      if( enableTimer && !HAS_TIMER ){
10500        raw_printf(stderr, "Error: timer not available on this system.\n");
10501        enableTimer = 0;
10502      }
10503    }else{
10504      raw_printf(stderr, "Usage: .timer on|off\n");
10505      rc = 1;
10506    }
10507  }else
10508
10509#ifndef SQLITE_OMIT_TRACE
10510  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10511    int mType = 0;
10512    int jj;
10513    open_db(p, 0);
10514    for(jj=1; jj<nArg; jj++){
10515      const char *z = azArg[jj];
10516      if( z[0]=='-' ){
10517        if( optionMatch(z, "expanded") ){
10518          p->eTraceType = SHELL_TRACE_EXPANDED;
10519        }
10520#ifdef SQLITE_ENABLE_NORMALIZE
10521        else if( optionMatch(z, "normalized") ){
10522          p->eTraceType = SHELL_TRACE_NORMALIZED;
10523        }
10524#endif
10525        else if( optionMatch(z, "plain") ){
10526          p->eTraceType = SHELL_TRACE_PLAIN;
10527        }
10528        else if( optionMatch(z, "profile") ){
10529          mType |= SQLITE_TRACE_PROFILE;
10530        }
10531        else if( optionMatch(z, "row") ){
10532          mType |= SQLITE_TRACE_ROW;
10533        }
10534        else if( optionMatch(z, "stmt") ){
10535          mType |= SQLITE_TRACE_STMT;
10536        }
10537        else if( optionMatch(z, "close") ){
10538          mType |= SQLITE_TRACE_CLOSE;
10539        }
10540        else {
10541          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10542          rc = 1;
10543          goto meta_command_exit;
10544        }
10545      }else{
10546        output_file_close(p->traceOut);
10547        p->traceOut = output_file_open(azArg[1], 0);
10548      }
10549    }
10550    if( p->traceOut==0 ){
10551      sqlite3_trace_v2(p->db, 0, 0, 0);
10552    }else{
10553      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10554      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10555    }
10556  }else
10557#endif /* !defined(SQLITE_OMIT_TRACE) */
10558
10559#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10560  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10561    int ii;
10562    int lenOpt;
10563    char *zOpt;
10564    if( nArg<2 ){
10565      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10566      rc = 1;
10567      goto meta_command_exit;
10568    }
10569    open_db(p, 0);
10570    zOpt = azArg[1];
10571    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10572    lenOpt = (int)strlen(zOpt);
10573    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10574      assert( azArg[nArg]==0 );
10575      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10576    }else{
10577      for(ii=1; ii<nArg; ii++){
10578        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10579      }
10580    }
10581  }else
10582#endif
10583
10584#if SQLITE_USER_AUTHENTICATION
10585  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10586    if( nArg<2 ){
10587      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10588      rc = 1;
10589      goto meta_command_exit;
10590    }
10591    open_db(p, 0);
10592    if( strcmp(azArg[1],"login")==0 ){
10593      if( nArg!=4 ){
10594        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10595        rc = 1;
10596        goto meta_command_exit;
10597      }
10598      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10599                                     strlen30(azArg[3]));
10600      if( rc ){
10601        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10602        rc = 1;
10603      }
10604    }else if( strcmp(azArg[1],"add")==0 ){
10605      if( nArg!=5 ){
10606        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10607        rc = 1;
10608        goto meta_command_exit;
10609      }
10610      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10611                            booleanValue(azArg[4]));
10612      if( rc ){
10613        raw_printf(stderr, "User-Add failed: %d\n", rc);
10614        rc = 1;
10615      }
10616    }else if( strcmp(azArg[1],"edit")==0 ){
10617      if( nArg!=5 ){
10618        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10619        rc = 1;
10620        goto meta_command_exit;
10621      }
10622      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10623                              booleanValue(azArg[4]));
10624      if( rc ){
10625        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10626        rc = 1;
10627      }
10628    }else if( strcmp(azArg[1],"delete")==0 ){
10629      if( nArg!=3 ){
10630        raw_printf(stderr, "Usage: .user delete USER\n");
10631        rc = 1;
10632        goto meta_command_exit;
10633      }
10634      rc = sqlite3_user_delete(p->db, azArg[2]);
10635      if( rc ){
10636        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10637        rc = 1;
10638      }
10639    }else{
10640      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10641      rc = 1;
10642      goto meta_command_exit;
10643    }
10644  }else
10645#endif /* SQLITE_USER_AUTHENTICATION */
10646
10647  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10648    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10649        sqlite3_libversion(), sqlite3_sourceid());
10650#if SQLITE_HAVE_ZLIB
10651    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10652#endif
10653#define CTIMEOPT_VAL_(opt) #opt
10654#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10655#if defined(__clang__) && defined(__clang_major__)
10656    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10657                    CTIMEOPT_VAL(__clang_minor__) "."
10658                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10659#elif defined(_MSC_VER)
10660    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10661#elif defined(__GNUC__) && defined(__VERSION__)
10662    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10663#endif
10664  }else
10665
10666  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10667    const char *zDbName = nArg==2 ? azArg[1] : "main";
10668    sqlite3_vfs *pVfs = 0;
10669    if( p->db ){
10670      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10671      if( pVfs ){
10672        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10673        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10674        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10675        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10676      }
10677    }
10678  }else
10679
10680  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10681    sqlite3_vfs *pVfs;
10682    sqlite3_vfs *pCurrent = 0;
10683    if( p->db ){
10684      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10685    }
10686    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10687      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10688           pVfs==pCurrent ? "  <--- CURRENT" : "");
10689      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10690      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10691      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10692      if( pVfs->pNext ){
10693        raw_printf(p->out, "-----------------------------------\n");
10694      }
10695    }
10696  }else
10697
10698  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10699    const char *zDbName = nArg==2 ? azArg[1] : "main";
10700    char *zVfsName = 0;
10701    if( p->db ){
10702      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10703      if( zVfsName ){
10704        utf8_printf(p->out, "%s\n", zVfsName);
10705        sqlite3_free(zVfsName);
10706      }
10707    }
10708  }else
10709
10710  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10711    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10712    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10713  }else
10714
10715  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10716    int j;
10717    assert( nArg<=ArraySize(azArg) );
10718    p->nWidth = nArg-1;
10719    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10720    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10721    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10722    for(j=1; j<nArg; j++){
10723      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10724    }
10725  }else
10726
10727  {
10728    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10729      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10730    rc = 1;
10731  }
10732
10733meta_command_exit:
10734  if( p->outCount ){
10735    p->outCount--;
10736    if( p->outCount==0 ) output_reset(p);
10737  }
10738  p->bSafeMode = p->bSafeModePersist;
10739  return rc;
10740}
10741
10742/* Line scan result and intermediate states (supporting scan resumption)
10743*/
10744#ifndef CHAR_BIT
10745# define CHAR_BIT 8
10746#endif
10747typedef enum {
10748  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10749  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10750  QSS_Start = 0
10751} QuickScanState;
10752#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10753#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10754#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10755#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10756#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10757
10758/*
10759** Scan line for classification to guide shell's handling.
10760** The scan is resumable for subsequent lines when prior
10761** return values are passed as the 2nd argument.
10762*/
10763static QuickScanState quickscan(char *zLine, QuickScanState qss){
10764  char cin;
10765  char cWait = (char)qss; /* intentional narrowing loss */
10766  if( cWait==0 ){
10767  PlainScan:
10768    assert( cWait==0 );
10769    while( (cin = *zLine++)!=0 ){
10770      if( IsSpace(cin) )
10771        continue;
10772      switch (cin){
10773      case '-':
10774        if( *zLine!='-' )
10775          break;
10776        while((cin = *++zLine)!=0 )
10777          if( cin=='\n')
10778            goto PlainScan;
10779        return qss;
10780      case ';':
10781        qss |= QSS_EndingSemi;
10782        continue;
10783      case '/':
10784        if( *zLine=='*' ){
10785          ++zLine;
10786          cWait = '*';
10787          qss = QSS_SETV(qss, cWait);
10788          goto TermScan;
10789        }
10790        break;
10791      case '[':
10792        cin = ']';
10793        /* fall thru */
10794      case '`': case '\'': case '"':
10795        cWait = cin;
10796        qss = QSS_HasDark | cWait;
10797        goto TermScan;
10798      default:
10799        break;
10800      }
10801      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10802    }
10803  }else{
10804  TermScan:
10805    while( (cin = *zLine++)!=0 ){
10806      if( cin==cWait ){
10807        switch( cWait ){
10808        case '*':
10809          if( *zLine != '/' )
10810            continue;
10811          ++zLine;
10812          cWait = 0;
10813          qss = QSS_SETV(qss, 0);
10814          goto PlainScan;
10815        case '`': case '\'': case '"':
10816          if(*zLine==cWait){
10817            ++zLine;
10818            continue;
10819          }
10820          /* fall thru */
10821        case ']':
10822          cWait = 0;
10823          qss = QSS_SETV(qss, 0);
10824          goto PlainScan;
10825        default: assert(0);
10826        }
10827      }
10828    }
10829  }
10830  return qss;
10831}
10832
10833/*
10834** Return TRUE if the line typed in is an SQL command terminator other
10835** than a semi-colon.  The SQL Server style "go" command is understood
10836** as is the Oracle "/".
10837*/
10838static int line_is_command_terminator(char *zLine){
10839  while( IsSpace(zLine[0]) ){ zLine++; };
10840  if( zLine[0]=='/' )
10841    zLine += 1; /* Oracle */
10842  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10843    zLine += 2; /* SQL Server */
10844  else
10845    return 0;
10846  return quickscan(zLine,QSS_Start)==QSS_Start;
10847}
10848
10849/*
10850** We need a default sqlite3_complete() implementation to use in case
10851** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10852** any arbitrary text is a complete SQL statement.  This is not very
10853** user-friendly, but it does seem to work.
10854*/
10855#ifdef SQLITE_OMIT_COMPLETE
10856#define sqlite3_complete(x) 1
10857#endif
10858
10859/*
10860** Return true if zSql is a complete SQL statement.  Return false if it
10861** ends in the middle of a string literal or C-style comment.
10862*/
10863static int line_is_complete(char *zSql, int nSql){
10864  int rc;
10865  if( zSql==0 ) return 1;
10866  zSql[nSql] = ';';
10867  zSql[nSql+1] = 0;
10868  rc = sqlite3_complete(zSql);
10869  zSql[nSql] = 0;
10870  return rc;
10871}
10872
10873/*
10874** Run a single line of SQL.  Return the number of errors.
10875*/
10876static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10877  int rc;
10878  char *zErrMsg = 0;
10879
10880  open_db(p, 0);
10881  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10882  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10883  BEGIN_TIMER;
10884  rc = shell_exec(p, zSql, &zErrMsg);
10885  END_TIMER;
10886  if( rc || zErrMsg ){
10887    char zPrefix[100];
10888    if( in!=0 || !stdin_is_interactive ){
10889      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10890                       "Error: near line %d:", startline);
10891    }else{
10892      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10893    }
10894    if( zErrMsg!=0 ){
10895      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10896      sqlite3_free(zErrMsg);
10897      zErrMsg = 0;
10898    }else{
10899      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10900    }
10901    return 1;
10902  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10903    char zLineBuf[2000];
10904    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
10905            "changes: %lld   total_changes: %lld",
10906            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
10907    raw_printf(p->out, "%s\n", zLineBuf);
10908  }
10909  return 0;
10910}
10911
10912
10913/*
10914** Read input from *in and process it.  If *in==0 then input
10915** is interactive - the user is typing it it.  Otherwise, input
10916** is coming from a file or device.  A prompt is issued and history
10917** is saved only if input is interactive.  An interrupt signal will
10918** cause this routine to exit immediately, unless input is interactive.
10919**
10920** Return the number of errors.
10921*/
10922static int process_input(ShellState *p){
10923  char *zLine = 0;          /* A single input line */
10924  char *zSql = 0;           /* Accumulated SQL text */
10925  int nLine;                /* Length of current line */
10926  int nSql = 0;             /* Bytes of zSql[] used */
10927  int nAlloc = 0;           /* Allocated zSql[] space */
10928  int rc;                   /* Error code */
10929  int errCnt = 0;           /* Number of errors seen */
10930  int startline = 0;        /* Line number for start of current input */
10931  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
10932
10933  p->lineno = 0;
10934  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10935    fflush(p->out);
10936    zLine = one_input_line(p->in, zLine, nSql>0);
10937    if( zLine==0 ){
10938      /* End of input */
10939      if( p->in==0 && stdin_is_interactive ) printf("\n");
10940      break;
10941    }
10942    if( seenInterrupt ){
10943      if( p->in!=0 ) break;
10944      seenInterrupt = 0;
10945    }
10946    p->lineno++;
10947    if( QSS_INPLAIN(qss)
10948        && line_is_command_terminator(zLine)
10949        && line_is_complete(zSql, nSql) ){
10950      memcpy(zLine,";",2);
10951    }
10952    qss = quickscan(zLine, qss);
10953    if( QSS_PLAINWHITE(qss) && nSql==0 ){
10954      if( ShellHasFlag(p, SHFLG_Echo) )
10955        printf("%s\n", zLine);
10956      /* Just swallow single-line whitespace */
10957      qss = QSS_Start;
10958      continue;
10959    }
10960    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10961      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10962      if( zLine[0]=='.' ){
10963        rc = do_meta_command(zLine, p);
10964        if( rc==2 ){ /* exit requested */
10965          break;
10966        }else if( rc ){
10967          errCnt++;
10968        }
10969      }
10970      qss = QSS_Start;
10971      continue;
10972    }
10973    /* No single-line dispositions remain; accumulate line(s). */
10974    nLine = strlen30(zLine);
10975    if( nSql+nLine+2>=nAlloc ){
10976      /* Grow buffer by half-again increments when big. */
10977      nAlloc = nSql+(nSql>>1)+nLine+100;
10978      zSql = realloc(zSql, nAlloc);
10979      shell_check_oom(zSql);
10980    }
10981    if( nSql==0 ){
10982      int i;
10983      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10984      assert( nAlloc>0 && zSql!=0 );
10985      memcpy(zSql, zLine+i, nLine+1-i);
10986      startline = p->lineno;
10987      nSql = nLine-i;
10988    }else{
10989      zSql[nSql++] = '\n';
10990      memcpy(zSql+nSql, zLine, nLine+1);
10991      nSql += nLine;
10992    }
10993    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
10994      errCnt += runOneSqlLine(p, zSql, p->in, startline);
10995      nSql = 0;
10996      if( p->outCount ){
10997        output_reset(p);
10998        p->outCount = 0;
10999      }else{
11000        clearTempFile(p);
11001      }
11002      p->bSafeMode = p->bSafeModePersist;
11003      qss = QSS_Start;
11004    }else if( nSql && QSS_PLAINWHITE(qss) ){
11005      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
11006      nSql = 0;
11007      qss = QSS_Start;
11008    }
11009  }
11010  if( nSql && QSS_PLAINDARK(qss) ){
11011    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11012  }
11013  free(zSql);
11014  free(zLine);
11015  return errCnt>0;
11016}
11017
11018/*
11019** Return a pathname which is the user's home directory.  A
11020** 0 return indicates an error of some kind.
11021*/
11022static char *find_home_dir(int clearFlag){
11023  static char *home_dir = NULL;
11024  if( clearFlag ){
11025    free(home_dir);
11026    home_dir = 0;
11027    return 0;
11028  }
11029  if( home_dir ) return home_dir;
11030
11031#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11032     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11033  {
11034    struct passwd *pwent;
11035    uid_t uid = getuid();
11036    if( (pwent=getpwuid(uid)) != NULL) {
11037      home_dir = pwent->pw_dir;
11038    }
11039  }
11040#endif
11041
11042#if defined(_WIN32_WCE)
11043  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11044   */
11045  home_dir = "/";
11046#else
11047
11048#if defined(_WIN32) || defined(WIN32)
11049  if (!home_dir) {
11050    home_dir = getenv("USERPROFILE");
11051  }
11052#endif
11053
11054  if (!home_dir) {
11055    home_dir = getenv("HOME");
11056  }
11057
11058#if defined(_WIN32) || defined(WIN32)
11059  if (!home_dir) {
11060    char *zDrive, *zPath;
11061    int n;
11062    zDrive = getenv("HOMEDRIVE");
11063    zPath = getenv("HOMEPATH");
11064    if( zDrive && zPath ){
11065      n = strlen30(zDrive) + strlen30(zPath) + 1;
11066      home_dir = malloc( n );
11067      if( home_dir==0 ) return 0;
11068      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11069      return home_dir;
11070    }
11071    home_dir = "c:\\";
11072  }
11073#endif
11074
11075#endif /* !_WIN32_WCE */
11076
11077  if( home_dir ){
11078    int n = strlen30(home_dir) + 1;
11079    char *z = malloc( n );
11080    if( z ) memcpy(z, home_dir, n);
11081    home_dir = z;
11082  }
11083
11084  return home_dir;
11085}
11086
11087/*
11088** Read input from the file given by sqliterc_override.  Or if that
11089** parameter is NULL, take input from ~/.sqliterc
11090**
11091** Returns the number of errors.
11092*/
11093static void process_sqliterc(
11094  ShellState *p,                  /* Configuration data */
11095  const char *sqliterc_override   /* Name of config file. NULL to use default */
11096){
11097  char *home_dir = NULL;
11098  const char *sqliterc = sqliterc_override;
11099  char *zBuf = 0;
11100  FILE *inSaved = p->in;
11101  int savedLineno = p->lineno;
11102
11103  if (sqliterc == NULL) {
11104    home_dir = find_home_dir(0);
11105    if( home_dir==0 ){
11106      raw_printf(stderr, "-- warning: cannot find home directory;"
11107                      " cannot read ~/.sqliterc\n");
11108      return;
11109    }
11110    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11111    shell_check_oom(zBuf);
11112    sqliterc = zBuf;
11113  }
11114  p->in = fopen(sqliterc,"rb");
11115  if( p->in ){
11116    if( stdin_is_interactive ){
11117      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11118    }
11119    if( process_input(p) && bail_on_error ) exit(1);
11120    fclose(p->in);
11121  }else if( sqliterc_override!=0 ){
11122    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11123    if( bail_on_error ) exit(1);
11124  }
11125  p->in = inSaved;
11126  p->lineno = savedLineno;
11127  sqlite3_free(zBuf);
11128}
11129
11130/*
11131** Show available command line options
11132*/
11133static const char zOptions[] =
11134#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11135  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11136#endif
11137  "   -append              append the database to the end of the file\n"
11138  "   -ascii               set output mode to 'ascii'\n"
11139  "   -bail                stop after hitting an error\n"
11140  "   -batch               force batch I/O\n"
11141  "   -box                 set output mode to 'box'\n"
11142  "   -column              set output mode to 'column'\n"
11143  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11144  "   -csv                 set output mode to 'csv'\n"
11145#if !defined(SQLITE_OMIT_DESERIALIZE)
11146  "   -deserialize         open the database using sqlite3_deserialize()\n"
11147#endif
11148  "   -echo                print commands before execution\n"
11149  "   -init FILENAME       read/process named file\n"
11150  "   -[no]header          turn headers on or off\n"
11151#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11152  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11153#endif
11154  "   -help                show this message\n"
11155  "   -html                set output mode to HTML\n"
11156  "   -interactive         force interactive I/O\n"
11157  "   -json                set output mode to 'json'\n"
11158  "   -line                set output mode to 'line'\n"
11159  "   -list                set output mode to 'list'\n"
11160  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11161  "   -markdown            set output mode to 'markdown'\n"
11162#if !defined(SQLITE_OMIT_DESERIALIZE)
11163  "   -maxsize N           maximum size for a --deserialize database\n"
11164#endif
11165  "   -memtrace            trace all memory allocations and deallocations\n"
11166  "   -mmap N              default mmap size set to N\n"
11167#ifdef SQLITE_ENABLE_MULTIPLEX
11168  "   -multiplex           enable the multiplexor VFS\n"
11169#endif
11170  "   -newline SEP         set output row separator. Default: '\\n'\n"
11171  "   -nofollow            refuse to open symbolic links to database files\n"
11172  "   -nonce STRING        set the safe-mode escape nonce\n"
11173  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11174  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11175  "   -quote               set output mode to 'quote'\n"
11176  "   -readonly            open the database read-only\n"
11177  "   -safe                enable safe-mode\n"
11178  "   -separator SEP       set output column separator. Default: '|'\n"
11179#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11180  "   -sorterref SIZE      sorter references threshold size\n"
11181#endif
11182  "   -stats               print memory stats before each finalize\n"
11183  "   -table               set output mode to 'table'\n"
11184  "   -tabs                set output mode to 'tabs'\n"
11185  "   -version             show SQLite version\n"
11186  "   -vfs NAME            use NAME as the default VFS\n"
11187#ifdef SQLITE_ENABLE_VFSTRACE
11188  "   -vfstrace            enable tracing of all VFS calls\n"
11189#endif
11190#ifdef SQLITE_HAVE_ZLIB
11191  "   -zip                 open the file as a ZIP Archive\n"
11192#endif
11193;
11194static void usage(int showDetail){
11195  utf8_printf(stderr,
11196      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11197      "FILENAME is the name of an SQLite database. A new database is created\n"
11198      "if the file does not previously exist.\n", Argv0);
11199  if( showDetail ){
11200    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11201  }else{
11202    raw_printf(stderr, "Use the -help option for additional information\n");
11203  }
11204  exit(1);
11205}
11206
11207/*
11208** Internal check:  Verify that the SQLite is uninitialized.  Print a
11209** error message if it is initialized.
11210*/
11211static void verify_uninitialized(void){
11212  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11213    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11214                        " initialization.\n");
11215  }
11216}
11217
11218/*
11219** Initialize the state information in data
11220*/
11221static void main_init(ShellState *data) {
11222  memset(data, 0, sizeof(*data));
11223  data->normalMode = data->cMode = data->mode = MODE_List;
11224  data->autoExplain = 1;
11225  data->pAuxDb = &data->aAuxDb[0];
11226  memcpy(data->colSeparator,SEP_Column, 2);
11227  memcpy(data->rowSeparator,SEP_Row, 2);
11228  data->showHeader = 0;
11229  data->shellFlgs = SHFLG_Lookaside;
11230  verify_uninitialized();
11231  sqlite3_config(SQLITE_CONFIG_URI, 1);
11232  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11233  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11234  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11235  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11236}
11237
11238/*
11239** Output text to the console in a font that attracts extra attention.
11240*/
11241#ifdef _WIN32
11242static void printBold(const char *zText){
11243#if !SQLITE_OS_WINRT
11244  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11245  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11246  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11247  SetConsoleTextAttribute(out,
11248         FOREGROUND_RED|FOREGROUND_INTENSITY
11249  );
11250#endif
11251  printf("%s", zText);
11252#if !SQLITE_OS_WINRT
11253  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11254#endif
11255}
11256#else
11257static void printBold(const char *zText){
11258  printf("\033[1m%s\033[0m", zText);
11259}
11260#endif
11261
11262/*
11263** Get the argument to an --option.  Throw an error and die if no argument
11264** is available.
11265*/
11266static char *cmdline_option_value(int argc, char **argv, int i){
11267  if( i==argc ){
11268    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11269            argv[0], argv[argc-1]);
11270    exit(1);
11271  }
11272  return argv[i];
11273}
11274
11275#ifndef SQLITE_SHELL_IS_UTF8
11276#  if (defined(_WIN32) || defined(WIN32)) \
11277   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11278#    define SQLITE_SHELL_IS_UTF8          (0)
11279#  else
11280#    define SQLITE_SHELL_IS_UTF8          (1)
11281#  endif
11282#endif
11283
11284#if SQLITE_SHELL_IS_UTF8
11285int SQLITE_CDECL main(int argc, char **argv){
11286#else
11287int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11288  char **argv;
11289#endif
11290  char *zErrMsg = 0;
11291  ShellState data;
11292  const char *zInitFile = 0;
11293  int i;
11294  int rc = 0;
11295  int warnInmemoryDb = 0;
11296  int readStdin = 1;
11297  int nCmd = 0;
11298  char **azCmd = 0;
11299  const char *zVfs = 0;           /* Value of -vfs command-line option */
11300#if !SQLITE_SHELL_IS_UTF8
11301  char **argvToFree = 0;
11302  int argcToFree = 0;
11303#endif
11304
11305  setBinaryMode(stdin, 0);
11306  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11307  stdin_is_interactive = isatty(0);
11308  stdout_is_console = isatty(1);
11309
11310#if !defined(_WIN32_WCE)
11311  if( getenv("SQLITE_DEBUG_BREAK") ){
11312    if( isatty(0) && isatty(2) ){
11313      fprintf(stderr,
11314          "attach debugger to process %d and press any key to continue.\n",
11315          GETPID());
11316      fgetc(stdin);
11317    }else{
11318#if defined(_WIN32) || defined(WIN32)
11319#if SQLITE_OS_WINRT
11320      __debugbreak();
11321#else
11322      DebugBreak();
11323#endif
11324#elif defined(SIGTRAP)
11325      raise(SIGTRAP);
11326#endif
11327    }
11328  }
11329#endif
11330
11331#if USE_SYSTEM_SQLITE+0!=1
11332  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11333    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11334            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11335    exit(1);
11336  }
11337#endif
11338  main_init(&data);
11339
11340  /* On Windows, we must translate command-line arguments into UTF-8.
11341  ** The SQLite memory allocator subsystem has to be enabled in order to
11342  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11343  ** subsequent sqlite3_config() calls will work.  So copy all results into
11344  ** memory that does not come from the SQLite memory allocator.
11345  */
11346#if !SQLITE_SHELL_IS_UTF8
11347  sqlite3_initialize();
11348  argvToFree = malloc(sizeof(argv[0])*argc*2);
11349  shell_check_oom(argvToFree);
11350  argcToFree = argc;
11351  argv = argvToFree + argc;
11352  for(i=0; i<argc; i++){
11353    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11354    int n;
11355    shell_check_oom(z);
11356    n = (int)strlen(z);
11357    argv[i] = malloc( n+1 );
11358    shell_check_oom(argv[i]);
11359    memcpy(argv[i], z, n+1);
11360    argvToFree[i] = argv[i];
11361    sqlite3_free(z);
11362  }
11363  sqlite3_shutdown();
11364#endif
11365
11366  assert( argc>=1 && argv && argv[0] );
11367  Argv0 = argv[0];
11368
11369  /* Make sure we have a valid signal handler early, before anything
11370  ** else is done.
11371  */
11372#ifdef SIGINT
11373  signal(SIGINT, interrupt_handler);
11374#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11375  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11376#endif
11377
11378#ifdef SQLITE_SHELL_DBNAME_PROC
11379  {
11380    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11381    ** of a C-function that will provide the name of the database file.  Use
11382    ** this compile-time option to embed this shell program in larger
11383    ** applications. */
11384    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11385    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11386    warnInmemoryDb = 0;
11387  }
11388#endif
11389
11390  /* Do an initial pass through the command-line argument to locate
11391  ** the name of the database file, the name of the initialization file,
11392  ** the size of the alternative malloc heap,
11393  ** and the first command to execute.
11394  */
11395  verify_uninitialized();
11396  for(i=1; i<argc; i++){
11397    char *z;
11398    z = argv[i];
11399    if( z[0]!='-' ){
11400      if( data.aAuxDb->zDbFilename==0 ){
11401        data.aAuxDb->zDbFilename = z;
11402      }else{
11403        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11404        ** mean that nothing is read from stdin */
11405        readStdin = 0;
11406        nCmd++;
11407        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11408        shell_check_oom(azCmd);
11409        azCmd[nCmd-1] = z;
11410      }
11411    }
11412    if( z[1]=='-' ) z++;
11413    if( strcmp(z,"-separator")==0
11414     || strcmp(z,"-nullvalue")==0
11415     || strcmp(z,"-newline")==0
11416     || strcmp(z,"-cmd")==0
11417    ){
11418      (void)cmdline_option_value(argc, argv, ++i);
11419    }else if( strcmp(z,"-init")==0 ){
11420      zInitFile = cmdline_option_value(argc, argv, ++i);
11421    }else if( strcmp(z,"-batch")==0 ){
11422      /* Need to check for batch mode here to so we can avoid printing
11423      ** informational messages (like from process_sqliterc) before
11424      ** we do the actual processing of arguments later in a second pass.
11425      */
11426      stdin_is_interactive = 0;
11427    }else if( strcmp(z,"-heap")==0 ){
11428#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11429      const char *zSize;
11430      sqlite3_int64 szHeap;
11431
11432      zSize = cmdline_option_value(argc, argv, ++i);
11433      szHeap = integerValue(zSize);
11434      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11435      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11436#else
11437      (void)cmdline_option_value(argc, argv, ++i);
11438#endif
11439    }else if( strcmp(z,"-pagecache")==0 ){
11440      sqlite3_int64 n, sz;
11441      sz = integerValue(cmdline_option_value(argc,argv,++i));
11442      if( sz>70000 ) sz = 70000;
11443      if( sz<0 ) sz = 0;
11444      n = integerValue(cmdline_option_value(argc,argv,++i));
11445      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11446        n = 0xffffffffffffLL/sz;
11447      }
11448      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11449                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11450      data.shellFlgs |= SHFLG_Pagecache;
11451    }else if( strcmp(z,"-lookaside")==0 ){
11452      int n, sz;
11453      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11454      if( sz<0 ) sz = 0;
11455      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11456      if( n<0 ) n = 0;
11457      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11458      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11459    }else if( strcmp(z,"-threadsafe")==0 ){
11460      int n;
11461      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11462      switch( n ){
11463         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11464         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11465         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11466      }
11467#ifdef SQLITE_ENABLE_VFSTRACE
11468    }else if( strcmp(z,"-vfstrace")==0 ){
11469      extern int vfstrace_register(
11470         const char *zTraceName,
11471         const char *zOldVfsName,
11472         int (*xOut)(const char*,void*),
11473         void *pOutArg,
11474         int makeDefault
11475      );
11476      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11477#endif
11478#ifdef SQLITE_ENABLE_MULTIPLEX
11479    }else if( strcmp(z,"-multiplex")==0 ){
11480      extern int sqlite3_multiple_initialize(const char*,int);
11481      sqlite3_multiplex_initialize(0, 1);
11482#endif
11483    }else if( strcmp(z,"-mmap")==0 ){
11484      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11485      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11486#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11487    }else if( strcmp(z,"-sorterref")==0 ){
11488      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11489      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11490#endif
11491    }else if( strcmp(z,"-vfs")==0 ){
11492      zVfs = cmdline_option_value(argc, argv, ++i);
11493#ifdef SQLITE_HAVE_ZLIB
11494    }else if( strcmp(z,"-zip")==0 ){
11495      data.openMode = SHELL_OPEN_ZIPFILE;
11496#endif
11497    }else if( strcmp(z,"-append")==0 ){
11498      data.openMode = SHELL_OPEN_APPENDVFS;
11499#ifndef SQLITE_OMIT_DESERIALIZE
11500    }else if( strcmp(z,"-deserialize")==0 ){
11501      data.openMode = SHELL_OPEN_DESERIALIZE;
11502    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11503      data.szMax = integerValue(argv[++i]);
11504#endif
11505    }else if( strcmp(z,"-readonly")==0 ){
11506      data.openMode = SHELL_OPEN_READONLY;
11507    }else if( strcmp(z,"-nofollow")==0 ){
11508      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11509#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11510    }else if( strncmp(z, "-A",2)==0 ){
11511      /* All remaining command-line arguments are passed to the ".archive"
11512      ** command, so ignore them */
11513      break;
11514#endif
11515    }else if( strcmp(z, "-memtrace")==0 ){
11516      sqlite3MemTraceActivate(stderr);
11517    }else if( strcmp(z,"-bail")==0 ){
11518      bail_on_error = 1;
11519    }else if( strcmp(z,"-nonce")==0 ){
11520      free(data.zNonce);
11521      data.zNonce = strdup(argv[++i]);
11522    }else if( strcmp(z,"-safe")==0 ){
11523      /* no-op - catch this on the second pass */
11524    }
11525  }
11526  verify_uninitialized();
11527
11528
11529#ifdef SQLITE_SHELL_INIT_PROC
11530  {
11531    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11532    ** of a C-function that will perform initialization actions on SQLite that
11533    ** occur just before or after sqlite3_initialize(). Use this compile-time
11534    ** option to embed this shell program in larger applications. */
11535    extern void SQLITE_SHELL_INIT_PROC(void);
11536    SQLITE_SHELL_INIT_PROC();
11537  }
11538#else
11539  /* All the sqlite3_config() calls have now been made. So it is safe
11540  ** to call sqlite3_initialize() and process any command line -vfs option. */
11541  sqlite3_initialize();
11542#endif
11543
11544  if( zVfs ){
11545    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11546    if( pVfs ){
11547      sqlite3_vfs_register(pVfs, 1);
11548    }else{
11549      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11550      exit(1);
11551    }
11552  }
11553
11554  if( data.pAuxDb->zDbFilename==0 ){
11555#ifndef SQLITE_OMIT_MEMORYDB
11556    data.pAuxDb->zDbFilename = ":memory:";
11557    warnInmemoryDb = argc==1;
11558#else
11559    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11560    return 1;
11561#endif
11562  }
11563  data.out = stdout;
11564  sqlite3_appendvfs_init(0,0,0);
11565
11566  /* Go ahead and open the database file if it already exists.  If the
11567  ** file does not exist, delay opening it.  This prevents empty database
11568  ** files from being created if a user mistypes the database name argument
11569  ** to the sqlite command-line tool.
11570  */
11571  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11572    open_db(&data, 0);
11573  }
11574
11575  /* Process the initialization file if there is one.  If no -init option
11576  ** is given on the command line, look for a file named ~/.sqliterc and
11577  ** try to process it.
11578  */
11579  process_sqliterc(&data,zInitFile);
11580
11581  /* Make a second pass through the command-line argument and set
11582  ** options.  This second pass is delayed until after the initialization
11583  ** file is processed so that the command-line arguments will override
11584  ** settings in the initialization file.
11585  */
11586  for(i=1; i<argc; i++){
11587    char *z = argv[i];
11588    if( z[0]!='-' ) continue;
11589    if( z[1]=='-' ){ z++; }
11590    if( strcmp(z,"-init")==0 ){
11591      i++;
11592    }else if( strcmp(z,"-html")==0 ){
11593      data.mode = MODE_Html;
11594    }else if( strcmp(z,"-list")==0 ){
11595      data.mode = MODE_List;
11596    }else if( strcmp(z,"-quote")==0 ){
11597      data.mode = MODE_Quote;
11598      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11599      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11600    }else if( strcmp(z,"-line")==0 ){
11601      data.mode = MODE_Line;
11602    }else if( strcmp(z,"-column")==0 ){
11603      data.mode = MODE_Column;
11604    }else if( strcmp(z,"-json")==0 ){
11605      data.mode = MODE_Json;
11606    }else if( strcmp(z,"-markdown")==0 ){
11607      data.mode = MODE_Markdown;
11608    }else if( strcmp(z,"-table")==0 ){
11609      data.mode = MODE_Table;
11610    }else if( strcmp(z,"-box")==0 ){
11611      data.mode = MODE_Box;
11612    }else if( strcmp(z,"-csv")==0 ){
11613      data.mode = MODE_Csv;
11614      memcpy(data.colSeparator,",",2);
11615#ifdef SQLITE_HAVE_ZLIB
11616    }else if( strcmp(z,"-zip")==0 ){
11617      data.openMode = SHELL_OPEN_ZIPFILE;
11618#endif
11619    }else if( strcmp(z,"-append")==0 ){
11620      data.openMode = SHELL_OPEN_APPENDVFS;
11621#ifndef SQLITE_OMIT_DESERIALIZE
11622    }else if( strcmp(z,"-deserialize")==0 ){
11623      data.openMode = SHELL_OPEN_DESERIALIZE;
11624    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11625      data.szMax = integerValue(argv[++i]);
11626#endif
11627    }else if( strcmp(z,"-readonly")==0 ){
11628      data.openMode = SHELL_OPEN_READONLY;
11629    }else if( strcmp(z,"-nofollow")==0 ){
11630      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11631    }else if( strcmp(z,"-ascii")==0 ){
11632      data.mode = MODE_Ascii;
11633      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11634      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11635    }else if( strcmp(z,"-tabs")==0 ){
11636      data.mode = MODE_List;
11637      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11638      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11639    }else if( strcmp(z,"-separator")==0 ){
11640      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11641                       "%s",cmdline_option_value(argc,argv,++i));
11642    }else if( strcmp(z,"-newline")==0 ){
11643      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11644                       "%s",cmdline_option_value(argc,argv,++i));
11645    }else if( strcmp(z,"-nullvalue")==0 ){
11646      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11647                       "%s",cmdline_option_value(argc,argv,++i));
11648    }else if( strcmp(z,"-header")==0 ){
11649      data.showHeader = 1;
11650      ShellSetFlag(&data, SHFLG_HeaderSet);
11651     }else if( strcmp(z,"-noheader")==0 ){
11652      data.showHeader = 0;
11653      ShellSetFlag(&data, SHFLG_HeaderSet);
11654    }else if( strcmp(z,"-echo")==0 ){
11655      ShellSetFlag(&data, SHFLG_Echo);
11656    }else if( strcmp(z,"-eqp")==0 ){
11657      data.autoEQP = AUTOEQP_on;
11658    }else if( strcmp(z,"-eqpfull")==0 ){
11659      data.autoEQP = AUTOEQP_full;
11660    }else if( strcmp(z,"-stats")==0 ){
11661      data.statsOn = 1;
11662    }else if( strcmp(z,"-scanstats")==0 ){
11663      data.scanstatsOn = 1;
11664    }else if( strcmp(z,"-backslash")==0 ){
11665      /* Undocumented command-line option: -backslash
11666      ** Causes C-style backslash escapes to be evaluated in SQL statements
11667      ** prior to sending the SQL into SQLite.  Useful for injecting
11668      ** crazy bytes in the middle of SQL statements for testing and debugging.
11669      */
11670      ShellSetFlag(&data, SHFLG_Backslash);
11671    }else if( strcmp(z,"-bail")==0 ){
11672      /* No-op.  The bail_on_error flag should already be set. */
11673    }else if( strcmp(z,"-version")==0 ){
11674      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11675      return 0;
11676    }else if( strcmp(z,"-interactive")==0 ){
11677      stdin_is_interactive = 1;
11678    }else if( strcmp(z,"-batch")==0 ){
11679      stdin_is_interactive = 0;
11680    }else if( strcmp(z,"-heap")==0 ){
11681      i++;
11682    }else if( strcmp(z,"-pagecache")==0 ){
11683      i+=2;
11684    }else if( strcmp(z,"-lookaside")==0 ){
11685      i+=2;
11686    }else if( strcmp(z,"-threadsafe")==0 ){
11687      i+=2;
11688    }else if( strcmp(z,"-nonce")==0 ){
11689      i += 2;
11690    }else if( strcmp(z,"-mmap")==0 ){
11691      i++;
11692    }else if( strcmp(z,"-memtrace")==0 ){
11693      i++;
11694#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11695    }else if( strcmp(z,"-sorterref")==0 ){
11696      i++;
11697#endif
11698    }else if( strcmp(z,"-vfs")==0 ){
11699      i++;
11700#ifdef SQLITE_ENABLE_VFSTRACE
11701    }else if( strcmp(z,"-vfstrace")==0 ){
11702      i++;
11703#endif
11704#ifdef SQLITE_ENABLE_MULTIPLEX
11705    }else if( strcmp(z,"-multiplex")==0 ){
11706      i++;
11707#endif
11708    }else if( strcmp(z,"-help")==0 ){
11709      usage(1);
11710    }else if( strcmp(z,"-cmd")==0 ){
11711      /* Run commands that follow -cmd first and separately from commands
11712      ** that simply appear on the command-line.  This seems goofy.  It would
11713      ** be better if all commands ran in the order that they appear.  But
11714      ** we retain the goofy behavior for historical compatibility. */
11715      if( i==argc-1 ) break;
11716      z = cmdline_option_value(argc,argv,++i);
11717      if( z[0]=='.' ){
11718        rc = do_meta_command(z, &data);
11719        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11720      }else{
11721        open_db(&data, 0);
11722        rc = shell_exec(&data, z, &zErrMsg);
11723        if( zErrMsg!=0 ){
11724          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11725          if( bail_on_error ) return rc!=0 ? rc : 1;
11726        }else if( rc!=0 ){
11727          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11728          if( bail_on_error ) return rc;
11729        }
11730      }
11731#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11732    }else if( strncmp(z, "-A", 2)==0 ){
11733      if( nCmd>0 ){
11734        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11735                            " with \"%s\"\n", z);
11736        return 1;
11737      }
11738      open_db(&data, OPEN_DB_ZIPFILE);
11739      if( z[2] ){
11740        argv[i] = &z[2];
11741        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11742      }else{
11743        arDotCommand(&data, 1, argv+i, argc-i);
11744      }
11745      readStdin = 0;
11746      break;
11747#endif
11748    }else if( strcmp(z,"-safe")==0 ){
11749      data.bSafeMode = data.bSafeModePersist = 1;
11750    }else{
11751      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11752      raw_printf(stderr,"Use -help for a list of options.\n");
11753      return 1;
11754    }
11755    data.cMode = data.mode;
11756  }
11757
11758  if( !readStdin ){
11759    /* Run all arguments that do not begin with '-' as if they were separate
11760    ** command-line inputs, except for the argToSkip argument which contains
11761    ** the database filename.
11762    */
11763    for(i=0; i<nCmd; i++){
11764      if( azCmd[i][0]=='.' ){
11765        rc = do_meta_command(azCmd[i], &data);
11766        if( rc ){
11767          free(azCmd);
11768          return rc==2 ? 0 : rc;
11769        }
11770      }else{
11771        open_db(&data, 0);
11772        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11773        if( zErrMsg || rc ){
11774          if( zErrMsg!=0 ){
11775            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11776          }else{
11777            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11778          }
11779          sqlite3_free(zErrMsg);
11780          free(azCmd);
11781          return rc!=0 ? rc : 1;
11782        }
11783      }
11784    }
11785  }else{
11786    /* Run commands received from standard input
11787    */
11788    if( stdin_is_interactive ){
11789      char *zHome;
11790      char *zHistory;
11791      int nHistory;
11792      printf(
11793        "SQLite version %s %.19s\n" /*extra-version-info*/
11794        "Enter \".help\" for usage hints.\n",
11795        sqlite3_libversion(), sqlite3_sourceid()
11796      );
11797      if( warnInmemoryDb ){
11798        printf("Connected to a ");
11799        printBold("transient in-memory database");
11800        printf(".\nUse \".open FILENAME\" to reopen on a "
11801               "persistent database.\n");
11802      }
11803      zHistory = getenv("SQLITE_HISTORY");
11804      if( zHistory ){
11805        zHistory = strdup(zHistory);
11806      }else if( (zHome = find_home_dir(0))!=0 ){
11807        nHistory = strlen30(zHome) + 20;
11808        if( (zHistory = malloc(nHistory))!=0 ){
11809          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11810        }
11811      }
11812      if( zHistory ){ shell_read_history(zHistory); }
11813#if HAVE_READLINE || HAVE_EDITLINE
11814      rl_attempted_completion_function = readline_completion;
11815#elif HAVE_LINENOISE
11816      linenoiseSetCompletionCallback(linenoise_completion);
11817#endif
11818      data.in = 0;
11819      rc = process_input(&data);
11820      if( zHistory ){
11821        shell_stifle_history(2000);
11822        shell_write_history(zHistory);
11823        free(zHistory);
11824      }
11825    }else{
11826      data.in = stdin;
11827      rc = process_input(&data);
11828    }
11829  }
11830  free(azCmd);
11831  set_table_name(&data, 0);
11832  if( data.db ){
11833    session_close_all(&data, -1);
11834    close_db(data.db);
11835  }
11836  for(i=0; i<ArraySize(data.aAuxDb); i++){
11837    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
11838    if( data.aAuxDb[i].db ){
11839      session_close_all(&data, i);
11840      close_db(data.aAuxDb[i].db);
11841    }
11842  }
11843  find_home_dir(1);
11844  output_reset(&data);
11845  data.doXdgOpen = 0;
11846  clearTempFile(&data);
11847#if !SQLITE_SHELL_IS_UTF8
11848  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11849  free(argvToFree);
11850#endif
11851  free(data.colWidth);
11852  free(data.zNonce);
11853  /* Clear the global data structure so that valgrind will detect memory
11854  ** leaks */
11855  memset(&data, 0, sizeof(data));
11856  return rc;
11857}
11858