xref: /sqlite-3.40.0/src/shell.c.in (revision 1182e2ac)
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#ifdef SQLITE_DEBUG
431/*
432** Out-of-memory simulator variables
433*/
434static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
435static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
436static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
437#endif /* SQLITE_DEBUG */
438
439/*
440** This is the name of our program. It is set in main(), used
441** in a number of other places, mostly for error messages.
442*/
443static char *Argv0;
444
445/*
446** Prompt strings. Initialized in main. Settable with
447**   .prompt main continue
448*/
449static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
450static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
451
452/*
453** Render output like fprintf().  Except, if the output is going to the
454** console and if this is running on a Windows machine, translate the
455** output from UTF-8 into MBCS.
456*/
457#if defined(_WIN32) || defined(WIN32)
458void utf8_printf(FILE *out, const char *zFormat, ...){
459  va_list ap;
460  va_start(ap, zFormat);
461  if( stdout_is_console && (out==stdout || out==stderr) ){
462    char *z1 = sqlite3_vmprintf(zFormat, ap);
463    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
464    sqlite3_free(z1);
465    fputs(z2, out);
466    sqlite3_free(z2);
467  }else{
468    vfprintf(out, zFormat, ap);
469  }
470  va_end(ap);
471}
472#elif !defined(utf8_printf)
473# define utf8_printf fprintf
474#endif
475
476/*
477** Render output like fprintf().  This should not be used on anything that
478** includes string formatting (e.g. "%s").
479*/
480#if !defined(raw_printf)
481# define raw_printf fprintf
482#endif
483
484/* Indicate out-of-memory and exit. */
485static void shell_out_of_memory(void){
486  raw_printf(stderr,"Error: out of memory\n");
487  exit(1);
488}
489
490#ifdef SQLITE_DEBUG
491/* This routine is called when a simulated OOM occurs.  It is broken
492** out as a separate routine to make it easy to set a breakpoint on
493** the OOM
494*/
495void shellOomFault(void){
496  if( oomRepeat>0 ){
497    oomRepeat--;
498  }else{
499    oomCounter--;
500  }
501}
502#endif /* SQLITE_DEBUG */
503
504#ifdef SQLITE_DEBUG
505/* This routine is a replacement malloc() that is used to simulate
506** Out-Of-Memory (OOM) errors for testing purposes.
507*/
508static void *oomMalloc(int nByte){
509  if( oomCounter ){
510    if( oomCounter==1 ){
511      shellOomFault();
512      return 0;
513    }else{
514      oomCounter--;
515    }
516  }
517  return defaultMalloc(nByte);
518}
519#endif /* SQLITE_DEBUG */
520
521#ifdef SQLITE_DEBUG
522/* Register the OOM simulator.  This must occur before any memory
523** allocations */
524static void registerOomSimulator(void){
525  sqlite3_mem_methods mem;
526  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
527  defaultMalloc = mem.xMalloc;
528  mem.xMalloc = oomMalloc;
529  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
530}
531#endif
532
533/*
534** Write I/O traces to the following stream.
535*/
536#ifdef SQLITE_ENABLE_IOTRACE
537static FILE *iotrace = 0;
538#endif
539
540/*
541** This routine works like printf in that its first argument is a
542** format string and subsequent arguments are values to be substituted
543** in place of % fields.  The result of formatting this string
544** is written to iotrace.
545*/
546#ifdef SQLITE_ENABLE_IOTRACE
547static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
548  va_list ap;
549  char *z;
550  if( iotrace==0 ) return;
551  va_start(ap, zFormat);
552  z = sqlite3_vmprintf(zFormat, ap);
553  va_end(ap);
554  utf8_printf(iotrace, "%s", z);
555  sqlite3_free(z);
556}
557#endif
558
559/*
560** Output string zUtf to stream pOut as w characters.  If w is negative,
561** then right-justify the text.  W is the width in UTF-8 characters, not
562** in bytes.  This is different from the %*.*s specification in printf
563** since with %*.*s the width is measured in bytes, not characters.
564*/
565static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
566  int i;
567  int n;
568  int aw = w<0 ? -w : w;
569  for(i=n=0; zUtf[i]; i++){
570    if( (zUtf[i]&0xc0)!=0x80 ){
571      n++;
572      if( n==aw ){
573        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
574        break;
575      }
576    }
577  }
578  if( n>=aw ){
579    utf8_printf(pOut, "%.*s", i, zUtf);
580  }else if( w<0 ){
581    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
582  }else{
583    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
584  }
585}
586
587
588/*
589** Determines if a string is a number of not.
590*/
591static int isNumber(const char *z, int *realnum){
592  if( *z=='-' || *z=='+' ) z++;
593  if( !IsDigit(*z) ){
594    return 0;
595  }
596  z++;
597  if( realnum ) *realnum = 0;
598  while( IsDigit(*z) ){ z++; }
599  if( *z=='.' ){
600    z++;
601    if( !IsDigit(*z) ) return 0;
602    while( IsDigit(*z) ){ z++; }
603    if( realnum ) *realnum = 1;
604  }
605  if( *z=='e' || *z=='E' ){
606    z++;
607    if( *z=='+' || *z=='-' ) z++;
608    if( !IsDigit(*z) ) return 0;
609    while( IsDigit(*z) ){ z++; }
610    if( realnum ) *realnum = 1;
611  }
612  return *z==0;
613}
614
615/*
616** Compute a string length that is limited to what can be stored in
617** lower 30 bits of a 32-bit signed integer.
618*/
619static int strlen30(const char *z){
620  const char *z2 = z;
621  while( *z2 ){ z2++; }
622  return 0x3fffffff & (int)(z2 - z);
623}
624
625/*
626** Return the length of a string in characters.  Multibyte UTF8 characters
627** count as a single character.
628*/
629static int strlenChar(const char *z){
630  int n = 0;
631  while( *z ){
632    if( (0xc0&*(z++))!=0x80 ) n++;
633  }
634  return n;
635}
636
637/*
638** Return open FILE * if zFile exists, can be opened for read
639** and is an ordinary file or a character stream source.
640** Otherwise return 0.
641*/
642static FILE * openChrSource(const char *zFile){
643#ifdef _WIN32
644  struct _stat x = {0};
645# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
646  /* On Windows, open first, then check the stream nature. This order
647  ** is necessary because _stat() and sibs, when checking a named pipe,
648  ** effectively break the pipe as its supplier sees it. */
649  FILE *rv = fopen(zFile, "rb");
650  if( rv==0 ) return 0;
651  if( _fstat(_fileno(rv), &x) != 0
652      || !STAT_CHR_SRC(x.st_mode)){
653    fclose(rv);
654    rv = 0;
655  }
656  return rv;
657#else
658  struct stat x = {0};
659  int rc = stat(zFile, &x);
660# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
661  if( rc!=0 ) return 0;
662  if( STAT_CHR_SRC(x.st_mode) ){
663    return fopen(zFile, "rb");
664  }else{
665    return 0;
666  }
667#endif
668#undef STAT_CHR_SRC
669}
670
671/*
672** This routine reads a line of text from FILE in, stores
673** the text in memory obtained from malloc() and returns a pointer
674** to the text.  NULL is returned at end of file, or if malloc()
675** fails.
676**
677** If zLine is not NULL then it is a malloced buffer returned from
678** a previous call to this routine that may be reused.
679*/
680static char *local_getline(char *zLine, FILE *in){
681  int nLine = zLine==0 ? 0 : 100;
682  int n = 0;
683
684  while( 1 ){
685    if( n+100>nLine ){
686      nLine = nLine*2 + 100;
687      zLine = realloc(zLine, nLine);
688      if( zLine==0 ) shell_out_of_memory();
689    }
690    if( fgets(&zLine[n], nLine - n, in)==0 ){
691      if( n==0 ){
692        free(zLine);
693        return 0;
694      }
695      zLine[n] = 0;
696      break;
697    }
698    while( zLine[n] ) n++;
699    if( n>0 && zLine[n-1]=='\n' ){
700      n--;
701      if( n>0 && zLine[n-1]=='\r' ) n--;
702      zLine[n] = 0;
703      break;
704    }
705  }
706#if defined(_WIN32) || defined(WIN32)
707  /* For interactive input on Windows systems, translate the
708  ** multi-byte characterset characters into UTF-8. */
709  if( stdin_is_interactive && in==stdin ){
710    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
711    if( zTrans ){
712      int nTrans = strlen30(zTrans)+1;
713      if( nTrans>nLine ){
714        zLine = realloc(zLine, nTrans);
715        if( zLine==0 ) shell_out_of_memory();
716      }
717      memcpy(zLine, zTrans, nTrans);
718      sqlite3_free(zTrans);
719    }
720  }
721#endif /* defined(_WIN32) || defined(WIN32) */
722  return zLine;
723}
724
725/*
726** Retrieve a single line of input text.
727**
728** If in==0 then read from standard input and prompt before each line.
729** If isContinuation is true, then a continuation prompt is appropriate.
730** If isContinuation is zero, then the main prompt should be used.
731**
732** If zPrior is not NULL then it is a buffer from a prior call to this
733** routine that can be reused.
734**
735** The result is stored in space obtained from malloc() and must either
736** be freed by the caller or else passed back into this routine via the
737** zPrior argument for reuse.
738*/
739static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
740  char *zPrompt;
741  char *zResult;
742  if( in!=0 ){
743    zResult = local_getline(zPrior, in);
744  }else{
745    zPrompt = isContinuation ? continuePrompt : mainPrompt;
746#if SHELL_USE_LOCAL_GETLINE
747    printf("%s", zPrompt);
748    fflush(stdout);
749    zResult = local_getline(zPrior, stdin);
750#else
751    free(zPrior);
752    zResult = shell_readline(zPrompt);
753    if( zResult && *zResult ) shell_add_history(zResult);
754#endif
755  }
756  return zResult;
757}
758
759
760/*
761** Return the value of a hexadecimal digit.  Return -1 if the input
762** is not a hex digit.
763*/
764static int hexDigitValue(char c){
765  if( c>='0' && c<='9' ) return c - '0';
766  if( c>='a' && c<='f' ) return c - 'a' + 10;
767  if( c>='A' && c<='F' ) return c - 'A' + 10;
768  return -1;
769}
770
771/*
772** Interpret zArg as an integer value, possibly with suffixes.
773*/
774static sqlite3_int64 integerValue(const char *zArg){
775  sqlite3_int64 v = 0;
776  static const struct { char *zSuffix; int iMult; } aMult[] = {
777    { "KiB", 1024 },
778    { "MiB", 1024*1024 },
779    { "GiB", 1024*1024*1024 },
780    { "KB",  1000 },
781    { "MB",  1000000 },
782    { "GB",  1000000000 },
783    { "K",   1000 },
784    { "M",   1000000 },
785    { "G",   1000000000 },
786  };
787  int i;
788  int isNeg = 0;
789  if( zArg[0]=='-' ){
790    isNeg = 1;
791    zArg++;
792  }else if( zArg[0]=='+' ){
793    zArg++;
794  }
795  if( zArg[0]=='0' && zArg[1]=='x' ){
796    int x;
797    zArg += 2;
798    while( (x = hexDigitValue(zArg[0]))>=0 ){
799      v = (v<<4) + x;
800      zArg++;
801    }
802  }else{
803    while( IsDigit(zArg[0]) ){
804      v = v*10 + zArg[0] - '0';
805      zArg++;
806    }
807  }
808  for(i=0; i<ArraySize(aMult); i++){
809    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
810      v *= aMult[i].iMult;
811      break;
812    }
813  }
814  return isNeg? -v : v;
815}
816
817/*
818** A variable length string to which one can append text.
819*/
820typedef struct ShellText ShellText;
821struct ShellText {
822  char *z;
823  int n;
824  int nAlloc;
825};
826
827/*
828** Initialize and destroy a ShellText object
829*/
830static void initText(ShellText *p){
831  memset(p, 0, sizeof(*p));
832}
833static void freeText(ShellText *p){
834  free(p->z);
835  initText(p);
836}
837
838/* zIn is either a pointer to a NULL-terminated string in memory obtained
839** from malloc(), or a NULL pointer. The string pointed to by zAppend is
840** added to zIn, and the result returned in memory obtained from malloc().
841** zIn, if it was not NULL, is freed.
842**
843** If the third argument, quote, is not '\0', then it is used as a
844** quote character for zAppend.
845*/
846static void appendText(ShellText *p, char const *zAppend, char quote){
847  int len;
848  int i;
849  int nAppend = strlen30(zAppend);
850
851  len = nAppend+p->n+1;
852  if( quote ){
853    len += 2;
854    for(i=0; i<nAppend; i++){
855      if( zAppend[i]==quote ) len++;
856    }
857  }
858
859  if( p->z==0 || p->n+len>=p->nAlloc ){
860    p->nAlloc = p->nAlloc*2 + len + 20;
861    p->z = realloc(p->z, p->nAlloc);
862    if( p->z==0 ) shell_out_of_memory();
863  }
864
865  if( quote ){
866    char *zCsr = p->z+p->n;
867    *zCsr++ = quote;
868    for(i=0; i<nAppend; i++){
869      *zCsr++ = zAppend[i];
870      if( zAppend[i]==quote ) *zCsr++ = quote;
871    }
872    *zCsr++ = quote;
873    p->n = (int)(zCsr - p->z);
874    *zCsr = '\0';
875  }else{
876    memcpy(p->z+p->n, zAppend, nAppend);
877    p->n += nAppend;
878    p->z[p->n] = '\0';
879  }
880}
881
882/*
883** Attempt to determine if identifier zName needs to be quoted, either
884** because it contains non-alphanumeric characters, or because it is an
885** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
886** that quoting is required.
887**
888** Return '"' if quoting is required.  Return 0 if no quoting is required.
889*/
890static char quoteChar(const char *zName){
891  int i;
892  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
893  for(i=0; zName[i]; i++){
894    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
895  }
896  return sqlite3_keyword_check(zName, i) ? '"' : 0;
897}
898
899/*
900** Construct a fake object name and column list to describe the structure
901** of the view, virtual table, or table valued function zSchema.zName.
902*/
903static char *shellFakeSchema(
904  sqlite3 *db,            /* The database connection containing the vtab */
905  const char *zSchema,    /* Schema of the database holding the vtab */
906  const char *zName       /* The name of the virtual table */
907){
908  sqlite3_stmt *pStmt = 0;
909  char *zSql;
910  ShellText s;
911  char cQuote;
912  char *zDiv = "(";
913  int nRow = 0;
914
915  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
916                         zSchema ? zSchema : "main", zName);
917  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
918  sqlite3_free(zSql);
919  initText(&s);
920  if( zSchema ){
921    cQuote = quoteChar(zSchema);
922    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
923    appendText(&s, zSchema, cQuote);
924    appendText(&s, ".", 0);
925  }
926  cQuote = quoteChar(zName);
927  appendText(&s, zName, cQuote);
928  while( sqlite3_step(pStmt)==SQLITE_ROW ){
929    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
930    nRow++;
931    appendText(&s, zDiv, 0);
932    zDiv = ",";
933    cQuote = quoteChar(zCol);
934    appendText(&s, zCol, cQuote);
935  }
936  appendText(&s, ")", 0);
937  sqlite3_finalize(pStmt);
938  if( nRow==0 ){
939    freeText(&s);
940    s.z = 0;
941  }
942  return s.z;
943}
944
945/*
946** SQL function:  shell_module_schema(X)
947**
948** Return a fake schema for the table-valued function or eponymous virtual
949** table X.
950*/
951static void shellModuleSchema(
952  sqlite3_context *pCtx,
953  int nVal,
954  sqlite3_value **apVal
955){
956  const char *zName = (const char*)sqlite3_value_text(apVal[0]);
957  char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
958  UNUSED_PARAMETER(nVal);
959  if( zFake ){
960    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
961                        -1, sqlite3_free);
962    free(zFake);
963  }
964}
965
966/*
967** SQL function:  shell_add_schema(S,X)
968**
969** Add the schema name X to the CREATE statement in S and return the result.
970** Examples:
971**
972**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
973**
974** Also works on
975**
976**    CREATE INDEX
977**    CREATE UNIQUE INDEX
978**    CREATE VIEW
979**    CREATE TRIGGER
980**    CREATE VIRTUAL TABLE
981**
982** This UDF is used by the .schema command to insert the schema name of
983** attached databases into the middle of the sqlite_schema.sql field.
984*/
985static void shellAddSchemaName(
986  sqlite3_context *pCtx,
987  int nVal,
988  sqlite3_value **apVal
989){
990  static const char *aPrefix[] = {
991     "TABLE",
992     "INDEX",
993     "UNIQUE INDEX",
994     "VIEW",
995     "TRIGGER",
996     "VIRTUAL TABLE"
997  };
998  int i = 0;
999  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1000  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1001  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1002  sqlite3 *db = sqlite3_context_db_handle(pCtx);
1003  UNUSED_PARAMETER(nVal);
1004  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
1005    for(i=0; i<ArraySize(aPrefix); i++){
1006      int n = strlen30(aPrefix[i]);
1007      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1008        char *z = 0;
1009        char *zFake = 0;
1010        if( zSchema ){
1011          char cQuote = quoteChar(zSchema);
1012          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1013            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1014          }else{
1015            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1016          }
1017        }
1018        if( zName
1019         && aPrefix[i][0]=='V'
1020         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1021        ){
1022          if( z==0 ){
1023            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1024          }else{
1025            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1026          }
1027          free(zFake);
1028        }
1029        if( z ){
1030          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1031          return;
1032        }
1033      }
1034    }
1035  }
1036  sqlite3_result_value(pCtx, apVal[0]);
1037}
1038
1039/*
1040** The source code for several run-time loadable extensions is inserted
1041** below by the ../tool/mkshellc.tcl script.  Before processing that included
1042** code, we need to override some macros to make the included program code
1043** work here in the middle of this regular program.
1044*/
1045#define SQLITE_EXTENSION_INIT1
1046#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1047
1048#if defined(_WIN32) && defined(_MSC_VER)
1049INCLUDE test_windirent.h
1050INCLUDE test_windirent.c
1051#define dirent DIRENT
1052#endif
1053INCLUDE ../ext/misc/shathree.c
1054INCLUDE ../ext/misc/fileio.c
1055INCLUDE ../ext/misc/completion.c
1056INCLUDE ../ext/misc/appendvfs.c
1057INCLUDE ../ext/misc/memtrace.c
1058INCLUDE ../ext/misc/uint.c
1059INCLUDE ../ext/misc/decimal.c
1060INCLUDE ../ext/misc/ieee754.c
1061INCLUDE ../ext/misc/series.c
1062INCLUDE ../ext/misc/regexp.c
1063#ifdef SQLITE_HAVE_ZLIB
1064INCLUDE ../ext/misc/zipfile.c
1065INCLUDE ../ext/misc/sqlar.c
1066#endif
1067INCLUDE ../ext/expert/sqlite3expert.h
1068INCLUDE ../ext/expert/sqlite3expert.c
1069
1070#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1071INCLUDE ../ext/misc/dbdata.c
1072#endif
1073
1074#if defined(SQLITE_ENABLE_SESSION)
1075/*
1076** State information for a single open session
1077*/
1078typedef struct OpenSession OpenSession;
1079struct OpenSession {
1080  char *zName;             /* Symbolic name for this session */
1081  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1082  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1083  sqlite3_session *p;      /* The open session */
1084};
1085#endif
1086
1087typedef struct ExpertInfo ExpertInfo;
1088struct ExpertInfo {
1089  sqlite3expert *pExpert;
1090  int bVerbose;
1091};
1092
1093/* A single line in the EQP output */
1094typedef struct EQPGraphRow EQPGraphRow;
1095struct EQPGraphRow {
1096  int iEqpId;           /* ID for this row */
1097  int iParentId;        /* ID of the parent row */
1098  EQPGraphRow *pNext;   /* Next row in sequence */
1099  char zText[1];        /* Text to display for this row */
1100};
1101
1102/* All EQP output is collected into an instance of the following */
1103typedef struct EQPGraph EQPGraph;
1104struct EQPGraph {
1105  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1106  EQPGraphRow *pLast;   /* Last element of the pRow list */
1107  char zPrefix[100];    /* Graph prefix */
1108};
1109
1110/*
1111** State information about the database connection is contained in an
1112** instance of the following structure.
1113*/
1114typedef struct ShellState ShellState;
1115struct ShellState {
1116  sqlite3 *db;           /* The database */
1117  u8 autoExplain;        /* Automatically turn on .explain mode */
1118  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1119  u8 autoEQPtest;        /* autoEQP is in test mode */
1120  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1121  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1122  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1123  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1124  u8 nEqpLevel;          /* Depth of the EQP output graph */
1125  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1126  u8 bSafeMode;          /* True to prohibit unsafe operations */
1127  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1128  unsigned statsOn;      /* True to display memory stats before each finalize */
1129  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1130  int outCount;          /* Revert to stdout when reaching zero */
1131  int cnt;               /* Number of records displayed so far */
1132  int lineno;            /* Line number of last line read from in */
1133  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1134  FILE *in;              /* Read commands from this stream */
1135  FILE *out;             /* Write results here */
1136  FILE *traceOut;        /* Output for sqlite3_trace() */
1137  int nErr;              /* Number of errors seen */
1138  int mode;              /* An output mode setting */
1139  int modePrior;         /* Saved mode */
1140  int cMode;             /* temporary output mode for the current query */
1141  int normalMode;        /* Output mode before ".explain on" */
1142  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1143  int showHeader;        /* True to show column names in List or Column mode */
1144  int nCheck;            /* Number of ".check" commands run */
1145  unsigned nProgress;    /* Number of progress callbacks encountered */
1146  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1147  unsigned flgProgress;  /* Flags for the progress callback */
1148  unsigned shellFlgs;    /* Various flags */
1149  unsigned priorShFlgs;  /* Saved copy of flags */
1150  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1151  char *zDestTable;      /* Name of destination table when MODE_Insert */
1152  char *zTempFile;       /* Temporary file that might need deleting */
1153  char zTestcase[30];    /* Name of current test case */
1154  char colSeparator[20]; /* Column separator character for several modes */
1155  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1156  char colSepPrior[20];  /* Saved column separator */
1157  char rowSepPrior[20];  /* Saved row separator */
1158  int *colWidth;         /* Requested width of each column in columnar modes */
1159  int *actualWidth;      /* Actual width of each column */
1160  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1161  char nullValue[20];    /* The text to print when a NULL comes back from
1162                         ** the database */
1163  char outfile[FILENAME_MAX]; /* Filename for *out */
1164  sqlite3_stmt *pStmt;   /* Current statement if any. */
1165  FILE *pLog;            /* Write log output here */
1166  struct AuxDb {         /* Storage space for auxiliary database connections */
1167    sqlite3 *db;               /* Connection pointer */
1168    const char *zDbFilename;   /* Filename used to open the connection */
1169    char *zFreeOnClose;        /* Free this memory allocation on close */
1170#if defined(SQLITE_ENABLE_SESSION)
1171    int nSession;              /* Number of active sessions */
1172    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1173#endif
1174  } aAuxDb[5],           /* Array of all database connections */
1175    *pAuxDb;             /* Currently active database connection */
1176  int *aiIndent;         /* Array of indents used in MODE_Explain */
1177  int nIndent;           /* Size of array aiIndent[] */
1178  int iIndent;           /* Index of current op in aiIndent[] */
1179  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1180  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1181  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1182};
1183
1184
1185/* Allowed values for ShellState.autoEQP
1186*/
1187#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1188#define AUTOEQP_on       1           /* Automatic EQP is on */
1189#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1190#define AUTOEQP_full     3           /* Show full EXPLAIN */
1191
1192/* Allowed values for ShellState.openMode
1193*/
1194#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1195#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1196#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1197#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1198#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1199#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1200#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1201
1202/* Allowed values for ShellState.eTraceType
1203*/
1204#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1205#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1206#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1207
1208/* Bits in the ShellState.flgProgress variable */
1209#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1210#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1211                                   ** callback limit is reached, and for each
1212                                   ** top-level SQL statement */
1213#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1214
1215/*
1216** These are the allowed shellFlgs values
1217*/
1218#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1219#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1220#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1221#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1222#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1223#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1224#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1225#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1226#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1227#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1228
1229/*
1230** Macros for testing and setting shellFlgs
1231*/
1232#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1233#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1234#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1235
1236/*
1237** These are the allowed modes.
1238*/
1239#define MODE_Line     0  /* One column per line.  Blank line between records */
1240#define MODE_Column   1  /* One record per line in neat columns */
1241#define MODE_List     2  /* One record per line with a separator */
1242#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1243#define MODE_Html     4  /* Generate an XHTML table */
1244#define MODE_Insert   5  /* Generate SQL "insert" statements */
1245#define MODE_Quote    6  /* Quote values as for SQL */
1246#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1247#define MODE_Csv      8  /* Quote strings, numbers are plain */
1248#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1249#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1250#define MODE_Pretty  11  /* Pretty-print schemas */
1251#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1252#define MODE_Json    13  /* Output JSON */
1253#define MODE_Markdown 14 /* Markdown formatting */
1254#define MODE_Table   15  /* MySQL-style table formatting */
1255#define MODE_Box     16  /* Unicode box-drawing characters */
1256
1257static const char *modeDescr[] = {
1258  "line",
1259  "column",
1260  "list",
1261  "semi",
1262  "html",
1263  "insert",
1264  "quote",
1265  "tcl",
1266  "csv",
1267  "explain",
1268  "ascii",
1269  "prettyprint",
1270  "eqp",
1271  "json",
1272  "markdown",
1273  "table",
1274  "box"
1275};
1276
1277/*
1278** These are the column/row/line separators used by the various
1279** import/export modes.
1280*/
1281#define SEP_Column    "|"
1282#define SEP_Row       "\n"
1283#define SEP_Tab       "\t"
1284#define SEP_Space     " "
1285#define SEP_Comma     ","
1286#define SEP_CrLf      "\r\n"
1287#define SEP_Unit      "\x1F"
1288#define SEP_Record    "\x1E"
1289
1290/*
1291** A callback for the sqlite3_log() interface.
1292*/
1293static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1294  ShellState *p = (ShellState*)pArg;
1295  if( p->pLog==0 ) return;
1296  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1297  fflush(p->pLog);
1298}
1299
1300/*
1301** SQL function:  shell_putsnl(X)
1302**
1303** Write the text X to the screen (or whatever output is being directed)
1304** adding a newline at the end, and then return X.
1305*/
1306static void shellPutsFunc(
1307  sqlite3_context *pCtx,
1308  int nVal,
1309  sqlite3_value **apVal
1310){
1311  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1312  (void)nVal;
1313  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1314  sqlite3_result_value(pCtx, apVal[0]);
1315}
1316
1317/*
1318** If in safe mode, print an error message described by the arguments
1319** and exit immediately.
1320*/
1321static void failIfSafeMode(
1322  ShellState *p,
1323  const char *zErrMsg,
1324  ...
1325){
1326  if( p->bSafeMode ){
1327    va_list ap;
1328    char *zMsg;
1329    va_start(ap, zErrMsg);
1330    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1331    va_end(ap);
1332    raw_printf(stderr, "line %d: ", p->lineno);
1333    utf8_printf(stderr, "%s\n", zMsg);
1334    exit(1);
1335  }
1336}
1337
1338/*
1339** SQL function:   edit(VALUE)
1340**                 edit(VALUE,EDITOR)
1341**
1342** These steps:
1343**
1344**     (1) Write VALUE into a temporary file.
1345**     (2) Run program EDITOR on that temporary file.
1346**     (3) Read the temporary file back and return its content as the result.
1347**     (4) Delete the temporary file
1348**
1349** If the EDITOR argument is omitted, use the value in the VISUAL
1350** environment variable.  If still there is no EDITOR, through an error.
1351**
1352** Also throw an error if the EDITOR program returns a non-zero exit code.
1353*/
1354#ifndef SQLITE_NOHAVE_SYSTEM
1355static void editFunc(
1356  sqlite3_context *context,
1357  int argc,
1358  sqlite3_value **argv
1359){
1360  const char *zEditor;
1361  char *zTempFile = 0;
1362  sqlite3 *db;
1363  char *zCmd = 0;
1364  int bBin;
1365  int rc;
1366  int hasCRNL = 0;
1367  FILE *f = 0;
1368  sqlite3_int64 sz;
1369  sqlite3_int64 x;
1370  unsigned char *p = 0;
1371
1372  if( argc==2 ){
1373    zEditor = (const char*)sqlite3_value_text(argv[1]);
1374  }else{
1375    zEditor = getenv("VISUAL");
1376  }
1377  if( zEditor==0 ){
1378    sqlite3_result_error(context, "no editor for edit()", -1);
1379    return;
1380  }
1381  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1382    sqlite3_result_error(context, "NULL input to edit()", -1);
1383    return;
1384  }
1385  db = sqlite3_context_db_handle(context);
1386  zTempFile = 0;
1387  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1388  if( zTempFile==0 ){
1389    sqlite3_uint64 r = 0;
1390    sqlite3_randomness(sizeof(r), &r);
1391    zTempFile = sqlite3_mprintf("temp%llx", r);
1392    if( zTempFile==0 ){
1393      sqlite3_result_error_nomem(context);
1394      return;
1395    }
1396  }
1397  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1398  /* When writing the file to be edited, do \n to \r\n conversions on systems
1399  ** that want \r\n line endings */
1400  f = fopen(zTempFile, bBin ? "wb" : "w");
1401  if( f==0 ){
1402    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1403    goto edit_func_end;
1404  }
1405  sz = sqlite3_value_bytes(argv[0]);
1406  if( bBin ){
1407    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1408  }else{
1409    const char *z = (const char*)sqlite3_value_text(argv[0]);
1410    /* Remember whether or not the value originally contained \r\n */
1411    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1412    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1413  }
1414  fclose(f);
1415  f = 0;
1416  if( x!=sz ){
1417    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1418    goto edit_func_end;
1419  }
1420  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1421  if( zCmd==0 ){
1422    sqlite3_result_error_nomem(context);
1423    goto edit_func_end;
1424  }
1425  rc = system(zCmd);
1426  sqlite3_free(zCmd);
1427  if( rc ){
1428    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1429    goto edit_func_end;
1430  }
1431  f = fopen(zTempFile, "rb");
1432  if( f==0 ){
1433    sqlite3_result_error(context,
1434      "edit() cannot reopen temp file after edit", -1);
1435    goto edit_func_end;
1436  }
1437  fseek(f, 0, SEEK_END);
1438  sz = ftell(f);
1439  rewind(f);
1440  p = sqlite3_malloc64( sz+1 );
1441  if( p==0 ){
1442    sqlite3_result_error_nomem(context);
1443    goto edit_func_end;
1444  }
1445  x = fread(p, 1, (size_t)sz, f);
1446  fclose(f);
1447  f = 0;
1448  if( x!=sz ){
1449    sqlite3_result_error(context, "could not read back the whole file", -1);
1450    goto edit_func_end;
1451  }
1452  if( bBin ){
1453    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1454  }else{
1455    sqlite3_int64 i, j;
1456    if( hasCRNL ){
1457      /* If the original contains \r\n then do no conversions back to \n */
1458    }else{
1459      /* If the file did not originally contain \r\n then convert any new
1460      ** \r\n back into \n */
1461      for(i=j=0; i<sz; i++){
1462        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1463        p[j++] = p[i];
1464      }
1465      sz = j;
1466      p[sz] = 0;
1467    }
1468    sqlite3_result_text64(context, (const char*)p, sz,
1469                          sqlite3_free, SQLITE_UTF8);
1470  }
1471  p = 0;
1472
1473edit_func_end:
1474  if( f ) fclose(f);
1475  unlink(zTempFile);
1476  sqlite3_free(zTempFile);
1477  sqlite3_free(p);
1478}
1479#endif /* SQLITE_NOHAVE_SYSTEM */
1480
1481/*
1482** Save or restore the current output mode
1483*/
1484static void outputModePush(ShellState *p){
1485  p->modePrior = p->mode;
1486  p->priorShFlgs = p->shellFlgs;
1487  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1488  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1489}
1490static void outputModePop(ShellState *p){
1491  p->mode = p->modePrior;
1492  p->shellFlgs = p->priorShFlgs;
1493  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1494  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1495}
1496
1497/*
1498** Output the given string as a hex-encoded blob (eg. X'1234' )
1499*/
1500static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1501  int i;
1502  char *zBlob = (char *)pBlob;
1503  raw_printf(out,"X'");
1504  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1505  raw_printf(out,"'");
1506}
1507
1508/*
1509** Find a string that is not found anywhere in z[].  Return a pointer
1510** to that string.
1511**
1512** Try to use zA and zB first.  If both of those are already found in z[]
1513** then make up some string and store it in the buffer zBuf.
1514*/
1515static const char *unused_string(
1516  const char *z,                    /* Result must not appear anywhere in z */
1517  const char *zA, const char *zB,   /* Try these first */
1518  char *zBuf                        /* Space to store a generated string */
1519){
1520  unsigned i = 0;
1521  if( strstr(z, zA)==0 ) return zA;
1522  if( strstr(z, zB)==0 ) return zB;
1523  do{
1524    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1525  }while( strstr(z,zBuf)!=0 );
1526  return zBuf;
1527}
1528
1529/*
1530** Output the given string as a quoted string using SQL quoting conventions.
1531**
1532** See also: output_quoted_escaped_string()
1533*/
1534static void output_quoted_string(FILE *out, const char *z){
1535  int i;
1536  char c;
1537  setBinaryMode(out, 1);
1538  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1539  if( c==0 ){
1540    utf8_printf(out,"'%s'",z);
1541  }else{
1542    raw_printf(out, "'");
1543    while( *z ){
1544      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1545      if( c=='\'' ) i++;
1546      if( i ){
1547        utf8_printf(out, "%.*s", i, z);
1548        z += i;
1549      }
1550      if( c=='\'' ){
1551        raw_printf(out, "'");
1552        continue;
1553      }
1554      if( c==0 ){
1555        break;
1556      }
1557      z++;
1558    }
1559    raw_printf(out, "'");
1560  }
1561  setTextMode(out, 1);
1562}
1563
1564/*
1565** Output the given string as a quoted string using SQL quoting conventions.
1566** Additionallly , escape the "\n" and "\r" characters so that they do not
1567** get corrupted by end-of-line translation facilities in some operating
1568** systems.
1569**
1570** This is like output_quoted_string() but with the addition of the \r\n
1571** escape mechanism.
1572*/
1573static void output_quoted_escaped_string(FILE *out, const char *z){
1574  int i;
1575  char c;
1576  setBinaryMode(out, 1);
1577  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1578  if( c==0 ){
1579    utf8_printf(out,"'%s'",z);
1580  }else{
1581    const char *zNL = 0;
1582    const char *zCR = 0;
1583    int nNL = 0;
1584    int nCR = 0;
1585    char zBuf1[20], zBuf2[20];
1586    for(i=0; z[i]; i++){
1587      if( z[i]=='\n' ) nNL++;
1588      if( z[i]=='\r' ) nCR++;
1589    }
1590    if( nNL ){
1591      raw_printf(out, "replace(");
1592      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1593    }
1594    if( nCR ){
1595      raw_printf(out, "replace(");
1596      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1597    }
1598    raw_printf(out, "'");
1599    while( *z ){
1600      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1601      if( c=='\'' ) i++;
1602      if( i ){
1603        utf8_printf(out, "%.*s", i, z);
1604        z += i;
1605      }
1606      if( c=='\'' ){
1607        raw_printf(out, "'");
1608        continue;
1609      }
1610      if( c==0 ){
1611        break;
1612      }
1613      z++;
1614      if( c=='\n' ){
1615        raw_printf(out, "%s", zNL);
1616        continue;
1617      }
1618      raw_printf(out, "%s", zCR);
1619    }
1620    raw_printf(out, "'");
1621    if( nCR ){
1622      raw_printf(out, ",'%s',char(13))", zCR);
1623    }
1624    if( nNL ){
1625      raw_printf(out, ",'%s',char(10))", zNL);
1626    }
1627  }
1628  setTextMode(out, 1);
1629}
1630
1631/*
1632** Output the given string as a quoted according to C or TCL quoting rules.
1633*/
1634static void output_c_string(FILE *out, const char *z){
1635  unsigned int c;
1636  fputc('"', out);
1637  while( (c = *(z++))!=0 ){
1638    if( c=='\\' ){
1639      fputc(c, out);
1640      fputc(c, out);
1641    }else if( c=='"' ){
1642      fputc('\\', out);
1643      fputc('"', out);
1644    }else if( c=='\t' ){
1645      fputc('\\', out);
1646      fputc('t', out);
1647    }else if( c=='\n' ){
1648      fputc('\\', out);
1649      fputc('n', out);
1650    }else if( c=='\r' ){
1651      fputc('\\', out);
1652      fputc('r', out);
1653    }else if( !isprint(c&0xff) ){
1654      raw_printf(out, "\\%03o", c&0xff);
1655    }else{
1656      fputc(c, out);
1657    }
1658  }
1659  fputc('"', out);
1660}
1661
1662/*
1663** Output the given string as a quoted according to JSON quoting rules.
1664*/
1665static void output_json_string(FILE *out, const char *z, int n){
1666  unsigned int c;
1667  if( n<0 ) n = (int)strlen(z);
1668  fputc('"', out);
1669  while( n-- ){
1670    c = *(z++);
1671    if( c=='\\' || c=='"' ){
1672      fputc('\\', out);
1673      fputc(c, out);
1674    }else if( c<=0x1f ){
1675      fputc('\\', out);
1676      if( c=='\b' ){
1677        fputc('b', out);
1678      }else if( c=='\f' ){
1679        fputc('f', out);
1680      }else if( c=='\n' ){
1681        fputc('n', out);
1682      }else if( c=='\r' ){
1683        fputc('r', out);
1684      }else if( c=='\t' ){
1685        fputc('t', out);
1686      }else{
1687         raw_printf(out, "u%04x",c);
1688      }
1689    }else{
1690      fputc(c, out);
1691    }
1692  }
1693  fputc('"', out);
1694}
1695
1696/*
1697** Output the given string with characters that are special to
1698** HTML escaped.
1699*/
1700static void output_html_string(FILE *out, const char *z){
1701  int i;
1702  if( z==0 ) z = "";
1703  while( *z ){
1704    for(i=0;   z[i]
1705            && z[i]!='<'
1706            && z[i]!='&'
1707            && z[i]!='>'
1708            && z[i]!='\"'
1709            && z[i]!='\'';
1710        i++){}
1711    if( i>0 ){
1712      utf8_printf(out,"%.*s",i,z);
1713    }
1714    if( z[i]=='<' ){
1715      raw_printf(out,"&lt;");
1716    }else if( z[i]=='&' ){
1717      raw_printf(out,"&amp;");
1718    }else if( z[i]=='>' ){
1719      raw_printf(out,"&gt;");
1720    }else if( z[i]=='\"' ){
1721      raw_printf(out,"&quot;");
1722    }else if( z[i]=='\'' ){
1723      raw_printf(out,"&#39;");
1724    }else{
1725      break;
1726    }
1727    z += i + 1;
1728  }
1729}
1730
1731/*
1732** If a field contains any character identified by a 1 in the following
1733** array, then the string must be quoted for CSV.
1734*/
1735static const char needCsvQuote[] = {
1736  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1737  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1738  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1739  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1740  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1741  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1742  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1743  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1744  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1745  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1746  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1747  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1748  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1749  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1750  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1751  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1752};
1753
1754/*
1755** Output a single term of CSV.  Actually, p->colSeparator is used for
1756** the separator, which may or may not be a comma.  p->nullValue is
1757** the null value.  Strings are quoted if necessary.  The separator
1758** is only issued if bSep is true.
1759*/
1760static void output_csv(ShellState *p, const char *z, int bSep){
1761  FILE *out = p->out;
1762  if( z==0 ){
1763    utf8_printf(out,"%s",p->nullValue);
1764  }else{
1765    int i;
1766    int nSep = strlen30(p->colSeparator);
1767    for(i=0; z[i]; i++){
1768      if( needCsvQuote[((unsigned char*)z)[i]]
1769         || (z[i]==p->colSeparator[0] &&
1770             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1771        i = 0;
1772        break;
1773      }
1774    }
1775    if( i==0 ){
1776      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1777      utf8_printf(out, "%s", zQuoted);
1778      sqlite3_free(zQuoted);
1779    }else{
1780      utf8_printf(out, "%s", z);
1781    }
1782  }
1783  if( bSep ){
1784    utf8_printf(p->out, "%s", p->colSeparator);
1785  }
1786}
1787
1788/*
1789** This routine runs when the user presses Ctrl-C
1790*/
1791static void interrupt_handler(int NotUsed){
1792  UNUSED_PARAMETER(NotUsed);
1793  seenInterrupt++;
1794  if( seenInterrupt>2 ) exit(1);
1795  if( globalDb ) sqlite3_interrupt(globalDb);
1796}
1797
1798#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1799/*
1800** This routine runs for console events (e.g. Ctrl-C) on Win32
1801*/
1802static BOOL WINAPI ConsoleCtrlHandler(
1803  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1804){
1805  if( dwCtrlType==CTRL_C_EVENT ){
1806    interrupt_handler(0);
1807    return TRUE;
1808  }
1809  return FALSE;
1810}
1811#endif
1812
1813#ifndef SQLITE_OMIT_AUTHORIZATION
1814/*
1815** This authorizer runs in safe mode.
1816*/
1817static int safeModeAuth(
1818  void *pClientData,
1819  int op,
1820  const char *zA1,
1821  const char *zA2,
1822  const char *zA3,
1823  const char *zA4
1824){
1825  ShellState *p = (ShellState*)pClientData;
1826  static const char *azProhibitedFunctions[] = {
1827    "edit",
1828    "fts3_tokenizer",
1829    "load_extension",
1830    "readfile",
1831    "writefile",
1832    "zipfile",
1833    "zipfile_cds",
1834  };
1835  UNUSED_PARAMETER(zA2);
1836  UNUSED_PARAMETER(zA3);
1837  UNUSED_PARAMETER(zA4);
1838  switch( op ){
1839    case SQLITE_ATTACH: {
1840      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1841      break;
1842    }
1843    case SQLITE_FUNCTION: {
1844      int i;
1845      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1846        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1847          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1848                         azProhibitedFunctions[i]);
1849        }
1850      }
1851      break;
1852    }
1853  }
1854  return SQLITE_OK;
1855}
1856
1857/*
1858** When the ".auth ON" is set, the following authorizer callback is
1859** invoked.  It always returns SQLITE_OK.
1860*/
1861static int shellAuth(
1862  void *pClientData,
1863  int op,
1864  const char *zA1,
1865  const char *zA2,
1866  const char *zA3,
1867  const char *zA4
1868){
1869  ShellState *p = (ShellState*)pClientData;
1870  static const char *azAction[] = { 0,
1871     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1872     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1873     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1874     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1875     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1876     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1877     "PRAGMA",               "READ",                 "SELECT",
1878     "TRANSACTION",          "UPDATE",               "ATTACH",
1879     "DETACH",               "ALTER_TABLE",          "REINDEX",
1880     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1881     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1882  };
1883  int i;
1884  const char *az[4];
1885  az[0] = zA1;
1886  az[1] = zA2;
1887  az[2] = zA3;
1888  az[3] = zA4;
1889  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1890  for(i=0; i<4; i++){
1891    raw_printf(p->out, " ");
1892    if( az[i] ){
1893      output_c_string(p->out, az[i]);
1894    }else{
1895      raw_printf(p->out, "NULL");
1896    }
1897  }
1898  raw_printf(p->out, "\n");
1899  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1900  return SQLITE_OK;
1901}
1902#endif
1903
1904/*
1905** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1906**
1907** This routine converts some CREATE TABLE statements for shadow tables
1908** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1909*/
1910static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1911  if( z==0 ) return;
1912  if( zTail==0 ) return;
1913  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1914    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1915  }else{
1916    utf8_printf(out, "%s%s", z, zTail);
1917  }
1918}
1919static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1920  char c = z[n];
1921  z[n] = 0;
1922  printSchemaLine(out, z, zTail);
1923  z[n] = c;
1924}
1925
1926/*
1927** Return true if string z[] has nothing but whitespace and comments to the
1928** end of the first line.
1929*/
1930static int wsToEol(const char *z){
1931  int i;
1932  for(i=0; z[i]; i++){
1933    if( z[i]=='\n' ) return 1;
1934    if( IsSpace(z[i]) ) continue;
1935    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1936    return 0;
1937  }
1938  return 1;
1939}
1940
1941/*
1942** Add a new entry to the EXPLAIN QUERY PLAN data
1943*/
1944static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1945  EQPGraphRow *pNew;
1946  int nText = strlen30(zText);
1947  if( p->autoEQPtest ){
1948    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1949  }
1950  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1951  if( pNew==0 ) shell_out_of_memory();
1952  pNew->iEqpId = iEqpId;
1953  pNew->iParentId = p2;
1954  memcpy(pNew->zText, zText, nText+1);
1955  pNew->pNext = 0;
1956  if( p->sGraph.pLast ){
1957    p->sGraph.pLast->pNext = pNew;
1958  }else{
1959    p->sGraph.pRow = pNew;
1960  }
1961  p->sGraph.pLast = pNew;
1962}
1963
1964/*
1965** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1966** in p->sGraph.
1967*/
1968static void eqp_reset(ShellState *p){
1969  EQPGraphRow *pRow, *pNext;
1970  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1971    pNext = pRow->pNext;
1972    sqlite3_free(pRow);
1973  }
1974  memset(&p->sGraph, 0, sizeof(p->sGraph));
1975}
1976
1977/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1978** pOld, or return the first such line if pOld is NULL
1979*/
1980static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1981  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1982  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1983  return pRow;
1984}
1985
1986/* Render a single level of the graph that has iEqpId as its parent.  Called
1987** recursively to render sublevels.
1988*/
1989static void eqp_render_level(ShellState *p, int iEqpId){
1990  EQPGraphRow *pRow, *pNext;
1991  int n = strlen30(p->sGraph.zPrefix);
1992  char *z;
1993  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1994    pNext = eqp_next_row(p, iEqpId, pRow);
1995    z = pRow->zText;
1996    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1997                pNext ? "|--" : "`--", z);
1998    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1999      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2000      eqp_render_level(p, pRow->iEqpId);
2001      p->sGraph.zPrefix[n] = 0;
2002    }
2003  }
2004}
2005
2006/*
2007** Display and reset the EXPLAIN QUERY PLAN data
2008*/
2009static void eqp_render(ShellState *p){
2010  EQPGraphRow *pRow = p->sGraph.pRow;
2011  if( pRow ){
2012    if( pRow->zText[0]=='-' ){
2013      if( pRow->pNext==0 ){
2014        eqp_reset(p);
2015        return;
2016      }
2017      utf8_printf(p->out, "%s\n", pRow->zText+3);
2018      p->sGraph.pRow = pRow->pNext;
2019      sqlite3_free(pRow);
2020    }else{
2021      utf8_printf(p->out, "QUERY PLAN\n");
2022    }
2023    p->sGraph.zPrefix[0] = 0;
2024    eqp_render_level(p, 0);
2025    eqp_reset(p);
2026  }
2027}
2028
2029#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2030/*
2031** Progress handler callback.
2032*/
2033static int progress_handler(void *pClientData) {
2034  ShellState *p = (ShellState*)pClientData;
2035  p->nProgress++;
2036  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2037    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2038    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2039    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2040    return 1;
2041  }
2042  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2043    raw_printf(p->out, "Progress %u\n", p->nProgress);
2044  }
2045  return 0;
2046}
2047#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2048
2049/*
2050** Print N dashes
2051*/
2052static void print_dashes(FILE *out, int N){
2053  const char zDash[] = "--------------------------------------------------";
2054  const int nDash = sizeof(zDash) - 1;
2055  while( N>nDash ){
2056    fputs(zDash, out);
2057    N -= nDash;
2058  }
2059  raw_printf(out, "%.*s", N, zDash);
2060}
2061
2062/*
2063** Print a markdown or table-style row separator using ascii-art
2064*/
2065static void print_row_separator(
2066  ShellState *p,
2067  int nArg,
2068  const char *zSep
2069){
2070  int i;
2071  if( nArg>0 ){
2072    fputs(zSep, p->out);
2073    print_dashes(p->out, p->actualWidth[0]+2);
2074    for(i=1; i<nArg; i++){
2075      fputs(zSep, p->out);
2076      print_dashes(p->out, p->actualWidth[i]+2);
2077    }
2078    fputs(zSep, p->out);
2079  }
2080  fputs("\n", p->out);
2081}
2082
2083/*
2084** This is the callback routine that the shell
2085** invokes for each row of a query result.
2086*/
2087static int shell_callback(
2088  void *pArg,
2089  int nArg,        /* Number of result columns */
2090  char **azArg,    /* Text of each result column */
2091  char **azCol,    /* Column names */
2092  int *aiType      /* Column types.  Might be NULL */
2093){
2094  int i;
2095  ShellState *p = (ShellState*)pArg;
2096
2097  if( azArg==0 ) return 0;
2098  switch( p->cMode ){
2099    case MODE_Line: {
2100      int w = 5;
2101      if( azArg==0 ) break;
2102      for(i=0; i<nArg; i++){
2103        int len = strlen30(azCol[i] ? azCol[i] : "");
2104        if( len>w ) w = len;
2105      }
2106      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2107      for(i=0; i<nArg; i++){
2108        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2109                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2110      }
2111      break;
2112    }
2113    case MODE_Explain: {
2114      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2115      if( nArg>ArraySize(aExplainWidth) ){
2116        nArg = ArraySize(aExplainWidth);
2117      }
2118      if( p->cnt++==0 ){
2119        for(i=0; i<nArg; i++){
2120          int w = aExplainWidth[i];
2121          utf8_width_print(p->out, w, azCol[i]);
2122          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2123        }
2124        for(i=0; i<nArg; i++){
2125          int w = aExplainWidth[i];
2126          print_dashes(p->out, w);
2127          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2128        }
2129      }
2130      if( azArg==0 ) break;
2131      for(i=0; i<nArg; i++){
2132        int w = aExplainWidth[i];
2133        if( i==nArg-1 ) w = 0;
2134        if( azArg[i] && strlenChar(azArg[i])>w ){
2135          w = strlenChar(azArg[i]);
2136        }
2137        if( i==1 && p->aiIndent && p->pStmt ){
2138          if( p->iIndent<p->nIndent ){
2139            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2140          }
2141          p->iIndent++;
2142        }
2143        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2144        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2145      }
2146      break;
2147    }
2148    case MODE_Semi: {   /* .schema and .fullschema output */
2149      printSchemaLine(p->out, azArg[0], ";\n");
2150      break;
2151    }
2152    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2153      char *z;
2154      int j;
2155      int nParen = 0;
2156      char cEnd = 0;
2157      char c;
2158      int nLine = 0;
2159      assert( nArg==1 );
2160      if( azArg[0]==0 ) break;
2161      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2162       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2163      ){
2164        utf8_printf(p->out, "%s;\n", azArg[0]);
2165        break;
2166      }
2167      z = sqlite3_mprintf("%s", azArg[0]);
2168      j = 0;
2169      for(i=0; IsSpace(z[i]); i++){}
2170      for(; (c = z[i])!=0; i++){
2171        if( IsSpace(c) ){
2172          if( z[j-1]=='\r' ) z[j-1] = '\n';
2173          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2174        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2175          j--;
2176        }
2177        z[j++] = c;
2178      }
2179      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2180      z[j] = 0;
2181      if( strlen30(z)>=79 ){
2182        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2183          if( c==cEnd ){
2184            cEnd = 0;
2185          }else if( c=='"' || c=='\'' || c=='`' ){
2186            cEnd = c;
2187          }else if( c=='[' ){
2188            cEnd = ']';
2189          }else if( c=='-' && z[i+1]=='-' ){
2190            cEnd = '\n';
2191          }else if( c=='(' ){
2192            nParen++;
2193          }else if( c==')' ){
2194            nParen--;
2195            if( nLine>0 && nParen==0 && j>0 ){
2196              printSchemaLineN(p->out, z, j, "\n");
2197              j = 0;
2198            }
2199          }
2200          z[j++] = c;
2201          if( nParen==1 && cEnd==0
2202           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2203          ){
2204            if( c=='\n' ) j--;
2205            printSchemaLineN(p->out, z, j, "\n  ");
2206            j = 0;
2207            nLine++;
2208            while( IsSpace(z[i+1]) ){ i++; }
2209          }
2210        }
2211        z[j] = 0;
2212      }
2213      printSchemaLine(p->out, z, ";\n");
2214      sqlite3_free(z);
2215      break;
2216    }
2217    case MODE_List: {
2218      if( p->cnt++==0 && p->showHeader ){
2219        for(i=0; i<nArg; i++){
2220          utf8_printf(p->out,"%s%s",azCol[i],
2221                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2222        }
2223      }
2224      if( azArg==0 ) break;
2225      for(i=0; i<nArg; i++){
2226        char *z = azArg[i];
2227        if( z==0 ) z = p->nullValue;
2228        utf8_printf(p->out, "%s", z);
2229        if( i<nArg-1 ){
2230          utf8_printf(p->out, "%s", p->colSeparator);
2231        }else{
2232          utf8_printf(p->out, "%s", p->rowSeparator);
2233        }
2234      }
2235      break;
2236    }
2237    case MODE_Html: {
2238      if( p->cnt++==0 && p->showHeader ){
2239        raw_printf(p->out,"<TR>");
2240        for(i=0; i<nArg; i++){
2241          raw_printf(p->out,"<TH>");
2242          output_html_string(p->out, azCol[i]);
2243          raw_printf(p->out,"</TH>\n");
2244        }
2245        raw_printf(p->out,"</TR>\n");
2246      }
2247      if( azArg==0 ) break;
2248      raw_printf(p->out,"<TR>");
2249      for(i=0; i<nArg; i++){
2250        raw_printf(p->out,"<TD>");
2251        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2252        raw_printf(p->out,"</TD>\n");
2253      }
2254      raw_printf(p->out,"</TR>\n");
2255      break;
2256    }
2257    case MODE_Tcl: {
2258      if( p->cnt++==0 && p->showHeader ){
2259        for(i=0; i<nArg; i++){
2260          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2261          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2262        }
2263        utf8_printf(p->out, "%s", p->rowSeparator);
2264      }
2265      if( azArg==0 ) break;
2266      for(i=0; i<nArg; i++){
2267        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2268        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2269      }
2270      utf8_printf(p->out, "%s", p->rowSeparator);
2271      break;
2272    }
2273    case MODE_Csv: {
2274      setBinaryMode(p->out, 1);
2275      if( p->cnt++==0 && p->showHeader ){
2276        for(i=0; i<nArg; i++){
2277          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2278        }
2279        utf8_printf(p->out, "%s", p->rowSeparator);
2280      }
2281      if( nArg>0 ){
2282        for(i=0; i<nArg; i++){
2283          output_csv(p, azArg[i], i<nArg-1);
2284        }
2285        utf8_printf(p->out, "%s", p->rowSeparator);
2286      }
2287      setTextMode(p->out, 1);
2288      break;
2289    }
2290    case MODE_Insert: {
2291      if( azArg==0 ) break;
2292      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2293      if( p->showHeader ){
2294        raw_printf(p->out,"(");
2295        for(i=0; i<nArg; i++){
2296          if( i>0 ) raw_printf(p->out, ",");
2297          if( quoteChar(azCol[i]) ){
2298            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2299            utf8_printf(p->out, "%s", z);
2300            sqlite3_free(z);
2301          }else{
2302            raw_printf(p->out, "%s", azCol[i]);
2303          }
2304        }
2305        raw_printf(p->out,")");
2306      }
2307      p->cnt++;
2308      for(i=0; i<nArg; i++){
2309        raw_printf(p->out, i>0 ? "," : " VALUES(");
2310        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2311          utf8_printf(p->out,"NULL");
2312        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2313          if( ShellHasFlag(p, SHFLG_Newlines) ){
2314            output_quoted_string(p->out, azArg[i]);
2315          }else{
2316            output_quoted_escaped_string(p->out, azArg[i]);
2317          }
2318        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2319          utf8_printf(p->out,"%s", azArg[i]);
2320        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2321          char z[50];
2322          double r = sqlite3_column_double(p->pStmt, i);
2323          sqlite3_uint64 ur;
2324          memcpy(&ur,&r,sizeof(r));
2325          if( ur==0x7ff0000000000000LL ){
2326            raw_printf(p->out, "1e999");
2327          }else if( ur==0xfff0000000000000LL ){
2328            raw_printf(p->out, "-1e999");
2329          }else{
2330            sqlite3_snprintf(50,z,"%!.20g", r);
2331            raw_printf(p->out, "%s", z);
2332          }
2333        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2334          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2335          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2336          output_hex_blob(p->out, pBlob, nBlob);
2337        }else if( isNumber(azArg[i], 0) ){
2338          utf8_printf(p->out,"%s", azArg[i]);
2339        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2340          output_quoted_string(p->out, azArg[i]);
2341        }else{
2342          output_quoted_escaped_string(p->out, azArg[i]);
2343        }
2344      }
2345      raw_printf(p->out,");\n");
2346      break;
2347    }
2348    case MODE_Json: {
2349      if( azArg==0 ) break;
2350      if( p->cnt==0 ){
2351        fputs("[{", p->out);
2352      }else{
2353        fputs(",\n{", p->out);
2354      }
2355      p->cnt++;
2356      for(i=0; i<nArg; i++){
2357        output_json_string(p->out, azCol[i], -1);
2358        putc(':', p->out);
2359        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2360          fputs("null",p->out);
2361        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2362          char z[50];
2363          double r = sqlite3_column_double(p->pStmt, i);
2364          sqlite3_uint64 ur;
2365          memcpy(&ur,&r,sizeof(r));
2366          if( ur==0x7ff0000000000000LL ){
2367            raw_printf(p->out, "1e999");
2368          }else if( ur==0xfff0000000000000LL ){
2369            raw_printf(p->out, "-1e999");
2370          }else{
2371            sqlite3_snprintf(50,z,"%!.20g", r);
2372            raw_printf(p->out, "%s", z);
2373          }
2374        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2375          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2376          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2377          output_json_string(p->out, pBlob, nBlob);
2378        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2379          output_json_string(p->out, azArg[i], -1);
2380        }else{
2381          utf8_printf(p->out,"%s", azArg[i]);
2382        }
2383        if( i<nArg-1 ){
2384          putc(',', p->out);
2385        }
2386      }
2387      putc('}', p->out);
2388      break;
2389    }
2390    case MODE_Quote: {
2391      if( azArg==0 ) break;
2392      if( p->cnt==0 && p->showHeader ){
2393        for(i=0; i<nArg; i++){
2394          if( i>0 ) fputs(p->colSeparator, p->out);
2395          output_quoted_string(p->out, azCol[i]);
2396        }
2397        fputs(p->rowSeparator, p->out);
2398      }
2399      p->cnt++;
2400      for(i=0; i<nArg; i++){
2401        if( i>0 ) fputs(p->colSeparator, p->out);
2402        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2403          utf8_printf(p->out,"NULL");
2404        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2405          output_quoted_string(p->out, azArg[i]);
2406        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2407          utf8_printf(p->out,"%s", azArg[i]);
2408        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2409          char z[50];
2410          double r = sqlite3_column_double(p->pStmt, i);
2411          sqlite3_snprintf(50,z,"%!.20g", r);
2412          raw_printf(p->out, "%s", z);
2413        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2414          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2415          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2416          output_hex_blob(p->out, pBlob, nBlob);
2417        }else if( isNumber(azArg[i], 0) ){
2418          utf8_printf(p->out,"%s", azArg[i]);
2419        }else{
2420          output_quoted_string(p->out, azArg[i]);
2421        }
2422      }
2423      fputs(p->rowSeparator, p->out);
2424      break;
2425    }
2426    case MODE_Ascii: {
2427      if( p->cnt++==0 && p->showHeader ){
2428        for(i=0; i<nArg; i++){
2429          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2430          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2431        }
2432        utf8_printf(p->out, "%s", p->rowSeparator);
2433      }
2434      if( azArg==0 ) break;
2435      for(i=0; i<nArg; i++){
2436        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2437        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2438      }
2439      utf8_printf(p->out, "%s", p->rowSeparator);
2440      break;
2441    }
2442    case MODE_EQP: {
2443      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2444      break;
2445    }
2446  }
2447  return 0;
2448}
2449
2450/*
2451** This is the callback routine that the SQLite library
2452** invokes for each row of a query result.
2453*/
2454static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2455  /* since we don't have type info, call the shell_callback with a NULL value */
2456  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2457}
2458
2459/*
2460** This is the callback routine from sqlite3_exec() that appends all
2461** output onto the end of a ShellText object.
2462*/
2463static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2464  ShellText *p = (ShellText*)pArg;
2465  int i;
2466  UNUSED_PARAMETER(az);
2467  if( azArg==0 ) return 0;
2468  if( p->n ) appendText(p, "|", 0);
2469  for(i=0; i<nArg; i++){
2470    if( i ) appendText(p, ",", 0);
2471    if( azArg[i] ) appendText(p, azArg[i], 0);
2472  }
2473  return 0;
2474}
2475
2476/*
2477** Generate an appropriate SELFTEST table in the main database.
2478*/
2479static void createSelftestTable(ShellState *p){
2480  char *zErrMsg = 0;
2481  sqlite3_exec(p->db,
2482    "SAVEPOINT selftest_init;\n"
2483    "CREATE TABLE IF NOT EXISTS selftest(\n"
2484    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2485    "  op TEXT,\n"                   /* Operator:  memo run */
2486    "  cmd TEXT,\n"                  /* Command text */
2487    "  ans TEXT\n"                   /* Desired answer */
2488    ");"
2489    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2490    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2491    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2492    "         'memo','Tests generated by --init');\n"
2493    "INSERT INTO [_shell$self]\n"
2494    "  SELECT 'run',\n"
2495    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2496                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2497    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2498                          "FROM sqlite_schema ORDER BY 2',224));\n"
2499    "INSERT INTO [_shell$self]\n"
2500    "  SELECT 'run',"
2501    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2502    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2503    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2504    "  FROM (\n"
2505    "    SELECT name FROM sqlite_schema\n"
2506    "     WHERE type='table'\n"
2507    "       AND name<>'selftest'\n"
2508    "       AND coalesce(rootpage,0)>0\n"
2509    "  )\n"
2510    " ORDER BY name;\n"
2511    "INSERT INTO [_shell$self]\n"
2512    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2513    "INSERT INTO selftest(tno,op,cmd,ans)"
2514    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2515    "DROP TABLE [_shell$self];"
2516    ,0,0,&zErrMsg);
2517  if( zErrMsg ){
2518    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2519    sqlite3_free(zErrMsg);
2520  }
2521  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2522}
2523
2524
2525/*
2526** Set the destination table field of the ShellState structure to
2527** the name of the table given.  Escape any quote characters in the
2528** table name.
2529*/
2530static void set_table_name(ShellState *p, const char *zName){
2531  int i, n;
2532  char cQuote;
2533  char *z;
2534
2535  if( p->zDestTable ){
2536    free(p->zDestTable);
2537    p->zDestTable = 0;
2538  }
2539  if( zName==0 ) return;
2540  cQuote = quoteChar(zName);
2541  n = strlen30(zName);
2542  if( cQuote ) n += n+2;
2543  z = p->zDestTable = malloc( n+1 );
2544  if( z==0 ) shell_out_of_memory();
2545  n = 0;
2546  if( cQuote ) z[n++] = cQuote;
2547  for(i=0; zName[i]; i++){
2548    z[n++] = zName[i];
2549    if( zName[i]==cQuote ) z[n++] = cQuote;
2550  }
2551  if( cQuote ) z[n++] = cQuote;
2552  z[n] = 0;
2553}
2554
2555
2556/*
2557** Execute a query statement that will generate SQL output.  Print
2558** the result columns, comma-separated, on a line and then add a
2559** semicolon terminator to the end of that line.
2560**
2561** If the number of columns is 1 and that column contains text "--"
2562** then write the semicolon on a separate line.  That way, if a
2563** "--" comment occurs at the end of the statement, the comment
2564** won't consume the semicolon terminator.
2565*/
2566static int run_table_dump_query(
2567  ShellState *p,           /* Query context */
2568  const char *zSelect      /* SELECT statement to extract content */
2569){
2570  sqlite3_stmt *pSelect;
2571  int rc;
2572  int nResult;
2573  int i;
2574  const char *z;
2575  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2576  if( rc!=SQLITE_OK || !pSelect ){
2577    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2578                sqlite3_errmsg(p->db));
2579    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2580    return rc;
2581  }
2582  rc = sqlite3_step(pSelect);
2583  nResult = sqlite3_column_count(pSelect);
2584  while( rc==SQLITE_ROW ){
2585    z = (const char*)sqlite3_column_text(pSelect, 0);
2586    utf8_printf(p->out, "%s", z);
2587    for(i=1; i<nResult; i++){
2588      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2589    }
2590    if( z==0 ) z = "";
2591    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2592    if( z[0] ){
2593      raw_printf(p->out, "\n;\n");
2594    }else{
2595      raw_printf(p->out, ";\n");
2596    }
2597    rc = sqlite3_step(pSelect);
2598  }
2599  rc = sqlite3_finalize(pSelect);
2600  if( rc!=SQLITE_OK ){
2601    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2602                sqlite3_errmsg(p->db));
2603    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2604  }
2605  return rc;
2606}
2607
2608/*
2609** Allocate space and save off string indicating current error.
2610*/
2611static char *save_err_msg(
2612  sqlite3 *db,           /* Database to query */
2613  const char *zWhen,     /* Qualifier (format) wrapper */
2614  int rc                 /* Error code returned from API */
2615){
2616  if( zWhen==0 )
2617    zWhen = "%s (%d)";
2618  return sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc);
2619}
2620
2621#ifdef __linux__
2622/*
2623** Attempt to display I/O stats on Linux using /proc/PID/io
2624*/
2625static void displayLinuxIoStats(FILE *out){
2626  FILE *in;
2627  char z[200];
2628  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2629  in = fopen(z, "rb");
2630  if( in==0 ) return;
2631  while( fgets(z, sizeof(z), in)!=0 ){
2632    static const struct {
2633      const char *zPattern;
2634      const char *zDesc;
2635    } aTrans[] = {
2636      { "rchar: ",                  "Bytes received by read():" },
2637      { "wchar: ",                  "Bytes sent to write():"    },
2638      { "syscr: ",                  "Read() system calls:"      },
2639      { "syscw: ",                  "Write() system calls:"     },
2640      { "read_bytes: ",             "Bytes read from storage:"  },
2641      { "write_bytes: ",            "Bytes written to storage:" },
2642      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2643    };
2644    int i;
2645    for(i=0; i<ArraySize(aTrans); i++){
2646      int n = strlen30(aTrans[i].zPattern);
2647      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2648        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2649        break;
2650      }
2651    }
2652  }
2653  fclose(in);
2654}
2655#endif
2656
2657/*
2658** Display a single line of status using 64-bit values.
2659*/
2660static void displayStatLine(
2661  ShellState *p,            /* The shell context */
2662  char *zLabel,             /* Label for this one line */
2663  char *zFormat,            /* Format for the result */
2664  int iStatusCtrl,          /* Which status to display */
2665  int bReset                /* True to reset the stats */
2666){
2667  sqlite3_int64 iCur = -1;
2668  sqlite3_int64 iHiwtr = -1;
2669  int i, nPercent;
2670  char zLine[200];
2671  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2672  for(i=0, nPercent=0; zFormat[i]; i++){
2673    if( zFormat[i]=='%' ) nPercent++;
2674  }
2675  if( nPercent>1 ){
2676    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2677  }else{
2678    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2679  }
2680  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2681}
2682
2683/*
2684** Display memory stats.
2685*/
2686static int display_stats(
2687  sqlite3 *db,                /* Database to query */
2688  ShellState *pArg,           /* Pointer to ShellState */
2689  int bReset                  /* True to reset the stats */
2690){
2691  int iCur;
2692  int iHiwtr;
2693  FILE *out;
2694  if( pArg==0 || pArg->out==0 ) return 0;
2695  out = pArg->out;
2696
2697  if( pArg->pStmt && pArg->statsOn==2 ){
2698    int nCol, i, x;
2699    sqlite3_stmt *pStmt = pArg->pStmt;
2700    char z[100];
2701    nCol = sqlite3_column_count(pStmt);
2702    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2703    for(i=0; i<nCol; i++){
2704      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2705      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2706#ifndef SQLITE_OMIT_DECLTYPE
2707      sqlite3_snprintf(30, z+x, "declared type:");
2708      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2709#endif
2710#ifdef SQLITE_ENABLE_COLUMN_METADATA
2711      sqlite3_snprintf(30, z+x, "database name:");
2712      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2713      sqlite3_snprintf(30, z+x, "table name:");
2714      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2715      sqlite3_snprintf(30, z+x, "origin name:");
2716      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2717#endif
2718    }
2719  }
2720
2721  if( pArg->statsOn==3 ){
2722    if( pArg->pStmt ){
2723      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2724      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2725    }
2726    return 0;
2727  }
2728
2729  displayStatLine(pArg, "Memory Used:",
2730     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2731  displayStatLine(pArg, "Number of Outstanding Allocations:",
2732     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2733  if( pArg->shellFlgs & SHFLG_Pagecache ){
2734    displayStatLine(pArg, "Number of Pcache Pages Used:",
2735       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2736  }
2737  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2738     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2739  displayStatLine(pArg, "Largest Allocation:",
2740     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2741  displayStatLine(pArg, "Largest Pcache Allocation:",
2742     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2743#ifdef YYTRACKMAXSTACKDEPTH
2744  displayStatLine(pArg, "Deepest Parser Stack:",
2745     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2746#endif
2747
2748  if( db ){
2749    if( pArg->shellFlgs & SHFLG_Lookaside ){
2750      iHiwtr = iCur = -1;
2751      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2752                        &iCur, &iHiwtr, bReset);
2753      raw_printf(pArg->out,
2754              "Lookaside Slots Used:                %d (max %d)\n",
2755              iCur, iHiwtr);
2756      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2757                        &iCur, &iHiwtr, bReset);
2758      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2759              iHiwtr);
2760      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2761                        &iCur, &iHiwtr, bReset);
2762      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2763              iHiwtr);
2764      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2765                        &iCur, &iHiwtr, bReset);
2766      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2767              iHiwtr);
2768    }
2769    iHiwtr = iCur = -1;
2770    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2771    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2772            iCur);
2773    iHiwtr = iCur = -1;
2774    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2775    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2776    iHiwtr = iCur = -1;
2777    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2778    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2779    iHiwtr = iCur = -1;
2780    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2781    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2782    iHiwtr = iCur = -1;
2783    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2784    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2785    iHiwtr = iCur = -1;
2786    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2787    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2788            iCur);
2789    iHiwtr = iCur = -1;
2790    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2791    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2792            iCur);
2793  }
2794
2795  if( pArg->pStmt ){
2796    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2797                               bReset);
2798    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2799    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2800    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2801    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2802    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2803    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2804    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2805    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2806    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2807    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2808    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2809    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2810    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2811  }
2812
2813#ifdef __linux__
2814  displayLinuxIoStats(pArg->out);
2815#endif
2816
2817  /* Do not remove this machine readable comment: extra-stats-output-here */
2818
2819  return 0;
2820}
2821
2822/*
2823** Display scan stats.
2824*/
2825static void display_scanstats(
2826  sqlite3 *db,                    /* Database to query */
2827  ShellState *pArg                /* Pointer to ShellState */
2828){
2829#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2830  UNUSED_PARAMETER(db);
2831  UNUSED_PARAMETER(pArg);
2832#else
2833  int i, k, n, mx;
2834  raw_printf(pArg->out, "-------- scanstats --------\n");
2835  mx = 0;
2836  for(k=0; k<=mx; k++){
2837    double rEstLoop = 1.0;
2838    for(i=n=0; 1; i++){
2839      sqlite3_stmt *p = pArg->pStmt;
2840      sqlite3_int64 nLoop, nVisit;
2841      double rEst;
2842      int iSid;
2843      const char *zExplain;
2844      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2845        break;
2846      }
2847      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2848      if( iSid>mx ) mx = iSid;
2849      if( iSid!=k ) continue;
2850      if( n==0 ){
2851        rEstLoop = (double)nLoop;
2852        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2853      }
2854      n++;
2855      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2856      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2857      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2858      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2859      rEstLoop *= rEst;
2860      raw_printf(pArg->out,
2861          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2862          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2863      );
2864    }
2865  }
2866  raw_printf(pArg->out, "---------------------------\n");
2867#endif
2868}
2869
2870/*
2871** Parameter azArray points to a zero-terminated array of strings. zStr
2872** points to a single nul-terminated string. Return non-zero if zStr
2873** is equal, according to strcmp(), to any of the strings in the array.
2874** Otherwise, return zero.
2875*/
2876static int str_in_array(const char *zStr, const char **azArray){
2877  int i;
2878  for(i=0; azArray[i]; i++){
2879    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2880  }
2881  return 0;
2882}
2883
2884/*
2885** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2886** and populate the ShellState.aiIndent[] array with the number of
2887** spaces each opcode should be indented before it is output.
2888**
2889** The indenting rules are:
2890**
2891**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2892**       all opcodes that occur between the p2 jump destination and the opcode
2893**       itself by 2 spaces.
2894**
2895**     * For each "Goto", if the jump destination is earlier in the program
2896**       and ends on one of:
2897**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2898**       or if the P1 parameter is one instead of zero,
2899**       then indent all opcodes between the earlier instruction
2900**       and "Goto" by 2 spaces.
2901*/
2902static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2903  const char *zSql;               /* The text of the SQL statement */
2904  const char *z;                  /* Used to check if this is an EXPLAIN */
2905  int *abYield = 0;               /* True if op is an OP_Yield */
2906  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2907  int iOp;                        /* Index of operation in p->aiIndent[] */
2908
2909  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2910  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2911                            "Rewind", 0 };
2912  const char *azGoto[] = { "Goto", 0 };
2913
2914  /* Try to figure out if this is really an EXPLAIN statement. If this
2915  ** cannot be verified, return early.  */
2916  if( sqlite3_column_count(pSql)!=8 ){
2917    p->cMode = p->mode;
2918    return;
2919  }
2920  zSql = sqlite3_sql(pSql);
2921  if( zSql==0 ) return;
2922  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2923  if( sqlite3_strnicmp(z, "explain", 7) ){
2924    p->cMode = p->mode;
2925    return;
2926  }
2927
2928  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2929    int i;
2930    int iAddr = sqlite3_column_int(pSql, 0);
2931    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2932
2933    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2934    ** p2 is an instruction address, set variable p2op to the index of that
2935    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2936    ** the current instruction is part of a sub-program generated by an
2937    ** SQL trigger or foreign key.  */
2938    int p2 = sqlite3_column_int(pSql, 3);
2939    int p2op = (p2 + (iOp-iAddr));
2940
2941    /* Grow the p->aiIndent array as required */
2942    if( iOp>=nAlloc ){
2943      if( iOp==0 ){
2944        /* Do further verfication that this is explain output.  Abort if
2945        ** it is not */
2946        static const char *explainCols[] = {
2947           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2948        int jj;
2949        for(jj=0; jj<ArraySize(explainCols); jj++){
2950          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2951            p->cMode = p->mode;
2952            sqlite3_reset(pSql);
2953            return;
2954          }
2955        }
2956      }
2957      nAlloc += 100;
2958      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2959      if( p->aiIndent==0 ) shell_out_of_memory();
2960      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2961      if( abYield==0 ) shell_out_of_memory();
2962    }
2963    abYield[iOp] = str_in_array(zOp, azYield);
2964    p->aiIndent[iOp] = 0;
2965    p->nIndent = iOp+1;
2966
2967    if( str_in_array(zOp, azNext) ){
2968      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2969    }
2970    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2971     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2972    ){
2973      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2974    }
2975  }
2976
2977  p->iIndent = 0;
2978  sqlite3_free(abYield);
2979  sqlite3_reset(pSql);
2980}
2981
2982/*
2983** Free the array allocated by explain_data_prepare().
2984*/
2985static void explain_data_delete(ShellState *p){
2986  sqlite3_free(p->aiIndent);
2987  p->aiIndent = 0;
2988  p->nIndent = 0;
2989  p->iIndent = 0;
2990}
2991
2992/*
2993** Disable and restore .wheretrace and .selecttrace settings.
2994*/
2995static unsigned int savedSelectTrace;
2996static unsigned int savedWhereTrace;
2997static void disable_debug_trace_modes(void){
2998  unsigned int zero = 0;
2999  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3000  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3001  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3002  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3003}
3004static void restore_debug_trace_modes(void){
3005  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3006  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3007}
3008
3009/* Create the TEMP table used to store parameter bindings */
3010static void bind_table_init(ShellState *p){
3011  int wrSchema = 0;
3012  int defensiveMode = 0;
3013  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3014  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3015  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3016  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3017  sqlite3_exec(p->db,
3018    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3019    "  key TEXT PRIMARY KEY,\n"
3020    "  value\n"
3021    ") WITHOUT ROWID;",
3022    0, 0, 0);
3023  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3024  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3025}
3026
3027/*
3028** Bind parameters on a prepared statement.
3029**
3030** Parameter bindings are taken from a TEMP table of the form:
3031**
3032**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3033**    WITHOUT ROWID;
3034**
3035** No bindings occur if this table does not exist.  The name of the table
3036** begins with "sqlite_" so that it will not collide with ordinary application
3037** tables.  The table must be in the TEMP schema.
3038*/
3039static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3040  int nVar;
3041  int i;
3042  int rc;
3043  sqlite3_stmt *pQ = 0;
3044
3045  nVar = sqlite3_bind_parameter_count(pStmt);
3046  if( nVar==0 ) return;  /* Nothing to do */
3047  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3048                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3049    return; /* Parameter table does not exist */
3050  }
3051  rc = sqlite3_prepare_v2(pArg->db,
3052          "SELECT value FROM temp.sqlite_parameters"
3053          " WHERE key=?1", -1, &pQ, 0);
3054  if( rc || pQ==0 ) return;
3055  for(i=1; i<=nVar; i++){
3056    char zNum[30];
3057    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3058    if( zVar==0 ){
3059      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3060      zVar = zNum;
3061    }
3062    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3063    if( sqlite3_step(pQ)==SQLITE_ROW ){
3064      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3065    }else{
3066      sqlite3_bind_null(pStmt, i);
3067    }
3068    sqlite3_reset(pQ);
3069  }
3070  sqlite3_finalize(pQ);
3071}
3072
3073/*
3074** UTF8 box-drawing characters.  Imagine box lines like this:
3075**
3076**           1
3077**           |
3078**       4 --+-- 2
3079**           |
3080**           3
3081**
3082** Each box characters has between 2 and 4 of the lines leading from
3083** the center.  The characters are here identified by the numbers of
3084** their corresponding lines.
3085*/
3086#define BOX_24   "\342\224\200"  /* U+2500 --- */
3087#define BOX_13   "\342\224\202"  /* U+2502  |  */
3088#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3089#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3090#define BOX_12   "\342\224\224"  /* U+2514  '- */
3091#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3092#define BOX_123  "\342\224\234"  /* U+251c  |- */
3093#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3094#define BOX_234  "\342\224\254"  /* U+252c -,- */
3095#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3096#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3097
3098/* Draw horizontal line N characters long using unicode box
3099** characters
3100*/
3101static void print_box_line(FILE *out, int N){
3102  const char zDash[] =
3103      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3104      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3105  const int nDash = sizeof(zDash) - 1;
3106  N *= 3;
3107  while( N>nDash ){
3108    utf8_printf(out, zDash);
3109    N -= nDash;
3110  }
3111  utf8_printf(out, "%.*s", N, zDash);
3112}
3113
3114/*
3115** Draw a horizontal separator for a MODE_Box table.
3116*/
3117static void print_box_row_separator(
3118  ShellState *p,
3119  int nArg,
3120  const char *zSep1,
3121  const char *zSep2,
3122  const char *zSep3
3123){
3124  int i;
3125  if( nArg>0 ){
3126    utf8_printf(p->out, "%s", zSep1);
3127    print_box_line(p->out, p->actualWidth[0]+2);
3128    for(i=1; i<nArg; i++){
3129      utf8_printf(p->out, "%s", zSep2);
3130      print_box_line(p->out, p->actualWidth[i]+2);
3131    }
3132    utf8_printf(p->out, "%s", zSep3);
3133  }
3134  fputs("\n", p->out);
3135}
3136
3137
3138
3139/*
3140** Run a prepared statement and output the result in one of the
3141** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3142** or MODE_Box.
3143**
3144** This is different from ordinary exec_prepared_stmt() in that
3145** it has to run the entire query and gather the results into memory
3146** first, in order to determine column widths, before providing
3147** any output.
3148*/
3149static void exec_prepared_stmt_columnar(
3150  ShellState *p,                        /* Pointer to ShellState */
3151  sqlite3_stmt *pStmt                   /* Statment to run */
3152){
3153  sqlite3_int64 nRow = 0;
3154  int nColumn = 0;
3155  char **azData = 0;
3156  sqlite3_int64 nAlloc = 0;
3157  const char *z;
3158  int rc;
3159  sqlite3_int64 i, nData;
3160  int j, nTotal, w, n;
3161  const char *colSep = 0;
3162  const char *rowSep = 0;
3163
3164  rc = sqlite3_step(pStmt);
3165  if( rc!=SQLITE_ROW ) return;
3166  nColumn = sqlite3_column_count(pStmt);
3167  nAlloc = nColumn*4;
3168  if( nAlloc<=0 ) nAlloc = 1;
3169  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3170  if( azData==0 ) shell_out_of_memory();
3171  for(i=0; i<nColumn; i++){
3172    azData[i] = strdup(sqlite3_column_name(pStmt,i));
3173  }
3174  do{
3175    if( (nRow+2)*nColumn >= nAlloc ){
3176      nAlloc *= 2;
3177      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3178      if( azData==0 ) shell_out_of_memory();
3179    }
3180    nRow++;
3181    for(i=0; i<nColumn; i++){
3182      z = (const char*)sqlite3_column_text(pStmt,i);
3183      azData[nRow*nColumn + i] = z ? strdup(z) : 0;
3184    }
3185  }while( sqlite3_step(pStmt)==SQLITE_ROW );
3186  if( nColumn>p->nWidth ){
3187    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3188    if( p->colWidth==0 ) shell_out_of_memory();
3189    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3190    p->nWidth = nColumn;
3191    p->actualWidth = &p->colWidth[nColumn];
3192  }
3193  memset(p->actualWidth, 0, nColumn*sizeof(int));
3194  for(i=0; i<nColumn; i++){
3195    w = p->colWidth[i];
3196    if( w<0 ) w = -w;
3197    p->actualWidth[i] = w;
3198  }
3199  nTotal = nColumn*(nRow+1);
3200  for(i=0; i<nTotal; i++){
3201    z = azData[i];
3202    if( z==0 ) z = p->nullValue;
3203    n = strlenChar(z);
3204    j = i%nColumn;
3205    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3206  }
3207  if( seenInterrupt ) goto columnar_end;
3208  if( nColumn==0 ) goto columnar_end;
3209  switch( p->cMode ){
3210    case MODE_Column: {
3211      colSep = "  ";
3212      rowSep = "\n";
3213      if( p->showHeader ){
3214        for(i=0; i<nColumn; i++){
3215          w = p->actualWidth[i];
3216          if( p->colWidth[i]<0 ) w = -w;
3217          utf8_width_print(p->out, w, azData[i]);
3218          fputs(i==nColumn-1?"\n":"  ", p->out);
3219        }
3220        for(i=0; i<nColumn; i++){
3221          print_dashes(p->out, p->actualWidth[i]);
3222          fputs(i==nColumn-1?"\n":"  ", p->out);
3223        }
3224      }
3225      break;
3226    }
3227    case MODE_Table: {
3228      colSep = " | ";
3229      rowSep = " |\n";
3230      print_row_separator(p, nColumn, "+");
3231      fputs("| ", p->out);
3232      for(i=0; i<nColumn; i++){
3233        w = p->actualWidth[i];
3234        n = strlenChar(azData[i]);
3235        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3236        fputs(i==nColumn-1?" |\n":" | ", p->out);
3237      }
3238      print_row_separator(p, nColumn, "+");
3239      break;
3240    }
3241    case MODE_Markdown: {
3242      colSep = " | ";
3243      rowSep = " |\n";
3244      fputs("| ", p->out);
3245      for(i=0; i<nColumn; i++){
3246        w = p->actualWidth[i];
3247        n = strlenChar(azData[i]);
3248        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3249        fputs(i==nColumn-1?" |\n":" | ", p->out);
3250      }
3251      print_row_separator(p, nColumn, "|");
3252      break;
3253    }
3254    case MODE_Box: {
3255      colSep = " " BOX_13 " ";
3256      rowSep = " " BOX_13 "\n";
3257      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3258      utf8_printf(p->out, BOX_13 " ");
3259      for(i=0; i<nColumn; i++){
3260        w = p->actualWidth[i];
3261        n = strlenChar(azData[i]);
3262        utf8_printf(p->out, "%*s%s%*s%s",
3263            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3264            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3265      }
3266      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3267      break;
3268    }
3269  }
3270  for(i=nColumn, j=0; i<nTotal; i++, j++){
3271    if( j==0 && p->cMode!=MODE_Column ){
3272      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3273    }
3274    z = azData[i];
3275    if( z==0 ) z = p->nullValue;
3276    w = p->actualWidth[j];
3277    if( p->colWidth[j]<0 ) w = -w;
3278    utf8_width_print(p->out, w, z);
3279    if( j==nColumn-1 ){
3280      utf8_printf(p->out, "%s", rowSep);
3281      j = -1;
3282      if( seenInterrupt ) goto columnar_end;
3283    }else{
3284      utf8_printf(p->out, "%s", colSep);
3285    }
3286  }
3287  if( p->cMode==MODE_Table ){
3288    print_row_separator(p, nColumn, "+");
3289  }else if( p->cMode==MODE_Box ){
3290    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3291  }
3292columnar_end:
3293  if( seenInterrupt ){
3294    utf8_printf(p->out, "Interrupt\n");
3295  }
3296  nData = (nRow+1)*nColumn;
3297  for(i=0; i<nData; i++) free(azData[i]);
3298  sqlite3_free(azData);
3299}
3300
3301/*
3302** Run a prepared statement
3303*/
3304static void exec_prepared_stmt(
3305  ShellState *pArg,                                /* Pointer to ShellState */
3306  sqlite3_stmt *pStmt                              /* Statment to run */
3307){
3308  int rc;
3309
3310  if( pArg->cMode==MODE_Column
3311   || pArg->cMode==MODE_Table
3312   || pArg->cMode==MODE_Box
3313   || pArg->cMode==MODE_Markdown
3314  ){
3315    exec_prepared_stmt_columnar(pArg, pStmt);
3316    return;
3317  }
3318
3319  /* perform the first step.  this will tell us if we
3320  ** have a result set or not and how wide it is.
3321  */
3322  rc = sqlite3_step(pStmt);
3323  /* if we have a result set... */
3324  if( SQLITE_ROW == rc ){
3325    /* allocate space for col name ptr, value ptr, and type */
3326    int nCol = sqlite3_column_count(pStmt);
3327    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3328    if( !pData ){
3329      shell_out_of_memory();
3330    }else{
3331      char **azCols = (char **)pData;      /* Names of result columns */
3332      char **azVals = &azCols[nCol];       /* Results */
3333      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3334      int i, x;
3335      assert(sizeof(int) <= sizeof(char *));
3336      /* save off ptrs to column names */
3337      for(i=0; i<nCol; i++){
3338        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3339      }
3340      do{
3341        /* extract the data and data types */
3342        for(i=0; i<nCol; i++){
3343          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3344          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3345            azVals[i] = "";
3346          }else{
3347            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3348          }
3349          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3350            rc = SQLITE_NOMEM;
3351            break; /* from for */
3352          }
3353        } /* end for */
3354
3355        /* if data and types extracted successfully... */
3356        if( SQLITE_ROW == rc ){
3357          /* call the supplied callback with the result row data */
3358          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3359            rc = SQLITE_ABORT;
3360          }else{
3361            rc = sqlite3_step(pStmt);
3362          }
3363        }
3364      } while( SQLITE_ROW == rc );
3365      sqlite3_free(pData);
3366      if( pArg->cMode==MODE_Json ){
3367        fputs("]\n", pArg->out);
3368      }
3369    }
3370  }
3371}
3372
3373#ifndef SQLITE_OMIT_VIRTUALTABLE
3374/*
3375** This function is called to process SQL if the previous shell command
3376** was ".expert". It passes the SQL in the second argument directly to
3377** the sqlite3expert object.
3378**
3379** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3380** code. In this case, (*pzErr) may be set to point to a buffer containing
3381** an English language error message. It is the responsibility of the
3382** caller to eventually free this buffer using sqlite3_free().
3383*/
3384static int expertHandleSQL(
3385  ShellState *pState,
3386  const char *zSql,
3387  char **pzErr
3388){
3389  assert( pState->expert.pExpert );
3390  assert( pzErr==0 || *pzErr==0 );
3391  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3392}
3393
3394/*
3395** This function is called either to silently clean up the object
3396** created by the ".expert" command (if bCancel==1), or to generate a
3397** report from it and then clean it up (if bCancel==0).
3398**
3399** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3400** code. In this case, (*pzErr) may be set to point to a buffer containing
3401** an English language error message. It is the responsibility of the
3402** caller to eventually free this buffer using sqlite3_free().
3403*/
3404static int expertFinish(
3405  ShellState *pState,
3406  int bCancel,
3407  char **pzErr
3408){
3409  int rc = SQLITE_OK;
3410  sqlite3expert *p = pState->expert.pExpert;
3411  assert( p );
3412  assert( bCancel || pzErr==0 || *pzErr==0 );
3413  if( bCancel==0 ){
3414    FILE *out = pState->out;
3415    int bVerbose = pState->expert.bVerbose;
3416
3417    rc = sqlite3_expert_analyze(p, pzErr);
3418    if( rc==SQLITE_OK ){
3419      int nQuery = sqlite3_expert_count(p);
3420      int i;
3421
3422      if( bVerbose ){
3423        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3424        raw_printf(out, "-- Candidates -----------------------------\n");
3425        raw_printf(out, "%s\n", zCand);
3426      }
3427      for(i=0; i<nQuery; i++){
3428        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3429        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3430        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3431        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3432        if( bVerbose ){
3433          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3434          raw_printf(out, "%s\n\n", zSql);
3435        }
3436        raw_printf(out, "%s\n", zIdx);
3437        raw_printf(out, "%s\n", zEQP);
3438      }
3439    }
3440  }
3441  sqlite3_expert_destroy(p);
3442  pState->expert.pExpert = 0;
3443  return rc;
3444}
3445
3446/*
3447** Implementation of ".expert" dot command.
3448*/
3449static int expertDotCommand(
3450  ShellState *pState,             /* Current shell tool state */
3451  char **azArg,                   /* Array of arguments passed to dot command */
3452  int nArg                        /* Number of entries in azArg[] */
3453){
3454  int rc = SQLITE_OK;
3455  char *zErr = 0;
3456  int i;
3457  int iSample = 0;
3458
3459  assert( pState->expert.pExpert==0 );
3460  memset(&pState->expert, 0, sizeof(ExpertInfo));
3461
3462  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3463    char *z = azArg[i];
3464    int n;
3465    if( z[0]=='-' && z[1]=='-' ) z++;
3466    n = strlen30(z);
3467    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3468      pState->expert.bVerbose = 1;
3469    }
3470    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3471      if( i==(nArg-1) ){
3472        raw_printf(stderr, "option requires an argument: %s\n", z);
3473        rc = SQLITE_ERROR;
3474      }else{
3475        iSample = (int)integerValue(azArg[++i]);
3476        if( iSample<0 || iSample>100 ){
3477          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3478          rc = SQLITE_ERROR;
3479        }
3480      }
3481    }
3482    else{
3483      raw_printf(stderr, "unknown option: %s\n", z);
3484      rc = SQLITE_ERROR;
3485    }
3486  }
3487
3488  if( rc==SQLITE_OK ){
3489    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3490    if( pState->expert.pExpert==0 ){
3491      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
3492      rc = SQLITE_ERROR;
3493    }else{
3494      sqlite3_expert_config(
3495          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3496      );
3497    }
3498  }
3499
3500  return rc;
3501}
3502#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3503
3504/*
3505** Execute a statement or set of statements.  Print
3506** any result rows/columns depending on the current mode
3507** set via the supplied callback.
3508**
3509** This is very similar to SQLite's built-in sqlite3_exec()
3510** function except it takes a slightly different callback
3511** and callback data argument.
3512*/
3513static int shell_exec(
3514  ShellState *pArg,                         /* Pointer to ShellState */
3515  const char *zSql,                         /* SQL to be evaluated */
3516  char **pzErrMsg                           /* Error msg written here */
3517){
3518  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3519  int rc = SQLITE_OK;             /* Return Code */
3520  int rc2;
3521  const char *zLeftover;          /* Tail of unprocessed SQL */
3522  sqlite3 *db = pArg->db;
3523
3524  if( pzErrMsg ){
3525    *pzErrMsg = NULL;
3526  }
3527
3528#ifndef SQLITE_OMIT_VIRTUALTABLE
3529  if( pArg->expert.pExpert ){
3530    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3531    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3532  }
3533#endif
3534
3535  while( zSql[0] && (SQLITE_OK == rc) ){
3536    static const char *zStmtSql;
3537    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3538    if( SQLITE_OK != rc ){
3539      if( pzErrMsg ){
3540        *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)", rc);
3541      }
3542    }else{
3543      if( !pStmt ){
3544        /* this happens for a comment or white-space */
3545        zSql = zLeftover;
3546        while( IsSpace(zSql[0]) ) zSql++;
3547        continue;
3548      }
3549      zStmtSql = sqlite3_sql(pStmt);
3550      if( zStmtSql==0 ) zStmtSql = "";
3551      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3552
3553      /* save off the prepared statment handle and reset row count */
3554      if( pArg ){
3555        pArg->pStmt = pStmt;
3556        pArg->cnt = 0;
3557      }
3558
3559      /* echo the sql statement if echo on */
3560      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3561        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3562      }
3563
3564      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3565      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3566        sqlite3_stmt *pExplain;
3567        char *zEQP;
3568        int triggerEQP = 0;
3569        disable_debug_trace_modes();
3570        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3571        if( pArg->autoEQP>=AUTOEQP_trigger ){
3572          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3573        }
3574        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3575        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3576        if( rc==SQLITE_OK ){
3577          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3578            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3579            int iEqpId = sqlite3_column_int(pExplain, 0);
3580            int iParentId = sqlite3_column_int(pExplain, 1);
3581            if( zEQPLine==0 ) zEQPLine = "";
3582            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3583            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3584          }
3585          eqp_render(pArg);
3586        }
3587        sqlite3_finalize(pExplain);
3588        sqlite3_free(zEQP);
3589        if( pArg->autoEQP>=AUTOEQP_full ){
3590          /* Also do an EXPLAIN for ".eqp full" mode */
3591          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3592          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3593          if( rc==SQLITE_OK ){
3594            pArg->cMode = MODE_Explain;
3595            explain_data_prepare(pArg, pExplain);
3596            exec_prepared_stmt(pArg, pExplain);
3597            explain_data_delete(pArg);
3598          }
3599          sqlite3_finalize(pExplain);
3600          sqlite3_free(zEQP);
3601        }
3602        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3603          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3604          /* Reprepare pStmt before reactiving trace modes */
3605          sqlite3_finalize(pStmt);
3606          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3607          if( pArg ) pArg->pStmt = pStmt;
3608        }
3609        restore_debug_trace_modes();
3610      }
3611
3612      if( pArg ){
3613        pArg->cMode = pArg->mode;
3614        if( pArg->autoExplain ){
3615          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3616            pArg->cMode = MODE_Explain;
3617          }
3618          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3619            pArg->cMode = MODE_EQP;
3620          }
3621        }
3622
3623        /* If the shell is currently in ".explain" mode, gather the extra
3624        ** data required to add indents to the output.*/
3625        if( pArg->cMode==MODE_Explain ){
3626          explain_data_prepare(pArg, pStmt);
3627        }
3628      }
3629
3630      bind_prepared_stmt(pArg, pStmt);
3631      exec_prepared_stmt(pArg, pStmt);
3632      explain_data_delete(pArg);
3633      eqp_render(pArg);
3634
3635      /* print usage stats if stats on */
3636      if( pArg && pArg->statsOn ){
3637        display_stats(db, pArg, 0);
3638      }
3639
3640      /* print loop-counters if required */
3641      if( pArg && pArg->scanstatsOn ){
3642        display_scanstats(db, pArg);
3643      }
3644
3645      /* Finalize the statement just executed. If this fails, save a
3646      ** copy of the error message. Otherwise, set zSql to point to the
3647      ** next statement to execute. */
3648      rc2 = sqlite3_finalize(pStmt);
3649      if( rc!=SQLITE_NOMEM ) rc = rc2;
3650      if( rc==SQLITE_OK ){
3651        zSql = zLeftover;
3652        while( IsSpace(zSql[0]) ) zSql++;
3653      }else if( pzErrMsg ){
3654        *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc);
3655      }
3656
3657      /* clear saved stmt handle */
3658      if( pArg ){
3659        pArg->pStmt = NULL;
3660      }
3661    }
3662  } /* end while */
3663
3664  return rc;
3665}
3666
3667/*
3668** Release memory previously allocated by tableColumnList().
3669*/
3670static void freeColumnList(char **azCol){
3671  int i;
3672  for(i=1; azCol[i]; i++){
3673    sqlite3_free(azCol[i]);
3674  }
3675  /* azCol[0] is a static string */
3676  sqlite3_free(azCol);
3677}
3678
3679/*
3680** Return a list of pointers to strings which are the names of all
3681** columns in table zTab.   The memory to hold the names is dynamically
3682** allocated and must be released by the caller using a subsequent call
3683** to freeColumnList().
3684**
3685** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3686** value that needs to be preserved, then azCol[0] is filled in with the
3687** name of the rowid column.
3688**
3689** The first regular column in the table is azCol[1].  The list is terminated
3690** by an entry with azCol[i]==0.
3691*/
3692static char **tableColumnList(ShellState *p, const char *zTab){
3693  char **azCol = 0;
3694  sqlite3_stmt *pStmt;
3695  char *zSql;
3696  int nCol = 0;
3697  int nAlloc = 0;
3698  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3699  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3700  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3701  int rc;
3702
3703  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3704  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3705  sqlite3_free(zSql);
3706  if( rc ) return 0;
3707  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3708    if( nCol>=nAlloc-2 ){
3709      nAlloc = nAlloc*2 + nCol + 10;
3710      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3711      if( azCol==0 ) shell_out_of_memory();
3712    }
3713    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3714    if( sqlite3_column_int(pStmt, 5) ){
3715      nPK++;
3716      if( nPK==1
3717       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3718                          "INTEGER")==0
3719      ){
3720        isIPK = 1;
3721      }else{
3722        isIPK = 0;
3723      }
3724    }
3725  }
3726  sqlite3_finalize(pStmt);
3727  if( azCol==0 ) return 0;
3728  azCol[0] = 0;
3729  azCol[nCol+1] = 0;
3730
3731  /* The decision of whether or not a rowid really needs to be preserved
3732  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3733  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3734  ** rowids on tables where the rowid is inaccessible because there are other
3735  ** columns in the table named "rowid", "_rowid_", and "oid".
3736  */
3737  if( preserveRowid && isIPK ){
3738    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3739    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3740    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3741    ** ROWID aliases.  To distinguish these cases, check to see if
3742    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3743    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3744    */
3745    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3746                           " WHERE origin='pk'", zTab);
3747    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3748    sqlite3_free(zSql);
3749    if( rc ){
3750      freeColumnList(azCol);
3751      return 0;
3752    }
3753    rc = sqlite3_step(pStmt);
3754    sqlite3_finalize(pStmt);
3755    preserveRowid = rc==SQLITE_ROW;
3756  }
3757  if( preserveRowid ){
3758    /* Only preserve the rowid if we can find a name to use for the
3759    ** rowid */
3760    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3761    int i, j;
3762    for(j=0; j<3; j++){
3763      for(i=1; i<=nCol; i++){
3764        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3765      }
3766      if( i>nCol ){
3767        /* At this point, we know that azRowid[j] is not the name of any
3768        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3769        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3770        ** tables will fail this last check */
3771        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3772        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3773        break;
3774      }
3775    }
3776  }
3777  return azCol;
3778}
3779
3780/*
3781** Toggle the reverse_unordered_selects setting.
3782*/
3783static void toggleSelectOrder(sqlite3 *db){
3784  sqlite3_stmt *pStmt = 0;
3785  int iSetting = 0;
3786  char zStmt[100];
3787  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3788  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3789    iSetting = sqlite3_column_int(pStmt, 0);
3790  }
3791  sqlite3_finalize(pStmt);
3792  sqlite3_snprintf(sizeof(zStmt), zStmt,
3793       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3794  sqlite3_exec(db, zStmt, 0, 0, 0);
3795}
3796
3797/*
3798** This is a different callback routine used for dumping the database.
3799** Each row received by this callback consists of a table name,
3800** the table type ("index" or "table") and SQL to create the table.
3801** This routine should print text sufficient to recreate the table.
3802*/
3803static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3804  int rc;
3805  const char *zTable;
3806  const char *zType;
3807  const char *zSql;
3808  ShellState *p = (ShellState *)pArg;
3809  int dataOnly;
3810  int noSys;
3811
3812  UNUSED_PARAMETER(azNotUsed);
3813  if( nArg!=3 || azArg==0 ) return 0;
3814  zTable = azArg[0];
3815  zType = azArg[1];
3816  zSql = azArg[2];
3817  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
3818  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
3819
3820  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
3821    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3822  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
3823    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3824  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3825    return 0;
3826  }else if( dataOnly ){
3827    /* no-op */
3828  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3829    char *zIns;
3830    if( !p->writableSchema ){
3831      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3832      p->writableSchema = 1;
3833    }
3834    zIns = sqlite3_mprintf(
3835       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3836       "VALUES('table','%q','%q',0,'%q');",
3837       zTable, zTable, zSql);
3838    utf8_printf(p->out, "%s\n", zIns);
3839    sqlite3_free(zIns);
3840    return 0;
3841  }else{
3842    printSchemaLine(p->out, zSql, ";\n");
3843  }
3844
3845  if( strcmp(zType, "table")==0 ){
3846    ShellText sSelect;
3847    ShellText sTable;
3848    char **azCol;
3849    int i;
3850    char *savedDestTable;
3851    int savedMode;
3852
3853    azCol = tableColumnList(p, zTable);
3854    if( azCol==0 ){
3855      p->nErr++;
3856      return 0;
3857    }
3858
3859    /* Always quote the table name, even if it appears to be pure ascii,
3860    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3861    initText(&sTable);
3862    appendText(&sTable, zTable, quoteChar(zTable));
3863    /* If preserving the rowid, add a column list after the table name.
3864    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3865    ** instead of the usual "INSERT INTO tab VALUES(...)".
3866    */
3867    if( azCol[0] ){
3868      appendText(&sTable, "(", 0);
3869      appendText(&sTable, azCol[0], 0);
3870      for(i=1; azCol[i]; i++){
3871        appendText(&sTable, ",", 0);
3872        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3873      }
3874      appendText(&sTable, ")", 0);
3875    }
3876
3877    /* Build an appropriate SELECT statement */
3878    initText(&sSelect);
3879    appendText(&sSelect, "SELECT ", 0);
3880    if( azCol[0] ){
3881      appendText(&sSelect, azCol[0], 0);
3882      appendText(&sSelect, ",", 0);
3883    }
3884    for(i=1; azCol[i]; i++){
3885      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3886      if( azCol[i+1] ){
3887        appendText(&sSelect, ",", 0);
3888      }
3889    }
3890    freeColumnList(azCol);
3891    appendText(&sSelect, " FROM ", 0);
3892    appendText(&sSelect, zTable, quoteChar(zTable));
3893
3894    savedDestTable = p->zDestTable;
3895    savedMode = p->mode;
3896    p->zDestTable = sTable.z;
3897    p->mode = p->cMode = MODE_Insert;
3898    rc = shell_exec(p, sSelect.z, 0);
3899    if( (rc&0xff)==SQLITE_CORRUPT ){
3900      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3901      toggleSelectOrder(p->db);
3902      shell_exec(p, sSelect.z, 0);
3903      toggleSelectOrder(p->db);
3904    }
3905    p->zDestTable = savedDestTable;
3906    p->mode = savedMode;
3907    freeText(&sTable);
3908    freeText(&sSelect);
3909    if( rc ) p->nErr++;
3910  }
3911  return 0;
3912}
3913
3914/*
3915** Run zQuery.  Use dump_callback() as the callback routine so that
3916** the contents of the query are output as SQL statements.
3917**
3918** If we get a SQLITE_CORRUPT error, rerun the query after appending
3919** "ORDER BY rowid DESC" to the end.
3920*/
3921static int run_schema_dump_query(
3922  ShellState *p,
3923  const char *zQuery
3924){
3925  int rc;
3926  char *zErr = 0;
3927  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3928  if( rc==SQLITE_CORRUPT ){
3929    char *zQ2;
3930    int len = strlen30(zQuery);
3931    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3932    if( zErr ){
3933      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3934      sqlite3_free(zErr);
3935      zErr = 0;
3936    }
3937    zQ2 = malloc( len+100 );
3938    if( zQ2==0 ) return rc;
3939    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3940    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3941    if( rc ){
3942      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3943    }else{
3944      rc = SQLITE_CORRUPT;
3945    }
3946    sqlite3_free(zErr);
3947    free(zQ2);
3948  }
3949  return rc;
3950}
3951
3952/*
3953** Text of help messages.
3954**
3955** The help text for each individual command begins with a line that starts
3956** with ".".  Subsequent lines are supplimental information.
3957**
3958** There must be two or more spaces between the end of the command and the
3959** start of the description of what that command does.
3960*/
3961static const char *(azHelp[]) = {
3962#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3963  ".archive ...             Manage SQL archives",
3964  "   Each command must have exactly one of the following options:",
3965  "     -c, --create               Create a new archive",
3966  "     -u, --update               Add or update files with changed mtime",
3967  "     -i, --insert               Like -u but always add even if unchanged",
3968  "     -r, --remove               Remove files from archive",
3969  "     -t, --list                 List contents of archive",
3970  "     -x, --extract              Extract files from archive",
3971  "   Optional arguments:",
3972  "     -v, --verbose              Print each filename as it is processed",
3973  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
3974  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
3975  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
3976  "     -g, --glob                 Use glob matching for names in archive",
3977  "     -n, --dryrun               Show the SQL that would have occurred",
3978  "   Examples:",
3979  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
3980  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
3981  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
3982  "   See also:",
3983  "      http://sqlite.org/cli.html#sqlite_archive_support",
3984#endif
3985#ifndef SQLITE_OMIT_AUTHORIZATION
3986  ".auth ON|OFF             Show authorizer callbacks",
3987#endif
3988  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
3989  "       --append            Use the appendvfs",
3990  "       --async             Write to FILE without journal and fsync()",
3991  ".bail on|off             Stop after hitting an error.  Default OFF",
3992  ".binary on|off           Turn binary output on or off.  Default OFF",
3993  ".cd DIRECTORY            Change the working directory to DIRECTORY",
3994  ".changes on|off          Show number of rows changed by SQL",
3995  ".check GLOB              Fail if output since .testcase does not match",
3996  ".clone NEWDB             Clone data into NEWDB from the existing database",
3997  ".connection [close] [#]  Open or close an auxiliary database connection",
3998  ".databases               List names and files of attached databases",
3999  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4000  ".dbinfo ?DB?             Show status information about the database",
4001  ".dump ?OBJECTS?          Render database content as SQL",
4002  "   Options:",
4003  "     --data-only            Output only INSERT statements",
4004  "     --newlines             Allow unescaped newline characters in output",
4005  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4006  "     --preserve-rowids      Include ROWID values in the output",
4007  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4008  "   Additional LIKE patterns can be given in subsequent arguments",
4009  ".echo on|off             Turn command echo on or off",
4010  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4011  "   Other Modes:",
4012#ifdef SQLITE_DEBUG
4013  "      test                  Show raw EXPLAIN QUERY PLAN output",
4014  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4015#endif
4016  "      trigger               Like \"full\" but also show trigger bytecode",
4017  ".excel                   Display the output of next command in spreadsheet",
4018  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4019  ".exit ?CODE?             Exit this program with return-code CODE",
4020  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4021  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4022  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4023  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4024  "   --help                  Show CMD details",
4025  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4026  ".headers on|off          Turn display of headers on or off",
4027  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4028  ".import FILE TABLE       Import data from FILE into TABLE",
4029  "   Options:",
4030  "     --ascii               Use \\037 and \\036 as column and row separators",
4031  "     --csv                 Use , and \\n as column and row separators",
4032  "     --skip N              Skip the first N rows of input",
4033  "     -v                    \"Verbose\" - increase auxiliary output",
4034  "   Notes:",
4035  "     *  If TABLE does not exist, it is created.  The first row of input",
4036  "        determines the column names.",
4037  "     *  If neither --csv or --ascii are used, the input mode is derived",
4038  "        from the \".mode\" output mode",
4039  "     *  If FILE begins with \"|\" then it is a command that generates the",
4040  "        input text.",
4041#ifndef SQLITE_OMIT_TEST_CONTROL
4042  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4043#endif
4044  ".indexes ?TABLE?         Show names of indexes",
4045  "                           If TABLE is specified, only show indexes for",
4046  "                           tables matching TABLE using the LIKE operator.",
4047#ifdef SQLITE_ENABLE_IOTRACE
4048  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4049#endif
4050  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4051  ".lint OPTIONS            Report potential schema issues.",
4052  "     Options:",
4053  "        fkey-indexes     Find missing foreign key indexes",
4054#ifndef SQLITE_OMIT_LOAD_EXTENSION
4055  ".load FILE ?ENTRY?       Load an extension library",
4056#endif
4057  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4058  ".mode MODE ?TABLE?       Set output mode",
4059  "   MODE is one of:",
4060  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
4061  "     box       Tables using unicode box-drawing characters",
4062  "     csv       Comma-separated values",
4063  "     column    Output in columns.  (See .width)",
4064  "     html      HTML <table> code",
4065  "     insert    SQL insert statements for TABLE",
4066  "     json      Results in a JSON array",
4067  "     line      One value per line",
4068  "     list      Values delimited by \"|\"",
4069  "     markdown  Markdown table format",
4070  "     quote     Escape answers as for SQL",
4071  "     table     ASCII-art table",
4072  "     tabs      Tab-separated values",
4073  "     tcl       TCL list elements",
4074  ".nonce STRING            Disable safe mode for one command if the nonce matches",
4075  ".nullvalue STRING        Use STRING in place of NULL values",
4076  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4077  "     If FILE begins with '|' then open as a pipe",
4078  "       --bom  Put a UTF8 byte-order mark at the beginning",
4079  "       -e     Send output to the system text editor",
4080  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4081#ifdef SQLITE_DEBUG
4082  ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
4083#endif
4084  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4085  "     Options:",
4086  "        --append        Use appendvfs to append database to the end of FILE",
4087#ifndef SQLITE_OMIT_DESERIALIZE
4088  "        --deserialize   Load into memory using sqlite3_deserialize()",
4089  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4090  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4091#endif
4092  "        --new           Initialize FILE to an empty database",
4093  "        --nofollow      Do not follow symbolic links",
4094  "        --readonly      Open FILE readonly",
4095  "        --zip           FILE is a ZIP archive",
4096  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4097  "   If FILE begins with '|' then open it as a pipe.",
4098  "   Options:",
4099  "     --bom                 Prefix output with a UTF8 byte-order mark",
4100  "     -e                    Send output to the system text editor",
4101  "     -x                    Send output as CSV to a spreadsheet",
4102  ".parameter CMD ...       Manage SQL parameter bindings",
4103  "   clear                   Erase all bindings",
4104  "   init                    Initialize the TEMP table that holds bindings",
4105  "   list                    List the current parameter bindings",
4106  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4107  "                           PARAMETER should start with one of: $ : @ ?",
4108  "   unset PARAMETER         Remove PARAMETER from the binding table",
4109  ".print STRING...         Print literal STRING",
4110#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4111  ".progress N              Invoke progress handler after every N opcodes",
4112  "   --limit N                 Interrupt after N progress callbacks",
4113  "   --once                    Do no more than one progress interrupt",
4114  "   --quiet|-q                No output except at interrupts",
4115  "   --reset                   Reset the count for each input and interrupt",
4116#endif
4117  ".prompt MAIN CONTINUE    Replace the standard prompts",
4118  ".quit                    Exit this program",
4119  ".read FILE               Read input from FILE",
4120#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4121  ".recover                 Recover as much data as possible from corrupt db.",
4122  "   --freelist-corrupt       Assume the freelist is corrupt",
4123  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4124  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4125  "   --no-rowids              Do not attempt to recover rowid values",
4126  "                            that are not also INTEGER PRIMARY KEYs",
4127#endif
4128  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4129  ".save FILE               Write in-memory database into FILE",
4130  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4131  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4132  "   Options:",
4133  "      --indent             Try to pretty-print the schema",
4134  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4135  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4136  "    Options:",
4137  "       --init               Create a new SELFTEST table",
4138  "       -v                   Verbose output",
4139  ".separator COL ?ROW?     Change the column and row separators",
4140#if defined(SQLITE_ENABLE_SESSION)
4141  ".session ?NAME? CMD ...  Create or control sessions",
4142  "   Subcommands:",
4143  "     attach TABLE             Attach TABLE",
4144  "     changeset FILE           Write a changeset into FILE",
4145  "     close                    Close one session",
4146  "     enable ?BOOLEAN?         Set or query the enable bit",
4147  "     filter GLOB...           Reject tables matching GLOBs",
4148  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4149  "     isempty                  Query whether the session is empty",
4150  "     list                     List currently open session names",
4151  "     open DB NAME             Open a new session on DB",
4152  "     patchset FILE            Write a patchset into FILE",
4153  "   If ?NAME? is omitted, the first defined session is used.",
4154#endif
4155  ".sha3sum ...             Compute a SHA3 hash of database content",
4156  "    Options:",
4157  "      --schema              Also hash the sqlite_schema table",
4158  "      --sha3-224            Use the sha3-224 algorithm",
4159  "      --sha3-256            Use the sha3-256 algorithm (default)",
4160  "      --sha3-384            Use the sha3-384 algorithm",
4161  "      --sha3-512            Use the sha3-512 algorithm",
4162  "    Any other argument is a LIKE pattern for tables to hash",
4163#ifndef SQLITE_NOHAVE_SYSTEM
4164  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4165#endif
4166  ".show                    Show the current values for various settings",
4167  ".stats ?ARG?             Show stats or turn stats on or off",
4168  "   off                      Turn off automatic stat display",
4169  "   on                       Turn on automatic stat display",
4170  "   stmt                     Show statement stats",
4171  "   vmstep                   Show the virtual machine step count only",
4172#ifndef SQLITE_NOHAVE_SYSTEM
4173  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4174#endif
4175  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4176  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4177  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4178  "                           Run \".testctrl\" with no arguments for details",
4179  ".timeout MS              Try opening locked tables for MS milliseconds",
4180  ".timer on|off            Turn SQL timer on or off",
4181#ifndef SQLITE_OMIT_TRACE
4182  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4183  "    FILE                    Send output to FILE",
4184  "    stdout                  Send output to stdout",
4185  "    stderr                  Send output to stderr",
4186  "    off                     Disable tracing",
4187  "    --expanded              Expand query parameters",
4188#ifdef SQLITE_ENABLE_NORMALIZE
4189  "    --normalized            Normal the SQL statements",
4190#endif
4191  "    --plain                 Show SQL as it is input",
4192  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4193  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4194  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4195  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4196#endif /* SQLITE_OMIT_TRACE */
4197#ifdef SQLITE_DEBUG
4198  ".unmodule NAME ...       Unregister virtual table modules",
4199  "    --allexcept             Unregister everything except those named",
4200#endif
4201  ".vfsinfo ?AUX?           Information about the top-level VFS",
4202  ".vfslist                 List all available VFSes",
4203  ".vfsname ?AUX?           Print the name of the VFS stack",
4204  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4205  "     Negative values right-justify",
4206};
4207
4208/*
4209** Output help text.
4210**
4211** zPattern describes the set of commands for which help text is provided.
4212** If zPattern is NULL, then show all commands, but only give a one-line
4213** description of each.
4214**
4215** Return the number of matches.
4216*/
4217static int showHelp(FILE *out, const char *zPattern){
4218  int i = 0;
4219  int j = 0;
4220  int n = 0;
4221  char *zPat;
4222  if( zPattern==0
4223   || zPattern[0]=='0'
4224   || strcmp(zPattern,"-a")==0
4225   || strcmp(zPattern,"-all")==0
4226   || strcmp(zPattern,"--all")==0
4227  ){
4228    /* Show all commands, but only one line per command */
4229    if( zPattern==0 ) zPattern = "";
4230    for(i=0; i<ArraySize(azHelp); i++){
4231      if( azHelp[i][0]=='.' || zPattern[0] ){
4232        utf8_printf(out, "%s\n", azHelp[i]);
4233        n++;
4234      }
4235    }
4236  }else{
4237    /* Look for commands that for which zPattern is an exact prefix */
4238    zPat = sqlite3_mprintf(".%s*", zPattern);
4239    for(i=0; i<ArraySize(azHelp); i++){
4240      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4241        utf8_printf(out, "%s\n", azHelp[i]);
4242        j = i+1;
4243        n++;
4244      }
4245    }
4246    sqlite3_free(zPat);
4247    if( n ){
4248      if( n==1 ){
4249        /* when zPattern is a prefix of exactly one command, then include the
4250        ** details of that command, which should begin at offset j */
4251        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4252          utf8_printf(out, "%s\n", azHelp[j]);
4253          j++;
4254        }
4255      }
4256      return n;
4257    }
4258    /* Look for commands that contain zPattern anywhere.  Show the complete
4259    ** text of all commands that match. */
4260    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4261    for(i=0; i<ArraySize(azHelp); i++){
4262      if( azHelp[i][0]=='.' ) j = i;
4263      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4264        utf8_printf(out, "%s\n", azHelp[j]);
4265        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4266          j++;
4267          utf8_printf(out, "%s\n", azHelp[j]);
4268        }
4269        i = j;
4270        n++;
4271      }
4272    }
4273    sqlite3_free(zPat);
4274  }
4275  return n;
4276}
4277
4278/* Forward reference */
4279static int process_input(ShellState *p);
4280
4281/*
4282** Read the content of file zName into memory obtained from sqlite3_malloc64()
4283** and return a pointer to the buffer. The caller is responsible for freeing
4284** the memory.
4285**
4286** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4287** read.
4288**
4289** For convenience, a nul-terminator byte is always appended to the data read
4290** from the file before the buffer is returned. This byte is not included in
4291** the final value of (*pnByte), if applicable.
4292**
4293** NULL is returned if any error is encountered. The final value of *pnByte
4294** is undefined in this case.
4295*/
4296static char *readFile(const char *zName, int *pnByte){
4297  FILE *in = fopen(zName, "rb");
4298  long nIn;
4299  size_t nRead;
4300  char *pBuf;
4301  if( in==0 ) return 0;
4302  fseek(in, 0, SEEK_END);
4303  nIn = ftell(in);
4304  rewind(in);
4305  pBuf = sqlite3_malloc64( nIn+1 );
4306  if( pBuf==0 ){ fclose(in); return 0; }
4307  nRead = fread(pBuf, nIn, 1, in);
4308  fclose(in);
4309  if( nRead!=1 ){
4310    sqlite3_free(pBuf);
4311    return 0;
4312  }
4313  pBuf[nIn] = 0;
4314  if( pnByte ) *pnByte = nIn;
4315  return pBuf;
4316}
4317
4318#if defined(SQLITE_ENABLE_SESSION)
4319/*
4320** Close a single OpenSession object and release all of its associated
4321** resources.
4322*/
4323static void session_close(OpenSession *pSession){
4324  int i;
4325  sqlite3session_delete(pSession->p);
4326  sqlite3_free(pSession->zName);
4327  for(i=0; i<pSession->nFilter; i++){
4328    sqlite3_free(pSession->azFilter[i]);
4329  }
4330  sqlite3_free(pSession->azFilter);
4331  memset(pSession, 0, sizeof(OpenSession));
4332}
4333#endif
4334
4335/*
4336** Close all OpenSession objects and release all associated resources.
4337*/
4338#if defined(SQLITE_ENABLE_SESSION)
4339static void session_close_all(ShellState *p, int i){
4340  int j;
4341  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4342  for(j=0; j<pAuxDb->nSession; j++){
4343    session_close(&pAuxDb->aSession[j]);
4344  }
4345  pAuxDb->nSession = 0;
4346}
4347#else
4348# define session_close_all(X,Y)
4349#endif
4350
4351/*
4352** Implementation of the xFilter function for an open session.  Omit
4353** any tables named by ".session filter" but let all other table through.
4354*/
4355#if defined(SQLITE_ENABLE_SESSION)
4356static int session_filter(void *pCtx, const char *zTab){
4357  OpenSession *pSession = (OpenSession*)pCtx;
4358  int i;
4359  for(i=0; i<pSession->nFilter; i++){
4360    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4361  }
4362  return 1;
4363}
4364#endif
4365
4366/*
4367** Try to deduce the type of file for zName based on its content.  Return
4368** one of the SHELL_OPEN_* constants.
4369**
4370** If the file does not exist or is empty but its name looks like a ZIP
4371** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4372** Otherwise, assume an ordinary database regardless of the filename if
4373** the type cannot be determined from content.
4374*/
4375int deduceDatabaseType(const char *zName, int dfltZip){
4376  FILE *f = fopen(zName, "rb");
4377  size_t n;
4378  int rc = SHELL_OPEN_UNSPEC;
4379  char zBuf[100];
4380  if( f==0 ){
4381    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4382       return SHELL_OPEN_ZIPFILE;
4383    }else{
4384       return SHELL_OPEN_NORMAL;
4385    }
4386  }
4387  n = fread(zBuf, 16, 1, f);
4388  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4389    fclose(f);
4390    return SHELL_OPEN_NORMAL;
4391  }
4392  fseek(f, -25, SEEK_END);
4393  n = fread(zBuf, 25, 1, f);
4394  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4395    rc = SHELL_OPEN_APPENDVFS;
4396  }else{
4397    fseek(f, -22, SEEK_END);
4398    n = fread(zBuf, 22, 1, f);
4399    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4400       && zBuf[3]==0x06 ){
4401      rc = SHELL_OPEN_ZIPFILE;
4402    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4403      rc = SHELL_OPEN_ZIPFILE;
4404    }
4405  }
4406  fclose(f);
4407  return rc;
4408}
4409
4410#ifndef SQLITE_OMIT_DESERIALIZE
4411/*
4412** Reconstruct an in-memory database using the output from the "dbtotxt"
4413** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4414** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4415*/
4416static unsigned char *readHexDb(ShellState *p, int *pnData){
4417  unsigned char *a = 0;
4418  int nLine;
4419  int n = 0;
4420  int pgsz = 0;
4421  int iOffset = 0;
4422  int j, k;
4423  int rc;
4424  FILE *in;
4425  const char *zDbFilename = p->pAuxDb->zDbFilename;
4426  unsigned int x[16];
4427  char zLine[1000];
4428  if( zDbFilename ){
4429    in = fopen(zDbFilename, "r");
4430    if( in==0 ){
4431      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4432      return 0;
4433    }
4434    nLine = 0;
4435  }else{
4436    in = p->in;
4437    nLine = p->lineno;
4438    if( in==0 ) in = stdin;
4439  }
4440  *pnData = 0;
4441  nLine++;
4442  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4443  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4444  if( rc!=2 ) goto readHexDb_error;
4445  if( n<0 ) goto readHexDb_error;
4446  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4447  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4448  a = sqlite3_malloc( n ? n : 1 );
4449  if( a==0 ){
4450    utf8_printf(stderr, "Out of memory!\n");
4451    goto readHexDb_error;
4452  }
4453  memset(a, 0, n);
4454  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4455    utf8_printf(stderr, "invalid pagesize\n");
4456    goto readHexDb_error;
4457  }
4458  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4459    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4460    if( rc==2 ){
4461      iOffset = k;
4462      continue;
4463    }
4464    if( strncmp(zLine, "| end ", 6)==0 ){
4465      break;
4466    }
4467    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4468                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4469                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4470    if( rc==17 ){
4471      k = iOffset+j;
4472      if( k+16<=n && k>=0 ){
4473        int ii;
4474        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4475      }
4476    }
4477  }
4478  *pnData = n;
4479  if( in!=p->in ){
4480    fclose(in);
4481  }else{
4482    p->lineno = nLine;
4483  }
4484  return a;
4485
4486readHexDb_error:
4487  if( in!=p->in ){
4488    fclose(in);
4489  }else{
4490    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4491      nLine++;
4492      if(strncmp(zLine, "| end ", 6)==0 ) break;
4493    }
4494    p->lineno = nLine;
4495  }
4496  sqlite3_free(a);
4497  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4498  return 0;
4499}
4500#endif /* SQLITE_OMIT_DESERIALIZE */
4501
4502/*
4503** Scalar function "shell_int32". The first argument to this function
4504** must be a blob. The second a non-negative integer. This function
4505** reads and returns a 32-bit big-endian integer from byte
4506** offset (4*<arg2>) of the blob.
4507*/
4508static void shellInt32(
4509  sqlite3_context *context,
4510  int argc,
4511  sqlite3_value **argv
4512){
4513  const unsigned char *pBlob;
4514  int nBlob;
4515  int iInt;
4516
4517  UNUSED_PARAMETER(argc);
4518  nBlob = sqlite3_value_bytes(argv[0]);
4519  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4520  iInt = sqlite3_value_int(argv[1]);
4521
4522  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4523    const unsigned char *a = &pBlob[iInt*4];
4524    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4525                       + ((sqlite3_int64)a[1]<<16)
4526                       + ((sqlite3_int64)a[2]<< 8)
4527                       + ((sqlite3_int64)a[3]<< 0);
4528    sqlite3_result_int64(context, iVal);
4529  }
4530}
4531
4532/*
4533** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4534** using "..." with internal double-quote characters doubled.
4535*/
4536static void shellIdQuote(
4537  sqlite3_context *context,
4538  int argc,
4539  sqlite3_value **argv
4540){
4541  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4542  UNUSED_PARAMETER(argc);
4543  if( zName ){
4544    char *z = sqlite3_mprintf("\"%w\"", zName);
4545    sqlite3_result_text(context, z, -1, sqlite3_free);
4546  }
4547}
4548
4549/*
4550** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4551*/
4552static void shellUSleepFunc(
4553  sqlite3_context *context,
4554  int argcUnused,
4555  sqlite3_value **argv
4556){
4557  int sleep = sqlite3_value_int(argv[0]);
4558  (void)argcUnused;
4559  sqlite3_sleep(sleep/1000);
4560  sqlite3_result_int(context, sleep);
4561}
4562
4563/*
4564** Scalar function "shell_escape_crnl" used by the .recover command.
4565** The argument passed to this function is the output of built-in
4566** function quote(). If the first character of the input is "'",
4567** indicating that the value passed to quote() was a text value,
4568** then this function searches the input for "\n" and "\r" characters
4569** and adds a wrapper similar to the following:
4570**
4571**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4572**
4573** Or, if the first character of the input is not "'", then a copy
4574** of the input is returned.
4575*/
4576static void shellEscapeCrnl(
4577  sqlite3_context *context,
4578  int argc,
4579  sqlite3_value **argv
4580){
4581  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4582  UNUSED_PARAMETER(argc);
4583  if( zText[0]=='\'' ){
4584    int nText = sqlite3_value_bytes(argv[0]);
4585    int i;
4586    char zBuf1[20];
4587    char zBuf2[20];
4588    const char *zNL = 0;
4589    const char *zCR = 0;
4590    int nCR = 0;
4591    int nNL = 0;
4592
4593    for(i=0; zText[i]; i++){
4594      if( zNL==0 && zText[i]=='\n' ){
4595        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4596        nNL = (int)strlen(zNL);
4597      }
4598      if( zCR==0 && zText[i]=='\r' ){
4599        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4600        nCR = (int)strlen(zCR);
4601      }
4602    }
4603
4604    if( zNL || zCR ){
4605      int iOut = 0;
4606      i64 nMax = (nNL > nCR) ? nNL : nCR;
4607      i64 nAlloc = nMax * nText + (nMax+64)*2;
4608      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4609      if( zOut==0 ){
4610        sqlite3_result_error_nomem(context);
4611        return;
4612      }
4613
4614      if( zNL && zCR ){
4615        memcpy(&zOut[iOut], "replace(replace(", 16);
4616        iOut += 16;
4617      }else{
4618        memcpy(&zOut[iOut], "replace(", 8);
4619        iOut += 8;
4620      }
4621      for(i=0; zText[i]; i++){
4622        if( zText[i]=='\n' ){
4623          memcpy(&zOut[iOut], zNL, nNL);
4624          iOut += nNL;
4625        }else if( zText[i]=='\r' ){
4626          memcpy(&zOut[iOut], zCR, nCR);
4627          iOut += nCR;
4628        }else{
4629          zOut[iOut] = zText[i];
4630          iOut++;
4631        }
4632      }
4633
4634      if( zNL ){
4635        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4636        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4637        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4638      }
4639      if( zCR ){
4640        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4641        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4642        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4643      }
4644
4645      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4646      sqlite3_free(zOut);
4647      return;
4648    }
4649  }
4650
4651  sqlite3_result_value(context, argv[0]);
4652}
4653
4654/* Flags for open_db().
4655**
4656** The default behavior of open_db() is to exit(1) if the database fails to
4657** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4658** but still returns without calling exit.
4659**
4660** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4661** ZIP archive if the file does not exist or is empty and its name matches
4662** the *.zip pattern.
4663*/
4664#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4665#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4666
4667/*
4668** Make sure the database is open.  If it is not, then open it.  If
4669** the database fails to open, print an error message and exit.
4670*/
4671static void open_db(ShellState *p, int openFlags){
4672  if( p->db==0 ){
4673    const char *zDbFilename = p->pAuxDb->zDbFilename;
4674    if( p->openMode==SHELL_OPEN_UNSPEC ){
4675      if( zDbFilename==0 || zDbFilename[0]==0 ){
4676        p->openMode = SHELL_OPEN_NORMAL;
4677      }else{
4678        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4679                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4680      }
4681    }
4682    switch( p->openMode ){
4683      case SHELL_OPEN_APPENDVFS: {
4684        sqlite3_open_v2(zDbFilename, &p->db,
4685           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4686        break;
4687      }
4688      case SHELL_OPEN_HEXDB:
4689      case SHELL_OPEN_DESERIALIZE: {
4690        sqlite3_open(0, &p->db);
4691        break;
4692      }
4693      case SHELL_OPEN_ZIPFILE: {
4694        sqlite3_open(":memory:", &p->db);
4695        break;
4696      }
4697      case SHELL_OPEN_READONLY: {
4698        sqlite3_open_v2(zDbFilename, &p->db,
4699            SQLITE_OPEN_READONLY|p->openFlags, 0);
4700        break;
4701      }
4702      case SHELL_OPEN_UNSPEC:
4703      case SHELL_OPEN_NORMAL: {
4704        sqlite3_open_v2(zDbFilename, &p->db,
4705           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4706        break;
4707      }
4708    }
4709    globalDb = p->db;
4710    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4711      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4712          zDbFilename, sqlite3_errmsg(p->db));
4713      if( openFlags & OPEN_DB_KEEPALIVE ){
4714        sqlite3_open(":memory:", &p->db);
4715        return;
4716      }
4717      exit(1);
4718    }
4719#ifndef SQLITE_OMIT_LOAD_EXTENSION
4720    sqlite3_enable_load_extension(p->db, 1);
4721#endif
4722    sqlite3_fileio_init(p->db, 0, 0);
4723    sqlite3_shathree_init(p->db, 0, 0);
4724    sqlite3_completion_init(p->db, 0, 0);
4725    sqlite3_uint_init(p->db, 0, 0);
4726    sqlite3_decimal_init(p->db, 0, 0);
4727    sqlite3_regexp_init(p->db, 0, 0);
4728    sqlite3_ieee_init(p->db, 0, 0);
4729    sqlite3_series_init(p->db, 0, 0);
4730#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4731    sqlite3_dbdata_init(p->db, 0, 0);
4732#endif
4733#ifdef SQLITE_HAVE_ZLIB
4734    sqlite3_zipfile_init(p->db, 0, 0);
4735    sqlite3_sqlar_init(p->db, 0, 0);
4736#endif
4737    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4738                            shellAddSchemaName, 0, 0);
4739    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4740                            shellModuleSchema, 0, 0);
4741    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4742                            shellPutsFunc, 0, 0);
4743    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4744                            shellEscapeCrnl, 0, 0);
4745    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4746                            shellInt32, 0, 0);
4747    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4748                            shellIdQuote, 0, 0);
4749    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
4750                            shellUSleepFunc, 0, 0);
4751#ifndef SQLITE_NOHAVE_SYSTEM
4752    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4753                            editFunc, 0, 0);
4754    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4755                            editFunc, 0, 0);
4756#endif
4757    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4758      char *zSql = sqlite3_mprintf(
4759         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
4760      sqlite3_exec(p->db, zSql, 0, 0, 0);
4761      sqlite3_free(zSql);
4762    }
4763#ifndef SQLITE_OMIT_DESERIALIZE
4764    else
4765    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4766      int rc;
4767      int nData = 0;
4768      unsigned char *aData;
4769      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4770        aData = (unsigned char*)readFile(zDbFilename, &nData);
4771      }else{
4772        aData = readHexDb(p, &nData);
4773        if( aData==0 ){
4774          return;
4775        }
4776      }
4777      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4778                   SQLITE_DESERIALIZE_RESIZEABLE |
4779                   SQLITE_DESERIALIZE_FREEONCLOSE);
4780      if( rc ){
4781        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4782      }
4783      if( p->szMax>0 ){
4784        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4785      }
4786    }
4787#endif
4788  }
4789  if( p->bSafeModePersist && p->db!=0 ){
4790    sqlite3_set_authorizer(p->db, safeModeAuth, p);
4791  }
4792}
4793
4794/*
4795** Attempt to close the databaes connection.  Report errors.
4796*/
4797void close_db(sqlite3 *db){
4798  int rc = sqlite3_close(db);
4799  if( rc ){
4800    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4801        rc, sqlite3_errmsg(db));
4802  }
4803}
4804
4805#if HAVE_READLINE || HAVE_EDITLINE
4806/*
4807** Readline completion callbacks
4808*/
4809static char *readline_completion_generator(const char *text, int state){
4810  static sqlite3_stmt *pStmt = 0;
4811  char *zRet;
4812  if( state==0 ){
4813    char *zSql;
4814    sqlite3_finalize(pStmt);
4815    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4816                           "  FROM completion(%Q) ORDER BY 1", text);
4817    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4818    sqlite3_free(zSql);
4819  }
4820  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4821    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4822  }else{
4823    sqlite3_finalize(pStmt);
4824    pStmt = 0;
4825    zRet = 0;
4826  }
4827  return zRet;
4828}
4829static char **readline_completion(const char *zText, int iStart, int iEnd){
4830  rl_attempted_completion_over = 1;
4831  return rl_completion_matches(zText, readline_completion_generator);
4832}
4833
4834#elif HAVE_LINENOISE
4835/*
4836** Linenoise completion callback
4837*/
4838static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4839  int nLine = strlen30(zLine);
4840  int i, iStart;
4841  sqlite3_stmt *pStmt = 0;
4842  char *zSql;
4843  char zBuf[1000];
4844
4845  if( nLine>sizeof(zBuf)-30 ) return;
4846  if( zLine[0]=='.' || zLine[0]=='#') return;
4847  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4848  if( i==nLine-1 ) return;
4849  iStart = i+1;
4850  memcpy(zBuf, zLine, iStart);
4851  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4852                         "  FROM completion(%Q,%Q) ORDER BY 1",
4853                         &zLine[iStart], zLine);
4854  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4855  sqlite3_free(zSql);
4856  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4857  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4858    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4859    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4860    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4861      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4862      linenoiseAddCompletion(lc, zBuf);
4863    }
4864  }
4865  sqlite3_finalize(pStmt);
4866}
4867#endif
4868
4869/*
4870** Do C-language style dequoting.
4871**
4872**    \a    -> alarm
4873**    \b    -> backspace
4874**    \t    -> tab
4875**    \n    -> newline
4876**    \v    -> vertical tab
4877**    \f    -> form feed
4878**    \r    -> carriage return
4879**    \s    -> space
4880**    \"    -> "
4881**    \'    -> '
4882**    \\    -> backslash
4883**    \NNN  -> ascii character NNN in octal
4884*/
4885static void resolve_backslashes(char *z){
4886  int i, j;
4887  char c;
4888  while( *z && *z!='\\' ) z++;
4889  for(i=j=0; (c = z[i])!=0; i++, j++){
4890    if( c=='\\' && z[i+1]!=0 ){
4891      c = z[++i];
4892      if( c=='a' ){
4893        c = '\a';
4894      }else if( c=='b' ){
4895        c = '\b';
4896      }else if( c=='t' ){
4897        c = '\t';
4898      }else if( c=='n' ){
4899        c = '\n';
4900      }else if( c=='v' ){
4901        c = '\v';
4902      }else if( c=='f' ){
4903        c = '\f';
4904      }else if( c=='r' ){
4905        c = '\r';
4906      }else if( c=='"' ){
4907        c = '"';
4908      }else if( c=='\'' ){
4909        c = '\'';
4910      }else if( c=='\\' ){
4911        c = '\\';
4912      }else if( c>='0' && c<='7' ){
4913        c -= '0';
4914        if( z[i+1]>='0' && z[i+1]<='7' ){
4915          i++;
4916          c = (c<<3) + z[i] - '0';
4917          if( z[i+1]>='0' && z[i+1]<='7' ){
4918            i++;
4919            c = (c<<3) + z[i] - '0';
4920          }
4921        }
4922      }
4923    }
4924    z[j] = c;
4925  }
4926  if( j<i ) z[j] = 0;
4927}
4928
4929/*
4930** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4931** for TRUE and FALSE.  Return the integer value if appropriate.
4932*/
4933static int booleanValue(const char *zArg){
4934  int i;
4935  if( zArg[0]=='0' && zArg[1]=='x' ){
4936    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4937  }else{
4938    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4939  }
4940  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4941  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4942    return 1;
4943  }
4944  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4945    return 0;
4946  }
4947  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4948          zArg);
4949  return 0;
4950}
4951
4952/*
4953** Set or clear a shell flag according to a boolean value.
4954*/
4955static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4956  if( booleanValue(zArg) ){
4957    ShellSetFlag(p, mFlag);
4958  }else{
4959    ShellClearFlag(p, mFlag);
4960  }
4961}
4962
4963/*
4964** Close an output file, assuming it is not stderr or stdout
4965*/
4966static void output_file_close(FILE *f){
4967  if( f && f!=stdout && f!=stderr ) fclose(f);
4968}
4969
4970/*
4971** Try to open an output file.   The names "stdout" and "stderr" are
4972** recognized and do the right thing.  NULL is returned if the output
4973** filename is "off".
4974*/
4975static FILE *output_file_open(const char *zFile, int bTextMode){
4976  FILE *f;
4977  if( strcmp(zFile,"stdout")==0 ){
4978    f = stdout;
4979  }else if( strcmp(zFile, "stderr")==0 ){
4980    f = stderr;
4981  }else if( strcmp(zFile, "off")==0 ){
4982    f = 0;
4983  }else{
4984    f = fopen(zFile, bTextMode ? "w" : "wb");
4985    if( f==0 ){
4986      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4987    }
4988  }
4989  return f;
4990}
4991
4992#ifndef SQLITE_OMIT_TRACE
4993/*
4994** A routine for handling output from sqlite3_trace().
4995*/
4996static int sql_trace_callback(
4997  unsigned mType,         /* The trace type */
4998  void *pArg,             /* The ShellState pointer */
4999  void *pP,               /* Usually a pointer to sqlite_stmt */
5000  void *pX                /* Auxiliary output */
5001){
5002  ShellState *p = (ShellState*)pArg;
5003  sqlite3_stmt *pStmt;
5004  const char *zSql;
5005  int nSql;
5006  if( p->traceOut==0 ) return 0;
5007  if( mType==SQLITE_TRACE_CLOSE ){
5008    utf8_printf(p->traceOut, "-- closing database connection\n");
5009    return 0;
5010  }
5011  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5012    zSql = (const char*)pX;
5013  }else{
5014    pStmt = (sqlite3_stmt*)pP;
5015    switch( p->eTraceType ){
5016      case SHELL_TRACE_EXPANDED: {
5017        zSql = sqlite3_expanded_sql(pStmt);
5018        break;
5019      }
5020#ifdef SQLITE_ENABLE_NORMALIZE
5021      case SHELL_TRACE_NORMALIZED: {
5022        zSql = sqlite3_normalized_sql(pStmt);
5023        break;
5024      }
5025#endif
5026      default: {
5027        zSql = sqlite3_sql(pStmt);
5028        break;
5029      }
5030    }
5031  }
5032  if( zSql==0 ) return 0;
5033  nSql = strlen30(zSql);
5034  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5035  switch( mType ){
5036    case SQLITE_TRACE_ROW:
5037    case SQLITE_TRACE_STMT: {
5038      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5039      break;
5040    }
5041    case SQLITE_TRACE_PROFILE: {
5042      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5043      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5044      break;
5045    }
5046  }
5047  return 0;
5048}
5049#endif
5050
5051/*
5052** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5053** a useful spot to set a debugger breakpoint.
5054*/
5055static void test_breakpoint(void){
5056  static int nCall = 0;
5057  nCall++;
5058}
5059
5060/*
5061** An object used to read a CSV and other files for import.
5062*/
5063typedef struct ImportCtx ImportCtx;
5064struct ImportCtx {
5065  const char *zFile;  /* Name of the input file */
5066  FILE *in;           /* Read the CSV text from this input stream */
5067  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5068  char *z;            /* Accumulated text for a field */
5069  int n;              /* Number of bytes in z */
5070  int nAlloc;         /* Space allocated for z[] */
5071  int nLine;          /* Current line number */
5072  int nRow;           /* Number of rows imported */
5073  int nErr;           /* Number of errors encountered */
5074  int bNotFirst;      /* True if one or more bytes already read */
5075  int cTerm;          /* Character that terminated the most recent field */
5076  int cColSep;        /* The column separator character.  (Usually ",") */
5077  int cRowSep;        /* The row separator character.  (Usually "\n") */
5078};
5079
5080/* Clean up resourced used by an ImportCtx */
5081static void import_cleanup(ImportCtx *p){
5082  if( p->in!=0 && p->xCloser!=0 ){
5083    p->xCloser(p->in);
5084    p->in = 0;
5085  }
5086  sqlite3_free(p->z);
5087  p->z = 0;
5088}
5089
5090/* Append a single byte to z[] */
5091static void import_append_char(ImportCtx *p, int c){
5092  if( p->n+1>=p->nAlloc ){
5093    p->nAlloc += p->nAlloc + 100;
5094    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5095    if( p->z==0 ) shell_out_of_memory();
5096  }
5097  p->z[p->n++] = (char)c;
5098}
5099
5100/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5101** with the option of having a separator other than ",".
5102**
5103**   +  Input comes from p->in.
5104**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5105**      from sqlite3_malloc64().
5106**   +  Use p->cSep as the column separator.  The default is ",".
5107**   +  Use p->rSep as the row separator.  The default is "\n".
5108**   +  Keep track of the line number in p->nLine.
5109**   +  Store the character that terminates the field in p->cTerm.  Store
5110**      EOF on end-of-file.
5111**   +  Report syntax errors on stderr
5112*/
5113static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5114  int c;
5115  int cSep = p->cColSep;
5116  int rSep = p->cRowSep;
5117  p->n = 0;
5118  c = fgetc(p->in);
5119  if( c==EOF || seenInterrupt ){
5120    p->cTerm = EOF;
5121    return 0;
5122  }
5123  if( c=='"' ){
5124    int pc, ppc;
5125    int startLine = p->nLine;
5126    int cQuote = c;
5127    pc = ppc = 0;
5128    while( 1 ){
5129      c = fgetc(p->in);
5130      if( c==rSep ) p->nLine++;
5131      if( c==cQuote ){
5132        if( pc==cQuote ){
5133          pc = 0;
5134          continue;
5135        }
5136      }
5137      if( (c==cSep && pc==cQuote)
5138       || (c==rSep && pc==cQuote)
5139       || (c==rSep && pc=='\r' && ppc==cQuote)
5140       || (c==EOF && pc==cQuote)
5141      ){
5142        do{ p->n--; }while( p->z[p->n]!=cQuote );
5143        p->cTerm = c;
5144        break;
5145      }
5146      if( pc==cQuote && c!='\r' ){
5147        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5148                p->zFile, p->nLine, cQuote);
5149      }
5150      if( c==EOF ){
5151        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5152                p->zFile, startLine, cQuote);
5153        p->cTerm = c;
5154        break;
5155      }
5156      import_append_char(p, c);
5157      ppc = pc;
5158      pc = c;
5159    }
5160  }else{
5161    /* If this is the first field being parsed and it begins with the
5162    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5163    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5164      import_append_char(p, c);
5165      c = fgetc(p->in);
5166      if( (c&0xff)==0xbb ){
5167        import_append_char(p, c);
5168        c = fgetc(p->in);
5169        if( (c&0xff)==0xbf ){
5170          p->bNotFirst = 1;
5171          p->n = 0;
5172          return csv_read_one_field(p);
5173        }
5174      }
5175    }
5176    while( c!=EOF && c!=cSep && c!=rSep ){
5177      import_append_char(p, c);
5178      c = fgetc(p->in);
5179    }
5180    if( c==rSep ){
5181      p->nLine++;
5182      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5183    }
5184    p->cTerm = c;
5185  }
5186  if( p->z ) p->z[p->n] = 0;
5187  p->bNotFirst = 1;
5188  return p->z;
5189}
5190
5191/* Read a single field of ASCII delimited text.
5192**
5193**   +  Input comes from p->in.
5194**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5195**      from sqlite3_malloc64().
5196**   +  Use p->cSep as the column separator.  The default is "\x1F".
5197**   +  Use p->rSep as the row separator.  The default is "\x1E".
5198**   +  Keep track of the row number in p->nLine.
5199**   +  Store the character that terminates the field in p->cTerm.  Store
5200**      EOF on end-of-file.
5201**   +  Report syntax errors on stderr
5202*/
5203static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5204  int c;
5205  int cSep = p->cColSep;
5206  int rSep = p->cRowSep;
5207  p->n = 0;
5208  c = fgetc(p->in);
5209  if( c==EOF || seenInterrupt ){
5210    p->cTerm = EOF;
5211    return 0;
5212  }
5213  while( c!=EOF && c!=cSep && c!=rSep ){
5214    import_append_char(p, c);
5215    c = fgetc(p->in);
5216  }
5217  if( c==rSep ){
5218    p->nLine++;
5219  }
5220  p->cTerm = c;
5221  if( p->z ) p->z[p->n] = 0;
5222  return p->z;
5223}
5224
5225/*
5226** Try to transfer data for table zTable.  If an error is seen while
5227** moving forward, try to go backwards.  The backwards movement won't
5228** work for WITHOUT ROWID tables.
5229*/
5230static void tryToCloneData(
5231  ShellState *p,
5232  sqlite3 *newDb,
5233  const char *zTable
5234){
5235  sqlite3_stmt *pQuery = 0;
5236  sqlite3_stmt *pInsert = 0;
5237  char *zQuery = 0;
5238  char *zInsert = 0;
5239  int rc;
5240  int i, j, n;
5241  int nTable = strlen30(zTable);
5242  int k = 0;
5243  int cnt = 0;
5244  const int spinRate = 10000;
5245
5246  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5247  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5248  if( rc ){
5249    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5250            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5251            zQuery);
5252    goto end_data_xfer;
5253  }
5254  n = sqlite3_column_count(pQuery);
5255  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5256  if( zInsert==0 ) shell_out_of_memory();
5257  sqlite3_snprintf(200+nTable,zInsert,
5258                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5259  i = strlen30(zInsert);
5260  for(j=1; j<n; j++){
5261    memcpy(zInsert+i, ",?", 2);
5262    i += 2;
5263  }
5264  memcpy(zInsert+i, ");", 3);
5265  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5266  if( rc ){
5267    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5268            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5269            zQuery);
5270    goto end_data_xfer;
5271  }
5272  for(k=0; k<2; k++){
5273    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5274      for(i=0; i<n; i++){
5275        switch( sqlite3_column_type(pQuery, i) ){
5276          case SQLITE_NULL: {
5277            sqlite3_bind_null(pInsert, i+1);
5278            break;
5279          }
5280          case SQLITE_INTEGER: {
5281            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5282            break;
5283          }
5284          case SQLITE_FLOAT: {
5285            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5286            break;
5287          }
5288          case SQLITE_TEXT: {
5289            sqlite3_bind_text(pInsert, i+1,
5290                             (const char*)sqlite3_column_text(pQuery,i),
5291                             -1, SQLITE_STATIC);
5292            break;
5293          }
5294          case SQLITE_BLOB: {
5295            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5296                                            sqlite3_column_bytes(pQuery,i),
5297                                            SQLITE_STATIC);
5298            break;
5299          }
5300        }
5301      } /* End for */
5302      rc = sqlite3_step(pInsert);
5303      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5304        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5305                        sqlite3_errmsg(newDb));
5306      }
5307      sqlite3_reset(pInsert);
5308      cnt++;
5309      if( (cnt%spinRate)==0 ){
5310        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5311        fflush(stdout);
5312      }
5313    } /* End while */
5314    if( rc==SQLITE_DONE ) break;
5315    sqlite3_finalize(pQuery);
5316    sqlite3_free(zQuery);
5317    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5318                             zTable);
5319    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5320    if( rc ){
5321      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5322      break;
5323    }
5324  } /* End for(k=0...) */
5325
5326end_data_xfer:
5327  sqlite3_finalize(pQuery);
5328  sqlite3_finalize(pInsert);
5329  sqlite3_free(zQuery);
5330  sqlite3_free(zInsert);
5331}
5332
5333
5334/*
5335** Try to transfer all rows of the schema that match zWhere.  For
5336** each row, invoke xForEach() on the object defined by that row.
5337** If an error is encountered while moving forward through the
5338** sqlite_schema table, try again moving backwards.
5339*/
5340static void tryToCloneSchema(
5341  ShellState *p,
5342  sqlite3 *newDb,
5343  const char *zWhere,
5344  void (*xForEach)(ShellState*,sqlite3*,const char*)
5345){
5346  sqlite3_stmt *pQuery = 0;
5347  char *zQuery = 0;
5348  int rc;
5349  const unsigned char *zName;
5350  const unsigned char *zSql;
5351  char *zErrMsg = 0;
5352
5353  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5354                           " WHERE %s", zWhere);
5355  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5356  if( rc ){
5357    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5358                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5359                    zQuery);
5360    goto end_schema_xfer;
5361  }
5362  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5363    zName = sqlite3_column_text(pQuery, 0);
5364    zSql = sqlite3_column_text(pQuery, 1);
5365    printf("%s... ", zName); fflush(stdout);
5366    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5367    if( zErrMsg ){
5368      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5369      sqlite3_free(zErrMsg);
5370      zErrMsg = 0;
5371    }
5372    if( xForEach ){
5373      xForEach(p, newDb, (const char*)zName);
5374    }
5375    printf("done\n");
5376  }
5377  if( rc!=SQLITE_DONE ){
5378    sqlite3_finalize(pQuery);
5379    sqlite3_free(zQuery);
5380    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5381                             " WHERE %s ORDER BY rowid DESC", zWhere);
5382    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5383    if( rc ){
5384      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5385                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5386                      zQuery);
5387      goto end_schema_xfer;
5388    }
5389    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5390      zName = sqlite3_column_text(pQuery, 0);
5391      zSql = sqlite3_column_text(pQuery, 1);
5392      printf("%s... ", zName); fflush(stdout);
5393      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5394      if( zErrMsg ){
5395        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5396        sqlite3_free(zErrMsg);
5397        zErrMsg = 0;
5398      }
5399      if( xForEach ){
5400        xForEach(p, newDb, (const char*)zName);
5401      }
5402      printf("done\n");
5403    }
5404  }
5405end_schema_xfer:
5406  sqlite3_finalize(pQuery);
5407  sqlite3_free(zQuery);
5408}
5409
5410/*
5411** Open a new database file named "zNewDb".  Try to recover as much information
5412** as possible out of the main database (which might be corrupt) and write it
5413** into zNewDb.
5414*/
5415static void tryToClone(ShellState *p, const char *zNewDb){
5416  int rc;
5417  sqlite3 *newDb = 0;
5418  if( access(zNewDb,0)==0 ){
5419    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5420    return;
5421  }
5422  rc = sqlite3_open(zNewDb, &newDb);
5423  if( rc ){
5424    utf8_printf(stderr, "Cannot create output database: %s\n",
5425            sqlite3_errmsg(newDb));
5426  }else{
5427    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5428    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5429    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5430    tryToCloneSchema(p, newDb, "type!='table'", 0);
5431    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5432    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5433  }
5434  close_db(newDb);
5435}
5436
5437/*
5438** Change the output file back to stdout.
5439**
5440** If the p->doXdgOpen flag is set, that means the output was being
5441** redirected to a temporary file named by p->zTempFile.  In that case,
5442** launch start/open/xdg-open on that temporary file.
5443*/
5444static void output_reset(ShellState *p){
5445  if( p->outfile[0]=='|' ){
5446#ifndef SQLITE_OMIT_POPEN
5447    pclose(p->out);
5448#endif
5449  }else{
5450    output_file_close(p->out);
5451#ifndef SQLITE_NOHAVE_SYSTEM
5452    if( p->doXdgOpen ){
5453      const char *zXdgOpenCmd =
5454#if defined(_WIN32)
5455      "start";
5456#elif defined(__APPLE__)
5457      "open";
5458#else
5459      "xdg-open";
5460#endif
5461      char *zCmd;
5462      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5463      if( system(zCmd) ){
5464        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5465      }else{
5466        /* Give the start/open/xdg-open command some time to get
5467        ** going before we continue, and potential delete the
5468        ** p->zTempFile data file out from under it */
5469        sqlite3_sleep(2000);
5470      }
5471      sqlite3_free(zCmd);
5472      outputModePop(p);
5473      p->doXdgOpen = 0;
5474    }
5475#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5476  }
5477  p->outfile[0] = 0;
5478  p->out = stdout;
5479}
5480
5481/*
5482** Run an SQL command and return the single integer result.
5483*/
5484static int db_int(ShellState *p, const char *zSql){
5485  sqlite3_stmt *pStmt;
5486  int res = 0;
5487  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5488  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5489    res = sqlite3_column_int(pStmt,0);
5490  }
5491  sqlite3_finalize(pStmt);
5492  return res;
5493}
5494
5495/*
5496** Convert a 2-byte or 4-byte big-endian integer into a native integer
5497*/
5498static unsigned int get2byteInt(unsigned char *a){
5499  return (a[0]<<8) + a[1];
5500}
5501static unsigned int get4byteInt(unsigned char *a){
5502  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5503}
5504
5505/*
5506** Implementation of the ".dbinfo" command.
5507**
5508** Return 1 on error, 2 to exit, and 0 otherwise.
5509*/
5510static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5511  static const struct { const char *zName; int ofst; } aField[] = {
5512     { "file change counter:",  24  },
5513     { "database page count:",  28  },
5514     { "freelist page count:",  36  },
5515     { "schema cookie:",        40  },
5516     { "schema format:",        44  },
5517     { "default cache size:",   48  },
5518     { "autovacuum top root:",  52  },
5519     { "incremental vacuum:",   64  },
5520     { "text encoding:",        56  },
5521     { "user version:",         60  },
5522     { "application id:",       68  },
5523     { "software version:",     96  },
5524  };
5525  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5526     { "number of tables:",
5527       "SELECT count(*) FROM %s WHERE type='table'" },
5528     { "number of indexes:",
5529       "SELECT count(*) FROM %s WHERE type='index'" },
5530     { "number of triggers:",
5531       "SELECT count(*) FROM %s WHERE type='trigger'" },
5532     { "number of views:",
5533       "SELECT count(*) FROM %s WHERE type='view'" },
5534     { "schema size:",
5535       "SELECT total(length(sql)) FROM %s" },
5536  };
5537  int i, rc;
5538  unsigned iDataVersion;
5539  char *zSchemaTab;
5540  char *zDb = nArg>=2 ? azArg[1] : "main";
5541  sqlite3_stmt *pStmt = 0;
5542  unsigned char aHdr[100];
5543  open_db(p, 0);
5544  if( p->db==0 ) return 1;
5545  rc = sqlite3_prepare_v2(p->db,
5546             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5547             -1, &pStmt, 0);
5548  if( rc ){
5549    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5550    sqlite3_finalize(pStmt);
5551    return 1;
5552  }
5553  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5554  if( sqlite3_step(pStmt)==SQLITE_ROW
5555   && sqlite3_column_bytes(pStmt,0)>100
5556  ){
5557    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5558    sqlite3_finalize(pStmt);
5559  }else{
5560    raw_printf(stderr, "unable to read database header\n");
5561    sqlite3_finalize(pStmt);
5562    return 1;
5563  }
5564  i = get2byteInt(aHdr+16);
5565  if( i==1 ) i = 65536;
5566  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5567  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5568  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5569  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5570  for(i=0; i<ArraySize(aField); i++){
5571    int ofst = aField[i].ofst;
5572    unsigned int val = get4byteInt(aHdr + ofst);
5573    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5574    switch( ofst ){
5575      case 56: {
5576        if( val==1 ) raw_printf(p->out, " (utf8)");
5577        if( val==2 ) raw_printf(p->out, " (utf16le)");
5578        if( val==3 ) raw_printf(p->out, " (utf16be)");
5579      }
5580    }
5581    raw_printf(p->out, "\n");
5582  }
5583  if( zDb==0 ){
5584    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5585  }else if( strcmp(zDb,"temp")==0 ){
5586    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5587  }else{
5588    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5589  }
5590  for(i=0; i<ArraySize(aQuery); i++){
5591    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5592    int val = db_int(p, zSql);
5593    sqlite3_free(zSql);
5594    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5595  }
5596  sqlite3_free(zSchemaTab);
5597  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5598  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5599  return 0;
5600}
5601
5602/*
5603** Print the current sqlite3_errmsg() value to stderr and return 1.
5604*/
5605static int shellDatabaseError(sqlite3 *db){
5606  const char *zErr = sqlite3_errmsg(db);
5607  utf8_printf(stderr, "Error: %s\n", zErr);
5608  return 1;
5609}
5610
5611/*
5612** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5613** if they match and FALSE (0) if they do not match.
5614**
5615** Globbing rules:
5616**
5617**      '*'       Matches any sequence of zero or more characters.
5618**
5619**      '?'       Matches exactly one character.
5620**
5621**     [...]      Matches one character from the enclosed list of
5622**                characters.
5623**
5624**     [^...]     Matches one character not in the enclosed list.
5625**
5626**      '#'       Matches any sequence of one or more digits with an
5627**                optional + or - sign in front
5628**
5629**      ' '       Any span of whitespace matches any other span of
5630**                whitespace.
5631**
5632** Extra whitespace at the end of z[] is ignored.
5633*/
5634static int testcase_glob(const char *zGlob, const char *z){
5635  int c, c2;
5636  int invert;
5637  int seen;
5638
5639  while( (c = (*(zGlob++)))!=0 ){
5640    if( IsSpace(c) ){
5641      if( !IsSpace(*z) ) return 0;
5642      while( IsSpace(*zGlob) ) zGlob++;
5643      while( IsSpace(*z) ) z++;
5644    }else if( c=='*' ){
5645      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5646        if( c=='?' && (*(z++))==0 ) return 0;
5647      }
5648      if( c==0 ){
5649        return 1;
5650      }else if( c=='[' ){
5651        while( *z && testcase_glob(zGlob-1,z)==0 ){
5652          z++;
5653        }
5654        return (*z)!=0;
5655      }
5656      while( (c2 = (*(z++)))!=0 ){
5657        while( c2!=c ){
5658          c2 = *(z++);
5659          if( c2==0 ) return 0;
5660        }
5661        if( testcase_glob(zGlob,z) ) return 1;
5662      }
5663      return 0;
5664    }else if( c=='?' ){
5665      if( (*(z++))==0 ) return 0;
5666    }else if( c=='[' ){
5667      int prior_c = 0;
5668      seen = 0;
5669      invert = 0;
5670      c = *(z++);
5671      if( c==0 ) return 0;
5672      c2 = *(zGlob++);
5673      if( c2=='^' ){
5674        invert = 1;
5675        c2 = *(zGlob++);
5676      }
5677      if( c2==']' ){
5678        if( c==']' ) seen = 1;
5679        c2 = *(zGlob++);
5680      }
5681      while( c2 && c2!=']' ){
5682        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5683          c2 = *(zGlob++);
5684          if( c>=prior_c && c<=c2 ) seen = 1;
5685          prior_c = 0;
5686        }else{
5687          if( c==c2 ){
5688            seen = 1;
5689          }
5690          prior_c = c2;
5691        }
5692        c2 = *(zGlob++);
5693      }
5694      if( c2==0 || (seen ^ invert)==0 ) return 0;
5695    }else if( c=='#' ){
5696      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5697      if( !IsDigit(z[0]) ) return 0;
5698      z++;
5699      while( IsDigit(z[0]) ){ z++; }
5700    }else{
5701      if( c!=(*(z++)) ) return 0;
5702    }
5703  }
5704  while( IsSpace(*z) ){ z++; }
5705  return *z==0;
5706}
5707
5708
5709/*
5710** Compare the string as a command-line option with either one or two
5711** initial "-" characters.
5712*/
5713static int optionMatch(const char *zStr, const char *zOpt){
5714  if( zStr[0]!='-' ) return 0;
5715  zStr++;
5716  if( zStr[0]=='-' ) zStr++;
5717  return strcmp(zStr, zOpt)==0;
5718}
5719
5720/*
5721** Delete a file.
5722*/
5723int shellDeleteFile(const char *zFilename){
5724  int rc;
5725#ifdef _WIN32
5726  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5727  rc = _wunlink(z);
5728  sqlite3_free(z);
5729#else
5730  rc = unlink(zFilename);
5731#endif
5732  return rc;
5733}
5734
5735/*
5736** Try to delete the temporary file (if there is one) and free the
5737** memory used to hold the name of the temp file.
5738*/
5739static void clearTempFile(ShellState *p){
5740  if( p->zTempFile==0 ) return;
5741  if( p->doXdgOpen ) return;
5742  if( shellDeleteFile(p->zTempFile) ) return;
5743  sqlite3_free(p->zTempFile);
5744  p->zTempFile = 0;
5745}
5746
5747/*
5748** Create a new temp file name with the given suffix.
5749*/
5750static void newTempFile(ShellState *p, const char *zSuffix){
5751  clearTempFile(p);
5752  sqlite3_free(p->zTempFile);
5753  p->zTempFile = 0;
5754  if( p->db ){
5755    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5756  }
5757  if( p->zTempFile==0 ){
5758    /* If p->db is an in-memory database then the TEMPFILENAME file-control
5759    ** will not work and we will need to fallback to guessing */
5760    char *zTemp;
5761    sqlite3_uint64 r;
5762    sqlite3_randomness(sizeof(r), &r);
5763    zTemp = getenv("TEMP");
5764    if( zTemp==0 ) zTemp = getenv("TMP");
5765    if( zTemp==0 ){
5766#ifdef _WIN32
5767      zTemp = "\\tmp";
5768#else
5769      zTemp = "/tmp";
5770#endif
5771    }
5772    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5773  }else{
5774    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5775  }
5776  if( p->zTempFile==0 ){
5777    shell_out_of_memory();
5778  }
5779}
5780
5781
5782/*
5783** The implementation of SQL scalar function fkey_collate_clause(), used
5784** by the ".lint fkey-indexes" command. This scalar function is always
5785** called with four arguments - the parent table name, the parent column name,
5786** the child table name and the child column name.
5787**
5788**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5789**
5790** If either of the named tables or columns do not exist, this function
5791** returns an empty string. An empty string is also returned if both tables
5792** and columns exist but have the same default collation sequence. Or,
5793** if both exist but the default collation sequences are different, this
5794** function returns the string " COLLATE <parent-collation>", where
5795** <parent-collation> is the default collation sequence of the parent column.
5796*/
5797static void shellFkeyCollateClause(
5798  sqlite3_context *pCtx,
5799  int nVal,
5800  sqlite3_value **apVal
5801){
5802  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5803  const char *zParent;
5804  const char *zParentCol;
5805  const char *zParentSeq;
5806  const char *zChild;
5807  const char *zChildCol;
5808  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5809  int rc;
5810
5811  assert( nVal==4 );
5812  zParent = (const char*)sqlite3_value_text(apVal[0]);
5813  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5814  zChild = (const char*)sqlite3_value_text(apVal[2]);
5815  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5816
5817  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5818  rc = sqlite3_table_column_metadata(
5819      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5820  );
5821  if( rc==SQLITE_OK ){
5822    rc = sqlite3_table_column_metadata(
5823        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5824    );
5825  }
5826
5827  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5828    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5829    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5830    sqlite3_free(z);
5831  }
5832}
5833
5834
5835/*
5836** The implementation of dot-command ".lint fkey-indexes".
5837*/
5838static int lintFkeyIndexes(
5839  ShellState *pState,             /* Current shell tool state */
5840  char **azArg,                   /* Array of arguments passed to dot command */
5841  int nArg                        /* Number of entries in azArg[] */
5842){
5843  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5844  FILE *out = pState->out;        /* Stream to write non-error output to */
5845  int bVerbose = 0;               /* If -verbose is present */
5846  int bGroupByParent = 0;         /* If -groupbyparent is present */
5847  int i;                          /* To iterate through azArg[] */
5848  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5849  int rc;                         /* Return code */
5850  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5851
5852  /*
5853  ** This SELECT statement returns one row for each foreign key constraint
5854  ** in the schema of the main database. The column values are:
5855  **
5856  ** 0. The text of an SQL statement similar to:
5857  **
5858  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5859  **
5860  **    This SELECT is similar to the one that the foreign keys implementation
5861  **    needs to run internally on child tables. If there is an index that can
5862  **    be used to optimize this query, then it can also be used by the FK
5863  **    implementation to optimize DELETE or UPDATE statements on the parent
5864  **    table.
5865  **
5866  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5867  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5868  **    contains an index that can be used to optimize the query.
5869  **
5870  ** 2. Human readable text that describes the child table and columns. e.g.
5871  **
5872  **       "child_table(child_key1, child_key2)"
5873  **
5874  ** 3. Human readable text that describes the parent table and columns. e.g.
5875  **
5876  **       "parent_table(parent_key1, parent_key2)"
5877  **
5878  ** 4. A full CREATE INDEX statement for an index that could be used to
5879  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5880  **
5881  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5882  **
5883  ** 5. The name of the parent table.
5884  **
5885  ** These six values are used by the C logic below to generate the report.
5886  */
5887  const char *zSql =
5888  "SELECT "
5889    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5890    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5891    "  || fkey_collate_clause("
5892    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5893    ", "
5894    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
5895    "  || group_concat('*=?', ' AND ') || ')'"
5896    ", "
5897    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5898    ", "
5899    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5900    ", "
5901    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5902    "  || ' ON ' || quote(s.name) || '('"
5903    "  || group_concat(quote(f.[from]) ||"
5904    "        fkey_collate_clause("
5905    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5906    "  || ');'"
5907    ", "
5908    "     f.[table] "
5909    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5910    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5911    "GROUP BY s.name, f.id "
5912    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5913  ;
5914  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
5915
5916  for(i=2; i<nArg; i++){
5917    int n = strlen30(azArg[i]);
5918    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5919      bVerbose = 1;
5920    }
5921    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5922      bGroupByParent = 1;
5923      zIndent = "    ";
5924    }
5925    else{
5926      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5927          azArg[0], azArg[1]
5928      );
5929      return SQLITE_ERROR;
5930    }
5931  }
5932
5933  /* Register the fkey_collate_clause() SQL function */
5934  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5935      0, shellFkeyCollateClause, 0, 0
5936  );
5937
5938
5939  if( rc==SQLITE_OK ){
5940    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5941  }
5942  if( rc==SQLITE_OK ){
5943    sqlite3_bind_int(pSql, 1, bGroupByParent);
5944  }
5945
5946  if( rc==SQLITE_OK ){
5947    int rc2;
5948    char *zPrev = 0;
5949    while( SQLITE_ROW==sqlite3_step(pSql) ){
5950      int res = -1;
5951      sqlite3_stmt *pExplain = 0;
5952      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5953      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5954      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5955      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5956      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5957      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5958
5959      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5960      if( rc!=SQLITE_OK ) break;
5961      if( SQLITE_ROW==sqlite3_step(pExplain) ){
5962        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5963        res = (
5964              0==sqlite3_strglob(zGlob, zPlan)
5965           || 0==sqlite3_strglob(zGlobIPK, zPlan)
5966        );
5967      }
5968      rc = sqlite3_finalize(pExplain);
5969      if( rc!=SQLITE_OK ) break;
5970
5971      if( res<0 ){
5972        raw_printf(stderr, "Error: internal error");
5973        break;
5974      }else{
5975        if( bGroupByParent
5976        && (bVerbose || res==0)
5977        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5978        ){
5979          raw_printf(out, "-- Parent table %s\n", zParent);
5980          sqlite3_free(zPrev);
5981          zPrev = sqlite3_mprintf("%s", zParent);
5982        }
5983
5984        if( res==0 ){
5985          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5986        }else if( bVerbose ){
5987          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5988              zIndent, zFrom, zTarget
5989          );
5990        }
5991      }
5992    }
5993    sqlite3_free(zPrev);
5994
5995    if( rc!=SQLITE_OK ){
5996      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5997    }
5998
5999    rc2 = sqlite3_finalize(pSql);
6000    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6001      rc = rc2;
6002      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6003    }
6004  }else{
6005    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6006  }
6007
6008  return rc;
6009}
6010
6011/*
6012** Implementation of ".lint" dot command.
6013*/
6014static int lintDotCommand(
6015  ShellState *pState,             /* Current shell tool state */
6016  char **azArg,                   /* Array of arguments passed to dot command */
6017  int nArg                        /* Number of entries in azArg[] */
6018){
6019  int n;
6020  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6021  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6022  return lintFkeyIndexes(pState, azArg, nArg);
6023
6024 usage:
6025  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6026  raw_printf(stderr, "Where sub-commands are:\n");
6027  raw_printf(stderr, "    fkey-indexes\n");
6028  return SQLITE_ERROR;
6029}
6030
6031#if !defined SQLITE_OMIT_VIRTUALTABLE
6032static void shellPrepare(
6033  sqlite3 *db,
6034  int *pRc,
6035  const char *zSql,
6036  sqlite3_stmt **ppStmt
6037){
6038  *ppStmt = 0;
6039  if( *pRc==SQLITE_OK ){
6040    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6041    if( rc!=SQLITE_OK ){
6042      raw_printf(stderr, "sql error: %s (%d)\n",
6043          sqlite3_errmsg(db), sqlite3_errcode(db)
6044      );
6045      *pRc = rc;
6046    }
6047  }
6048}
6049
6050/*
6051** Create a prepared statement using printf-style arguments for the SQL.
6052**
6053** This routine is could be marked "static".  But it is not always used,
6054** depending on compile-time options.  By omitting the "static", we avoid
6055** nuisance compiler warnings about "defined but not used".
6056*/
6057void shellPreparePrintf(
6058  sqlite3 *db,
6059  int *pRc,
6060  sqlite3_stmt **ppStmt,
6061  const char *zFmt,
6062  ...
6063){
6064  *ppStmt = 0;
6065  if( *pRc==SQLITE_OK ){
6066    va_list ap;
6067    char *z;
6068    va_start(ap, zFmt);
6069    z = sqlite3_vmprintf(zFmt, ap);
6070    va_end(ap);
6071    if( z==0 ){
6072      *pRc = SQLITE_NOMEM;
6073    }else{
6074      shellPrepare(db, pRc, z, ppStmt);
6075      sqlite3_free(z);
6076    }
6077  }
6078}
6079
6080/* Finalize the prepared statement created using shellPreparePrintf().
6081**
6082** This routine is could be marked "static".  But it is not always used,
6083** depending on compile-time options.  By omitting the "static", we avoid
6084** nuisance compiler warnings about "defined but not used".
6085*/
6086void shellFinalize(
6087  int *pRc,
6088  sqlite3_stmt *pStmt
6089){
6090  if( pStmt ){
6091    sqlite3 *db = sqlite3_db_handle(pStmt);
6092    int rc = sqlite3_finalize(pStmt);
6093    if( *pRc==SQLITE_OK ){
6094      if( rc!=SQLITE_OK ){
6095        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6096      }
6097      *pRc = rc;
6098    }
6099  }
6100}
6101
6102/* Reset the prepared statement created using shellPreparePrintf().
6103**
6104** This routine is could be marked "static".  But it is not always used,
6105** depending on compile-time options.  By omitting the "static", we avoid
6106** nuisance compiler warnings about "defined but not used".
6107*/
6108void shellReset(
6109  int *pRc,
6110  sqlite3_stmt *pStmt
6111){
6112  int rc = sqlite3_reset(pStmt);
6113  if( *pRc==SQLITE_OK ){
6114    if( rc!=SQLITE_OK ){
6115      sqlite3 *db = sqlite3_db_handle(pStmt);
6116      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6117    }
6118    *pRc = rc;
6119  }
6120}
6121#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6122
6123#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6124/******************************************************************************
6125** The ".archive" or ".ar" command.
6126*/
6127/*
6128** Structure representing a single ".ar" command.
6129*/
6130typedef struct ArCommand ArCommand;
6131struct ArCommand {
6132  u8 eCmd;                        /* An AR_CMD_* value */
6133  u8 bVerbose;                    /* True if --verbose */
6134  u8 bZip;                        /* True if the archive is a ZIP */
6135  u8 bDryRun;                     /* True if --dry-run */
6136  u8 bAppend;                     /* True if --append */
6137  u8 bGlob;                       /* True if --glob */
6138  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6139  int nArg;                       /* Number of command arguments */
6140  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6141  const char *zFile;              /* --file argument, or NULL */
6142  const char *zDir;               /* --directory argument, or NULL */
6143  char **azArg;                   /* Array of command arguments */
6144  ShellState *p;                  /* Shell state */
6145  sqlite3 *db;                    /* Database containing the archive */
6146};
6147
6148/*
6149** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6150*/
6151static int arUsage(FILE *f){
6152  showHelp(f,"archive");
6153  return SQLITE_ERROR;
6154}
6155
6156/*
6157** Print an error message for the .ar command to stderr and return
6158** SQLITE_ERROR.
6159*/
6160static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6161  va_list ap;
6162  char *z;
6163  va_start(ap, zFmt);
6164  z = sqlite3_vmprintf(zFmt, ap);
6165  va_end(ap);
6166  utf8_printf(stderr, "Error: %s\n", z);
6167  if( pAr->fromCmdLine ){
6168    utf8_printf(stderr, "Use \"-A\" for more help\n");
6169  }else{
6170    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6171  }
6172  sqlite3_free(z);
6173  return SQLITE_ERROR;
6174}
6175
6176/*
6177** Values for ArCommand.eCmd.
6178*/
6179#define AR_CMD_CREATE       1
6180#define AR_CMD_UPDATE       2
6181#define AR_CMD_INSERT       3
6182#define AR_CMD_EXTRACT      4
6183#define AR_CMD_LIST         5
6184#define AR_CMD_HELP         6
6185#define AR_CMD_REMOVE       7
6186
6187/*
6188** Other (non-command) switches.
6189*/
6190#define AR_SWITCH_VERBOSE     8
6191#define AR_SWITCH_FILE        9
6192#define AR_SWITCH_DIRECTORY  10
6193#define AR_SWITCH_APPEND     11
6194#define AR_SWITCH_DRYRUN     12
6195#define AR_SWITCH_GLOB       13
6196
6197static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6198  switch( eSwitch ){
6199    case AR_CMD_CREATE:
6200    case AR_CMD_EXTRACT:
6201    case AR_CMD_LIST:
6202    case AR_CMD_REMOVE:
6203    case AR_CMD_UPDATE:
6204    case AR_CMD_INSERT:
6205    case AR_CMD_HELP:
6206      if( pAr->eCmd ){
6207        return arErrorMsg(pAr, "multiple command options");
6208      }
6209      pAr->eCmd = eSwitch;
6210      break;
6211
6212    case AR_SWITCH_DRYRUN:
6213      pAr->bDryRun = 1;
6214      break;
6215    case AR_SWITCH_GLOB:
6216      pAr->bGlob = 1;
6217      break;
6218    case AR_SWITCH_VERBOSE:
6219      pAr->bVerbose = 1;
6220      break;
6221    case AR_SWITCH_APPEND:
6222      pAr->bAppend = 1;
6223      /* Fall thru into --file */
6224    case AR_SWITCH_FILE:
6225      pAr->zFile = zArg;
6226      break;
6227    case AR_SWITCH_DIRECTORY:
6228      pAr->zDir = zArg;
6229      break;
6230  }
6231
6232  return SQLITE_OK;
6233}
6234
6235/*
6236** Parse the command line for an ".ar" command. The results are written into
6237** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6238** successfully, otherwise an error message is written to stderr and
6239** SQLITE_ERROR returned.
6240*/
6241static int arParseCommand(
6242  char **azArg,                   /* Array of arguments passed to dot command */
6243  int nArg,                       /* Number of entries in azArg[] */
6244  ArCommand *pAr                  /* Populate this object */
6245){
6246  struct ArSwitch {
6247    const char *zLong;
6248    char cShort;
6249    u8 eSwitch;
6250    u8 bArg;
6251  } aSwitch[] = {
6252    { "create",    'c', AR_CMD_CREATE,       0 },
6253    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6254    { "insert",    'i', AR_CMD_INSERT,       0 },
6255    { "list",      't', AR_CMD_LIST,         0 },
6256    { "remove",    'r', AR_CMD_REMOVE,       0 },
6257    { "update",    'u', AR_CMD_UPDATE,       0 },
6258    { "help",      'h', AR_CMD_HELP,         0 },
6259    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6260    { "file",      'f', AR_SWITCH_FILE,      1 },
6261    { "append",    'a', AR_SWITCH_APPEND,    1 },
6262    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6263    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6264    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6265  };
6266  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6267  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6268
6269  if( nArg<=1 ){
6270    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6271    return arUsage(stderr);
6272  }else{
6273    char *z = azArg[1];
6274    if( z[0]!='-' ){
6275      /* Traditional style [tar] invocation */
6276      int i;
6277      int iArg = 2;
6278      for(i=0; z[i]; i++){
6279        const char *zArg = 0;
6280        struct ArSwitch *pOpt;
6281        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6282          if( z[i]==pOpt->cShort ) break;
6283        }
6284        if( pOpt==pEnd ){
6285          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6286        }
6287        if( pOpt->bArg ){
6288          if( iArg>=nArg ){
6289            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6290          }
6291          zArg = azArg[iArg++];
6292        }
6293        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6294      }
6295      pAr->nArg = nArg-iArg;
6296      if( pAr->nArg>0 ){
6297        pAr->azArg = &azArg[iArg];
6298      }
6299    }else{
6300      /* Non-traditional invocation */
6301      int iArg;
6302      for(iArg=1; iArg<nArg; iArg++){
6303        int n;
6304        z = azArg[iArg];
6305        if( z[0]!='-' ){
6306          /* All remaining command line words are command arguments. */
6307          pAr->azArg = &azArg[iArg];
6308          pAr->nArg = nArg-iArg;
6309          break;
6310        }
6311        n = strlen30(z);
6312
6313        if( z[1]!='-' ){
6314          int i;
6315          /* One or more short options */
6316          for(i=1; i<n; i++){
6317            const char *zArg = 0;
6318            struct ArSwitch *pOpt;
6319            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6320              if( z[i]==pOpt->cShort ) break;
6321            }
6322            if( pOpt==pEnd ){
6323              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6324            }
6325            if( pOpt->bArg ){
6326              if( i<(n-1) ){
6327                zArg = &z[i+1];
6328                i = n;
6329              }else{
6330                if( iArg>=(nArg-1) ){
6331                  return arErrorMsg(pAr, "option requires an argument: %c",
6332                                    z[i]);
6333                }
6334                zArg = azArg[++iArg];
6335              }
6336            }
6337            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6338          }
6339        }else if( z[2]=='\0' ){
6340          /* A -- option, indicating that all remaining command line words
6341          ** are command arguments.  */
6342          pAr->azArg = &azArg[iArg+1];
6343          pAr->nArg = nArg-iArg-1;
6344          break;
6345        }else{
6346          /* A long option */
6347          const char *zArg = 0;             /* Argument for option, if any */
6348          struct ArSwitch *pMatch = 0;      /* Matching option */
6349          struct ArSwitch *pOpt;            /* Iterator */
6350          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6351            const char *zLong = pOpt->zLong;
6352            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6353              if( pMatch ){
6354                return arErrorMsg(pAr, "ambiguous option: %s",z);
6355              }else{
6356                pMatch = pOpt;
6357              }
6358            }
6359          }
6360
6361          if( pMatch==0 ){
6362            return arErrorMsg(pAr, "unrecognized option: %s", z);
6363          }
6364          if( pMatch->bArg ){
6365            if( iArg>=(nArg-1) ){
6366              return arErrorMsg(pAr, "option requires an argument: %s", z);
6367            }
6368            zArg = azArg[++iArg];
6369          }
6370          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6371        }
6372      }
6373    }
6374  }
6375
6376  return SQLITE_OK;
6377}
6378
6379/*
6380** This function assumes that all arguments within the ArCommand.azArg[]
6381** array refer to archive members, as for the --extract, --list or --remove
6382** commands. It checks that each of them are "present". If any specified
6383** file is not present in the archive, an error is printed to stderr and an
6384** error code returned. Otherwise, if all specified arguments are present
6385** in the archive, SQLITE_OK is returned. Here, "present" means either an
6386** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6387** when pAr->bGlob is true.
6388**
6389** This function strips any trailing '/' characters from each argument.
6390** This is consistent with the way the [tar] command seems to work on
6391** Linux.
6392*/
6393static int arCheckEntries(ArCommand *pAr){
6394  int rc = SQLITE_OK;
6395  if( pAr->nArg ){
6396    int i, j;
6397    sqlite3_stmt *pTest = 0;
6398    const char *zSel = (pAr->bGlob)
6399      ? "SELECT name FROM %s WHERE glob($name,name)"
6400      : "SELECT name FROM %s WHERE name=$name";
6401
6402    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6403    j = sqlite3_bind_parameter_index(pTest, "$name");
6404    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6405      char *z = pAr->azArg[i];
6406      int n = strlen30(z);
6407      int bOk = 0;
6408      while( n>0 && z[n-1]=='/' ) n--;
6409      z[n] = '\0';
6410      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6411      if( SQLITE_ROW==sqlite3_step(pTest) ){
6412        bOk = 1;
6413      }
6414      shellReset(&rc, pTest);
6415      if( rc==SQLITE_OK && bOk==0 ){
6416        utf8_printf(stderr, "not found in archive: %s\n", z);
6417        rc = SQLITE_ERROR;
6418      }
6419    }
6420    shellFinalize(&rc, pTest);
6421  }
6422  return rc;
6423}
6424
6425/*
6426** Format a WHERE clause that can be used against the "sqlar" table to
6427** identify all archive members that match the command arguments held
6428** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6429** The caller is responsible for eventually calling sqlite3_free() on
6430** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6431** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6432*/
6433static void arWhereClause(
6434  int *pRc,
6435  ArCommand *pAr,
6436  char **pzWhere                  /* OUT: New WHERE clause */
6437){
6438  char *zWhere = 0;
6439  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6440  if( *pRc==SQLITE_OK ){
6441    if( pAr->nArg==0 ){
6442      zWhere = sqlite3_mprintf("1");
6443    }else{
6444      int i;
6445      const char *zSep = "";
6446      for(i=0; i<pAr->nArg; i++){
6447        const char *z = pAr->azArg[i];
6448        zWhere = sqlite3_mprintf(
6449          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6450          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6451        );
6452        if( zWhere==0 ){
6453          *pRc = SQLITE_NOMEM;
6454          break;
6455        }
6456        zSep = " OR ";
6457      }
6458    }
6459  }
6460  *pzWhere = zWhere;
6461}
6462
6463/*
6464** Implementation of .ar "lisT" command.
6465*/
6466static int arListCommand(ArCommand *pAr){
6467  const char *zSql = "SELECT %s FROM %s WHERE %s";
6468  const char *azCols[] = {
6469    "name",
6470    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6471  };
6472
6473  char *zWhere = 0;
6474  sqlite3_stmt *pSql = 0;
6475  int rc;
6476
6477  rc = arCheckEntries(pAr);
6478  arWhereClause(&rc, pAr, &zWhere);
6479
6480  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6481                     pAr->zSrcTable, zWhere);
6482  if( pAr->bDryRun ){
6483    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6484  }else{
6485    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6486      if( pAr->bVerbose ){
6487        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6488            sqlite3_column_text(pSql, 0),
6489            sqlite3_column_int(pSql, 1),
6490            sqlite3_column_text(pSql, 2),
6491            sqlite3_column_text(pSql, 3)
6492        );
6493      }else{
6494        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6495      }
6496    }
6497  }
6498  shellFinalize(&rc, pSql);
6499  sqlite3_free(zWhere);
6500  return rc;
6501}
6502
6503
6504/*
6505** Implementation of .ar "Remove" command.
6506*/
6507static int arRemoveCommand(ArCommand *pAr){
6508  int rc = 0;
6509  char *zSql = 0;
6510  char *zWhere = 0;
6511
6512  if( pAr->nArg ){
6513    /* Verify that args actually exist within the archive before proceeding.
6514    ** And formulate a WHERE clause to match them.  */
6515    rc = arCheckEntries(pAr);
6516    arWhereClause(&rc, pAr, &zWhere);
6517  }
6518  if( rc==SQLITE_OK ){
6519    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6520                           pAr->zSrcTable, zWhere);
6521    if( pAr->bDryRun ){
6522      utf8_printf(pAr->p->out, "%s\n", zSql);
6523    }else{
6524      char *zErr = 0;
6525      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6526      if( rc==SQLITE_OK ){
6527        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6528        if( rc!=SQLITE_OK ){
6529          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6530        }else{
6531          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6532        }
6533      }
6534      if( zErr ){
6535        utf8_printf(stdout, "ERROR: %s\n", zErr);
6536        sqlite3_free(zErr);
6537      }
6538    }
6539  }
6540  sqlite3_free(zWhere);
6541  sqlite3_free(zSql);
6542  return rc;
6543}
6544
6545/*
6546** Implementation of .ar "eXtract" command.
6547*/
6548static int arExtractCommand(ArCommand *pAr){
6549  const char *zSql1 =
6550    "SELECT "
6551    " ($dir || name),"
6552    " writefile(($dir || name), %s, mode, mtime) "
6553    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6554    " AND name NOT GLOB '*..[/\\]*'";
6555
6556  const char *azExtraArg[] = {
6557    "sqlar_uncompress(data, sz)",
6558    "data"
6559  };
6560
6561  sqlite3_stmt *pSql = 0;
6562  int rc = SQLITE_OK;
6563  char *zDir = 0;
6564  char *zWhere = 0;
6565  int i, j;
6566
6567  /* If arguments are specified, check that they actually exist within
6568  ** the archive before proceeding. And formulate a WHERE clause to
6569  ** match them.  */
6570  rc = arCheckEntries(pAr);
6571  arWhereClause(&rc, pAr, &zWhere);
6572
6573  if( rc==SQLITE_OK ){
6574    if( pAr->zDir ){
6575      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6576    }else{
6577      zDir = sqlite3_mprintf("");
6578    }
6579    if( zDir==0 ) rc = SQLITE_NOMEM;
6580  }
6581
6582  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6583      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6584  );
6585
6586  if( rc==SQLITE_OK ){
6587    j = sqlite3_bind_parameter_index(pSql, "$dir");
6588    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6589
6590    /* Run the SELECT statement twice. The first time, writefile() is called
6591    ** for all archive members that should be extracted. The second time,
6592    ** only for the directories. This is because the timestamps for
6593    ** extracted directories must be reset after they are populated (as
6594    ** populating them changes the timestamp).  */
6595    for(i=0; i<2; i++){
6596      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6597      sqlite3_bind_int(pSql, j, i);
6598      if( pAr->bDryRun ){
6599        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6600      }else{
6601        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6602          if( i==0 && pAr->bVerbose ){
6603            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6604          }
6605        }
6606      }
6607      shellReset(&rc, pSql);
6608    }
6609    shellFinalize(&rc, pSql);
6610  }
6611
6612  sqlite3_free(zDir);
6613  sqlite3_free(zWhere);
6614  return rc;
6615}
6616
6617/*
6618** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6619*/
6620static int arExecSql(ArCommand *pAr, const char *zSql){
6621  int rc;
6622  if( pAr->bDryRun ){
6623    utf8_printf(pAr->p->out, "%s\n", zSql);
6624    rc = SQLITE_OK;
6625  }else{
6626    char *zErr = 0;
6627    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6628    if( zErr ){
6629      utf8_printf(stdout, "ERROR: %s\n", zErr);
6630      sqlite3_free(zErr);
6631    }
6632  }
6633  return rc;
6634}
6635
6636
6637/*
6638** Implementation of .ar "create", "insert", and "update" commands.
6639**
6640**     create    ->     Create a new SQL archive
6641**     insert    ->     Insert or reinsert all files listed
6642**     update    ->     Insert files that have changed or that were not
6643**                      previously in the archive
6644**
6645** Create the "sqlar" table in the database if it does not already exist.
6646** Then add each file in the azFile[] array to the archive. Directories
6647** are added recursively. If argument bVerbose is non-zero, a message is
6648** printed on stdout for each file archived.
6649**
6650** The create command is the same as update, except that it drops
6651** any existing "sqlar" table before beginning.  The "insert" command
6652** always overwrites every file named on the command-line, where as
6653** "update" only overwrites if the size or mtime or mode has changed.
6654*/
6655static int arCreateOrUpdateCommand(
6656  ArCommand *pAr,                 /* Command arguments and options */
6657  int bUpdate,                    /* true for a --create. */
6658  int bOnlyIfChanged              /* Only update if file has changed */
6659){
6660  const char *zCreate =
6661      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6662      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6663      "  mode INT,               -- access permissions\n"
6664      "  mtime INT,              -- last modification time\n"
6665      "  sz INT,                 -- original file size\n"
6666      "  data BLOB               -- compressed content\n"
6667      ")";
6668  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6669  const char *zInsertFmt[2] = {
6670     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6671     "  SELECT\n"
6672     "    %s,\n"
6673     "    mode,\n"
6674     "    mtime,\n"
6675     "    CASE substr(lsmode(mode),1,1)\n"
6676     "      WHEN '-' THEN length(data)\n"
6677     "      WHEN 'd' THEN 0\n"
6678     "      ELSE -1 END,\n"
6679     "    sqlar_compress(data)\n"
6680     "  FROM fsdir(%Q,%Q) AS disk\n"
6681     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6682     ,
6683     "REPLACE INTO %s(name,mode,mtime,data)\n"
6684     "  SELECT\n"
6685     "    %s,\n"
6686     "    mode,\n"
6687     "    mtime,\n"
6688     "    data\n"
6689     "  FROM fsdir(%Q,%Q) AS disk\n"
6690     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6691  };
6692  int i;                          /* For iterating through azFile[] */
6693  int rc;                         /* Return code */
6694  const char *zTab = 0;           /* SQL table into which to insert */
6695  char *zSql;
6696  char zTemp[50];
6697  char *zExists = 0;
6698
6699  arExecSql(pAr, "PRAGMA page_size=512");
6700  rc = arExecSql(pAr, "SAVEPOINT ar;");
6701  if( rc!=SQLITE_OK ) return rc;
6702  zTemp[0] = 0;
6703  if( pAr->bZip ){
6704    /* Initialize the zipfile virtual table, if necessary */
6705    if( pAr->zFile ){
6706      sqlite3_uint64 r;
6707      sqlite3_randomness(sizeof(r),&r);
6708      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6709      zTab = zTemp;
6710      zSql = sqlite3_mprintf(
6711         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6712         zTab, pAr->zFile
6713      );
6714      rc = arExecSql(pAr, zSql);
6715      sqlite3_free(zSql);
6716    }else{
6717      zTab = "zip";
6718    }
6719  }else{
6720    /* Initialize the table for an SQLAR */
6721    zTab = "sqlar";
6722    if( bUpdate==0 ){
6723      rc = arExecSql(pAr, zDrop);
6724      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6725    }
6726    rc = arExecSql(pAr, zCreate);
6727  }
6728  if( bOnlyIfChanged ){
6729    zExists = sqlite3_mprintf(
6730      " AND NOT EXISTS("
6731          "SELECT 1 FROM %s AS mem"
6732          " WHERE mem.name=disk.name"
6733          " AND mem.mtime=disk.mtime"
6734          " AND mem.mode=disk.mode)", zTab);
6735  }else{
6736    zExists = sqlite3_mprintf("");
6737  }
6738  if( zExists==0 ) rc = SQLITE_NOMEM;
6739  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6740    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6741        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6742        pAr->azArg[i], pAr->zDir, zExists);
6743    rc = arExecSql(pAr, zSql2);
6744    sqlite3_free(zSql2);
6745  }
6746end_ar_transaction:
6747  if( rc!=SQLITE_OK ){
6748    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6749  }else{
6750    rc = arExecSql(pAr, "RELEASE ar;");
6751    if( pAr->bZip && pAr->zFile ){
6752      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6753      arExecSql(pAr, zSql);
6754      sqlite3_free(zSql);
6755    }
6756  }
6757  sqlite3_free(zExists);
6758  return rc;
6759}
6760
6761/*
6762** Implementation of ".ar" dot command.
6763*/
6764static int arDotCommand(
6765  ShellState *pState,          /* Current shell tool state */
6766  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
6767  char **azArg,                /* Array of arguments passed to dot command */
6768  int nArg                     /* Number of entries in azArg[] */
6769){
6770  ArCommand cmd;
6771  int rc;
6772  memset(&cmd, 0, sizeof(cmd));
6773  cmd.fromCmdLine = fromCmdLine;
6774  rc = arParseCommand(azArg, nArg, &cmd);
6775  if( rc==SQLITE_OK ){
6776    int eDbType = SHELL_OPEN_UNSPEC;
6777    cmd.p = pState;
6778    cmd.db = pState->db;
6779    if( cmd.zFile ){
6780      eDbType = deduceDatabaseType(cmd.zFile, 1);
6781    }else{
6782      eDbType = pState->openMode;
6783    }
6784    if( eDbType==SHELL_OPEN_ZIPFILE ){
6785      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6786        if( cmd.zFile==0 ){
6787          cmd.zSrcTable = sqlite3_mprintf("zip");
6788        }else{
6789          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6790        }
6791      }
6792      cmd.bZip = 1;
6793    }else if( cmd.zFile ){
6794      int flags;
6795      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6796      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6797           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
6798        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6799      }else{
6800        flags = SQLITE_OPEN_READONLY;
6801      }
6802      cmd.db = 0;
6803      if( cmd.bDryRun ){
6804        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6805             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6806      }
6807      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6808             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6809      if( rc!=SQLITE_OK ){
6810        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6811            cmd.zFile, sqlite3_errmsg(cmd.db)
6812        );
6813        goto end_ar_command;
6814      }
6815      sqlite3_fileio_init(cmd.db, 0, 0);
6816      sqlite3_sqlar_init(cmd.db, 0, 0);
6817      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6818                              shellPutsFunc, 0, 0);
6819
6820    }
6821    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6822      if( cmd.eCmd!=AR_CMD_CREATE
6823       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6824      ){
6825        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6826        rc = SQLITE_ERROR;
6827        goto end_ar_command;
6828      }
6829      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6830    }
6831
6832    switch( cmd.eCmd ){
6833      case AR_CMD_CREATE:
6834        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6835        break;
6836
6837      case AR_CMD_EXTRACT:
6838        rc = arExtractCommand(&cmd);
6839        break;
6840
6841      case AR_CMD_LIST:
6842        rc = arListCommand(&cmd);
6843        break;
6844
6845      case AR_CMD_HELP:
6846        arUsage(pState->out);
6847        break;
6848
6849      case AR_CMD_INSERT:
6850        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6851        break;
6852
6853      case AR_CMD_REMOVE:
6854        rc = arRemoveCommand(&cmd);
6855        break;
6856
6857      default:
6858        assert( cmd.eCmd==AR_CMD_UPDATE );
6859        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6860        break;
6861    }
6862  }
6863end_ar_command:
6864  if( cmd.db!=pState->db ){
6865    close_db(cmd.db);
6866  }
6867  sqlite3_free(cmd.zSrcTable);
6868
6869  return rc;
6870}
6871/* End of the ".archive" or ".ar" command logic
6872*******************************************************************************/
6873#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6874
6875#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6876/*
6877** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6878** Otherwise, the SQL statement or statements in zSql are executed using
6879** database connection db and the error code written to *pRc before
6880** this function returns.
6881*/
6882static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6883  int rc = *pRc;
6884  if( rc==SQLITE_OK ){
6885    char *zErr = 0;
6886    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6887    if( rc!=SQLITE_OK ){
6888      raw_printf(stderr, "SQL error: %s\n", zErr);
6889    }
6890    sqlite3_free(zErr);
6891    *pRc = rc;
6892  }
6893}
6894
6895/*
6896** Like shellExec(), except that zFmt is a printf() style format string.
6897*/
6898static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6899  char *z = 0;
6900  if( *pRc==SQLITE_OK ){
6901    va_list ap;
6902    va_start(ap, zFmt);
6903    z = sqlite3_vmprintf(zFmt, ap);
6904    va_end(ap);
6905    if( z==0 ){
6906      *pRc = SQLITE_NOMEM;
6907    }else{
6908      shellExec(db, pRc, z);
6909    }
6910    sqlite3_free(z);
6911  }
6912}
6913
6914/*
6915** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6916** Otherwise, an attempt is made to allocate, zero and return a pointer
6917** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6918** to SQLITE_NOMEM and NULL returned.
6919*/
6920static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6921  void *pRet = 0;
6922  if( *pRc==SQLITE_OK ){
6923    pRet = sqlite3_malloc64(nByte);
6924    if( pRet==0 ){
6925      *pRc = SQLITE_NOMEM;
6926    }else{
6927      memset(pRet, 0, nByte);
6928    }
6929  }
6930  return pRet;
6931}
6932
6933/*
6934** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6935** Otherwise, zFmt is treated as a printf() style string. The result of
6936** formatting it along with any trailing arguments is written into a
6937** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6938** It is the responsibility of the caller to eventually free this buffer
6939** using a call to sqlite3_free().
6940**
6941** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6942** pointer returned.
6943*/
6944static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6945  char *z = 0;
6946  if( *pRc==SQLITE_OK ){
6947    va_list ap;
6948    va_start(ap, zFmt);
6949    z = sqlite3_vmprintf(zFmt, ap);
6950    va_end(ap);
6951    if( z==0 ){
6952      *pRc = SQLITE_NOMEM;
6953    }
6954  }
6955  return z;
6956}
6957
6958/*
6959** When running the ".recover" command, each output table, and the special
6960** orphaned row table if it is required, is represented by an instance
6961** of the following struct.
6962*/
6963typedef struct RecoverTable RecoverTable;
6964struct RecoverTable {
6965  char *zQuoted;                  /* Quoted version of table name */
6966  int nCol;                       /* Number of columns in table */
6967  char **azlCol;                  /* Array of column lists */
6968  int iPk;                        /* Index of IPK column */
6969};
6970
6971/*
6972** Free a RecoverTable object allocated by recoverFindTable() or
6973** recoverOrphanTable().
6974*/
6975static void recoverFreeTable(RecoverTable *pTab){
6976  if( pTab ){
6977    sqlite3_free(pTab->zQuoted);
6978    if( pTab->azlCol ){
6979      int i;
6980      for(i=0; i<=pTab->nCol; i++){
6981        sqlite3_free(pTab->azlCol[i]);
6982      }
6983      sqlite3_free(pTab->azlCol);
6984    }
6985    sqlite3_free(pTab);
6986  }
6987}
6988
6989/*
6990** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6991** Otherwise, it allocates and returns a RecoverTable object based on the
6992** final four arguments passed to this function. It is the responsibility
6993** of the caller to eventually free the returned object using
6994** recoverFreeTable().
6995*/
6996static RecoverTable *recoverNewTable(
6997  int *pRc,                       /* IN/OUT: Error code */
6998  const char *zName,              /* Name of table */
6999  const char *zSql,               /* CREATE TABLE statement */
7000  int bIntkey,
7001  int nCol
7002){
7003  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7004  int rc = *pRc;
7005  RecoverTable *pTab = 0;
7006
7007  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7008  if( rc==SQLITE_OK ){
7009    int nSqlCol = 0;
7010    int bSqlIntkey = 0;
7011    sqlite3_stmt *pStmt = 0;
7012
7013    rc = sqlite3_open("", &dbtmp);
7014    if( rc==SQLITE_OK ){
7015      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7016                              shellIdQuote, 0, 0);
7017    }
7018    if( rc==SQLITE_OK ){
7019      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7020    }
7021    if( rc==SQLITE_OK ){
7022      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7023      if( rc==SQLITE_ERROR ){
7024        rc = SQLITE_OK;
7025        goto finished;
7026      }
7027    }
7028    shellPreparePrintf(dbtmp, &rc, &pStmt,
7029        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7030    );
7031    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7032      nSqlCol = sqlite3_column_int(pStmt, 0);
7033    }
7034    shellFinalize(&rc, pStmt);
7035
7036    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7037      goto finished;
7038    }
7039
7040    shellPreparePrintf(dbtmp, &rc, &pStmt,
7041      "SELECT ("
7042      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7043      ") FROM sqlite_schema WHERE name = %Q", zName
7044    );
7045    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7046      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7047    }
7048    shellFinalize(&rc, pStmt);
7049
7050    if( bIntkey==bSqlIntkey ){
7051      int i;
7052      const char *zPk = "_rowid_";
7053      sqlite3_stmt *pPkFinder = 0;
7054
7055      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7056      ** set zPk to the name of the PK column, and pTab->iPk to the index
7057      ** of the column, where columns are 0-numbered from left to right.
7058      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7059      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7060      pTab->iPk = -2;
7061      if( bIntkey ){
7062        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7063          "SELECT cid, name FROM pragma_table_info(%Q) "
7064          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7065          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7066          , zName, zName
7067        );
7068        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7069          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7070          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7071        }
7072      }
7073
7074      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7075      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7076      pTab->nCol = nSqlCol;
7077
7078      if( bIntkey ){
7079        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7080      }else{
7081        pTab->azlCol[0] = shellMPrintf(&rc, "");
7082      }
7083      i = 1;
7084      shellPreparePrintf(dbtmp, &rc, &pStmt,
7085          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7086          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7087          "FROM pragma_table_info(%Q)",
7088          bIntkey ? ", " : "", pTab->iPk,
7089          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7090          zName
7091      );
7092      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7093        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7094        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7095        i++;
7096      }
7097      shellFinalize(&rc, pStmt);
7098
7099      shellFinalize(&rc, pPkFinder);
7100    }
7101  }
7102
7103 finished:
7104  sqlite3_close(dbtmp);
7105  *pRc = rc;
7106  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7107    recoverFreeTable(pTab);
7108    pTab = 0;
7109  }
7110  return pTab;
7111}
7112
7113/*
7114** This function is called to search the schema recovered from the
7115** sqlite_schema table of the (possibly) corrupt database as part
7116** of a ".recover" command. Specifically, for a table with root page
7117** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7118** table must be a WITHOUT ROWID table, or if non-zero, not one of
7119** those.
7120**
7121** If a table is found, a (RecoverTable*) object is returned. Or, if
7122** no such table is found, but bIntkey is false and iRoot is the
7123** root page of an index in the recovered schema, then (*pbNoop) is
7124** set to true and NULL returned. Or, if there is no such table or
7125** index, NULL is returned and (*pbNoop) set to 0, indicating that
7126** the caller should write data to the orphans table.
7127*/
7128static RecoverTable *recoverFindTable(
7129  ShellState *pState,             /* Shell state object */
7130  int *pRc,                       /* IN/OUT: Error code */
7131  int iRoot,                      /* Root page of table */
7132  int bIntkey,                    /* True for an intkey table */
7133  int nCol,                       /* Number of columns in table */
7134  int *pbNoop                     /* OUT: True if iRoot is root of index */
7135){
7136  sqlite3_stmt *pStmt = 0;
7137  RecoverTable *pRet = 0;
7138  int bNoop = 0;
7139  const char *zSql = 0;
7140  const char *zName = 0;
7141
7142  /* Search the recovered schema for an object with root page iRoot. */
7143  shellPreparePrintf(pState->db, pRc, &pStmt,
7144      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7145  );
7146  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7147    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7148    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7149      bNoop = 1;
7150      break;
7151    }
7152    if( sqlite3_stricmp(zType, "table")==0 ){
7153      zName = (const char*)sqlite3_column_text(pStmt, 1);
7154      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7155      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7156      break;
7157    }
7158  }
7159
7160  shellFinalize(pRc, pStmt);
7161  *pbNoop = bNoop;
7162  return pRet;
7163}
7164
7165/*
7166** Return a RecoverTable object representing the orphans table.
7167*/
7168static RecoverTable *recoverOrphanTable(
7169  ShellState *pState,             /* Shell state object */
7170  int *pRc,                       /* IN/OUT: Error code */
7171  const char *zLostAndFound,      /* Base name for orphans table */
7172  int nCol                        /* Number of user data columns */
7173){
7174  RecoverTable *pTab = 0;
7175  if( nCol>=0 && *pRc==SQLITE_OK ){
7176    int i;
7177
7178    /* This block determines the name of the orphan table. The prefered
7179    ** name is zLostAndFound. But if that clashes with another name
7180    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7181    ** and so on until a non-clashing name is found.  */
7182    int iTab = 0;
7183    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7184    sqlite3_stmt *pTest = 0;
7185    shellPrepare(pState->db, pRc,
7186        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7187    );
7188    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7189    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7190      shellReset(pRc, pTest);
7191      sqlite3_free(zTab);
7192      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7193      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7194    }
7195    shellFinalize(pRc, pTest);
7196
7197    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7198    if( pTab ){
7199      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7200      pTab->nCol = nCol;
7201      pTab->iPk = -2;
7202      if( nCol>0 ){
7203        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7204        if( pTab->azlCol ){
7205          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7206          for(i=nCol-1; i>=0; i--){
7207            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7208          }
7209        }
7210      }
7211
7212      if( *pRc!=SQLITE_OK ){
7213        recoverFreeTable(pTab);
7214        pTab = 0;
7215      }else{
7216        raw_printf(pState->out,
7217            "CREATE TABLE %s(rootpgno INTEGER, "
7218            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7219        );
7220        for(i=0; i<nCol; i++){
7221          raw_printf(pState->out, ", c%d", i);
7222        }
7223        raw_printf(pState->out, ");\n");
7224      }
7225    }
7226    sqlite3_free(zTab);
7227  }
7228  return pTab;
7229}
7230
7231/*
7232** This function is called to recover data from the database. A script
7233** to construct a new database containing all recovered data is output
7234** on stream pState->out.
7235*/
7236static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7237  int rc = SQLITE_OK;
7238  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7239  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7240  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7241  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7242  const char *zLostAndFound = "lost_and_found";
7243  int i;
7244  int nOrphan = -1;
7245  RecoverTable *pOrphan = 0;
7246
7247  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7248  int bRowids = 1;                /* 0 if --no-rowids */
7249  for(i=1; i<nArg; i++){
7250    char *z = azArg[i];
7251    int n;
7252    if( z[0]=='-' && z[1]=='-' ) z++;
7253    n = strlen30(z);
7254    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7255      bFreelist = 0;
7256    }else
7257    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7258      i++;
7259      zRecoveryDb = azArg[i];
7260    }else
7261    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7262      i++;
7263      zLostAndFound = azArg[i];
7264    }else
7265    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7266      bRowids = 0;
7267    }
7268    else{
7269      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7270      showHelp(pState->out, azArg[0]);
7271      return 1;
7272    }
7273  }
7274
7275  shellExecPrintf(pState->db, &rc,
7276    /* Attach an in-memory database named 'recovery'. Create an indexed
7277    ** cache of the sqlite_dbptr virtual table. */
7278    "PRAGMA writable_schema = on;"
7279    "ATTACH %Q AS recovery;"
7280    "DROP TABLE IF EXISTS recovery.dbptr;"
7281    "DROP TABLE IF EXISTS recovery.freelist;"
7282    "DROP TABLE IF EXISTS recovery.map;"
7283    "DROP TABLE IF EXISTS recovery.schema;"
7284    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7285  );
7286
7287  if( bFreelist ){
7288    shellExec(pState->db, &rc,
7289      "WITH trunk(pgno) AS ("
7290      "  SELECT shell_int32("
7291      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7292      "      WHERE x>0"
7293      "    UNION"
7294      "  SELECT shell_int32("
7295      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7296      "      FROM trunk WHERE x>0"
7297      "),"
7298      "freelist(data, n, freepgno) AS ("
7299      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7300      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7301      "    UNION ALL"
7302      "  SELECT data, n-1, shell_int32(data, 2+n) "
7303      "      FROM freelist WHERE n>=0"
7304      ")"
7305      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7306    );
7307  }
7308
7309  /* If this is an auto-vacuum database, add all pointer-map pages to
7310  ** the freelist table. Do this regardless of whether or not
7311  ** --freelist-corrupt was specified.  */
7312  shellExec(pState->db, &rc,
7313    "WITH ptrmap(pgno) AS ("
7314    "  SELECT 2 WHERE shell_int32("
7315    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7316    "  )"
7317    "    UNION ALL "
7318    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7319    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7320    ")"
7321    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7322  );
7323
7324  shellExec(pState->db, &rc,
7325    "CREATE TABLE recovery.dbptr("
7326    "      pgno, child, PRIMARY KEY(child, pgno)"
7327    ") WITHOUT ROWID;"
7328    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7329    "    SELECT * FROM sqlite_dbptr"
7330    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7331
7332    /* Delete any pointer to page 1. This ensures that page 1 is considered
7333    ** a root page, regardless of how corrupt the db is. */
7334    "DELETE FROM recovery.dbptr WHERE child = 1;"
7335
7336    /* Delete all pointers to any pages that have more than one pointer
7337    ** to them. Such pages will be treated as root pages when recovering
7338    ** data.  */
7339    "DELETE FROM recovery.dbptr WHERE child IN ("
7340    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7341    ");"
7342
7343    /* Create the "map" table that will (eventually) contain instructions
7344    ** for dealing with each page in the db that contains one or more
7345    ** records. */
7346    "CREATE TABLE recovery.map("
7347      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7348    ");"
7349
7350    /* Populate table [map]. If there are circular loops of pages in the
7351    ** database, the following adds all pages in such a loop to the map
7352    ** as individual root pages. This could be handled better.  */
7353    "WITH pages(i, maxlen) AS ("
7354    "  SELECT page_count, ("
7355    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7356    "  ) FROM pragma_page_count WHERE page_count>0"
7357    "    UNION ALL"
7358    "  SELECT i-1, ("
7359    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7360    "  ) FROM pages WHERE i>=2"
7361    ")"
7362    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7363    "  SELECT i, maxlen, NULL, ("
7364    "    WITH p(orig, pgno, parent) AS ("
7365    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7366    "        UNION "
7367    "      SELECT i, p.parent, "
7368    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7369    "    )"
7370    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7371    ") "
7372    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7373    "UPDATE recovery.map AS o SET intkey = ("
7374    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7375    ");"
7376
7377    /* Extract data from page 1 and any linked pages into table
7378    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7379    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7380    "INSERT INTO recovery.schema SELECT "
7381    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7382    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7383    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7384    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7385    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7386    "FROM sqlite_dbdata WHERE pgno IN ("
7387    "  SELECT pgno FROM recovery.map WHERE root=1"
7388    ")"
7389    "GROUP BY pgno, cell;"
7390    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7391  );
7392
7393  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7394  ** CREATE TABLE statements that extracted from the existing schema.  */
7395  if( rc==SQLITE_OK ){
7396    sqlite3_stmt *pStmt = 0;
7397    /* ".recover" might output content in an order which causes immediate
7398    ** foreign key constraints to be violated. So disable foreign-key
7399    ** constraint enforcement to prevent problems when running the output
7400    ** script. */
7401    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7402    raw_printf(pState->out, "BEGIN;\n");
7403    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7404    shellPrepare(pState->db, &rc,
7405        "SELECT sql FROM recovery.schema "
7406        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7407    );
7408    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7409      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7410      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7411          &zCreateTable[12]
7412      );
7413    }
7414    shellFinalize(&rc, pStmt);
7415  }
7416
7417  /* Figure out if an orphan table will be required. And if so, how many
7418  ** user columns it should contain */
7419  shellPrepare(pState->db, &rc,
7420      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7421      , &pLoop
7422  );
7423  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7424    nOrphan = sqlite3_column_int(pLoop, 0);
7425  }
7426  shellFinalize(&rc, pLoop);
7427  pLoop = 0;
7428
7429  shellPrepare(pState->db, &rc,
7430      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7431  );
7432
7433  shellPrepare(pState->db, &rc,
7434      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7435      "(case when (? AND field<0) then NULL else value end)"
7436      "), ', ')"
7437      ", min(field) "
7438      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7439      "GROUP BY cell", &pCells
7440  );
7441
7442  /* Loop through each root page. */
7443  shellPrepare(pState->db, &rc,
7444      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7445      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7446      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7447      ")", &pLoop
7448  );
7449  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7450    int iRoot = sqlite3_column_int(pLoop, 0);
7451    int bIntkey = sqlite3_column_int(pLoop, 1);
7452    int nCol = sqlite3_column_int(pLoop, 2);
7453    int bNoop = 0;
7454    RecoverTable *pTab;
7455
7456    assert( bIntkey==0 || bIntkey==1 );
7457    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7458    if( bNoop || rc ) continue;
7459    if( pTab==0 ){
7460      if( pOrphan==0 ){
7461        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7462      }
7463      pTab = pOrphan;
7464      if( pTab==0 ) break;
7465    }
7466
7467    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7468      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7469    }
7470    sqlite3_bind_int(pPages, 1, iRoot);
7471    if( bRowids==0 && pTab->iPk<0 ){
7472      sqlite3_bind_int(pCells, 1, 1);
7473    }else{
7474      sqlite3_bind_int(pCells, 1, 0);
7475    }
7476    sqlite3_bind_int(pCells, 3, pTab->iPk);
7477
7478    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7479      int iPgno = sqlite3_column_int(pPages, 0);
7480      sqlite3_bind_int(pCells, 2, iPgno);
7481      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7482        int nField = sqlite3_column_int(pCells, 0);
7483        int iMin = sqlite3_column_int(pCells, 2);
7484        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7485
7486        RecoverTable *pTab2 = pTab;
7487        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7488          if( pOrphan==0 ){
7489            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7490          }
7491          pTab2 = pOrphan;
7492          if( pTab2==0 ) break;
7493        }
7494
7495        nField = nField+1;
7496        if( pTab2==pOrphan ){
7497          raw_printf(pState->out,
7498              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7499              pTab2->zQuoted, iRoot, iPgno, nField,
7500              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7501          );
7502        }else{
7503          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7504              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7505          );
7506        }
7507      }
7508      shellReset(&rc, pCells);
7509    }
7510    shellReset(&rc, pPages);
7511    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7512  }
7513  shellFinalize(&rc, pLoop);
7514  shellFinalize(&rc, pPages);
7515  shellFinalize(&rc, pCells);
7516  recoverFreeTable(pOrphan);
7517
7518  /* The rest of the schema */
7519  if( rc==SQLITE_OK ){
7520    sqlite3_stmt *pStmt = 0;
7521    shellPrepare(pState->db, &rc,
7522        "SELECT sql, name FROM recovery.schema "
7523        "WHERE sql NOT LIKE 'create table%'", &pStmt
7524    );
7525    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7526      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7527      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7528        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7529        char *zPrint = shellMPrintf(&rc,
7530          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7531          zName, zName, zSql
7532        );
7533        raw_printf(pState->out, "%s;\n", zPrint);
7534        sqlite3_free(zPrint);
7535      }else{
7536        raw_printf(pState->out, "%s;\n", zSql);
7537      }
7538    }
7539    shellFinalize(&rc, pStmt);
7540  }
7541
7542  if( rc==SQLITE_OK ){
7543    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7544    raw_printf(pState->out, "COMMIT;\n");
7545  }
7546  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7547  return rc;
7548}
7549#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7550
7551/*
7552** If an input line begins with "." then invoke this routine to
7553** process that line.
7554**
7555** Return 1 on error, 2 to exit, and 0 otherwise.
7556*/
7557static int do_meta_command(char *zLine, ShellState *p){
7558  int h = 1;
7559  int nArg = 0;
7560  int n, c;
7561  int rc = 0;
7562  char *azArg[52];
7563
7564#ifndef SQLITE_OMIT_VIRTUALTABLE
7565  if( p->expert.pExpert ){
7566    expertFinish(p, 1, 0);
7567  }
7568#endif
7569
7570  /* Parse the input line into tokens.
7571  */
7572  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7573    while( IsSpace(zLine[h]) ){ h++; }
7574    if( zLine[h]==0 ) break;
7575    if( zLine[h]=='\'' || zLine[h]=='"' ){
7576      int delim = zLine[h++];
7577      azArg[nArg++] = &zLine[h];
7578      while( zLine[h] && zLine[h]!=delim ){
7579        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7580        h++;
7581      }
7582      if( zLine[h]==delim ){
7583        zLine[h++] = 0;
7584      }
7585      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7586    }else{
7587      azArg[nArg++] = &zLine[h];
7588      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7589      if( zLine[h] ) zLine[h++] = 0;
7590      resolve_backslashes(azArg[nArg-1]);
7591    }
7592  }
7593  azArg[nArg] = 0;
7594
7595  /* Process the input line.
7596  */
7597  if( nArg==0 ) return 0; /* no tokens, no error */
7598  n = strlen30(azArg[0]);
7599  c = azArg[0][0];
7600  clearTempFile(p);
7601
7602#ifndef SQLITE_OMIT_AUTHORIZATION
7603  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7604    if( nArg!=2 ){
7605      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7606      rc = 1;
7607      goto meta_command_exit;
7608    }
7609    open_db(p, 0);
7610    if( booleanValue(azArg[1]) ){
7611      sqlite3_set_authorizer(p->db, shellAuth, p);
7612    }else if( p->bSafeModePersist ){
7613      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7614    }else{
7615      sqlite3_set_authorizer(p->db, 0, 0);
7616    }
7617  }else
7618#endif
7619
7620#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7621  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7622    open_db(p, 0);
7623    failIfSafeMode(p, "cannot run .archive in safe mode");
7624    rc = arDotCommand(p, 0, azArg, nArg);
7625  }else
7626#endif
7627
7628  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7629   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7630  ){
7631    const char *zDestFile = 0;
7632    const char *zDb = 0;
7633    sqlite3 *pDest;
7634    sqlite3_backup *pBackup;
7635    int j;
7636    int bAsync = 0;
7637    const char *zVfs = 0;
7638    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7639    for(j=1; j<nArg; j++){
7640      const char *z = azArg[j];
7641      if( z[0]=='-' ){
7642        if( z[1]=='-' ) z++;
7643        if( strcmp(z, "-append")==0 ){
7644          zVfs = "apndvfs";
7645        }else
7646        if( strcmp(z, "-async")==0 ){
7647          bAsync = 1;
7648        }else
7649        {
7650          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7651          return 1;
7652        }
7653      }else if( zDestFile==0 ){
7654        zDestFile = azArg[j];
7655      }else if( zDb==0 ){
7656        zDb = zDestFile;
7657        zDestFile = azArg[j];
7658      }else{
7659        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7660        return 1;
7661      }
7662    }
7663    if( zDestFile==0 ){
7664      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7665      return 1;
7666    }
7667    if( zDb==0 ) zDb = "main";
7668    rc = sqlite3_open_v2(zDestFile, &pDest,
7669                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7670    if( rc!=SQLITE_OK ){
7671      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7672      close_db(pDest);
7673      return 1;
7674    }
7675    if( bAsync ){
7676      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7677                   0, 0, 0);
7678    }
7679    open_db(p, 0);
7680    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7681    if( pBackup==0 ){
7682      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7683      close_db(pDest);
7684      return 1;
7685    }
7686    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7687    sqlite3_backup_finish(pBackup);
7688    if( rc==SQLITE_DONE ){
7689      rc = 0;
7690    }else{
7691      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7692      rc = 1;
7693    }
7694    close_db(pDest);
7695  }else
7696
7697  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7698    if( nArg==2 ){
7699      bail_on_error = booleanValue(azArg[1]);
7700    }else{
7701      raw_printf(stderr, "Usage: .bail on|off\n");
7702      rc = 1;
7703    }
7704  }else
7705
7706  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7707    if( nArg==2 ){
7708      if( booleanValue(azArg[1]) ){
7709        setBinaryMode(p->out, 1);
7710      }else{
7711        setTextMode(p->out, 1);
7712      }
7713    }else{
7714      raw_printf(stderr, "Usage: .binary on|off\n");
7715      rc = 1;
7716    }
7717  }else
7718
7719  /* The undocumented ".breakpoint" command causes a call to the no-op
7720  ** routine named test_breakpoint().
7721  */
7722  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7723    test_breakpoint();
7724  }else
7725
7726  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7727    failIfSafeMode(p, "cannot run .cd in safe mode");
7728    if( nArg==2 ){
7729#if defined(_WIN32) || defined(WIN32)
7730      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7731      rc = !SetCurrentDirectoryW(z);
7732      sqlite3_free(z);
7733#else
7734      rc = chdir(azArg[1]);
7735#endif
7736      if( rc ){
7737        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7738        rc = 1;
7739      }
7740    }else{
7741      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7742      rc = 1;
7743    }
7744  }else
7745
7746  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7747    if( nArg==2 ){
7748      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7749    }else{
7750      raw_printf(stderr, "Usage: .changes on|off\n");
7751      rc = 1;
7752    }
7753  }else
7754
7755  /* Cancel output redirection, if it is currently set (by .testcase)
7756  ** Then read the content of the testcase-out.txt file and compare against
7757  ** azArg[1].  If there are differences, report an error and exit.
7758  */
7759  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7760    char *zRes = 0;
7761    output_reset(p);
7762    if( nArg!=2 ){
7763      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7764      rc = 2;
7765    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7766      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7767      rc = 2;
7768    }else if( testcase_glob(azArg[1],zRes)==0 ){
7769      utf8_printf(stderr,
7770                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7771                 p->zTestcase, azArg[1], zRes);
7772      rc = 1;
7773    }else{
7774      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7775      p->nCheck++;
7776    }
7777    sqlite3_free(zRes);
7778  }else
7779
7780  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7781    failIfSafeMode(p, "cannot run .clone in safe mode");
7782    if( nArg==2 ){
7783      tryToClone(p, azArg[1]);
7784    }else{
7785      raw_printf(stderr, "Usage: .clone FILENAME\n");
7786      rc = 1;
7787    }
7788  }else
7789
7790  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
7791    if( nArg==1 ){
7792      /* List available connections */
7793      int i;
7794      for(i=0; i<ArraySize(p->aAuxDb); i++){
7795        const char *zFile = p->aAuxDb[i].zDbFilename;
7796        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7797          zFile = "(not open)";
7798        }else if( zFile==0 ){
7799          zFile = "(memory)";
7800        }else if( zFile[0]==0 ){
7801          zFile = "(temporary-file)";
7802        }
7803        if( p->pAuxDb == &p->aAuxDb[i] ){
7804          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7805        }else if( p->aAuxDb[i].db!=0 ){
7806          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7807        }
7808      }
7809    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7810      int i = azArg[1][0] - '0';
7811      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7812        p->pAuxDb->db = p->db;
7813        p->pAuxDb = &p->aAuxDb[i];
7814        globalDb = p->db = p->pAuxDb->db;
7815        p->pAuxDb->db = 0;
7816      }
7817    }else if( nArg==3 && strcmp(azArg[1], "close")==0
7818           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7819      int i = azArg[2][0] - '0';
7820      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7821        /* No-op */
7822      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7823        raw_printf(stderr, "cannot close the active database connection\n");
7824        rc = 1;
7825      }else if( p->aAuxDb[i].db ){
7826        session_close_all(p, i);
7827        close_db(p->aAuxDb[i].db);
7828        p->aAuxDb[i].db = 0;
7829      }
7830    }else{
7831      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7832      rc = 1;
7833    }
7834  }else
7835
7836  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7837    char **azName = 0;
7838    int nName = 0;
7839    sqlite3_stmt *pStmt;
7840    int i;
7841    open_db(p, 0);
7842    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7843    if( rc ){
7844      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7845      rc = 1;
7846    }else{
7847      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7848        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7849        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7850        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7851        if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
7852        azName[nName*2] = strdup(zSchema);
7853        azName[nName*2+1] = strdup(zFile);
7854        nName++;
7855      }
7856    }
7857    sqlite3_finalize(pStmt);
7858    for(i=0; i<nName; i++){
7859      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7860      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7861      const char *z = azName[i*2+1];
7862      utf8_printf(p->out, "%s: %s %s%s\n",
7863         azName[i*2],
7864         z && z[0] ? z : "\"\"",
7865         bRdonly ? "r/o" : "r/w",
7866         eTxn==SQLITE_TXN_NONE ? "" :
7867            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7868      free(azName[i*2]);
7869      free(azName[i*2+1]);
7870    }
7871    sqlite3_free(azName);
7872  }else
7873
7874  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7875    static const struct DbConfigChoices {
7876      const char *zName;
7877      int op;
7878    } aDbConfig[] = {
7879        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7880        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7881        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7882        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7883        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7884        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7885        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7886        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7887        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7888        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7889        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7890        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7891        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7892        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7893        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7894        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7895    };
7896    int ii, v;
7897    open_db(p, 0);
7898    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7899      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7900      if( nArg>=3 ){
7901        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7902      }
7903      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7904      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7905      if( nArg>1 ) break;
7906    }
7907    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7908      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7909      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7910    }
7911  }else
7912
7913  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7914    rc = shell_dbinfo_command(p, nArg, azArg);
7915  }else
7916
7917#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7918  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7919    open_db(p, 0);
7920    rc = recoverDatabaseCmd(p, nArg, azArg);
7921  }else
7922#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7923
7924  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7925    char *zLike = 0;
7926    char *zSql;
7927    int i;
7928    int savedShowHeader = p->showHeader;
7929    int savedShellFlags = p->shellFlgs;
7930    ShellClearFlag(p,
7931       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7932       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7933    for(i=1; i<nArg; i++){
7934      if( azArg[i][0]=='-' ){
7935        const char *z = azArg[i]+1;
7936        if( z[0]=='-' ) z++;
7937        if( strcmp(z,"preserve-rowids")==0 ){
7938#ifdef SQLITE_OMIT_VIRTUALTABLE
7939          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7940                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7941          rc = 1;
7942          sqlite3_free(zLike);
7943          goto meta_command_exit;
7944#else
7945          ShellSetFlag(p, SHFLG_PreserveRowid);
7946#endif
7947        }else
7948        if( strcmp(z,"newlines")==0 ){
7949          ShellSetFlag(p, SHFLG_Newlines);
7950        }else
7951        if( strcmp(z,"data-only")==0 ){
7952          ShellSetFlag(p, SHFLG_DumpDataOnly);
7953        }else
7954        if( strcmp(z,"nosys")==0 ){
7955          ShellSetFlag(p, SHFLG_DumpNoSys);
7956        }else
7957        {
7958          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7959          rc = 1;
7960          sqlite3_free(zLike);
7961          goto meta_command_exit;
7962        }
7963      }else{
7964        /* azArg[i] contains a LIKE pattern. This ".dump" request should
7965        ** only dump data for tables for which either the table name matches
7966        ** the LIKE pattern, or the table appears to be a shadow table of
7967        ** a virtual table for which the name matches the LIKE pattern.
7968        */
7969        char *zExpr = sqlite3_mprintf(
7970            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
7971            "  SELECT 1 FROM sqlite_schema WHERE "
7972            "    name LIKE %Q ESCAPE '\\' AND"
7973            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
7974            "    substr(o.name, 1, length(name)+1) == (name||'_')"
7975            ")", azArg[i], azArg[i]
7976        );
7977
7978        if( zLike ){
7979          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
7980        }else{
7981          zLike = zExpr;
7982        }
7983      }
7984    }
7985
7986    open_db(p, 0);
7987
7988    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7989      /* When playing back a "dump", the content might appear in an order
7990      ** which causes immediate foreign key constraints to be violated.
7991      ** So disable foreign-key constraint enforcement to prevent problems. */
7992      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7993      raw_printf(p->out, "BEGIN TRANSACTION;\n");
7994    }
7995    p->writableSchema = 0;
7996    p->showHeader = 0;
7997    /* Set writable_schema=ON since doing so forces SQLite to initialize
7998    ** as much of the schema as it can even if the sqlite_schema table is
7999    ** corrupt. */
8000    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8001    p->nErr = 0;
8002    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8003    zSql = sqlite3_mprintf(
8004      "SELECT name, type, sql FROM sqlite_schema AS o "
8005      "WHERE (%s) AND type=='table'"
8006      "  AND sql NOT NULL"
8007      " ORDER BY tbl_name='sqlite_sequence', rowid",
8008      zLike
8009    );
8010    run_schema_dump_query(p,zSql);
8011    sqlite3_free(zSql);
8012    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8013      zSql = sqlite3_mprintf(
8014        "SELECT sql FROM sqlite_schema AS o "
8015        "WHERE (%s) AND sql NOT NULL"
8016        "  AND type IN ('index','trigger','view')",
8017        zLike
8018      );
8019      run_table_dump_query(p, zSql);
8020      sqlite3_free(zSql);
8021    }
8022    sqlite3_free(zLike);
8023    if( p->writableSchema ){
8024      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8025      p->writableSchema = 0;
8026    }
8027    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8028    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8029    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8030      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8031    }
8032    p->showHeader = savedShowHeader;
8033    p->shellFlgs = savedShellFlags;
8034  }else
8035
8036  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8037    if( nArg==2 ){
8038      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8039    }else{
8040      raw_printf(stderr, "Usage: .echo on|off\n");
8041      rc = 1;
8042    }
8043  }else
8044
8045  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8046    if( nArg==2 ){
8047      p->autoEQPtest = 0;
8048      if( p->autoEQPtrace ){
8049        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8050        p->autoEQPtrace = 0;
8051      }
8052      if( strcmp(azArg[1],"full")==0 ){
8053        p->autoEQP = AUTOEQP_full;
8054      }else if( strcmp(azArg[1],"trigger")==0 ){
8055        p->autoEQP = AUTOEQP_trigger;
8056#ifdef SQLITE_DEBUG
8057      }else if( strcmp(azArg[1],"test")==0 ){
8058        p->autoEQP = AUTOEQP_on;
8059        p->autoEQPtest = 1;
8060      }else if( strcmp(azArg[1],"trace")==0 ){
8061        p->autoEQP = AUTOEQP_full;
8062        p->autoEQPtrace = 1;
8063        open_db(p, 0);
8064        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8065        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8066#endif
8067      }else{
8068        p->autoEQP = (u8)booleanValue(azArg[1]);
8069      }
8070    }else{
8071      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8072      rc = 1;
8073    }
8074  }else
8075
8076  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8077    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8078    rc = 2;
8079  }else
8080
8081  /* The ".explain" command is automatic now.  It is largely pointless.  It
8082  ** retained purely for backwards compatibility */
8083  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8084    int val = 1;
8085    if( nArg>=2 ){
8086      if( strcmp(azArg[1],"auto")==0 ){
8087        val = 99;
8088      }else{
8089        val =  booleanValue(azArg[1]);
8090      }
8091    }
8092    if( val==1 && p->mode!=MODE_Explain ){
8093      p->normalMode = p->mode;
8094      p->mode = MODE_Explain;
8095      p->autoExplain = 0;
8096    }else if( val==0 ){
8097      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8098      p->autoExplain = 0;
8099    }else if( val==99 ){
8100      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8101      p->autoExplain = 1;
8102    }
8103  }else
8104
8105#ifndef SQLITE_OMIT_VIRTUALTABLE
8106  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8107    open_db(p, 0);
8108    expertDotCommand(p, azArg, nArg);
8109  }else
8110#endif
8111
8112  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8113    static const struct {
8114       const char *zCtrlName;   /* Name of a test-control option */
8115       int ctrlCode;            /* Integer code for that option */
8116       const char *zUsage;      /* Usage notes */
8117    } aCtrl[] = {
8118      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8119      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8120      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8121      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8122      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8123   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8124      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8125      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8126      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8127      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8128   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8129    };
8130    int filectrl = -1;
8131    int iCtrl = -1;
8132    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8133    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8134    int n2, i;
8135    const char *zCmd = 0;
8136    const char *zSchema = 0;
8137
8138    open_db(p, 0);
8139    zCmd = nArg>=2 ? azArg[1] : "help";
8140
8141    if( zCmd[0]=='-'
8142     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8143     && nArg>=4
8144    ){
8145      zSchema = azArg[2];
8146      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8147      nArg -= 2;
8148      zCmd = azArg[1];
8149    }
8150
8151    /* The argument can optionally begin with "-" or "--" */
8152    if( zCmd[0]=='-' && zCmd[1] ){
8153      zCmd++;
8154      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8155    }
8156
8157    /* --help lists all file-controls */
8158    if( strcmp(zCmd,"help")==0 ){
8159      utf8_printf(p->out, "Available file-controls:\n");
8160      for(i=0; i<ArraySize(aCtrl); i++){
8161        utf8_printf(p->out, "  .filectrl %s %s\n",
8162                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8163      }
8164      rc = 1;
8165      goto meta_command_exit;
8166    }
8167
8168    /* convert filectrl text option to value. allow any unique prefix
8169    ** of the option name, or a numerical value. */
8170    n2 = strlen30(zCmd);
8171    for(i=0; i<ArraySize(aCtrl); i++){
8172      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8173        if( filectrl<0 ){
8174          filectrl = aCtrl[i].ctrlCode;
8175          iCtrl = i;
8176        }else{
8177          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8178                              "Use \".filectrl --help\" for help\n", zCmd);
8179          rc = 1;
8180          goto meta_command_exit;
8181        }
8182      }
8183    }
8184    if( filectrl<0 ){
8185      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8186                         "Use \".filectrl --help\" for help\n", zCmd);
8187    }else{
8188      switch(filectrl){
8189        case SQLITE_FCNTL_SIZE_LIMIT: {
8190          if( nArg!=2 && nArg!=3 ) break;
8191          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8192          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8193          isOk = 1;
8194          break;
8195        }
8196        case SQLITE_FCNTL_LOCK_TIMEOUT:
8197        case SQLITE_FCNTL_CHUNK_SIZE: {
8198          int x;
8199          if( nArg!=3 ) break;
8200          x = (int)integerValue(azArg[2]);
8201          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8202          isOk = 2;
8203          break;
8204        }
8205        case SQLITE_FCNTL_PERSIST_WAL:
8206        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8207          int x;
8208          if( nArg!=2 && nArg!=3 ) break;
8209          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8210          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8211          iRes = x;
8212          isOk = 1;
8213          break;
8214        }
8215        case SQLITE_FCNTL_DATA_VERSION:
8216        case SQLITE_FCNTL_HAS_MOVED: {
8217          int x;
8218          if( nArg!=2 ) break;
8219          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8220          iRes = x;
8221          isOk = 1;
8222          break;
8223        }
8224        case SQLITE_FCNTL_TEMPFILENAME: {
8225          char *z = 0;
8226          if( nArg!=2 ) break;
8227          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8228          if( z ){
8229            utf8_printf(p->out, "%s\n", z);
8230            sqlite3_free(z);
8231          }
8232          isOk = 2;
8233          break;
8234        }
8235        case SQLITE_FCNTL_RESERVE_BYTES: {
8236          int x;
8237          if( nArg>=3 ){
8238            x = atoi(azArg[2]);
8239            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8240          }
8241          x = -1;
8242          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8243          utf8_printf(p->out,"%d\n", x);
8244          isOk = 2;
8245          break;
8246        }
8247      }
8248    }
8249    if( isOk==0 && iCtrl>=0 ){
8250      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8251      rc = 1;
8252    }else if( isOk==1 ){
8253      char zBuf[100];
8254      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8255      raw_printf(p->out, "%s\n", zBuf);
8256    }
8257  }else
8258
8259  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8260    ShellState data;
8261    int doStats = 0;
8262    memcpy(&data, p, sizeof(data));
8263    data.showHeader = 0;
8264    data.cMode = data.mode = MODE_Semi;
8265    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8266      data.cMode = data.mode = MODE_Pretty;
8267      nArg = 1;
8268    }
8269    if( nArg!=1 ){
8270      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8271      rc = 1;
8272      goto meta_command_exit;
8273    }
8274    open_db(p, 0);
8275    rc = sqlite3_exec(p->db,
8276       "SELECT sql FROM"
8277       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8278       "     FROM sqlite_schema UNION ALL"
8279       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8280       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8281       "ORDER BY x",
8282       callback, &data, 0
8283    );
8284    if( rc==SQLITE_OK ){
8285      sqlite3_stmt *pStmt;
8286      rc = sqlite3_prepare_v2(p->db,
8287               "SELECT rowid FROM sqlite_schema"
8288               " WHERE name GLOB 'sqlite_stat[134]'",
8289               -1, &pStmt, 0);
8290      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8291      sqlite3_finalize(pStmt);
8292    }
8293    if( doStats==0 ){
8294      raw_printf(p->out, "/* No STAT tables available */\n");
8295    }else{
8296      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8297      data.cMode = data.mode = MODE_Insert;
8298      data.zDestTable = "sqlite_stat1";
8299      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8300      data.zDestTable = "sqlite_stat4";
8301      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8302      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8303    }
8304  }else
8305
8306  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8307    if( nArg==2 ){
8308      p->showHeader = booleanValue(azArg[1]);
8309      p->shellFlgs |= SHFLG_HeaderSet;
8310    }else{
8311      raw_printf(stderr, "Usage: .headers on|off\n");
8312      rc = 1;
8313    }
8314  }else
8315
8316  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8317    if( nArg>=2 ){
8318      n = showHelp(p->out, azArg[1]);
8319      if( n==0 ){
8320        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8321      }
8322    }else{
8323      showHelp(p->out, 0);
8324    }
8325  }else
8326
8327  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8328    char *zTable = 0;           /* Insert data into this table */
8329    char *zFile = 0;            /* Name of file to extra content from */
8330    sqlite3_stmt *pStmt = NULL; /* A statement */
8331    int nCol;                   /* Number of columns in the table */
8332    int nByte;                  /* Number of bytes in an SQL string */
8333    int i, j;                   /* Loop counters */
8334    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8335    int nSep;                   /* Number of bytes in p->colSeparator[] */
8336    char *zSql;                 /* An SQL statement */
8337    ImportCtx sCtx;             /* Reader context */
8338    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8339    int eVerbose = 0;           /* Larger for more console output */
8340    int nSkip = 0;              /* Initial lines to skip */
8341    int useOutputMode = 1;      /* Use output mode to determine separators */
8342
8343    failIfSafeMode(p, "cannot run .import in safe mode");
8344    memset(&sCtx, 0, sizeof(sCtx));
8345    sCtx.z = sqlite3_malloc64(120);
8346    if( sCtx.z==0 ){
8347      import_cleanup(&sCtx);
8348      shell_out_of_memory();
8349    }
8350    if( p->mode==MODE_Ascii ){
8351      xRead = ascii_read_one_field;
8352    }else{
8353      xRead = csv_read_one_field;
8354    }
8355    for(i=1; i<nArg; i++){
8356      char *z = azArg[i];
8357      if( z[0]=='-' && z[1]=='-' ) z++;
8358      if( z[0]!='-' ){
8359        if( zFile==0 ){
8360          zFile = z;
8361        }else if( zTable==0 ){
8362          zTable = z;
8363        }else{
8364          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8365          showHelp(p->out, "import");
8366          rc = 1;
8367          goto meta_command_exit;
8368        }
8369      }else if( strcmp(z,"-v")==0 ){
8370        eVerbose++;
8371      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8372        nSkip = integerValue(azArg[++i]);
8373      }else if( strcmp(z,"-ascii")==0 ){
8374        sCtx.cColSep = SEP_Unit[0];
8375        sCtx.cRowSep = SEP_Record[0];
8376        xRead = ascii_read_one_field;
8377        useOutputMode = 0;
8378      }else if( strcmp(z,"-csv")==0 ){
8379        sCtx.cColSep = ',';
8380        sCtx.cRowSep = '\n';
8381        xRead = csv_read_one_field;
8382        useOutputMode = 0;
8383      }else{
8384        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8385        showHelp(p->out, "import");
8386        rc = 1;
8387        goto meta_command_exit;
8388      }
8389    }
8390    if( zTable==0 ){
8391      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8392                  zFile==0 ? "FILE" : "TABLE");
8393      showHelp(p->out, "import");
8394      rc = 1;
8395      goto meta_command_exit;
8396    }
8397    seenInterrupt = 0;
8398    open_db(p, 0);
8399    if( useOutputMode ){
8400      /* If neither the --csv or --ascii options are specified, then set
8401      ** the column and row separator characters from the output mode. */
8402      nSep = strlen30(p->colSeparator);
8403      if( nSep==0 ){
8404        raw_printf(stderr,
8405                   "Error: non-null column separator required for import\n");
8406        rc = 1;
8407        goto meta_command_exit;
8408      }
8409      if( nSep>1 ){
8410        raw_printf(stderr,
8411              "Error: multi-character column separators not allowed"
8412              " for import\n");
8413        rc = 1;
8414        goto meta_command_exit;
8415      }
8416      nSep = strlen30(p->rowSeparator);
8417      if( nSep==0 ){
8418        raw_printf(stderr,
8419            "Error: non-null row separator required for import\n");
8420        rc = 1;
8421        goto meta_command_exit;
8422      }
8423      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8424        /* When importing CSV (only), if the row separator is set to the
8425        ** default output row separator, change it to the default input
8426        ** row separator.  This avoids having to maintain different input
8427        ** and output row separators. */
8428        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8429        nSep = strlen30(p->rowSeparator);
8430      }
8431      if( nSep>1 ){
8432        raw_printf(stderr, "Error: multi-character row separators not allowed"
8433                           " for import\n");
8434        rc = 1;
8435        goto meta_command_exit;
8436      }
8437      sCtx.cColSep = p->colSeparator[0];
8438      sCtx.cRowSep = p->rowSeparator[0];
8439    }
8440    sCtx.zFile = zFile;
8441    sCtx.nLine = 1;
8442    if( sCtx.zFile[0]=='|' ){
8443#ifdef SQLITE_OMIT_POPEN
8444      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8445      rc = 1;
8446      goto meta_command_exit;
8447#else
8448      sCtx.in = popen(sCtx.zFile+1, "r");
8449      sCtx.zFile = "<pipe>";
8450      sCtx.xCloser = pclose;
8451#endif
8452    }else{
8453      sCtx.in = fopen(sCtx.zFile, "rb");
8454      sCtx.xCloser = fclose;
8455    }
8456    if( sCtx.in==0 ){
8457      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8458      rc = 1;
8459      import_cleanup(&sCtx);
8460      goto meta_command_exit;
8461    }
8462    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8463      char zSep[2];
8464      zSep[1] = 0;
8465      zSep[0] = sCtx.cColSep;
8466      utf8_printf(p->out, "Column separator ");
8467      output_c_string(p->out, zSep);
8468      utf8_printf(p->out, ", row separator ");
8469      zSep[0] = sCtx.cRowSep;
8470      output_c_string(p->out, zSep);
8471      utf8_printf(p->out, "\n");
8472    }
8473    while( (nSkip--)>0 ){
8474      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8475    }
8476    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
8477    if( zSql==0 ){
8478      import_cleanup(&sCtx);
8479      shell_out_of_memory();
8480    }
8481    nByte = strlen30(zSql);
8482    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8483    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8484    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8485      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
8486      char cSep = '(';
8487      while( xRead(&sCtx) ){
8488        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
8489        cSep = ',';
8490        if( sCtx.cTerm!=sCtx.cColSep ) break;
8491      }
8492      if( cSep=='(' ){
8493        sqlite3_free(zCreate);
8494        import_cleanup(&sCtx);
8495        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8496        rc = 1;
8497        goto meta_command_exit;
8498      }
8499      zCreate = sqlite3_mprintf("%z\n)", zCreate);
8500      if( eVerbose>=1 ){
8501        utf8_printf(p->out, "%s\n", zCreate);
8502      }
8503      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8504      sqlite3_free(zCreate);
8505      if( rc ){
8506        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
8507                sqlite3_errmsg(p->db));
8508        import_cleanup(&sCtx);
8509        rc = 1;
8510        goto meta_command_exit;
8511      }
8512      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8513    }
8514    sqlite3_free(zSql);
8515    if( rc ){
8516      if (pStmt) sqlite3_finalize(pStmt);
8517      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8518      import_cleanup(&sCtx);
8519      rc = 1;
8520      goto meta_command_exit;
8521    }
8522    nCol = sqlite3_column_count(pStmt);
8523    sqlite3_finalize(pStmt);
8524    pStmt = 0;
8525    if( nCol==0 ) return 0; /* no columns, no error */
8526    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8527    if( zSql==0 ){
8528      import_cleanup(&sCtx);
8529      shell_out_of_memory();
8530    }
8531    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8532    j = strlen30(zSql);
8533    for(i=1; i<nCol; i++){
8534      zSql[j++] = ',';
8535      zSql[j++] = '?';
8536    }
8537    zSql[j++] = ')';
8538    zSql[j] = 0;
8539    if( eVerbose>=2 ){
8540      utf8_printf(p->out, "Insert using: %s\n", zSql);
8541    }
8542    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8543    sqlite3_free(zSql);
8544    if( rc ){
8545      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8546      if (pStmt) sqlite3_finalize(pStmt);
8547      import_cleanup(&sCtx);
8548      rc = 1;
8549      goto meta_command_exit;
8550    }
8551    needCommit = sqlite3_get_autocommit(p->db);
8552    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8553    do{
8554      int startLine = sCtx.nLine;
8555      for(i=0; i<nCol; i++){
8556        char *z = xRead(&sCtx);
8557        /*
8558        ** Did we reach end-of-file before finding any columns?
8559        ** If so, stop instead of NULL filling the remaining columns.
8560        */
8561        if( z==0 && i==0 ) break;
8562        /*
8563        ** Did we reach end-of-file OR end-of-line before finding any
8564        ** columns in ASCII mode?  If so, stop instead of NULL filling
8565        ** the remaining columns.
8566        */
8567        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8568        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8569        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8570          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8571                          "filling the rest with NULL\n",
8572                          sCtx.zFile, startLine, nCol, i+1);
8573          i += 2;
8574          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8575        }
8576      }
8577      if( sCtx.cTerm==sCtx.cColSep ){
8578        do{
8579          xRead(&sCtx);
8580          i++;
8581        }while( sCtx.cTerm==sCtx.cColSep );
8582        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8583                        "extras ignored\n",
8584                        sCtx.zFile, startLine, nCol, i);
8585      }
8586      if( i>=nCol ){
8587        sqlite3_step(pStmt);
8588        rc = sqlite3_reset(pStmt);
8589        if( rc!=SQLITE_OK ){
8590          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8591                      startLine, sqlite3_errmsg(p->db));
8592          sCtx.nErr++;
8593        }else{
8594          sCtx.nRow++;
8595        }
8596      }
8597    }while( sCtx.cTerm!=EOF );
8598
8599    import_cleanup(&sCtx);
8600    sqlite3_finalize(pStmt);
8601    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8602    if( eVerbose>0 ){
8603      utf8_printf(p->out,
8604          "Added %d rows with %d errors using %d lines of input\n",
8605          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8606    }
8607  }else
8608
8609#ifndef SQLITE_UNTESTABLE
8610  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8611    char *zSql;
8612    char *zCollist = 0;
8613    sqlite3_stmt *pStmt;
8614    int tnum = 0;
8615    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8616    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8617    int i;
8618    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8619      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8620                          "       .imposter off\n");
8621      /* Also allowed, but not documented:
8622      **
8623      **    .imposter TABLE IMPOSTER
8624      **
8625      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8626      ** imposter is another WITHOUT ROWID table with the columns in
8627      ** storage order. */
8628      rc = 1;
8629      goto meta_command_exit;
8630    }
8631    open_db(p, 0);
8632    if( nArg==2 ){
8633      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8634      goto meta_command_exit;
8635    }
8636    zSql = sqlite3_mprintf(
8637      "SELECT rootpage, 0 FROM sqlite_schema"
8638      " WHERE name='%q' AND type='index'"
8639      "UNION ALL "
8640      "SELECT rootpage, 1 FROM sqlite_schema"
8641      " WHERE name='%q' AND type='table'"
8642      "   AND sql LIKE '%%without%%rowid%%'",
8643      azArg[1], azArg[1]
8644    );
8645    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8646    sqlite3_free(zSql);
8647    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8648      tnum = sqlite3_column_int(pStmt, 0);
8649      isWO = sqlite3_column_int(pStmt, 1);
8650    }
8651    sqlite3_finalize(pStmt);
8652    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8653    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8654    sqlite3_free(zSql);
8655    i = 0;
8656    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8657      char zLabel[20];
8658      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8659      i++;
8660      if( zCol==0 ){
8661        if( sqlite3_column_int(pStmt,1)==-1 ){
8662          zCol = "_ROWID_";
8663        }else{
8664          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8665          zCol = zLabel;
8666        }
8667      }
8668      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8669        lenPK = (int)strlen(zCollist);
8670      }
8671      if( zCollist==0 ){
8672        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8673      }else{
8674        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8675      }
8676    }
8677    sqlite3_finalize(pStmt);
8678    if( i==0 || tnum==0 ){
8679      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8680      rc = 1;
8681      sqlite3_free(zCollist);
8682      goto meta_command_exit;
8683    }
8684    if( lenPK==0 ) lenPK = 100000;
8685    zSql = sqlite3_mprintf(
8686          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8687          azArg[2], zCollist, lenPK, zCollist);
8688    sqlite3_free(zCollist);
8689    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8690    if( rc==SQLITE_OK ){
8691      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8692      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8693      if( rc ){
8694        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8695      }else{
8696        utf8_printf(stdout, "%s;\n", zSql);
8697        raw_printf(stdout,
8698          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8699          azArg[1], isWO ? "table" : "index"
8700        );
8701      }
8702    }else{
8703      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8704      rc = 1;
8705    }
8706    sqlite3_free(zSql);
8707  }else
8708#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8709
8710#ifdef SQLITE_ENABLE_IOTRACE
8711  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8712    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8713    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8714    iotrace = 0;
8715    if( nArg<2 ){
8716      sqlite3IoTrace = 0;
8717    }else if( strcmp(azArg[1], "-")==0 ){
8718      sqlite3IoTrace = iotracePrintf;
8719      iotrace = stdout;
8720    }else{
8721      iotrace = fopen(azArg[1], "w");
8722      if( iotrace==0 ){
8723        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8724        sqlite3IoTrace = 0;
8725        rc = 1;
8726      }else{
8727        sqlite3IoTrace = iotracePrintf;
8728      }
8729    }
8730  }else
8731#endif
8732
8733  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8734    static const struct {
8735       const char *zLimitName;   /* Name of a limit */
8736       int limitCode;            /* Integer code for that limit */
8737    } aLimit[] = {
8738      { "length",                SQLITE_LIMIT_LENGTH                    },
8739      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8740      { "column",                SQLITE_LIMIT_COLUMN                    },
8741      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8742      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8743      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8744      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8745      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8746      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8747      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8748      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8749      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8750    };
8751    int i, n2;
8752    open_db(p, 0);
8753    if( nArg==1 ){
8754      for(i=0; i<ArraySize(aLimit); i++){
8755        printf("%20s %d\n", aLimit[i].zLimitName,
8756               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8757      }
8758    }else if( nArg>3 ){
8759      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8760      rc = 1;
8761      goto meta_command_exit;
8762    }else{
8763      int iLimit = -1;
8764      n2 = strlen30(azArg[1]);
8765      for(i=0; i<ArraySize(aLimit); i++){
8766        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8767          if( iLimit<0 ){
8768            iLimit = i;
8769          }else{
8770            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8771            rc = 1;
8772            goto meta_command_exit;
8773          }
8774        }
8775      }
8776      if( iLimit<0 ){
8777        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8778                        "enter \".limits\" with no arguments for a list.\n",
8779                         azArg[1]);
8780        rc = 1;
8781        goto meta_command_exit;
8782      }
8783      if( nArg==3 ){
8784        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8785                      (int)integerValue(azArg[2]));
8786      }
8787      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8788             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8789    }
8790  }else
8791
8792  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8793    open_db(p, 0);
8794    lintDotCommand(p, azArg, nArg);
8795  }else
8796
8797#ifndef SQLITE_OMIT_LOAD_EXTENSION
8798  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8799    const char *zFile, *zProc;
8800    char *zErrMsg = 0;
8801    failIfSafeMode(p, "cannot run .load in safe mode");
8802    if( nArg<2 ){
8803      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8804      rc = 1;
8805      goto meta_command_exit;
8806    }
8807    zFile = azArg[1];
8808    zProc = nArg>=3 ? azArg[2] : 0;
8809    open_db(p, 0);
8810    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8811    if( rc!=SQLITE_OK ){
8812      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8813      sqlite3_free(zErrMsg);
8814      rc = 1;
8815    }
8816  }else
8817#endif
8818
8819  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8820    failIfSafeMode(p, "cannot run .log in safe mode");
8821    if( nArg!=2 ){
8822      raw_printf(stderr, "Usage: .log FILENAME\n");
8823      rc = 1;
8824    }else{
8825      const char *zFile = azArg[1];
8826      output_file_close(p->pLog);
8827      p->pLog = output_file_open(zFile, 0);
8828    }
8829  }else
8830
8831  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8832    const char *zMode = nArg>=2 ? azArg[1] : "";
8833    int n2 = strlen30(zMode);
8834    int c2 = zMode[0];
8835    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8836      p->mode = MODE_Line;
8837      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8838    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8839      p->mode = MODE_Column;
8840      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8841        p->showHeader = 1;
8842      }
8843      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8844    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8845      p->mode = MODE_List;
8846      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8847      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8848    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8849      p->mode = MODE_Html;
8850    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8851      p->mode = MODE_Tcl;
8852      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8853      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8854    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8855      p->mode = MODE_Csv;
8856      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8857      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8858    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8859      p->mode = MODE_List;
8860      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8861    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8862      p->mode = MODE_Insert;
8863      set_table_name(p, nArg>=3 ? azArg[2] : "table");
8864    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8865      p->mode = MODE_Quote;
8866      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8867      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8868    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8869      p->mode = MODE_Ascii;
8870      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8871      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8872    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8873      p->mode = MODE_Markdown;
8874    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8875      p->mode = MODE_Table;
8876    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8877      p->mode = MODE_Box;
8878    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8879      p->mode = MODE_Json;
8880    }else if( nArg==1 ){
8881      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8882    }else{
8883      raw_printf(stderr, "Error: mode should be one of: "
8884         "ascii box column csv html insert json line list markdown "
8885         "quote table tabs tcl\n");
8886      rc = 1;
8887    }
8888    p->cMode = p->mode;
8889  }else
8890
8891  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
8892    if( nArg!=2 ){
8893      raw_printf(stderr, "Usage: .nonce NONCE\n");
8894      rc = 1;
8895    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
8896      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", p->lineno, azArg[1]);
8897      exit(1);
8898    }else{
8899      p->bSafeMode = 0;
8900      return 0;  /* Return immediately to bypass the safe mode reset
8901                 ** at the end of this procedure */
8902    }
8903  }else
8904
8905  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8906    if( nArg==2 ){
8907      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8908                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8909    }else{
8910      raw_printf(stderr, "Usage: .nullvalue STRING\n");
8911      rc = 1;
8912    }
8913  }else
8914
8915#ifdef SQLITE_DEBUG
8916  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8917    int i;
8918    for(i=1; i<nArg; i++){
8919      const char *z = azArg[i];
8920      if( z[0]=='-' && z[1]=='-' ) z++;
8921      if( strcmp(z,"-repeat")==0 ){
8922        if( i==nArg-1 ){
8923          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8924          rc = 1;
8925        }else{
8926          oomRepeat = (int)integerValue(azArg[++i]);
8927        }
8928      }else if( IsDigit(z[0]) ){
8929        oomCounter = (int)integerValue(azArg[i]);
8930      }else{
8931        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8932        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8933        rc = 1;
8934      }
8935    }
8936    if( rc==0 ){
8937      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8938      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
8939    }
8940  }else
8941#endif /* SQLITE_DEBUG */
8942
8943  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8944    char *zNewFilename = 0;  /* Name of the database file to open */
8945    int iName = 1;           /* Index in azArg[] of the filename */
8946    int newFlag = 0;         /* True to delete file before opening */
8947    /* Close the existing database */
8948    session_close_all(p, -1);
8949    close_db(p->db);
8950    p->db = 0;
8951    p->pAuxDb->zDbFilename = 0;
8952    sqlite3_free(p->pAuxDb->zFreeOnClose);
8953    p->pAuxDb->zFreeOnClose = 0;
8954    p->openMode = SHELL_OPEN_UNSPEC;
8955    p->openFlags = 0;
8956    p->szMax = 0;
8957    /* Check for command-line arguments */
8958    for(iName=1; iName<nArg; iName++){
8959      const char *z = azArg[iName];
8960      if( optionMatch(z,"new") ){
8961        newFlag = 1;
8962#ifdef SQLITE_HAVE_ZLIB
8963      }else if( optionMatch(z, "zip") ){
8964        p->openMode = SHELL_OPEN_ZIPFILE;
8965#endif
8966      }else if( optionMatch(z, "append") ){
8967        p->openMode = SHELL_OPEN_APPENDVFS;
8968      }else if( optionMatch(z, "readonly") ){
8969        p->openMode = SHELL_OPEN_READONLY;
8970      }else if( optionMatch(z, "nofollow") ){
8971        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8972#ifndef SQLITE_OMIT_DESERIALIZE
8973      }else if( optionMatch(z, "deserialize") ){
8974        p->openMode = SHELL_OPEN_DESERIALIZE;
8975      }else if( optionMatch(z, "hexdb") ){
8976        p->openMode = SHELL_OPEN_HEXDB;
8977      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8978        p->szMax = integerValue(azArg[++iName]);
8979#endif /* SQLITE_OMIT_DESERIALIZE */
8980      }else if( z[0]=='-' ){
8981        utf8_printf(stderr, "unknown option: %s\n", z);
8982        rc = 1;
8983        goto meta_command_exit;
8984      }else if( zNewFilename ){
8985        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8986        rc = 1;
8987        goto meta_command_exit;
8988      }else{
8989        zNewFilename = sqlite3_mprintf("%s", z);
8990      }
8991    }
8992    /* If a filename is specified, try to open it first */
8993    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8994      if( newFlag && !p->bSafeMode ) shellDeleteFile(zNewFilename);
8995      if( p->bSafeMode
8996       && p->openMode!=SHELL_OPEN_HEXDB
8997       && zNewFilename
8998       && strcmp(zNewFilename,":memory:")!=0
8999      ){
9000        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9001      }
9002      p->pAuxDb->zDbFilename = zNewFilename;
9003      open_db(p, OPEN_DB_KEEPALIVE);
9004      if( p->db==0 ){
9005        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9006        sqlite3_free(zNewFilename);
9007      }else{
9008        p->pAuxDb->zFreeOnClose = zNewFilename;
9009      }
9010    }
9011    if( p->db==0 ){
9012      /* As a fall-back open a TEMP database */
9013      p->pAuxDb->zDbFilename = 0;
9014      open_db(p, 0);
9015    }
9016  }else
9017
9018  if( (c=='o'
9019        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9020   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9021  ){
9022    char *zFile = 0;
9023    int bTxtMode = 0;
9024    int i;
9025    int eMode = 0;
9026    int bBOM = 0;
9027    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
9028
9029    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9030    if( c=='e' ){
9031      eMode = 'x';
9032      bOnce = 2;
9033    }else if( strncmp(azArg[0],"once",n)==0 ){
9034      bOnce = 1;
9035    }
9036    for(i=1; i<nArg; i++){
9037      char *z = azArg[i];
9038      if( z[0]=='-' ){
9039        if( z[1]=='-' ) z++;
9040        if( strcmp(z,"-bom")==0 ){
9041          bBOM = 1;
9042        }else if( c!='e' && strcmp(z,"-x")==0 ){
9043          eMode = 'x';  /* spreadsheet */
9044        }else if( c!='e' && strcmp(z,"-e")==0 ){
9045          eMode = 'e';  /* text editor */
9046        }else{
9047          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9048                      azArg[i]);
9049          showHelp(p->out, azArg[0]);
9050          rc = 1;
9051          goto meta_command_exit;
9052        }
9053      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9054        zFile = sqlite3_mprintf("%s", z);
9055        if( zFile[0]=='|' ){
9056          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9057          break;
9058        }
9059      }else{
9060        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9061                    azArg[i]);
9062        showHelp(p->out, azArg[0]);
9063        rc = 1;
9064        sqlite3_free(zFile);
9065        goto meta_command_exit;
9066      }
9067    }
9068    if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
9069    if( bOnce ){
9070      p->outCount = 2;
9071    }else{
9072      p->outCount = 0;
9073    }
9074    output_reset(p);
9075#ifndef SQLITE_NOHAVE_SYSTEM
9076    if( eMode=='e' || eMode=='x' ){
9077      p->doXdgOpen = 1;
9078      outputModePush(p);
9079      if( eMode=='x' ){
9080        /* spreadsheet mode.  Output as CSV. */
9081        newTempFile(p, "csv");
9082        ShellClearFlag(p, SHFLG_Echo);
9083        p->mode = MODE_Csv;
9084        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9085        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9086      }else{
9087        /* text editor mode */
9088        newTempFile(p, "txt");
9089        bTxtMode = 1;
9090      }
9091      sqlite3_free(zFile);
9092      zFile = sqlite3_mprintf("%s", p->zTempFile);
9093    }
9094#endif /* SQLITE_NOHAVE_SYSTEM */
9095    if( zFile[0]=='|' ){
9096#ifdef SQLITE_OMIT_POPEN
9097      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9098      rc = 1;
9099      p->out = stdout;
9100#else
9101      p->out = popen(zFile + 1, "w");
9102      if( p->out==0 ){
9103        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9104        p->out = stdout;
9105        rc = 1;
9106      }else{
9107        if( bBOM ) fprintf(p->out,"\357\273\277");
9108        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9109      }
9110#endif
9111    }else{
9112      p->out = output_file_open(zFile, bTxtMode);
9113      if( p->out==0 ){
9114        if( strcmp(zFile,"off")!=0 ){
9115          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9116        }
9117        p->out = stdout;
9118        rc = 1;
9119      } else {
9120        if( bBOM ) fprintf(p->out,"\357\273\277");
9121        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9122      }
9123    }
9124    sqlite3_free(zFile);
9125  }else
9126
9127  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9128    open_db(p,0);
9129    if( nArg<=1 ) goto parameter_syntax_error;
9130
9131    /* .parameter clear
9132    ** Clear all bind parameters by dropping the TEMP table that holds them.
9133    */
9134    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9135      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9136                   0, 0, 0);
9137    }else
9138
9139    /* .parameter list
9140    ** List all bind parameters.
9141    */
9142    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9143      sqlite3_stmt *pStmt = 0;
9144      int rx;
9145      int len = 0;
9146      rx = sqlite3_prepare_v2(p->db,
9147             "SELECT max(length(key)) "
9148             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9149      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9150        len = sqlite3_column_int(pStmt, 0);
9151        if( len>40 ) len = 40;
9152      }
9153      sqlite3_finalize(pStmt);
9154      pStmt = 0;
9155      if( len ){
9156        rx = sqlite3_prepare_v2(p->db,
9157             "SELECT key, quote(value) "
9158             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9159        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9160          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9161                      sqlite3_column_text(pStmt,1));
9162        }
9163        sqlite3_finalize(pStmt);
9164      }
9165    }else
9166
9167    /* .parameter init
9168    ** Make sure the TEMP table used to hold bind parameters exists.
9169    ** Create it if necessary.
9170    */
9171    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9172      bind_table_init(p);
9173    }else
9174
9175    /* .parameter set NAME VALUE
9176    ** Set or reset a bind parameter.  NAME should be the full parameter
9177    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9178    ** VALUE can be in either SQL literal notation, or if not it will be
9179    ** understood to be a text string.
9180    */
9181    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9182      int rx;
9183      char *zSql;
9184      sqlite3_stmt *pStmt;
9185      const char *zKey = azArg[2];
9186      const char *zValue = azArg[3];
9187      bind_table_init(p);
9188      zSql = sqlite3_mprintf(
9189                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9190                  "VALUES(%Q,%s);", zKey, zValue);
9191      if( zSql==0 ) shell_out_of_memory();
9192      pStmt = 0;
9193      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9194      sqlite3_free(zSql);
9195      if( rx!=SQLITE_OK ){
9196        sqlite3_finalize(pStmt);
9197        pStmt = 0;
9198        zSql = sqlite3_mprintf(
9199                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9200                   "VALUES(%Q,%Q);", zKey, zValue);
9201        if( zSql==0 ) shell_out_of_memory();
9202        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9203        sqlite3_free(zSql);
9204        if( rx!=SQLITE_OK ){
9205          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9206          sqlite3_finalize(pStmt);
9207          pStmt = 0;
9208          rc = 1;
9209        }
9210      }
9211      sqlite3_step(pStmt);
9212      sqlite3_finalize(pStmt);
9213    }else
9214
9215    /* .parameter unset NAME
9216    ** Remove the NAME binding from the parameter binding table, if it
9217    ** exists.
9218    */
9219    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9220      char *zSql = sqlite3_mprintf(
9221          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9222      if( zSql==0 ) shell_out_of_memory();
9223      sqlite3_exec(p->db, zSql, 0, 0, 0);
9224      sqlite3_free(zSql);
9225    }else
9226    /* If no command name matches, show a syntax error */
9227    parameter_syntax_error:
9228    showHelp(p->out, "parameter");
9229  }else
9230
9231  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9232    int i;
9233    for(i=1; i<nArg; i++){
9234      if( i>1 ) raw_printf(p->out, " ");
9235      utf8_printf(p->out, "%s", azArg[i]);
9236    }
9237    raw_printf(p->out, "\n");
9238  }else
9239
9240#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9241  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9242    int i;
9243    int nn = 0;
9244    p->flgProgress = 0;
9245    p->mxProgress = 0;
9246    p->nProgress = 0;
9247    for(i=1; i<nArg; i++){
9248      const char *z = azArg[i];
9249      if( z[0]=='-' ){
9250        z++;
9251        if( z[0]=='-' ) z++;
9252        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9253          p->flgProgress |= SHELL_PROGRESS_QUIET;
9254          continue;
9255        }
9256        if( strcmp(z,"reset")==0 ){
9257          p->flgProgress |= SHELL_PROGRESS_RESET;
9258          continue;
9259        }
9260        if( strcmp(z,"once")==0 ){
9261          p->flgProgress |= SHELL_PROGRESS_ONCE;
9262          continue;
9263        }
9264        if( strcmp(z,"limit")==0 ){
9265          if( i+1>=nArg ){
9266            utf8_printf(stderr, "Error: missing argument on --limit\n");
9267            rc = 1;
9268            goto meta_command_exit;
9269          }else{
9270            p->mxProgress = (int)integerValue(azArg[++i]);
9271          }
9272          continue;
9273        }
9274        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9275        rc = 1;
9276        goto meta_command_exit;
9277      }else{
9278        nn = (int)integerValue(z);
9279      }
9280    }
9281    open_db(p, 0);
9282    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9283  }else
9284#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9285
9286  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9287    if( nArg >= 2) {
9288      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9289    }
9290    if( nArg >= 3) {
9291      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9292    }
9293  }else
9294
9295  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9296    rc = 2;
9297  }else
9298
9299  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9300    FILE *inSaved = p->in;
9301    int savedLineno = p->lineno;
9302    failIfSafeMode(p, "cannot run .read in safe mode");
9303    if( nArg!=2 ){
9304      raw_printf(stderr, "Usage: .read FILE\n");
9305      rc = 1;
9306      goto meta_command_exit;
9307    }
9308    if( azArg[1][0]=='|' ){
9309#ifdef SQLITE_OMIT_POPEN
9310      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9311      rc = 1;
9312      p->out = stdout;
9313#else
9314      p->in = popen(azArg[1]+1, "r");
9315      if( p->in==0 ){
9316        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9317        rc = 1;
9318      }else{
9319        rc = process_input(p);
9320        pclose(p->in);
9321      }
9322#endif
9323    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9324      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9325      rc = 1;
9326    }else{
9327      rc = process_input(p);
9328      fclose(p->in);
9329    }
9330    p->in = inSaved;
9331    p->lineno = savedLineno;
9332  }else
9333
9334  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9335    const char *zSrcFile;
9336    const char *zDb;
9337    sqlite3 *pSrc;
9338    sqlite3_backup *pBackup;
9339    int nTimeout = 0;
9340
9341    failIfSafeMode(p, "cannot run .restore in safe mode");
9342    if( nArg==2 ){
9343      zSrcFile = azArg[1];
9344      zDb = "main";
9345    }else if( nArg==3 ){
9346      zSrcFile = azArg[2];
9347      zDb = azArg[1];
9348    }else{
9349      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9350      rc = 1;
9351      goto meta_command_exit;
9352    }
9353    rc = sqlite3_open(zSrcFile, &pSrc);
9354    if( rc!=SQLITE_OK ){
9355      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9356      close_db(pSrc);
9357      return 1;
9358    }
9359    open_db(p, 0);
9360    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9361    if( pBackup==0 ){
9362      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9363      close_db(pSrc);
9364      return 1;
9365    }
9366    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9367          || rc==SQLITE_BUSY  ){
9368      if( rc==SQLITE_BUSY ){
9369        if( nTimeout++ >= 3 ) break;
9370        sqlite3_sleep(100);
9371      }
9372    }
9373    sqlite3_backup_finish(pBackup);
9374    if( rc==SQLITE_DONE ){
9375      rc = 0;
9376    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9377      raw_printf(stderr, "Error: source database is busy\n");
9378      rc = 1;
9379    }else{
9380      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9381      rc = 1;
9382    }
9383    close_db(pSrc);
9384  }else
9385
9386  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9387    if( nArg==2 ){
9388      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9389#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9390      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9391#endif
9392    }else{
9393      raw_printf(stderr, "Usage: .scanstats on|off\n");
9394      rc = 1;
9395    }
9396  }else
9397
9398  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9399    ShellText sSelect;
9400    ShellState data;
9401    char *zErrMsg = 0;
9402    const char *zDiv = "(";
9403    const char *zName = 0;
9404    int iSchema = 0;
9405    int bDebug = 0;
9406    int bNoSystemTabs = 0;
9407    int ii;
9408
9409    open_db(p, 0);
9410    memcpy(&data, p, sizeof(data));
9411    data.showHeader = 0;
9412    data.cMode = data.mode = MODE_Semi;
9413    initText(&sSelect);
9414    for(ii=1; ii<nArg; ii++){
9415      if( optionMatch(azArg[ii],"indent") ){
9416        data.cMode = data.mode = MODE_Pretty;
9417      }else if( optionMatch(azArg[ii],"debug") ){
9418        bDebug = 1;
9419      }else if( optionMatch(azArg[ii],"nosys") ){
9420        bNoSystemTabs = 1;
9421      }else if( azArg[ii][0]=='-' ){
9422        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9423        rc = 1;
9424        goto meta_command_exit;
9425      }else if( zName==0 ){
9426        zName = azArg[ii];
9427      }else{
9428        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9429        rc = 1;
9430        goto meta_command_exit;
9431      }
9432    }
9433    if( zName!=0 ){
9434      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9435                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9436                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9437                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9438      if( isSchema ){
9439        char *new_argv[2], *new_colv[2];
9440        new_argv[0] = sqlite3_mprintf(
9441                      "CREATE TABLE %s (\n"
9442                      "  type text,\n"
9443                      "  name text,\n"
9444                      "  tbl_name text,\n"
9445                      "  rootpage integer,\n"
9446                      "  sql text\n"
9447                      ")", zName);
9448        new_argv[1] = 0;
9449        new_colv[0] = "sql";
9450        new_colv[1] = 0;
9451        callback(&data, 1, new_argv, new_colv);
9452        sqlite3_free(new_argv[0]);
9453      }
9454    }
9455    if( zDiv ){
9456      sqlite3_stmt *pStmt = 0;
9457      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9458                              -1, &pStmt, 0);
9459      if( rc ){
9460        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9461        sqlite3_finalize(pStmt);
9462        rc = 1;
9463        goto meta_command_exit;
9464      }
9465      appendText(&sSelect, "SELECT sql FROM", 0);
9466      iSchema = 0;
9467      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9468        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9469        char zScNum[30];
9470        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9471        appendText(&sSelect, zDiv, 0);
9472        zDiv = " UNION ALL ";
9473        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9474        if( sqlite3_stricmp(zDb, "main")!=0 ){
9475          appendText(&sSelect, zDb, '\'');
9476        }else{
9477          appendText(&sSelect, "NULL", 0);
9478        }
9479        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9480        appendText(&sSelect, zScNum, 0);
9481        appendText(&sSelect, " AS snum, ", 0);
9482        appendText(&sSelect, zDb, '\'');
9483        appendText(&sSelect, " AS sname FROM ", 0);
9484        appendText(&sSelect, zDb, quoteChar(zDb));
9485        appendText(&sSelect, ".sqlite_schema", 0);
9486      }
9487      sqlite3_finalize(pStmt);
9488#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9489      if( zName ){
9490        appendText(&sSelect,
9491           " UNION ALL SELECT shell_module_schema(name),"
9492           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9493        0);
9494      }
9495#endif
9496      appendText(&sSelect, ") WHERE ", 0);
9497      if( zName ){
9498        char *zQarg = sqlite3_mprintf("%Q", zName);
9499        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9500                    strchr(zName, '[') != 0;
9501        if( strchr(zName, '.') ){
9502          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9503        }else{
9504          appendText(&sSelect, "lower(tbl_name)", 0);
9505        }
9506        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9507        appendText(&sSelect, zQarg, 0);
9508        if( !bGlob ){
9509          appendText(&sSelect, " ESCAPE '\\' ", 0);
9510        }
9511        appendText(&sSelect, " AND ", 0);
9512        sqlite3_free(zQarg);
9513      }
9514      if( bNoSystemTabs ){
9515        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9516      }
9517      appendText(&sSelect, "sql IS NOT NULL"
9518                           " ORDER BY snum, rowid", 0);
9519      if( bDebug ){
9520        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9521      }else{
9522        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9523      }
9524      freeText(&sSelect);
9525    }
9526    if( zErrMsg ){
9527      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9528      sqlite3_free(zErrMsg);
9529      rc = 1;
9530    }else if( rc != SQLITE_OK ){
9531      raw_printf(stderr,"Error: querying schema information\n");
9532      rc = 1;
9533    }else{
9534      rc = 0;
9535    }
9536  }else
9537
9538  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9539    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9540    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9541  }else
9542
9543#if defined(SQLITE_ENABLE_SESSION)
9544  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9545    struct AuxDb *pAuxDb = p->pAuxDb;
9546    OpenSession *pSession = &pAuxDb->aSession[0];
9547    char **azCmd = &azArg[1];
9548    int iSes = 0;
9549    int nCmd = nArg - 1;
9550    int i;
9551    if( nArg<=1 ) goto session_syntax_error;
9552    open_db(p, 0);
9553    if( nArg>=3 ){
9554      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9555        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9556      }
9557      if( iSes<pAuxDb->nSession ){
9558        pSession = &pAuxDb->aSession[iSes];
9559        azCmd++;
9560        nCmd--;
9561      }else{
9562        pSession = &pAuxDb->aSession[0];
9563        iSes = 0;
9564      }
9565    }
9566
9567    /* .session attach TABLE
9568    ** Invoke the sqlite3session_attach() interface to attach a particular
9569    ** table so that it is never filtered.
9570    */
9571    if( strcmp(azCmd[0],"attach")==0 ){
9572      if( nCmd!=2 ) goto session_syntax_error;
9573      if( pSession->p==0 ){
9574        session_not_open:
9575        raw_printf(stderr, "ERROR: No sessions are open\n");
9576      }else{
9577        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9578        if( rc ){
9579          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9580          rc = 0;
9581        }
9582      }
9583    }else
9584
9585    /* .session changeset FILE
9586    ** .session patchset FILE
9587    ** Write a changeset or patchset into a file.  The file is overwritten.
9588    */
9589    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9590      FILE *out = 0;
9591      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9592      if( nCmd!=2 ) goto session_syntax_error;
9593      if( pSession->p==0 ) goto session_not_open;
9594      out = fopen(azCmd[1], "wb");
9595      if( out==0 ){
9596        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9597                    azCmd[1]);
9598      }else{
9599        int szChng;
9600        void *pChng;
9601        if( azCmd[0][0]=='c' ){
9602          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9603        }else{
9604          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9605        }
9606        if( rc ){
9607          printf("Error: error code %d\n", rc);
9608          rc = 0;
9609        }
9610        if( pChng
9611          && fwrite(pChng, szChng, 1, out)!=1 ){
9612          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9613                  szChng);
9614        }
9615        sqlite3_free(pChng);
9616        fclose(out);
9617      }
9618    }else
9619
9620    /* .session close
9621    ** Close the identified session
9622    */
9623    if( strcmp(azCmd[0], "close")==0 ){
9624      if( nCmd!=1 ) goto session_syntax_error;
9625      if( pAuxDb->nSession ){
9626        session_close(pSession);
9627        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9628      }
9629    }else
9630
9631    /* .session enable ?BOOLEAN?
9632    ** Query or set the enable flag
9633    */
9634    if( strcmp(azCmd[0], "enable")==0 ){
9635      int ii;
9636      if( nCmd>2 ) goto session_syntax_error;
9637      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9638      if( pAuxDb->nSession ){
9639        ii = sqlite3session_enable(pSession->p, ii);
9640        utf8_printf(p->out, "session %s enable flag = %d\n",
9641                    pSession->zName, ii);
9642      }
9643    }else
9644
9645    /* .session filter GLOB ....
9646    ** Set a list of GLOB patterns of table names to be excluded.
9647    */
9648    if( strcmp(azCmd[0], "filter")==0 ){
9649      int ii, nByte;
9650      if( nCmd<2 ) goto session_syntax_error;
9651      if( pAuxDb->nSession ){
9652        for(ii=0; ii<pSession->nFilter; ii++){
9653          sqlite3_free(pSession->azFilter[ii]);
9654        }
9655        sqlite3_free(pSession->azFilter);
9656        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9657        pSession->azFilter = sqlite3_malloc( nByte );
9658        if( pSession->azFilter==0 ){
9659          raw_printf(stderr, "Error: out or memory\n");
9660          exit(1);
9661        }
9662        for(ii=1; ii<nCmd; ii++){
9663          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9664        }
9665        pSession->nFilter = ii-1;
9666      }
9667    }else
9668
9669    /* .session indirect ?BOOLEAN?
9670    ** Query or set the indirect flag
9671    */
9672    if( strcmp(azCmd[0], "indirect")==0 ){
9673      int ii;
9674      if( nCmd>2 ) goto session_syntax_error;
9675      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9676      if( pAuxDb->nSession ){
9677        ii = sqlite3session_indirect(pSession->p, ii);
9678        utf8_printf(p->out, "session %s indirect flag = %d\n",
9679                    pSession->zName, ii);
9680      }
9681    }else
9682
9683    /* .session isempty
9684    ** Determine if the session is empty
9685    */
9686    if( strcmp(azCmd[0], "isempty")==0 ){
9687      int ii;
9688      if( nCmd!=1 ) goto session_syntax_error;
9689      if( pAuxDb->nSession ){
9690        ii = sqlite3session_isempty(pSession->p);
9691        utf8_printf(p->out, "session %s isempty flag = %d\n",
9692                    pSession->zName, ii);
9693      }
9694    }else
9695
9696    /* .session list
9697    ** List all currently open sessions
9698    */
9699    if( strcmp(azCmd[0],"list")==0 ){
9700      for(i=0; i<pAuxDb->nSession; i++){
9701        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9702      }
9703    }else
9704
9705    /* .session open DB NAME
9706    ** Open a new session called NAME on the attached database DB.
9707    ** DB is normally "main".
9708    */
9709    if( strcmp(azCmd[0],"open")==0 ){
9710      char *zName;
9711      if( nCmd!=3 ) goto session_syntax_error;
9712      zName = azCmd[2];
9713      if( zName[0]==0 ) goto session_syntax_error;
9714      for(i=0; i<pAuxDb->nSession; i++){
9715        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9716          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9717          goto meta_command_exit;
9718        }
9719      }
9720      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9721        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9722        goto meta_command_exit;
9723      }
9724      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9725      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9726      if( rc ){
9727        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9728        rc = 0;
9729        goto meta_command_exit;
9730      }
9731      pSession->nFilter = 0;
9732      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9733      pAuxDb->nSession++;
9734      pSession->zName = sqlite3_mprintf("%s", zName);
9735    }else
9736    /* If no command name matches, show a syntax error */
9737    session_syntax_error:
9738    showHelp(p->out, "session");
9739  }else
9740#endif
9741
9742#ifdef SQLITE_DEBUG
9743  /* Undocumented commands for internal testing.  Subject to change
9744  ** without notice. */
9745  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9746    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9747      int i, v;
9748      for(i=1; i<nArg; i++){
9749        v = booleanValue(azArg[i]);
9750        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9751      }
9752    }
9753    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9754      int i; sqlite3_int64 v;
9755      for(i=1; i<nArg; i++){
9756        char zBuf[200];
9757        v = integerValue(azArg[i]);
9758        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9759        utf8_printf(p->out, "%s", zBuf);
9760      }
9761    }
9762  }else
9763#endif
9764
9765  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9766    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9767    int bVerbose = 0;        /* Verbose output */
9768    int bSelftestExists;     /* True if SELFTEST already exists */
9769    int i, k;                /* Loop counters */
9770    int nTest = 0;           /* Number of tests runs */
9771    int nErr = 0;            /* Number of errors seen */
9772    ShellText str;           /* Answer for a query */
9773    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9774
9775    open_db(p,0);
9776    for(i=1; i<nArg; i++){
9777      const char *z = azArg[i];
9778      if( z[0]=='-' && z[1]=='-' ) z++;
9779      if( strcmp(z,"-init")==0 ){
9780        bIsInit = 1;
9781      }else
9782      if( strcmp(z,"-v")==0 ){
9783        bVerbose++;
9784      }else
9785      {
9786        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9787                    azArg[i], azArg[0]);
9788        raw_printf(stderr, "Should be one of: --init -v\n");
9789        rc = 1;
9790        goto meta_command_exit;
9791      }
9792    }
9793    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9794           != SQLITE_OK ){
9795      bSelftestExists = 0;
9796    }else{
9797      bSelftestExists = 1;
9798    }
9799    if( bIsInit ){
9800      createSelftestTable(p);
9801      bSelftestExists = 1;
9802    }
9803    initText(&str);
9804    appendText(&str, "x", 0);
9805    for(k=bSelftestExists; k>=0; k--){
9806      if( k==1 ){
9807        rc = sqlite3_prepare_v2(p->db,
9808            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9809            -1, &pStmt, 0);
9810      }else{
9811        rc = sqlite3_prepare_v2(p->db,
9812          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9813          "      (1,'run','PRAGMA integrity_check','ok')",
9814          -1, &pStmt, 0);
9815      }
9816      if( rc ){
9817        raw_printf(stderr, "Error querying the selftest table\n");
9818        rc = 1;
9819        sqlite3_finalize(pStmt);
9820        goto meta_command_exit;
9821      }
9822      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9823        int tno = sqlite3_column_int(pStmt, 0);
9824        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9825        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9826        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9827
9828        k = 0;
9829        if( bVerbose>0 ){
9830          char *zQuote = sqlite3_mprintf("%q", zSql);
9831          printf("%d: %s %s\n", tno, zOp, zSql);
9832          sqlite3_free(zQuote);
9833        }
9834        if( strcmp(zOp,"memo")==0 ){
9835          utf8_printf(p->out, "%s\n", zSql);
9836        }else
9837        if( strcmp(zOp,"run")==0 ){
9838          char *zErrMsg = 0;
9839          str.n = 0;
9840          str.z[0] = 0;
9841          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9842          nTest++;
9843          if( bVerbose ){
9844            utf8_printf(p->out, "Result: %s\n", str.z);
9845          }
9846          if( rc || zErrMsg ){
9847            nErr++;
9848            rc = 1;
9849            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9850            sqlite3_free(zErrMsg);
9851          }else if( strcmp(zAns,str.z)!=0 ){
9852            nErr++;
9853            rc = 1;
9854            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9855            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9856          }
9857        }else
9858        {
9859          utf8_printf(stderr,
9860            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9861          rc = 1;
9862          break;
9863        }
9864      } /* End loop over rows of content from SELFTEST */
9865      sqlite3_finalize(pStmt);
9866    } /* End loop over k */
9867    freeText(&str);
9868    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9869  }else
9870
9871  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9872    if( nArg<2 || nArg>3 ){
9873      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9874      rc = 1;
9875    }
9876    if( nArg>=2 ){
9877      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9878                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9879    }
9880    if( nArg>=3 ){
9881      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9882                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9883    }
9884  }else
9885
9886  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9887    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
9888    int i;                   /* Loop counter */
9889    int bSchema = 0;         /* Also hash the schema */
9890    int bSeparate = 0;       /* Hash each table separately */
9891    int iSize = 224;         /* Hash algorithm to use */
9892    int bDebug = 0;          /* Only show the query that would have run */
9893    sqlite3_stmt *pStmt;     /* For querying tables names */
9894    char *zSql;              /* SQL to be run */
9895    char *zSep;              /* Separator */
9896    ShellText sSql;          /* Complete SQL for the query to run the hash */
9897    ShellText sQuery;        /* Set of queries used to read all content */
9898    open_db(p, 0);
9899    for(i=1; i<nArg; i++){
9900      const char *z = azArg[i];
9901      if( z[0]=='-' ){
9902        z++;
9903        if( z[0]=='-' ) z++;
9904        if( strcmp(z,"schema")==0 ){
9905          bSchema = 1;
9906        }else
9907        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9908         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9909        ){
9910          iSize = atoi(&z[5]);
9911        }else
9912        if( strcmp(z,"debug")==0 ){
9913          bDebug = 1;
9914        }else
9915        {
9916          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9917                      azArg[i], azArg[0]);
9918          showHelp(p->out, azArg[0]);
9919          rc = 1;
9920          goto meta_command_exit;
9921        }
9922      }else if( zLike ){
9923        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9924        rc = 1;
9925        goto meta_command_exit;
9926      }else{
9927        zLike = z;
9928        bSeparate = 1;
9929        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9930      }
9931    }
9932    if( bSchema ){
9933      zSql = "SELECT lower(name) FROM sqlite_schema"
9934             " WHERE type='table' AND coalesce(rootpage,0)>1"
9935             " UNION ALL SELECT 'sqlite_schema'"
9936             " ORDER BY 1 collate nocase";
9937    }else{
9938      zSql = "SELECT lower(name) FROM sqlite_schema"
9939             " WHERE type='table' AND coalesce(rootpage,0)>1"
9940             " AND name NOT LIKE 'sqlite_%'"
9941             " ORDER BY 1 collate nocase";
9942    }
9943    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9944    initText(&sQuery);
9945    initText(&sSql);
9946    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9947    zSep = "VALUES(";
9948    while( SQLITE_ROW==sqlite3_step(pStmt) ){
9949      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
9950      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
9951      if( strncmp(zTab, "sqlite_",7)!=0 ){
9952        appendText(&sQuery,"SELECT * FROM ", 0);
9953        appendText(&sQuery,zTab,'"');
9954        appendText(&sQuery," NOT INDEXED;", 0);
9955      }else if( strcmp(zTab, "sqlite_schema")==0 ){
9956        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
9957                           " ORDER BY name;", 0);
9958      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
9959        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
9960                           " ORDER BY name;", 0);
9961      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
9962        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
9963                           " ORDER BY tbl,idx;", 0);
9964      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
9965        appendText(&sQuery, "SELECT * FROM ", 0);
9966        appendText(&sQuery, zTab, 0);
9967        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
9968      }
9969      appendText(&sSql, zSep, 0);
9970      appendText(&sSql, sQuery.z, '\'');
9971      sQuery.n = 0;
9972      appendText(&sSql, ",", 0);
9973      appendText(&sSql, zTab, '\'');
9974      zSep = "),(";
9975    }
9976    sqlite3_finalize(pStmt);
9977    if( bSeparate ){
9978      zSql = sqlite3_mprintf(
9979          "%s))"
9980          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
9981          "   FROM [sha3sum$query]",
9982          sSql.z, iSize);
9983    }else{
9984      zSql = sqlite3_mprintf(
9985          "%s))"
9986          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
9987          "   FROM [sha3sum$query]",
9988          sSql.z, iSize);
9989    }
9990    freeText(&sQuery);
9991    freeText(&sSql);
9992    if( bDebug ){
9993      utf8_printf(p->out, "%s\n", zSql);
9994    }else{
9995      shell_exec(p, zSql, 0);
9996    }
9997    sqlite3_free(zSql);
9998  }else
9999
10000#ifndef SQLITE_NOHAVE_SYSTEM
10001  if( c=='s'
10002   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10003  ){
10004    char *zCmd;
10005    int i, x;
10006    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10007    if( nArg<2 ){
10008      raw_printf(stderr, "Usage: .system COMMAND\n");
10009      rc = 1;
10010      goto meta_command_exit;
10011    }
10012    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10013    for(i=2; i<nArg; i++){
10014      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10015                             zCmd, azArg[i]);
10016    }
10017    x = system(zCmd);
10018    sqlite3_free(zCmd);
10019    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10020  }else
10021#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10022
10023  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10024    static const char *azBool[] = { "off", "on", "trigger", "full"};
10025    const char *zOut;
10026    int i;
10027    if( nArg!=1 ){
10028      raw_printf(stderr, "Usage: .show\n");
10029      rc = 1;
10030      goto meta_command_exit;
10031    }
10032    utf8_printf(p->out, "%12.12s: %s\n","echo",
10033                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10034    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10035    utf8_printf(p->out, "%12.12s: %s\n","explain",
10036         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10037    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10038    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10039    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10040      output_c_string(p->out, p->nullValue);
10041      raw_printf(p->out, "\n");
10042    utf8_printf(p->out,"%12.12s: %s\n","output",
10043            strlen30(p->outfile) ? p->outfile : "stdout");
10044    utf8_printf(p->out,"%12.12s: ", "colseparator");
10045      output_c_string(p->out, p->colSeparator);
10046      raw_printf(p->out, "\n");
10047    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10048      output_c_string(p->out, p->rowSeparator);
10049      raw_printf(p->out, "\n");
10050    switch( p->statsOn ){
10051      case 0:  zOut = "off";     break;
10052      default: zOut = "on";      break;
10053      case 2:  zOut = "stmt";    break;
10054      case 3:  zOut = "vmstep";  break;
10055    }
10056    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10057    utf8_printf(p->out, "%12.12s: ", "width");
10058    for (i=0;i<p->nWidth;i++) {
10059      raw_printf(p->out, "%d ", p->colWidth[i]);
10060    }
10061    raw_printf(p->out, "\n");
10062    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10063                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10064  }else
10065
10066  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10067    if( nArg==2 ){
10068      if( strcmp(azArg[1],"stmt")==0 ){
10069        p->statsOn = 2;
10070      }else if( strcmp(azArg[1],"vmstep")==0 ){
10071        p->statsOn = 3;
10072      }else{
10073        p->statsOn = (u8)booleanValue(azArg[1]);
10074      }
10075    }else if( nArg==1 ){
10076      display_stats(p->db, p, 0);
10077    }else{
10078      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10079      rc = 1;
10080    }
10081  }else
10082
10083  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10084   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10085                 || strncmp(azArg[0], "indexes", n)==0) )
10086  ){
10087    sqlite3_stmt *pStmt;
10088    char **azResult;
10089    int nRow, nAlloc;
10090    int ii;
10091    ShellText s;
10092    initText(&s);
10093    open_db(p, 0);
10094    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10095    if( rc ){
10096      sqlite3_finalize(pStmt);
10097      return shellDatabaseError(p->db);
10098    }
10099
10100    if( nArg>2 && c=='i' ){
10101      /* It is an historical accident that the .indexes command shows an error
10102      ** when called with the wrong number of arguments whereas the .tables
10103      ** command does not. */
10104      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10105      rc = 1;
10106      sqlite3_finalize(pStmt);
10107      goto meta_command_exit;
10108    }
10109    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10110      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10111      if( zDbName==0 ) continue;
10112      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10113      if( sqlite3_stricmp(zDbName, "main")==0 ){
10114        appendText(&s, "SELECT name FROM ", 0);
10115      }else{
10116        appendText(&s, "SELECT ", 0);
10117        appendText(&s, zDbName, '\'');
10118        appendText(&s, "||'.'||name FROM ", 0);
10119      }
10120      appendText(&s, zDbName, '"');
10121      appendText(&s, ".sqlite_schema ", 0);
10122      if( c=='t' ){
10123        appendText(&s," WHERE type IN ('table','view')"
10124                      "   AND name NOT LIKE 'sqlite_%'"
10125                      "   AND name LIKE ?1", 0);
10126      }else{
10127        appendText(&s," WHERE type='index'"
10128                      "   AND tbl_name LIKE ?1", 0);
10129      }
10130    }
10131    rc = sqlite3_finalize(pStmt);
10132    if( rc==SQLITE_OK ){
10133      appendText(&s, " ORDER BY 1", 0);
10134      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10135    }
10136    freeText(&s);
10137    if( rc ) return shellDatabaseError(p->db);
10138
10139    /* Run the SQL statement prepared by the above block. Store the results
10140    ** as an array of nul-terminated strings in azResult[].  */
10141    nRow = nAlloc = 0;
10142    azResult = 0;
10143    if( nArg>1 ){
10144      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10145    }else{
10146      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10147    }
10148    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10149      if( nRow>=nAlloc ){
10150        char **azNew;
10151        int n2 = nAlloc*2 + 10;
10152        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10153        if( azNew==0 ) shell_out_of_memory();
10154        nAlloc = n2;
10155        azResult = azNew;
10156      }
10157      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10158      if( 0==azResult[nRow] ) shell_out_of_memory();
10159      nRow++;
10160    }
10161    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10162      rc = shellDatabaseError(p->db);
10163    }
10164
10165    /* Pretty-print the contents of array azResult[] to the output */
10166    if( rc==0 && nRow>0 ){
10167      int len, maxlen = 0;
10168      int i, j;
10169      int nPrintCol, nPrintRow;
10170      for(i=0; i<nRow; i++){
10171        len = strlen30(azResult[i]);
10172        if( len>maxlen ) maxlen = len;
10173      }
10174      nPrintCol = 80/(maxlen+2);
10175      if( nPrintCol<1 ) nPrintCol = 1;
10176      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10177      for(i=0; i<nPrintRow; i++){
10178        for(j=i; j<nRow; j+=nPrintRow){
10179          char *zSp = j<nPrintRow ? "" : "  ";
10180          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10181                      azResult[j] ? azResult[j]:"");
10182        }
10183        raw_printf(p->out, "\n");
10184      }
10185    }
10186
10187    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10188    sqlite3_free(azResult);
10189  }else
10190
10191  /* Begin redirecting output to the file "testcase-out.txt" */
10192  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10193    output_reset(p);
10194    p->out = output_file_open("testcase-out.txt", 0);
10195    if( p->out==0 ){
10196      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10197    }
10198    if( nArg>=2 ){
10199      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10200    }else{
10201      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10202    }
10203  }else
10204
10205#ifndef SQLITE_UNTESTABLE
10206  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10207    static const struct {
10208       const char *zCtrlName;   /* Name of a test-control option */
10209       int ctrlCode;            /* Integer code for that option */
10210       const char *zUsage;      /* Usage notes */
10211    } aCtrl[] = {
10212      { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
10213      { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
10214    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
10215    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
10216      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
10217      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
10218    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
10219      { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
10220      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
10221      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
10222      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
10223      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
10224#ifdef YYCOVERAGE
10225      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
10226#endif
10227      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
10228      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
10229      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
10230      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
10231      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
10232      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP,   "NMAX"           },
10233      { "tune",               SQLITE_TESTCTRL_TUNE,          "ID VALUE"       },
10234    };
10235    int testctrl = -1;
10236    int iCtrl = -1;
10237    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10238    int isOk = 0;
10239    int i, n2;
10240    const char *zCmd = 0;
10241
10242    open_db(p, 0);
10243    zCmd = nArg>=2 ? azArg[1] : "help";
10244
10245    /* The argument can optionally begin with "-" or "--" */
10246    if( zCmd[0]=='-' && zCmd[1] ){
10247      zCmd++;
10248      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10249    }
10250
10251    /* --help lists all test-controls */
10252    if( strcmp(zCmd,"help")==0 ){
10253      utf8_printf(p->out, "Available test-controls:\n");
10254      for(i=0; i<ArraySize(aCtrl); i++){
10255        utf8_printf(p->out, "  .testctrl %s %s\n",
10256                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10257      }
10258      rc = 1;
10259      goto meta_command_exit;
10260    }
10261
10262    /* convert testctrl text option to value. allow any unique prefix
10263    ** of the option name, or a numerical value. */
10264    n2 = strlen30(zCmd);
10265    for(i=0; i<ArraySize(aCtrl); i++){
10266      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10267        if( testctrl<0 ){
10268          testctrl = aCtrl[i].ctrlCode;
10269          iCtrl = i;
10270        }else{
10271          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10272                              "Use \".testctrl --help\" for help\n", zCmd);
10273          rc = 1;
10274          goto meta_command_exit;
10275        }
10276      }
10277    }
10278    if( testctrl<0 ){
10279      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10280                         "Use \".testctrl --help\" for help\n", zCmd);
10281    }else{
10282      switch(testctrl){
10283
10284        /* sqlite3_test_control(int, db, int) */
10285        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10286          if( nArg==3 ){
10287            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10288            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10289            isOk = 3;
10290          }
10291          break;
10292
10293        /* sqlite3_test_control(int) */
10294        case SQLITE_TESTCTRL_PRNG_SAVE:
10295        case SQLITE_TESTCTRL_PRNG_RESTORE:
10296        case SQLITE_TESTCTRL_BYTEORDER:
10297          if( nArg==2 ){
10298            rc2 = sqlite3_test_control(testctrl);
10299            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10300          }
10301          break;
10302
10303        /* sqlite3_test_control(int, uint) */
10304        case SQLITE_TESTCTRL_PENDING_BYTE:
10305          if( nArg==3 ){
10306            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10307            rc2 = sqlite3_test_control(testctrl, opt);
10308            isOk = 3;
10309          }
10310          break;
10311
10312        /* sqlite3_test_control(int, int, sqlite3*) */
10313        case SQLITE_TESTCTRL_PRNG_SEED:
10314          if( nArg==3 || nArg==4 ){
10315            int ii = (int)integerValue(azArg[2]);
10316            sqlite3 *db;
10317            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10318              sqlite3_randomness(sizeof(ii),&ii);
10319              printf("-- random seed: %d\n", ii);
10320            }
10321            if( nArg==3 ){
10322              db = 0;
10323            }else{
10324              db = p->db;
10325              /* Make sure the schema has been loaded */
10326              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10327            }
10328            rc2 = sqlite3_test_control(testctrl, ii, db);
10329            isOk = 3;
10330          }
10331          break;
10332
10333        /* sqlite3_test_control(int, int) */
10334        case SQLITE_TESTCTRL_ASSERT:
10335        case SQLITE_TESTCTRL_ALWAYS:
10336          if( nArg==3 ){
10337            int opt = booleanValue(azArg[2]);
10338            rc2 = sqlite3_test_control(testctrl, opt);
10339            isOk = 1;
10340          }
10341          break;
10342
10343        /* sqlite3_test_control(int, int) */
10344        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10345        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10346          if( nArg==3 ){
10347            int opt = booleanValue(azArg[2]);
10348            rc2 = sqlite3_test_control(testctrl, opt);
10349            isOk = 3;
10350          }
10351          break;
10352
10353        /* sqlite3_test_control(sqlite3*) */
10354        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10355          rc2 = sqlite3_test_control(testctrl, p->db);
10356          isOk = 3;
10357          break;
10358
10359        case SQLITE_TESTCTRL_IMPOSTER:
10360          if( nArg==5 ){
10361            rc2 = sqlite3_test_control(testctrl, p->db,
10362                          azArg[2],
10363                          integerValue(azArg[3]),
10364                          integerValue(azArg[4]));
10365            isOk = 3;
10366          }
10367          break;
10368
10369        case SQLITE_TESTCTRL_SEEK_COUNT: {
10370          u64 x = 0;
10371          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10372          utf8_printf(p->out, "%llu\n", x);
10373          isOk = 3;
10374          break;
10375        }
10376
10377#ifdef YYCOVERAGE
10378        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10379          if( nArg==2 ){
10380            sqlite3_test_control(testctrl, p->out);
10381            isOk = 3;
10382          }
10383          break;
10384        }
10385#endif
10386#ifdef SQLITE_DEBUG
10387        case SQLITE_TESTCTRL_TUNE: {
10388          if( nArg==4 ){
10389            int id = (int)integerValue(azArg[2]);
10390            int val = (int)integerValue(azArg[3]);
10391            sqlite3_test_control(testctrl, id, &val);
10392            isOk = 3;
10393          }else if( nArg==3 ){
10394            int id = (int)integerValue(azArg[2]);
10395            sqlite3_test_control(testctrl, -id, &rc2);
10396            isOk = 1;
10397          }else if( nArg==2 ){
10398            int id = 1;
10399            while(1){
10400              int val = 0;
10401              rc2 = sqlite3_test_control(testctrl, -id, &val);
10402              if( rc2!=SQLITE_OK ) break;
10403              if( id>1 ) utf8_printf(p->out, "  ");
10404              utf8_printf(p->out, "%d: %d", id, val);
10405              id++;
10406            }
10407            if( id>1 ) utf8_printf(p->out, "\n");
10408            isOk = 3;
10409          }
10410          break;
10411        }
10412#endif
10413        case SQLITE_TESTCTRL_SORTER_MMAP:
10414          if( nArg==3 ){
10415            int opt = (unsigned int)integerValue(azArg[2]);
10416            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10417            isOk = 3;
10418          }
10419          break;
10420      }
10421    }
10422    if( isOk==0 && iCtrl>=0 ){
10423      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10424      rc = 1;
10425    }else if( isOk==1 ){
10426      raw_printf(p->out, "%d\n", rc2);
10427    }else if( isOk==2 ){
10428      raw_printf(p->out, "0x%08x\n", rc2);
10429    }
10430  }else
10431#endif /* !defined(SQLITE_UNTESTABLE) */
10432
10433  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10434    open_db(p, 0);
10435    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10436  }else
10437
10438  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10439    if( nArg==2 ){
10440      enableTimer = booleanValue(azArg[1]);
10441      if( enableTimer && !HAS_TIMER ){
10442        raw_printf(stderr, "Error: timer not available on this system.\n");
10443        enableTimer = 0;
10444      }
10445    }else{
10446      raw_printf(stderr, "Usage: .timer on|off\n");
10447      rc = 1;
10448    }
10449  }else
10450
10451#ifndef SQLITE_OMIT_TRACE
10452  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10453    int mType = 0;
10454    int jj;
10455    open_db(p, 0);
10456    for(jj=1; jj<nArg; jj++){
10457      const char *z = azArg[jj];
10458      if( z[0]=='-' ){
10459        if( optionMatch(z, "expanded") ){
10460          p->eTraceType = SHELL_TRACE_EXPANDED;
10461        }
10462#ifdef SQLITE_ENABLE_NORMALIZE
10463        else if( optionMatch(z, "normalized") ){
10464          p->eTraceType = SHELL_TRACE_NORMALIZED;
10465        }
10466#endif
10467        else if( optionMatch(z, "plain") ){
10468          p->eTraceType = SHELL_TRACE_PLAIN;
10469        }
10470        else if( optionMatch(z, "profile") ){
10471          mType |= SQLITE_TRACE_PROFILE;
10472        }
10473        else if( optionMatch(z, "row") ){
10474          mType |= SQLITE_TRACE_ROW;
10475        }
10476        else if( optionMatch(z, "stmt") ){
10477          mType |= SQLITE_TRACE_STMT;
10478        }
10479        else if( optionMatch(z, "close") ){
10480          mType |= SQLITE_TRACE_CLOSE;
10481        }
10482        else {
10483          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10484          rc = 1;
10485          goto meta_command_exit;
10486        }
10487      }else{
10488        output_file_close(p->traceOut);
10489        p->traceOut = output_file_open(azArg[1], 0);
10490      }
10491    }
10492    if( p->traceOut==0 ){
10493      sqlite3_trace_v2(p->db, 0, 0, 0);
10494    }else{
10495      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10496      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10497    }
10498  }else
10499#endif /* !defined(SQLITE_OMIT_TRACE) */
10500
10501#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10502  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10503    int ii;
10504    int lenOpt;
10505    char *zOpt;
10506    if( nArg<2 ){
10507      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10508      rc = 1;
10509      goto meta_command_exit;
10510    }
10511    open_db(p, 0);
10512    zOpt = azArg[1];
10513    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10514    lenOpt = (int)strlen(zOpt);
10515    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10516      assert( azArg[nArg]==0 );
10517      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10518    }else{
10519      for(ii=1; ii<nArg; ii++){
10520        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10521      }
10522    }
10523  }else
10524#endif
10525
10526#if SQLITE_USER_AUTHENTICATION
10527  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10528    if( nArg<2 ){
10529      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10530      rc = 1;
10531      goto meta_command_exit;
10532    }
10533    open_db(p, 0);
10534    if( strcmp(azArg[1],"login")==0 ){
10535      if( nArg!=4 ){
10536        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10537        rc = 1;
10538        goto meta_command_exit;
10539      }
10540      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10541                                     strlen30(azArg[3]));
10542      if( rc ){
10543        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10544        rc = 1;
10545      }
10546    }else if( strcmp(azArg[1],"add")==0 ){
10547      if( nArg!=5 ){
10548        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10549        rc = 1;
10550        goto meta_command_exit;
10551      }
10552      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10553                            booleanValue(azArg[4]));
10554      if( rc ){
10555        raw_printf(stderr, "User-Add failed: %d\n", rc);
10556        rc = 1;
10557      }
10558    }else if( strcmp(azArg[1],"edit")==0 ){
10559      if( nArg!=5 ){
10560        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10561        rc = 1;
10562        goto meta_command_exit;
10563      }
10564      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10565                              booleanValue(azArg[4]));
10566      if( rc ){
10567        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10568        rc = 1;
10569      }
10570    }else if( strcmp(azArg[1],"delete")==0 ){
10571      if( nArg!=3 ){
10572        raw_printf(stderr, "Usage: .user delete USER\n");
10573        rc = 1;
10574        goto meta_command_exit;
10575      }
10576      rc = sqlite3_user_delete(p->db, azArg[2]);
10577      if( rc ){
10578        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10579        rc = 1;
10580      }
10581    }else{
10582      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10583      rc = 1;
10584      goto meta_command_exit;
10585    }
10586  }else
10587#endif /* SQLITE_USER_AUTHENTICATION */
10588
10589  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10590    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10591        sqlite3_libversion(), sqlite3_sourceid());
10592#if SQLITE_HAVE_ZLIB
10593    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10594#endif
10595#define CTIMEOPT_VAL_(opt) #opt
10596#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10597#if defined(__clang__) && defined(__clang_major__)
10598    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10599                    CTIMEOPT_VAL(__clang_minor__) "."
10600                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10601#elif defined(_MSC_VER)
10602    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10603#elif defined(__GNUC__) && defined(__VERSION__)
10604    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10605#endif
10606  }else
10607
10608  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10609    const char *zDbName = nArg==2 ? azArg[1] : "main";
10610    sqlite3_vfs *pVfs = 0;
10611    if( p->db ){
10612      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10613      if( pVfs ){
10614        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10615        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10616        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10617        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10618      }
10619    }
10620  }else
10621
10622  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10623    sqlite3_vfs *pVfs;
10624    sqlite3_vfs *pCurrent = 0;
10625    if( p->db ){
10626      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10627    }
10628    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10629      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10630           pVfs==pCurrent ? "  <--- CURRENT" : "");
10631      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10632      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10633      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10634      if( pVfs->pNext ){
10635        raw_printf(p->out, "-----------------------------------\n");
10636      }
10637    }
10638  }else
10639
10640  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10641    const char *zDbName = nArg==2 ? azArg[1] : "main";
10642    char *zVfsName = 0;
10643    if( p->db ){
10644      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10645      if( zVfsName ){
10646        utf8_printf(p->out, "%s\n", zVfsName);
10647        sqlite3_free(zVfsName);
10648      }
10649    }
10650  }else
10651
10652  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10653    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10654    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10655  }else
10656
10657  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10658    int j;
10659    assert( nArg<=ArraySize(azArg) );
10660    p->nWidth = nArg-1;
10661    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10662    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10663    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10664    for(j=1; j<nArg; j++){
10665      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10666    }
10667  }else
10668
10669  {
10670    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10671      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10672    rc = 1;
10673  }
10674
10675meta_command_exit:
10676  if( p->outCount ){
10677    p->outCount--;
10678    if( p->outCount==0 ) output_reset(p);
10679  }
10680  p->bSafeMode = p->bSafeModePersist;
10681  return rc;
10682}
10683
10684/* Line scan result and intermediate states (supporting scan resumption)
10685*/
10686#ifndef CHAR_BIT
10687# define CHAR_BIT 8
10688#endif
10689typedef enum {
10690  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10691  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10692  QSS_Start = 0
10693} QuickScanState;
10694#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10695#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10696#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10697#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10698#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10699
10700/*
10701** Scan line for classification to guide shell's handling.
10702** The scan is resumable for subsequent lines when prior
10703** return values are passed as the 2nd argument.
10704*/
10705static QuickScanState quickscan(char *zLine, QuickScanState qss){
10706  char cin;
10707  char cWait = (char)qss; /* intentional narrowing loss */
10708  if( cWait==0 ){
10709  PlainScan:
10710    assert( cWait==0 );
10711    while( (cin = *zLine++)!=0 ){
10712      if( IsSpace(cin) )
10713        continue;
10714      switch (cin){
10715      case '-':
10716        if( *zLine!='-' )
10717          break;
10718        while((cin = *++zLine)!=0 )
10719          if( cin=='\n')
10720            goto PlainScan;
10721        return qss;
10722      case ';':
10723        qss |= QSS_EndingSemi;
10724        continue;
10725      case '/':
10726        if( *zLine=='*' ){
10727          ++zLine;
10728          cWait = '*';
10729          qss = QSS_SETV(qss, cWait);
10730          goto TermScan;
10731        }
10732        break;
10733      case '[':
10734        cin = ']';
10735        /* fall thru */
10736      case '`': case '\'': case '"':
10737        cWait = cin;
10738        qss = QSS_HasDark | cWait;
10739        goto TermScan;
10740      default:
10741        break;
10742      }
10743      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10744    }
10745  }else{
10746  TermScan:
10747    while( (cin = *zLine++)!=0 ){
10748      if( cin==cWait ){
10749        switch( cWait ){
10750        case '*':
10751          if( *zLine != '/' )
10752            continue;
10753          ++zLine;
10754          cWait = 0;
10755          qss = QSS_SETV(qss, 0);
10756          goto PlainScan;
10757        case '`': case '\'': case '"':
10758          if(*zLine==cWait){
10759            ++zLine;
10760            continue;
10761          }
10762          /* fall thru */
10763        case ']':
10764          cWait = 0;
10765          qss = QSS_SETV(qss, 0);
10766          goto PlainScan;
10767        default: assert(0);
10768        }
10769      }
10770    }
10771  }
10772  return qss;
10773}
10774
10775/*
10776** Return TRUE if the line typed in is an SQL command terminator other
10777** than a semi-colon.  The SQL Server style "go" command is understood
10778** as is the Oracle "/".
10779*/
10780static int line_is_command_terminator(char *zLine){
10781  while( IsSpace(zLine[0]) ){ zLine++; };
10782  if( zLine[0]=='/' )
10783    zLine += 1; /* Oracle */
10784  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10785    zLine += 2; /* SQL Server */
10786  else
10787    return 0;
10788  return quickscan(zLine,QSS_Start)==QSS_Start;
10789}
10790
10791/*
10792** We need a default sqlite3_complete() implementation to use in case
10793** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10794** any arbitrary text is a complete SQL statement.  This is not very
10795** user-friendly, but it does seem to work.
10796*/
10797#ifdef SQLITE_OMIT_COMPLETE
10798#define sqlite3_complete(x) 1
10799#endif
10800
10801/*
10802** Return true if zSql is a complete SQL statement.  Return false if it
10803** ends in the middle of a string literal or C-style comment.
10804*/
10805static int line_is_complete(char *zSql, int nSql){
10806  int rc;
10807  if( zSql==0 ) return 1;
10808  zSql[nSql] = ';';
10809  zSql[nSql+1] = 0;
10810  rc = sqlite3_complete(zSql);
10811  zSql[nSql] = 0;
10812  return rc;
10813}
10814
10815/*
10816** Run a single line of SQL.  Return the number of errors.
10817*/
10818static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10819  int rc;
10820  char *zErrMsg = 0;
10821
10822  open_db(p, 0);
10823  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10824  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10825  BEGIN_TIMER;
10826  rc = shell_exec(p, zSql, &zErrMsg);
10827  END_TIMER;
10828  if( rc || zErrMsg ){
10829    char zPrefix[100];
10830    if( in!=0 || !stdin_is_interactive ){
10831      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10832                       "Error: near line %d:", startline);
10833    }else{
10834      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10835    }
10836    if( zErrMsg!=0 ){
10837      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10838      sqlite3_free(zErrMsg);
10839      zErrMsg = 0;
10840    }else{
10841      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10842    }
10843    return 1;
10844  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10845    char zLineBuf[2000];
10846    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
10847            "changes: %lld   total_changes: %lld",
10848            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
10849    raw_printf(p->out, "%s\n", zLineBuf);
10850  }
10851  return 0;
10852}
10853
10854
10855/*
10856** Read input from *in and process it.  If *in==0 then input
10857** is interactive - the user is typing it it.  Otherwise, input
10858** is coming from a file or device.  A prompt is issued and history
10859** is saved only if input is interactive.  An interrupt signal will
10860** cause this routine to exit immediately, unless input is interactive.
10861**
10862** Return the number of errors.
10863*/
10864static int process_input(ShellState *p){
10865  char *zLine = 0;          /* A single input line */
10866  char *zSql = 0;           /* Accumulated SQL text */
10867  int nLine;                /* Length of current line */
10868  int nSql = 0;             /* Bytes of zSql[] used */
10869  int nAlloc = 0;           /* Allocated zSql[] space */
10870  int rc;                   /* Error code */
10871  int errCnt = 0;           /* Number of errors seen */
10872  int startline = 0;        /* Line number for start of current input */
10873  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
10874
10875  p->lineno = 0;
10876  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10877    fflush(p->out);
10878    zLine = one_input_line(p->in, zLine, nSql>0);
10879    if( zLine==0 ){
10880      /* End of input */
10881      if( p->in==0 && stdin_is_interactive ) printf("\n");
10882      break;
10883    }
10884    if( seenInterrupt ){
10885      if( p->in!=0 ) break;
10886      seenInterrupt = 0;
10887    }
10888    p->lineno++;
10889    if( QSS_INPLAIN(qss)
10890        && line_is_command_terminator(zLine)
10891        && line_is_complete(zSql, nSql) ){
10892      memcpy(zLine,";",2);
10893    }
10894    qss = quickscan(zLine, qss);
10895    if( QSS_PLAINWHITE(qss) && nSql==0 ){
10896      if( ShellHasFlag(p, SHFLG_Echo) )
10897        printf("%s\n", zLine);
10898      /* Just swallow single-line whitespace */
10899      qss = QSS_Start;
10900      continue;
10901    }
10902    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10903      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10904      if( zLine[0]=='.' ){
10905        rc = do_meta_command(zLine, p);
10906        if( rc==2 ){ /* exit requested */
10907          break;
10908        }else if( rc ){
10909          errCnt++;
10910        }
10911      }
10912      qss = QSS_Start;
10913      continue;
10914    }
10915    /* No single-line dispositions remain; accumulate line(s). */
10916    nLine = strlen30(zLine);
10917    if( nSql+nLine+2>=nAlloc ){
10918      /* Grow buffer by half-again increments when big. */
10919      nAlloc = nSql+(nSql>>1)+nLine+100;
10920      zSql = realloc(zSql, nAlloc);
10921      if( zSql==0 ) shell_out_of_memory();
10922    }
10923    if( nSql==0 ){
10924      int i;
10925      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10926      assert( nAlloc>0 && zSql!=0 );
10927      memcpy(zSql, zLine+i, nLine+1-i);
10928      startline = p->lineno;
10929      nSql = nLine-i;
10930    }else{
10931      zSql[nSql++] = '\n';
10932      memcpy(zSql+nSql, zLine, nLine+1);
10933      nSql += nLine;
10934    }
10935    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
10936      errCnt += runOneSqlLine(p, zSql, p->in, startline);
10937      nSql = 0;
10938      if( p->outCount ){
10939        output_reset(p);
10940        p->outCount = 0;
10941      }else{
10942        clearTempFile(p);
10943      }
10944      p->bSafeMode = p->bSafeModePersist;
10945      qss = QSS_Start;
10946    }else if( nSql && QSS_PLAINWHITE(qss) ){
10947      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
10948      nSql = 0;
10949      qss = QSS_Start;
10950    }
10951  }
10952  if( nSql && QSS_PLAINDARK(qss) ){
10953    errCnt += runOneSqlLine(p, zSql, p->in, startline);
10954  }
10955  free(zSql);
10956  free(zLine);
10957  return errCnt>0;
10958}
10959
10960/*
10961** Return a pathname which is the user's home directory.  A
10962** 0 return indicates an error of some kind.
10963*/
10964static char *find_home_dir(int clearFlag){
10965  static char *home_dir = NULL;
10966  if( clearFlag ){
10967    free(home_dir);
10968    home_dir = 0;
10969    return 0;
10970  }
10971  if( home_dir ) return home_dir;
10972
10973#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
10974     && !defined(__RTP__) && !defined(_WRS_KERNEL)
10975  {
10976    struct passwd *pwent;
10977    uid_t uid = getuid();
10978    if( (pwent=getpwuid(uid)) != NULL) {
10979      home_dir = pwent->pw_dir;
10980    }
10981  }
10982#endif
10983
10984#if defined(_WIN32_WCE)
10985  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
10986   */
10987  home_dir = "/";
10988#else
10989
10990#if defined(_WIN32) || defined(WIN32)
10991  if (!home_dir) {
10992    home_dir = getenv("USERPROFILE");
10993  }
10994#endif
10995
10996  if (!home_dir) {
10997    home_dir = getenv("HOME");
10998  }
10999
11000#if defined(_WIN32) || defined(WIN32)
11001  if (!home_dir) {
11002    char *zDrive, *zPath;
11003    int n;
11004    zDrive = getenv("HOMEDRIVE");
11005    zPath = getenv("HOMEPATH");
11006    if( zDrive && zPath ){
11007      n = strlen30(zDrive) + strlen30(zPath) + 1;
11008      home_dir = malloc( n );
11009      if( home_dir==0 ) return 0;
11010      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11011      return home_dir;
11012    }
11013    home_dir = "c:\\";
11014  }
11015#endif
11016
11017#endif /* !_WIN32_WCE */
11018
11019  if( home_dir ){
11020    int n = strlen30(home_dir) + 1;
11021    char *z = malloc( n );
11022    if( z ) memcpy(z, home_dir, n);
11023    home_dir = z;
11024  }
11025
11026  return home_dir;
11027}
11028
11029/*
11030** Read input from the file given by sqliterc_override.  Or if that
11031** parameter is NULL, take input from ~/.sqliterc
11032**
11033** Returns the number of errors.
11034*/
11035static void process_sqliterc(
11036  ShellState *p,                  /* Configuration data */
11037  const char *sqliterc_override   /* Name of config file. NULL to use default */
11038){
11039  char *home_dir = NULL;
11040  const char *sqliterc = sqliterc_override;
11041  char *zBuf = 0;
11042  FILE *inSaved = p->in;
11043  int savedLineno = p->lineno;
11044
11045  if (sqliterc == NULL) {
11046    home_dir = find_home_dir(0);
11047    if( home_dir==0 ){
11048      raw_printf(stderr, "-- warning: cannot find home directory;"
11049                      " cannot read ~/.sqliterc\n");
11050      return;
11051    }
11052    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11053    sqliterc = zBuf;
11054  }
11055  p->in = fopen(sqliterc,"rb");
11056  if( p->in ){
11057    if( stdin_is_interactive ){
11058      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11059    }
11060    if( process_input(p) && bail_on_error ) exit(1);
11061    fclose(p->in);
11062  }else if( sqliterc_override!=0 ){
11063    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11064    if( bail_on_error ) exit(1);
11065  }
11066  p->in = inSaved;
11067  p->lineno = savedLineno;
11068  sqlite3_free(zBuf);
11069}
11070
11071/*
11072** Show available command line options
11073*/
11074static const char zOptions[] =
11075#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11076  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11077#endif
11078  "   -append              append the database to the end of the file\n"
11079  "   -ascii               set output mode to 'ascii'\n"
11080  "   -bail                stop after hitting an error\n"
11081  "   -batch               force batch I/O\n"
11082  "   -box                 set output mode to 'box'\n"
11083  "   -column              set output mode to 'column'\n"
11084  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11085  "   -csv                 set output mode to 'csv'\n"
11086#if !defined(SQLITE_OMIT_DESERIALIZE)
11087  "   -deserialize         open the database using sqlite3_deserialize()\n"
11088#endif
11089  "   -echo                print commands before execution\n"
11090  "   -init FILENAME       read/process named file\n"
11091  "   -[no]header          turn headers on or off\n"
11092#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11093  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11094#endif
11095  "   -help                show this message\n"
11096  "   -html                set output mode to HTML\n"
11097  "   -interactive         force interactive I/O\n"
11098  "   -json                set output mode to 'json'\n"
11099  "   -line                set output mode to 'line'\n"
11100  "   -list                set output mode to 'list'\n"
11101  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11102  "   -markdown            set output mode to 'markdown'\n"
11103#if !defined(SQLITE_OMIT_DESERIALIZE)
11104  "   -maxsize N           maximum size for a --deserialize database\n"
11105#endif
11106  "   -memtrace            trace all memory allocations and deallocations\n"
11107  "   -mmap N              default mmap size set to N\n"
11108#ifdef SQLITE_ENABLE_MULTIPLEX
11109  "   -multiplex           enable the multiplexor VFS\n"
11110#endif
11111  "   -newline SEP         set output row separator. Default: '\\n'\n"
11112  "   -nofollow            refuse to open symbolic links to database files\n"
11113  "   -nonce STRING        set the safe-mode escape nonce\n"
11114  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11115  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11116  "   -quote               set output mode to 'quote'\n"
11117  "   -readonly            open the database read-only\n"
11118  "   -safe                enable safe-mode\n"
11119  "   -separator SEP       set output column separator. Default: '|'\n"
11120#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11121  "   -sorterref SIZE      sorter references threshold size\n"
11122#endif
11123  "   -stats               print memory stats before each finalize\n"
11124  "   -table               set output mode to 'table'\n"
11125  "   -tabs                set output mode to 'tabs'\n"
11126  "   -version             show SQLite version\n"
11127  "   -vfs NAME            use NAME as the default VFS\n"
11128#ifdef SQLITE_ENABLE_VFSTRACE
11129  "   -vfstrace            enable tracing of all VFS calls\n"
11130#endif
11131#ifdef SQLITE_HAVE_ZLIB
11132  "   -zip                 open the file as a ZIP Archive\n"
11133#endif
11134;
11135static void usage(int showDetail){
11136  utf8_printf(stderr,
11137      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11138      "FILENAME is the name of an SQLite database. A new database is created\n"
11139      "if the file does not previously exist.\n", Argv0);
11140  if( showDetail ){
11141    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11142  }else{
11143    raw_printf(stderr, "Use the -help option for additional information\n");
11144  }
11145  exit(1);
11146}
11147
11148/*
11149** Internal check:  Verify that the SQLite is uninitialized.  Print a
11150** error message if it is initialized.
11151*/
11152static void verify_uninitialized(void){
11153  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11154    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11155                        " initialization.\n");
11156  }
11157}
11158
11159/*
11160** Initialize the state information in data
11161*/
11162static void main_init(ShellState *data) {
11163  memset(data, 0, sizeof(*data));
11164  data->normalMode = data->cMode = data->mode = MODE_List;
11165  data->autoExplain = 1;
11166  data->pAuxDb = &data->aAuxDb[0];
11167  memcpy(data->colSeparator,SEP_Column, 2);
11168  memcpy(data->rowSeparator,SEP_Row, 2);
11169  data->showHeader = 0;
11170  data->shellFlgs = SHFLG_Lookaside;
11171  verify_uninitialized();
11172  sqlite3_config(SQLITE_CONFIG_URI, 1);
11173  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11174  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11175  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11176  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11177}
11178
11179/*
11180** Output text to the console in a font that attracts extra attention.
11181*/
11182#ifdef _WIN32
11183static void printBold(const char *zText){
11184#if !SQLITE_OS_WINRT
11185  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11186  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11187  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11188  SetConsoleTextAttribute(out,
11189         FOREGROUND_RED|FOREGROUND_INTENSITY
11190  );
11191#endif
11192  printf("%s", zText);
11193#if !SQLITE_OS_WINRT
11194  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11195#endif
11196}
11197#else
11198static void printBold(const char *zText){
11199  printf("\033[1m%s\033[0m", zText);
11200}
11201#endif
11202
11203/*
11204** Get the argument to an --option.  Throw an error and die if no argument
11205** is available.
11206*/
11207static char *cmdline_option_value(int argc, char **argv, int i){
11208  if( i==argc ){
11209    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11210            argv[0], argv[argc-1]);
11211    exit(1);
11212  }
11213  return argv[i];
11214}
11215
11216#ifndef SQLITE_SHELL_IS_UTF8
11217#  if (defined(_WIN32) || defined(WIN32)) \
11218   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11219#    define SQLITE_SHELL_IS_UTF8          (0)
11220#  else
11221#    define SQLITE_SHELL_IS_UTF8          (1)
11222#  endif
11223#endif
11224
11225#if SQLITE_SHELL_IS_UTF8
11226int SQLITE_CDECL main(int argc, char **argv){
11227#else
11228int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11229  char **argv;
11230#endif
11231  char *zErrMsg = 0;
11232  ShellState data;
11233  const char *zInitFile = 0;
11234  int i;
11235  int rc = 0;
11236  int warnInmemoryDb = 0;
11237  int readStdin = 1;
11238  int nCmd = 0;
11239  char **azCmd = 0;
11240  const char *zVfs = 0;           /* Value of -vfs command-line option */
11241#if !SQLITE_SHELL_IS_UTF8
11242  char **argvToFree = 0;
11243  int argcToFree = 0;
11244#endif
11245
11246  setBinaryMode(stdin, 0);
11247  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11248  stdin_is_interactive = isatty(0);
11249  stdout_is_console = isatty(1);
11250
11251#ifdef SQLITE_DEBUG
11252  registerOomSimulator();
11253#endif
11254
11255#if !defined(_WIN32_WCE)
11256  if( getenv("SQLITE_DEBUG_BREAK") ){
11257    if( isatty(0) && isatty(2) ){
11258      fprintf(stderr,
11259          "attach debugger to process %d and press any key to continue.\n",
11260          GETPID());
11261      fgetc(stdin);
11262    }else{
11263#if defined(_WIN32) || defined(WIN32)
11264#if SQLITE_OS_WINRT
11265      __debugbreak();
11266#else
11267      DebugBreak();
11268#endif
11269#elif defined(SIGTRAP)
11270      raise(SIGTRAP);
11271#endif
11272    }
11273  }
11274#endif
11275
11276#if USE_SYSTEM_SQLITE+0!=1
11277  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11278    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11279            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11280    exit(1);
11281  }
11282#endif
11283  main_init(&data);
11284
11285  /* On Windows, we must translate command-line arguments into UTF-8.
11286  ** The SQLite memory allocator subsystem has to be enabled in order to
11287  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11288  ** subsequent sqlite3_config() calls will work.  So copy all results into
11289  ** memory that does not come from the SQLite memory allocator.
11290  */
11291#if !SQLITE_SHELL_IS_UTF8
11292  sqlite3_initialize();
11293  argvToFree = malloc(sizeof(argv[0])*argc*2);
11294  argcToFree = argc;
11295  argv = argvToFree + argc;
11296  if( argv==0 ) shell_out_of_memory();
11297  for(i=0; i<argc; i++){
11298    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11299    int n;
11300    if( z==0 ) shell_out_of_memory();
11301    n = (int)strlen(z);
11302    argv[i] = malloc( n+1 );
11303    if( argv[i]==0 ) shell_out_of_memory();
11304    memcpy(argv[i], z, n+1);
11305    argvToFree[i] = argv[i];
11306    sqlite3_free(z);
11307  }
11308  sqlite3_shutdown();
11309#endif
11310
11311  assert( argc>=1 && argv && argv[0] );
11312  Argv0 = argv[0];
11313
11314  /* Make sure we have a valid signal handler early, before anything
11315  ** else is done.
11316  */
11317#ifdef SIGINT
11318  signal(SIGINT, interrupt_handler);
11319#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11320  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11321#endif
11322
11323#ifdef SQLITE_SHELL_DBNAME_PROC
11324  {
11325    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11326    ** of a C-function that will provide the name of the database file.  Use
11327    ** this compile-time option to embed this shell program in larger
11328    ** applications. */
11329    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11330    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11331    warnInmemoryDb = 0;
11332  }
11333#endif
11334
11335  /* Do an initial pass through the command-line argument to locate
11336  ** the name of the database file, the name of the initialization file,
11337  ** the size of the alternative malloc heap,
11338  ** and the first command to execute.
11339  */
11340  verify_uninitialized();
11341  for(i=1; i<argc; i++){
11342    char *z;
11343    z = argv[i];
11344    if( z[0]!='-' ){
11345      if( data.aAuxDb->zDbFilename==0 ){
11346        data.aAuxDb->zDbFilename = z;
11347      }else{
11348        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11349        ** mean that nothing is read from stdin */
11350        readStdin = 0;
11351        nCmd++;
11352        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11353        if( azCmd==0 ) shell_out_of_memory();
11354        azCmd[nCmd-1] = z;
11355      }
11356    }
11357    if( z[1]=='-' ) z++;
11358    if( strcmp(z,"-separator")==0
11359     || strcmp(z,"-nullvalue")==0
11360     || strcmp(z,"-newline")==0
11361     || strcmp(z,"-cmd")==0
11362    ){
11363      (void)cmdline_option_value(argc, argv, ++i);
11364    }else if( strcmp(z,"-init")==0 ){
11365      zInitFile = cmdline_option_value(argc, argv, ++i);
11366    }else if( strcmp(z,"-batch")==0 ){
11367      /* Need to check for batch mode here to so we can avoid printing
11368      ** informational messages (like from process_sqliterc) before
11369      ** we do the actual processing of arguments later in a second pass.
11370      */
11371      stdin_is_interactive = 0;
11372    }else if( strcmp(z,"-heap")==0 ){
11373#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11374      const char *zSize;
11375      sqlite3_int64 szHeap;
11376
11377      zSize = cmdline_option_value(argc, argv, ++i);
11378      szHeap = integerValue(zSize);
11379      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11380      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11381#else
11382      (void)cmdline_option_value(argc, argv, ++i);
11383#endif
11384    }else if( strcmp(z,"-pagecache")==0 ){
11385      sqlite3_int64 n, sz;
11386      sz = integerValue(cmdline_option_value(argc,argv,++i));
11387      if( sz>70000 ) sz = 70000;
11388      if( sz<0 ) sz = 0;
11389      n = integerValue(cmdline_option_value(argc,argv,++i));
11390      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11391        n = 0xffffffffffffLL/sz;
11392      }
11393      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11394                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11395      data.shellFlgs |= SHFLG_Pagecache;
11396    }else if( strcmp(z,"-lookaside")==0 ){
11397      int n, sz;
11398      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11399      if( sz<0 ) sz = 0;
11400      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11401      if( n<0 ) n = 0;
11402      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11403      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11404    }else if( strcmp(z,"-threadsafe")==0 ){
11405      int n;
11406      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11407      switch( n ){
11408         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11409         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11410         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11411      }
11412#ifdef SQLITE_ENABLE_VFSTRACE
11413    }else if( strcmp(z,"-vfstrace")==0 ){
11414      extern int vfstrace_register(
11415         const char *zTraceName,
11416         const char *zOldVfsName,
11417         int (*xOut)(const char*,void*),
11418         void *pOutArg,
11419         int makeDefault
11420      );
11421      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11422#endif
11423#ifdef SQLITE_ENABLE_MULTIPLEX
11424    }else if( strcmp(z,"-multiplex")==0 ){
11425      extern int sqlite3_multiple_initialize(const char*,int);
11426      sqlite3_multiplex_initialize(0, 1);
11427#endif
11428    }else if( strcmp(z,"-mmap")==0 ){
11429      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11430      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11431#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11432    }else if( strcmp(z,"-sorterref")==0 ){
11433      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11434      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11435#endif
11436    }else if( strcmp(z,"-vfs")==0 ){
11437      zVfs = cmdline_option_value(argc, argv, ++i);
11438#ifdef SQLITE_HAVE_ZLIB
11439    }else if( strcmp(z,"-zip")==0 ){
11440      data.openMode = SHELL_OPEN_ZIPFILE;
11441#endif
11442    }else if( strcmp(z,"-append")==0 ){
11443      data.openMode = SHELL_OPEN_APPENDVFS;
11444#ifndef SQLITE_OMIT_DESERIALIZE
11445    }else if( strcmp(z,"-deserialize")==0 ){
11446      data.openMode = SHELL_OPEN_DESERIALIZE;
11447    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11448      data.szMax = integerValue(argv[++i]);
11449#endif
11450    }else if( strcmp(z,"-readonly")==0 ){
11451      data.openMode = SHELL_OPEN_READONLY;
11452    }else if( strcmp(z,"-nofollow")==0 ){
11453      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11454#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11455    }else if( strncmp(z, "-A",2)==0 ){
11456      /* All remaining command-line arguments are passed to the ".archive"
11457      ** command, so ignore them */
11458      break;
11459#endif
11460    }else if( strcmp(z, "-memtrace")==0 ){
11461      sqlite3MemTraceActivate(stderr);
11462    }else if( strcmp(z,"-bail")==0 ){
11463      bail_on_error = 1;
11464    }else if( strcmp(z,"-nonce")==0 ){
11465      free(data.zNonce);
11466      data.zNonce = strdup(argv[++i]);
11467    }else if( strcmp(z,"-safe")==0 ){
11468      /* no-op - catch this on the second pass */
11469    }
11470  }
11471  verify_uninitialized();
11472
11473
11474#ifdef SQLITE_SHELL_INIT_PROC
11475  {
11476    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11477    ** of a C-function that will perform initialization actions on SQLite that
11478    ** occur just before or after sqlite3_initialize(). Use this compile-time
11479    ** option to embed this shell program in larger applications. */
11480    extern void SQLITE_SHELL_INIT_PROC(void);
11481    SQLITE_SHELL_INIT_PROC();
11482  }
11483#else
11484  /* All the sqlite3_config() calls have now been made. So it is safe
11485  ** to call sqlite3_initialize() and process any command line -vfs option. */
11486  sqlite3_initialize();
11487#endif
11488
11489  if( zVfs ){
11490    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11491    if( pVfs ){
11492      sqlite3_vfs_register(pVfs, 1);
11493    }else{
11494      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11495      exit(1);
11496    }
11497  }
11498
11499  if( data.pAuxDb->zDbFilename==0 ){
11500#ifndef SQLITE_OMIT_MEMORYDB
11501    data.pAuxDb->zDbFilename = ":memory:";
11502    warnInmemoryDb = argc==1;
11503#else
11504    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11505    return 1;
11506#endif
11507  }
11508  data.out = stdout;
11509  sqlite3_appendvfs_init(0,0,0);
11510
11511  /* Go ahead and open the database file if it already exists.  If the
11512  ** file does not exist, delay opening it.  This prevents empty database
11513  ** files from being created if a user mistypes the database name argument
11514  ** to the sqlite command-line tool.
11515  */
11516  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11517    open_db(&data, 0);
11518  }
11519
11520  /* Process the initialization file if there is one.  If no -init option
11521  ** is given on the command line, look for a file named ~/.sqliterc and
11522  ** try to process it.
11523  */
11524  process_sqliterc(&data,zInitFile);
11525
11526  /* Make a second pass through the command-line argument and set
11527  ** options.  This second pass is delayed until after the initialization
11528  ** file is processed so that the command-line arguments will override
11529  ** settings in the initialization file.
11530  */
11531  for(i=1; i<argc; i++){
11532    char *z = argv[i];
11533    if( z[0]!='-' ) continue;
11534    if( z[1]=='-' ){ z++; }
11535    if( strcmp(z,"-init")==0 ){
11536      i++;
11537    }else if( strcmp(z,"-html")==0 ){
11538      data.mode = MODE_Html;
11539    }else if( strcmp(z,"-list")==0 ){
11540      data.mode = MODE_List;
11541    }else if( strcmp(z,"-quote")==0 ){
11542      data.mode = MODE_Quote;
11543      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11544      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11545    }else if( strcmp(z,"-line")==0 ){
11546      data.mode = MODE_Line;
11547    }else if( strcmp(z,"-column")==0 ){
11548      data.mode = MODE_Column;
11549    }else if( strcmp(z,"-json")==0 ){
11550      data.mode = MODE_Json;
11551    }else if( strcmp(z,"-markdown")==0 ){
11552      data.mode = MODE_Markdown;
11553    }else if( strcmp(z,"-table")==0 ){
11554      data.mode = MODE_Table;
11555    }else if( strcmp(z,"-box")==0 ){
11556      data.mode = MODE_Box;
11557    }else if( strcmp(z,"-csv")==0 ){
11558      data.mode = MODE_Csv;
11559      memcpy(data.colSeparator,",",2);
11560#ifdef SQLITE_HAVE_ZLIB
11561    }else if( strcmp(z,"-zip")==0 ){
11562      data.openMode = SHELL_OPEN_ZIPFILE;
11563#endif
11564    }else if( strcmp(z,"-append")==0 ){
11565      data.openMode = SHELL_OPEN_APPENDVFS;
11566#ifndef SQLITE_OMIT_DESERIALIZE
11567    }else if( strcmp(z,"-deserialize")==0 ){
11568      data.openMode = SHELL_OPEN_DESERIALIZE;
11569    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11570      data.szMax = integerValue(argv[++i]);
11571#endif
11572    }else if( strcmp(z,"-readonly")==0 ){
11573      data.openMode = SHELL_OPEN_READONLY;
11574    }else if( strcmp(z,"-nofollow")==0 ){
11575      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11576    }else if( strcmp(z,"-ascii")==0 ){
11577      data.mode = MODE_Ascii;
11578      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11579      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11580    }else if( strcmp(z,"-tabs")==0 ){
11581      data.mode = MODE_List;
11582      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11583      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11584    }else if( strcmp(z,"-separator")==0 ){
11585      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11586                       "%s",cmdline_option_value(argc,argv,++i));
11587    }else if( strcmp(z,"-newline")==0 ){
11588      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11589                       "%s",cmdline_option_value(argc,argv,++i));
11590    }else if( strcmp(z,"-nullvalue")==0 ){
11591      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11592                       "%s",cmdline_option_value(argc,argv,++i));
11593    }else if( strcmp(z,"-header")==0 ){
11594      data.showHeader = 1;
11595      ShellSetFlag(&data, SHFLG_HeaderSet);
11596     }else if( strcmp(z,"-noheader")==0 ){
11597      data.showHeader = 0;
11598      ShellSetFlag(&data, SHFLG_HeaderSet);
11599    }else if( strcmp(z,"-echo")==0 ){
11600      ShellSetFlag(&data, SHFLG_Echo);
11601    }else if( strcmp(z,"-eqp")==0 ){
11602      data.autoEQP = AUTOEQP_on;
11603    }else if( strcmp(z,"-eqpfull")==0 ){
11604      data.autoEQP = AUTOEQP_full;
11605    }else if( strcmp(z,"-stats")==0 ){
11606      data.statsOn = 1;
11607    }else if( strcmp(z,"-scanstats")==0 ){
11608      data.scanstatsOn = 1;
11609    }else if( strcmp(z,"-backslash")==0 ){
11610      /* Undocumented command-line option: -backslash
11611      ** Causes C-style backslash escapes to be evaluated in SQL statements
11612      ** prior to sending the SQL into SQLite.  Useful for injecting
11613      ** crazy bytes in the middle of SQL statements for testing and debugging.
11614      */
11615      ShellSetFlag(&data, SHFLG_Backslash);
11616    }else if( strcmp(z,"-bail")==0 ){
11617      /* No-op.  The bail_on_error flag should already be set. */
11618    }else if( strcmp(z,"-version")==0 ){
11619      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11620      return 0;
11621    }else if( strcmp(z,"-interactive")==0 ){
11622      stdin_is_interactive = 1;
11623    }else if( strcmp(z,"-batch")==0 ){
11624      stdin_is_interactive = 0;
11625    }else if( strcmp(z,"-heap")==0 ){
11626      i++;
11627    }else if( strcmp(z,"-pagecache")==0 ){
11628      i+=2;
11629    }else if( strcmp(z,"-lookaside")==0 ){
11630      i+=2;
11631    }else if( strcmp(z,"-threadsafe")==0 ){
11632      i+=2;
11633    }else if( strcmp(z,"-nonce")==0 ){
11634      i += 2;
11635    }else if( strcmp(z,"-mmap")==0 ){
11636      i++;
11637    }else if( strcmp(z,"-memtrace")==0 ){
11638      i++;
11639#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11640    }else if( strcmp(z,"-sorterref")==0 ){
11641      i++;
11642#endif
11643    }else if( strcmp(z,"-vfs")==0 ){
11644      i++;
11645#ifdef SQLITE_ENABLE_VFSTRACE
11646    }else if( strcmp(z,"-vfstrace")==0 ){
11647      i++;
11648#endif
11649#ifdef SQLITE_ENABLE_MULTIPLEX
11650    }else if( strcmp(z,"-multiplex")==0 ){
11651      i++;
11652#endif
11653    }else if( strcmp(z,"-help")==0 ){
11654      usage(1);
11655    }else if( strcmp(z,"-cmd")==0 ){
11656      /* Run commands that follow -cmd first and separately from commands
11657      ** that simply appear on the command-line.  This seems goofy.  It would
11658      ** be better if all commands ran in the order that they appear.  But
11659      ** we retain the goofy behavior for historical compatibility. */
11660      if( i==argc-1 ) break;
11661      z = cmdline_option_value(argc,argv,++i);
11662      if( z[0]=='.' ){
11663        rc = do_meta_command(z, &data);
11664        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11665      }else{
11666        open_db(&data, 0);
11667        rc = shell_exec(&data, z, &zErrMsg);
11668        if( zErrMsg!=0 ){
11669          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11670          if( bail_on_error ) return rc!=0 ? rc : 1;
11671        }else if( rc!=0 ){
11672          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11673          if( bail_on_error ) return rc;
11674        }
11675      }
11676#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11677    }else if( strncmp(z, "-A", 2)==0 ){
11678      if( nCmd>0 ){
11679        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11680                            " with \"%s\"\n", z);
11681        return 1;
11682      }
11683      open_db(&data, OPEN_DB_ZIPFILE);
11684      if( z[2] ){
11685        argv[i] = &z[2];
11686        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11687      }else{
11688        arDotCommand(&data, 1, argv+i, argc-i);
11689      }
11690      readStdin = 0;
11691      break;
11692#endif
11693    }else if( strcmp(z,"-safe")==0 ){
11694      data.bSafeMode = data.bSafeModePersist = 1;
11695    }else{
11696      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11697      raw_printf(stderr,"Use -help for a list of options.\n");
11698      return 1;
11699    }
11700    data.cMode = data.mode;
11701  }
11702
11703  if( !readStdin ){
11704    /* Run all arguments that do not begin with '-' as if they were separate
11705    ** command-line inputs, except for the argToSkip argument which contains
11706    ** the database filename.
11707    */
11708    for(i=0; i<nCmd; i++){
11709      if( azCmd[i][0]=='.' ){
11710        rc = do_meta_command(azCmd[i], &data);
11711        if( rc ){
11712          free(azCmd);
11713          return rc==2 ? 0 : rc;
11714        }
11715      }else{
11716        open_db(&data, 0);
11717        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11718        if( zErrMsg || rc ){
11719          if( zErrMsg!=0 ){
11720            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11721          }else{
11722            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11723          }
11724          sqlite3_free(zErrMsg);
11725          free(azCmd);
11726          return rc!=0 ? rc : 1;
11727        }
11728      }
11729    }
11730  }else{
11731    /* Run commands received from standard input
11732    */
11733    if( stdin_is_interactive ){
11734      char *zHome;
11735      char *zHistory;
11736      int nHistory;
11737      printf(
11738        "SQLite version %s %.19s\n" /*extra-version-info*/
11739        "Enter \".help\" for usage hints.\n",
11740        sqlite3_libversion(), sqlite3_sourceid()
11741      );
11742      if( warnInmemoryDb ){
11743        printf("Connected to a ");
11744        printBold("transient in-memory database");
11745        printf(".\nUse \".open FILENAME\" to reopen on a "
11746               "persistent database.\n");
11747      }
11748      zHistory = getenv("SQLITE_HISTORY");
11749      if( zHistory ){
11750        zHistory = strdup(zHistory);
11751      }else if( (zHome = find_home_dir(0))!=0 ){
11752        nHistory = strlen30(zHome) + 20;
11753        if( (zHistory = malloc(nHistory))!=0 ){
11754          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11755        }
11756      }
11757      if( zHistory ){ shell_read_history(zHistory); }
11758#if HAVE_READLINE || HAVE_EDITLINE
11759      rl_attempted_completion_function = readline_completion;
11760#elif HAVE_LINENOISE
11761      linenoiseSetCompletionCallback(linenoise_completion);
11762#endif
11763      data.in = 0;
11764      rc = process_input(&data);
11765      if( zHistory ){
11766        shell_stifle_history(2000);
11767        shell_write_history(zHistory);
11768        free(zHistory);
11769      }
11770    }else{
11771      data.in = stdin;
11772      rc = process_input(&data);
11773    }
11774  }
11775  free(azCmd);
11776  set_table_name(&data, 0);
11777  if( data.db ){
11778    session_close_all(&data, -1);
11779    close_db(data.db);
11780  }
11781  for(i=0; i<ArraySize(data.aAuxDb); i++){
11782    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
11783    if( data.aAuxDb[i].db ){
11784      session_close_all(&data, i);
11785      close_db(data.aAuxDb[i].db);
11786    }
11787  }
11788  find_home_dir(1);
11789  output_reset(&data);
11790  data.doXdgOpen = 0;
11791  clearTempFile(&data);
11792#if !SQLITE_SHELL_IS_UTF8
11793  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11794  free(argvToFree);
11795#endif
11796  free(data.colWidth);
11797  free(data.zNonce);
11798  /* Clear the global data structure so that valgrind will detect memory
11799  ** leaks */
11800  memset(&data, 0, sizeof(data));
11801  return rc;
11802}
11803