xref: /sqlite-3.40.0/src/shell.c.in (revision e0adf602)
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/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
491** out-of-memory error.
492*/
493static void shell_check_oom(void *p){
494  if( p==0 ) shell_out_of_memory();
495}
496
497#ifdef SQLITE_DEBUG
498/* This routine is called when a simulated OOM occurs.  It is broken
499** out as a separate routine to make it easy to set a breakpoint on
500** the OOM
501*/
502void shellOomFault(void){
503  if( oomRepeat>0 ){
504    oomRepeat--;
505  }else{
506    oomCounter--;
507  }
508}
509#endif /* SQLITE_DEBUG */
510
511#ifdef SQLITE_DEBUG
512/* This routine is a replacement malloc() that is used to simulate
513** Out-Of-Memory (OOM) errors for testing purposes.
514*/
515static void *oomMalloc(int nByte){
516  if( oomCounter ){
517    if( oomCounter==1 ){
518      shellOomFault();
519      return 0;
520    }else{
521      oomCounter--;
522    }
523  }
524  return defaultMalloc(nByte);
525}
526#endif /* SQLITE_DEBUG */
527
528#ifdef SQLITE_DEBUG
529/* Register the OOM simulator.  This must occur before any memory
530** allocations */
531static void registerOomSimulator(void){
532  sqlite3_mem_methods mem;
533  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
534  defaultMalloc = mem.xMalloc;
535  mem.xMalloc = oomMalloc;
536  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
537}
538#endif
539
540/*
541** Write I/O traces to the following stream.
542*/
543#ifdef SQLITE_ENABLE_IOTRACE
544static FILE *iotrace = 0;
545#endif
546
547/*
548** This routine works like printf in that its first argument is a
549** format string and subsequent arguments are values to be substituted
550** in place of % fields.  The result of formatting this string
551** is written to iotrace.
552*/
553#ifdef SQLITE_ENABLE_IOTRACE
554static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
555  va_list ap;
556  char *z;
557  if( iotrace==0 ) return;
558  va_start(ap, zFormat);
559  z = sqlite3_vmprintf(zFormat, ap);
560  va_end(ap);
561  utf8_printf(iotrace, "%s", z);
562  sqlite3_free(z);
563}
564#endif
565
566/*
567** Output string zUtf to stream pOut as w characters.  If w is negative,
568** then right-justify the text.  W is the width in UTF-8 characters, not
569** in bytes.  This is different from the %*.*s specification in printf
570** since with %*.*s the width is measured in bytes, not characters.
571*/
572static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
573  int i;
574  int n;
575  int aw = w<0 ? -w : w;
576  for(i=n=0; zUtf[i]; i++){
577    if( (zUtf[i]&0xc0)!=0x80 ){
578      n++;
579      if( n==aw ){
580        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
581        break;
582      }
583    }
584  }
585  if( n>=aw ){
586    utf8_printf(pOut, "%.*s", i, zUtf);
587  }else if( w<0 ){
588    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
589  }else{
590    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
591  }
592}
593
594
595/*
596** Determines if a string is a number of not.
597*/
598static int isNumber(const char *z, int *realnum){
599  if( *z=='-' || *z=='+' ) z++;
600  if( !IsDigit(*z) ){
601    return 0;
602  }
603  z++;
604  if( realnum ) *realnum = 0;
605  while( IsDigit(*z) ){ z++; }
606  if( *z=='.' ){
607    z++;
608    if( !IsDigit(*z) ) return 0;
609    while( IsDigit(*z) ){ z++; }
610    if( realnum ) *realnum = 1;
611  }
612  if( *z=='e' || *z=='E' ){
613    z++;
614    if( *z=='+' || *z=='-' ) z++;
615    if( !IsDigit(*z) ) return 0;
616    while( IsDigit(*z) ){ z++; }
617    if( realnum ) *realnum = 1;
618  }
619  return *z==0;
620}
621
622/*
623** Compute a string length that is limited to what can be stored in
624** lower 30 bits of a 32-bit signed integer.
625*/
626static int strlen30(const char *z){
627  const char *z2 = z;
628  while( *z2 ){ z2++; }
629  return 0x3fffffff & (int)(z2 - z);
630}
631
632/*
633** Return the length of a string in characters.  Multibyte UTF8 characters
634** count as a single character.
635*/
636static int strlenChar(const char *z){
637  int n = 0;
638  while( *z ){
639    if( (0xc0&*(z++))!=0x80 ) n++;
640  }
641  return n;
642}
643
644/*
645** Return open FILE * if zFile exists, can be opened for read
646** and is an ordinary file or a character stream source.
647** Otherwise return 0.
648*/
649static FILE * openChrSource(const char *zFile){
650#ifdef _WIN32
651  struct _stat x = {0};
652# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
653  /* On Windows, open first, then check the stream nature. This order
654  ** is necessary because _stat() and sibs, when checking a named pipe,
655  ** effectively break the pipe as its supplier sees it. */
656  FILE *rv = fopen(zFile, "rb");
657  if( rv==0 ) return 0;
658  if( _fstat(_fileno(rv), &x) != 0
659      || !STAT_CHR_SRC(x.st_mode)){
660    fclose(rv);
661    rv = 0;
662  }
663  return rv;
664#else
665  struct stat x = {0};
666  int rc = stat(zFile, &x);
667# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
668  if( rc!=0 ) return 0;
669  if( STAT_CHR_SRC(x.st_mode) ){
670    return fopen(zFile, "rb");
671  }else{
672    return 0;
673  }
674#endif
675#undef STAT_CHR_SRC
676}
677
678/*
679** This routine reads a line of text from FILE in, stores
680** the text in memory obtained from malloc() and returns a pointer
681** to the text.  NULL is returned at end of file, or if malloc()
682** fails.
683**
684** If zLine is not NULL then it is a malloced buffer returned from
685** a previous call to this routine that may be reused.
686*/
687static char *local_getline(char *zLine, FILE *in){
688  int nLine = zLine==0 ? 0 : 100;
689  int n = 0;
690
691  while( 1 ){
692    if( n+100>nLine ){
693      nLine = nLine*2 + 100;
694      zLine = realloc(zLine, nLine);
695      shell_check_oom(zLine);
696    }
697    if( fgets(&zLine[n], nLine - n, in)==0 ){
698      if( n==0 ){
699        free(zLine);
700        return 0;
701      }
702      zLine[n] = 0;
703      break;
704    }
705    while( zLine[n] ) n++;
706    if( n>0 && zLine[n-1]=='\n' ){
707      n--;
708      if( n>0 && zLine[n-1]=='\r' ) n--;
709      zLine[n] = 0;
710      break;
711    }
712  }
713#if defined(_WIN32) || defined(WIN32)
714  /* For interactive input on Windows systems, translate the
715  ** multi-byte characterset characters into UTF-8. */
716  if( stdin_is_interactive && in==stdin ){
717    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
718    if( zTrans ){
719      int nTrans = strlen30(zTrans)+1;
720      if( nTrans>nLine ){
721        zLine = realloc(zLine, nTrans);
722        shell_check_oom(zLine);
723      }
724      memcpy(zLine, zTrans, nTrans);
725      sqlite3_free(zTrans);
726    }
727  }
728#endif /* defined(_WIN32) || defined(WIN32) */
729  return zLine;
730}
731
732/*
733** Retrieve a single line of input text.
734**
735** If in==0 then read from standard input and prompt before each line.
736** If isContinuation is true, then a continuation prompt is appropriate.
737** If isContinuation is zero, then the main prompt should be used.
738**
739** If zPrior is not NULL then it is a buffer from a prior call to this
740** routine that can be reused.
741**
742** The result is stored in space obtained from malloc() and must either
743** be freed by the caller or else passed back into this routine via the
744** zPrior argument for reuse.
745*/
746static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
747  char *zPrompt;
748  char *zResult;
749  if( in!=0 ){
750    zResult = local_getline(zPrior, in);
751  }else{
752    zPrompt = isContinuation ? continuePrompt : mainPrompt;
753#if SHELL_USE_LOCAL_GETLINE
754    printf("%s", zPrompt);
755    fflush(stdout);
756    zResult = local_getline(zPrior, stdin);
757#else
758    free(zPrior);
759    zResult = shell_readline(zPrompt);
760    if( zResult && *zResult ) shell_add_history(zResult);
761#endif
762  }
763  return zResult;
764}
765
766
767/*
768** Return the value of a hexadecimal digit.  Return -1 if the input
769** is not a hex digit.
770*/
771static int hexDigitValue(char c){
772  if( c>='0' && c<='9' ) return c - '0';
773  if( c>='a' && c<='f' ) return c - 'a' + 10;
774  if( c>='A' && c<='F' ) return c - 'A' + 10;
775  return -1;
776}
777
778/*
779** Interpret zArg as an integer value, possibly with suffixes.
780*/
781static sqlite3_int64 integerValue(const char *zArg){
782  sqlite3_int64 v = 0;
783  static const struct { char *zSuffix; int iMult; } aMult[] = {
784    { "KiB", 1024 },
785    { "MiB", 1024*1024 },
786    { "GiB", 1024*1024*1024 },
787    { "KB",  1000 },
788    { "MB",  1000000 },
789    { "GB",  1000000000 },
790    { "K",   1000 },
791    { "M",   1000000 },
792    { "G",   1000000000 },
793  };
794  int i;
795  int isNeg = 0;
796  if( zArg[0]=='-' ){
797    isNeg = 1;
798    zArg++;
799  }else if( zArg[0]=='+' ){
800    zArg++;
801  }
802  if( zArg[0]=='0' && zArg[1]=='x' ){
803    int x;
804    zArg += 2;
805    while( (x = hexDigitValue(zArg[0]))>=0 ){
806      v = (v<<4) + x;
807      zArg++;
808    }
809  }else{
810    while( IsDigit(zArg[0]) ){
811      v = v*10 + zArg[0] - '0';
812      zArg++;
813    }
814  }
815  for(i=0; i<ArraySize(aMult); i++){
816    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
817      v *= aMult[i].iMult;
818      break;
819    }
820  }
821  return isNeg? -v : v;
822}
823
824/*
825** A variable length string to which one can append text.
826*/
827typedef struct ShellText ShellText;
828struct ShellText {
829  char *z;
830  int n;
831  int nAlloc;
832};
833
834/*
835** Initialize and destroy a ShellText object
836*/
837static void initText(ShellText *p){
838  memset(p, 0, sizeof(*p));
839}
840static void freeText(ShellText *p){
841  free(p->z);
842  initText(p);
843}
844
845/* zIn is either a pointer to a NULL-terminated string in memory obtained
846** from malloc(), or a NULL pointer. The string pointed to by zAppend is
847** added to zIn, and the result returned in memory obtained from malloc().
848** zIn, if it was not NULL, is freed.
849**
850** If the third argument, quote, is not '\0', then it is used as a
851** quote character for zAppend.
852*/
853static void appendText(ShellText *p, char const *zAppend, char quote){
854  int len;
855  int i;
856  int nAppend = strlen30(zAppend);
857
858  len = nAppend+p->n+1;
859  if( quote ){
860    len += 2;
861    for(i=0; i<nAppend; i++){
862      if( zAppend[i]==quote ) len++;
863    }
864  }
865
866  if( p->z==0 || p->n+len>=p->nAlloc ){
867    p->nAlloc = p->nAlloc*2 + len + 20;
868    p->z = realloc(p->z, p->nAlloc);
869    shell_check_oom(p->z);
870  }
871
872  if( quote ){
873    char *zCsr = p->z+p->n;
874    *zCsr++ = quote;
875    for(i=0; i<nAppend; i++){
876      *zCsr++ = zAppend[i];
877      if( zAppend[i]==quote ) *zCsr++ = quote;
878    }
879    *zCsr++ = quote;
880    p->n = (int)(zCsr - p->z);
881    *zCsr = '\0';
882  }else{
883    memcpy(p->z+p->n, zAppend, nAppend);
884    p->n += nAppend;
885    p->z[p->n] = '\0';
886  }
887}
888
889/*
890** Attempt to determine if identifier zName needs to be quoted, either
891** because it contains non-alphanumeric characters, or because it is an
892** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
893** that quoting is required.
894**
895** Return '"' if quoting is required.  Return 0 if no quoting is required.
896*/
897static char quoteChar(const char *zName){
898  int i;
899  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
900  for(i=0; zName[i]; i++){
901    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
902  }
903  return sqlite3_keyword_check(zName, i) ? '"' : 0;
904}
905
906/*
907** Construct a fake object name and column list to describe the structure
908** of the view, virtual table, or table valued function zSchema.zName.
909*/
910static char *shellFakeSchema(
911  sqlite3 *db,            /* The database connection containing the vtab */
912  const char *zSchema,    /* Schema of the database holding the vtab */
913  const char *zName       /* The name of the virtual table */
914){
915  sqlite3_stmt *pStmt = 0;
916  char *zSql;
917  ShellText s;
918  char cQuote;
919  char *zDiv = "(";
920  int nRow = 0;
921
922  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
923                         zSchema ? zSchema : "main", zName);
924  shell_check_oom(zSql);
925  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
926  sqlite3_free(zSql);
927  initText(&s);
928  if( zSchema ){
929    cQuote = quoteChar(zSchema);
930    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
931    appendText(&s, zSchema, cQuote);
932    appendText(&s, ".", 0);
933  }
934  cQuote = quoteChar(zName);
935  appendText(&s, zName, cQuote);
936  while( sqlite3_step(pStmt)==SQLITE_ROW ){
937    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
938    nRow++;
939    appendText(&s, zDiv, 0);
940    zDiv = ",";
941    cQuote = quoteChar(zCol);
942    appendText(&s, zCol, cQuote);
943  }
944  appendText(&s, ")", 0);
945  sqlite3_finalize(pStmt);
946  if( nRow==0 ){
947    freeText(&s);
948    s.z = 0;
949  }
950  return s.z;
951}
952
953/*
954** SQL function:  shell_module_schema(X)
955**
956** Return a fake schema for the table-valued function or eponymous virtual
957** table X.
958*/
959static void shellModuleSchema(
960  sqlite3_context *pCtx,
961  int nVal,
962  sqlite3_value **apVal
963){
964  const char *zName;
965  char *zFake;
966  UNUSED_PARAMETER(nVal);
967  zName = (const char*)sqlite3_value_text(apVal[0]);
968  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
969  if( zFake ){
970    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
971                        -1, sqlite3_free);
972    free(zFake);
973  }
974}
975
976/*
977** SQL function:  shell_add_schema(S,X)
978**
979** Add the schema name X to the CREATE statement in S and return the result.
980** Examples:
981**
982**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
983**
984** Also works on
985**
986**    CREATE INDEX
987**    CREATE UNIQUE INDEX
988**    CREATE VIEW
989**    CREATE TRIGGER
990**    CREATE VIRTUAL TABLE
991**
992** This UDF is used by the .schema command to insert the schema name of
993** attached databases into the middle of the sqlite_schema.sql field.
994*/
995static void shellAddSchemaName(
996  sqlite3_context *pCtx,
997  int nVal,
998  sqlite3_value **apVal
999){
1000  static const char *aPrefix[] = {
1001     "TABLE",
1002     "INDEX",
1003     "UNIQUE INDEX",
1004     "VIEW",
1005     "TRIGGER",
1006     "VIRTUAL TABLE"
1007  };
1008  int i = 0;
1009  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
1010  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
1011  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
1012  sqlite3 *db = sqlite3_context_db_handle(pCtx);
1013  UNUSED_PARAMETER(nVal);
1014  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
1015    for(i=0; i<ArraySize(aPrefix); i++){
1016      int n = strlen30(aPrefix[i]);
1017      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
1018        char *z = 0;
1019        char *zFake = 0;
1020        if( zSchema ){
1021          char cQuote = quoteChar(zSchema);
1022          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1023            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1024          }else{
1025            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1026          }
1027        }
1028        if( zName
1029         && aPrefix[i][0]=='V'
1030         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1031        ){
1032          if( z==0 ){
1033            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1034          }else{
1035            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1036          }
1037          free(zFake);
1038        }
1039        if( z ){
1040          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1041          return;
1042        }
1043      }
1044    }
1045  }
1046  sqlite3_result_value(pCtx, apVal[0]);
1047}
1048
1049/*
1050** The source code for several run-time loadable extensions is inserted
1051** below by the ../tool/mkshellc.tcl script.  Before processing that included
1052** code, we need to override some macros to make the included program code
1053** work here in the middle of this regular program.
1054*/
1055#define SQLITE_EXTENSION_INIT1
1056#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1057
1058#if defined(_WIN32) && defined(_MSC_VER)
1059INCLUDE test_windirent.h
1060INCLUDE test_windirent.c
1061#define dirent DIRENT
1062#endif
1063INCLUDE ../ext/misc/shathree.c
1064INCLUDE ../ext/misc/fileio.c
1065INCLUDE ../ext/misc/completion.c
1066INCLUDE ../ext/misc/appendvfs.c
1067INCLUDE ../ext/misc/memtrace.c
1068INCLUDE ../ext/misc/uint.c
1069INCLUDE ../ext/misc/decimal.c
1070INCLUDE ../ext/misc/ieee754.c
1071INCLUDE ../ext/misc/series.c
1072INCLUDE ../ext/misc/regexp.c
1073#ifdef SQLITE_HAVE_ZLIB
1074INCLUDE ../ext/misc/zipfile.c
1075INCLUDE ../ext/misc/sqlar.c
1076#endif
1077INCLUDE ../ext/expert/sqlite3expert.h
1078INCLUDE ../ext/expert/sqlite3expert.c
1079
1080#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1081INCLUDE ../ext/misc/dbdata.c
1082#endif
1083
1084#if defined(SQLITE_ENABLE_SESSION)
1085/*
1086** State information for a single open session
1087*/
1088typedef struct OpenSession OpenSession;
1089struct OpenSession {
1090  char *zName;             /* Symbolic name for this session */
1091  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1092  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1093  sqlite3_session *p;      /* The open session */
1094};
1095#endif
1096
1097typedef struct ExpertInfo ExpertInfo;
1098struct ExpertInfo {
1099  sqlite3expert *pExpert;
1100  int bVerbose;
1101};
1102
1103/* A single line in the EQP output */
1104typedef struct EQPGraphRow EQPGraphRow;
1105struct EQPGraphRow {
1106  int iEqpId;           /* ID for this row */
1107  int iParentId;        /* ID of the parent row */
1108  EQPGraphRow *pNext;   /* Next row in sequence */
1109  char zText[1];        /* Text to display for this row */
1110};
1111
1112/* All EQP output is collected into an instance of the following */
1113typedef struct EQPGraph EQPGraph;
1114struct EQPGraph {
1115  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1116  EQPGraphRow *pLast;   /* Last element of the pRow list */
1117  char zPrefix[100];    /* Graph prefix */
1118};
1119
1120/*
1121** State information about the database connection is contained in an
1122** instance of the following structure.
1123*/
1124typedef struct ShellState ShellState;
1125struct ShellState {
1126  sqlite3 *db;           /* The database */
1127  u8 autoExplain;        /* Automatically turn on .explain mode */
1128  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1129  u8 autoEQPtest;        /* autoEQP is in test mode */
1130  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1131  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1132  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1133  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1134  u8 nEqpLevel;          /* Depth of the EQP output graph */
1135  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1136  u8 bSafeMode;          /* True to prohibit unsafe operations */
1137  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1138  unsigned statsOn;      /* True to display memory stats before each finalize */
1139  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1140  int outCount;          /* Revert to stdout when reaching zero */
1141  int cnt;               /* Number of records displayed so far */
1142  int lineno;            /* Line number of last line read from in */
1143  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1144  FILE *in;              /* Read commands from this stream */
1145  FILE *out;             /* Write results here */
1146  FILE *traceOut;        /* Output for sqlite3_trace() */
1147  int nErr;              /* Number of errors seen */
1148  int mode;              /* An output mode setting */
1149  int modePrior;         /* Saved mode */
1150  int cMode;             /* temporary output mode for the current query */
1151  int normalMode;        /* Output mode before ".explain on" */
1152  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1153  int showHeader;        /* True to show column names in List or Column mode */
1154  int nCheck;            /* Number of ".check" commands run */
1155  unsigned nProgress;    /* Number of progress callbacks encountered */
1156  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1157  unsigned flgProgress;  /* Flags for the progress callback */
1158  unsigned shellFlgs;    /* Various flags */
1159  unsigned priorShFlgs;  /* Saved copy of flags */
1160  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1161  char *zDestTable;      /* Name of destination table when MODE_Insert */
1162  char *zTempFile;       /* Temporary file that might need deleting */
1163  char zTestcase[30];    /* Name of current test case */
1164  char colSeparator[20]; /* Column separator character for several modes */
1165  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1166  char colSepPrior[20];  /* Saved column separator */
1167  char rowSepPrior[20];  /* Saved row separator */
1168  int *colWidth;         /* Requested width of each column in columnar modes */
1169  int *actualWidth;      /* Actual width of each column */
1170  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1171  char nullValue[20];    /* The text to print when a NULL comes back from
1172                         ** the database */
1173  char outfile[FILENAME_MAX]; /* Filename for *out */
1174  sqlite3_stmt *pStmt;   /* Current statement if any. */
1175  FILE *pLog;            /* Write log output here */
1176  struct AuxDb {         /* Storage space for auxiliary database connections */
1177    sqlite3 *db;               /* Connection pointer */
1178    const char *zDbFilename;   /* Filename used to open the connection */
1179    char *zFreeOnClose;        /* Free this memory allocation on close */
1180#if defined(SQLITE_ENABLE_SESSION)
1181    int nSession;              /* Number of active sessions */
1182    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1183#endif
1184  } aAuxDb[5],           /* Array of all database connections */
1185    *pAuxDb;             /* Currently active database connection */
1186  int *aiIndent;         /* Array of indents used in MODE_Explain */
1187  int nIndent;           /* Size of array aiIndent[] */
1188  int iIndent;           /* Index of current op in aiIndent[] */
1189  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1190  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1191  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1192};
1193
1194
1195/* Allowed values for ShellState.autoEQP
1196*/
1197#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1198#define AUTOEQP_on       1           /* Automatic EQP is on */
1199#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1200#define AUTOEQP_full     3           /* Show full EXPLAIN */
1201
1202/* Allowed values for ShellState.openMode
1203*/
1204#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1205#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1206#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1207#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1208#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1209#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1210#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1211
1212/* Allowed values for ShellState.eTraceType
1213*/
1214#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1215#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1216#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1217
1218/* Bits in the ShellState.flgProgress variable */
1219#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1220#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1221                                   ** callback limit is reached, and for each
1222                                   ** top-level SQL statement */
1223#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1224
1225/*
1226** These are the allowed shellFlgs values
1227*/
1228#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1229#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1230#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1231#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1232#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1233#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1234#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1235#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1236#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1237#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1238
1239/*
1240** Macros for testing and setting shellFlgs
1241*/
1242#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1243#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1244#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1245
1246/*
1247** These are the allowed modes.
1248*/
1249#define MODE_Line     0  /* One column per line.  Blank line between records */
1250#define MODE_Column   1  /* One record per line in neat columns */
1251#define MODE_List     2  /* One record per line with a separator */
1252#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1253#define MODE_Html     4  /* Generate an XHTML table */
1254#define MODE_Insert   5  /* Generate SQL "insert" statements */
1255#define MODE_Quote    6  /* Quote values as for SQL */
1256#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1257#define MODE_Csv      8  /* Quote strings, numbers are plain */
1258#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1259#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1260#define MODE_Pretty  11  /* Pretty-print schemas */
1261#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1262#define MODE_Json    13  /* Output JSON */
1263#define MODE_Markdown 14 /* Markdown formatting */
1264#define MODE_Table   15  /* MySQL-style table formatting */
1265#define MODE_Box     16  /* Unicode box-drawing characters */
1266#define MODE_Count   17  /* Output only a count of the rows of output */
1267#define MODE_Off     18  /* No query output shown */
1268
1269static const char *modeDescr[] = {
1270  "line",
1271  "column",
1272  "list",
1273  "semi",
1274  "html",
1275  "insert",
1276  "quote",
1277  "tcl",
1278  "csv",
1279  "explain",
1280  "ascii",
1281  "prettyprint",
1282  "eqp",
1283  "json",
1284  "markdown",
1285  "table",
1286  "box",
1287  "count",
1288  "off"
1289};
1290
1291/*
1292** These are the column/row/line separators used by the various
1293** import/export modes.
1294*/
1295#define SEP_Column    "|"
1296#define SEP_Row       "\n"
1297#define SEP_Tab       "\t"
1298#define SEP_Space     " "
1299#define SEP_Comma     ","
1300#define SEP_CrLf      "\r\n"
1301#define SEP_Unit      "\x1F"
1302#define SEP_Record    "\x1E"
1303
1304/*
1305** A callback for the sqlite3_log() interface.
1306*/
1307static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1308  ShellState *p = (ShellState*)pArg;
1309  if( p->pLog==0 ) return;
1310  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1311  fflush(p->pLog);
1312}
1313
1314/*
1315** SQL function:  shell_putsnl(X)
1316**
1317** Write the text X to the screen (or whatever output is being directed)
1318** adding a newline at the end, and then return X.
1319*/
1320static void shellPutsFunc(
1321  sqlite3_context *pCtx,
1322  int nVal,
1323  sqlite3_value **apVal
1324){
1325  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1326  (void)nVal;
1327  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1328  sqlite3_result_value(pCtx, apVal[0]);
1329}
1330
1331/*
1332** If in safe mode, print an error message described by the arguments
1333** and exit immediately.
1334*/
1335static void failIfSafeMode(
1336  ShellState *p,
1337  const char *zErrMsg,
1338  ...
1339){
1340  if( p->bSafeMode ){
1341    va_list ap;
1342    char *zMsg;
1343    va_start(ap, zErrMsg);
1344    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1345    va_end(ap);
1346    raw_printf(stderr, "line %d: ", p->lineno);
1347    utf8_printf(stderr, "%s\n", zMsg);
1348    exit(1);
1349  }
1350}
1351
1352/*
1353** SQL function:   edit(VALUE)
1354**                 edit(VALUE,EDITOR)
1355**
1356** These steps:
1357**
1358**     (1) Write VALUE into a temporary file.
1359**     (2) Run program EDITOR on that temporary file.
1360**     (3) Read the temporary file back and return its content as the result.
1361**     (4) Delete the temporary file
1362**
1363** If the EDITOR argument is omitted, use the value in the VISUAL
1364** environment variable.  If still there is no EDITOR, through an error.
1365**
1366** Also throw an error if the EDITOR program returns a non-zero exit code.
1367*/
1368#ifndef SQLITE_NOHAVE_SYSTEM
1369static void editFunc(
1370  sqlite3_context *context,
1371  int argc,
1372  sqlite3_value **argv
1373){
1374  const char *zEditor;
1375  char *zTempFile = 0;
1376  sqlite3 *db;
1377  char *zCmd = 0;
1378  int bBin;
1379  int rc;
1380  int hasCRNL = 0;
1381  FILE *f = 0;
1382  sqlite3_int64 sz;
1383  sqlite3_int64 x;
1384  unsigned char *p = 0;
1385
1386  if( argc==2 ){
1387    zEditor = (const char*)sqlite3_value_text(argv[1]);
1388  }else{
1389    zEditor = getenv("VISUAL");
1390  }
1391  if( zEditor==0 ){
1392    sqlite3_result_error(context, "no editor for edit()", -1);
1393    return;
1394  }
1395  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1396    sqlite3_result_error(context, "NULL input to edit()", -1);
1397    return;
1398  }
1399  db = sqlite3_context_db_handle(context);
1400  zTempFile = 0;
1401  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1402  if( zTempFile==0 ){
1403    sqlite3_uint64 r = 0;
1404    sqlite3_randomness(sizeof(r), &r);
1405    zTempFile = sqlite3_mprintf("temp%llx", r);
1406    if( zTempFile==0 ){
1407      sqlite3_result_error_nomem(context);
1408      return;
1409    }
1410  }
1411  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1412  /* When writing the file to be edited, do \n to \r\n conversions on systems
1413  ** that want \r\n line endings */
1414  f = fopen(zTempFile, bBin ? "wb" : "w");
1415  if( f==0 ){
1416    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1417    goto edit_func_end;
1418  }
1419  sz = sqlite3_value_bytes(argv[0]);
1420  if( bBin ){
1421    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1422  }else{
1423    const char *z = (const char*)sqlite3_value_text(argv[0]);
1424    /* Remember whether or not the value originally contained \r\n */
1425    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1426    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1427  }
1428  fclose(f);
1429  f = 0;
1430  if( x!=sz ){
1431    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1432    goto edit_func_end;
1433  }
1434  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1435  if( zCmd==0 ){
1436    sqlite3_result_error_nomem(context);
1437    goto edit_func_end;
1438  }
1439  rc = system(zCmd);
1440  sqlite3_free(zCmd);
1441  if( rc ){
1442    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1443    goto edit_func_end;
1444  }
1445  f = fopen(zTempFile, "rb");
1446  if( f==0 ){
1447    sqlite3_result_error(context,
1448      "edit() cannot reopen temp file after edit", -1);
1449    goto edit_func_end;
1450  }
1451  fseek(f, 0, SEEK_END);
1452  sz = ftell(f);
1453  rewind(f);
1454  p = sqlite3_malloc64( sz+1 );
1455  if( p==0 ){
1456    sqlite3_result_error_nomem(context);
1457    goto edit_func_end;
1458  }
1459  x = fread(p, 1, (size_t)sz, f);
1460  fclose(f);
1461  f = 0;
1462  if( x!=sz ){
1463    sqlite3_result_error(context, "could not read back the whole file", -1);
1464    goto edit_func_end;
1465  }
1466  if( bBin ){
1467    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1468  }else{
1469    sqlite3_int64 i, j;
1470    if( hasCRNL ){
1471      /* If the original contains \r\n then do no conversions back to \n */
1472    }else{
1473      /* If the file did not originally contain \r\n then convert any new
1474      ** \r\n back into \n */
1475      for(i=j=0; i<sz; i++){
1476        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1477        p[j++] = p[i];
1478      }
1479      sz = j;
1480      p[sz] = 0;
1481    }
1482    sqlite3_result_text64(context, (const char*)p, sz,
1483                          sqlite3_free, SQLITE_UTF8);
1484  }
1485  p = 0;
1486
1487edit_func_end:
1488  if( f ) fclose(f);
1489  unlink(zTempFile);
1490  sqlite3_free(zTempFile);
1491  sqlite3_free(p);
1492}
1493#endif /* SQLITE_NOHAVE_SYSTEM */
1494
1495/*
1496** Save or restore the current output mode
1497*/
1498static void outputModePush(ShellState *p){
1499  p->modePrior = p->mode;
1500  p->priorShFlgs = p->shellFlgs;
1501  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1502  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1503}
1504static void outputModePop(ShellState *p){
1505  p->mode = p->modePrior;
1506  p->shellFlgs = p->priorShFlgs;
1507  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1508  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1509}
1510
1511/*
1512** Output the given string as a hex-encoded blob (eg. X'1234' )
1513*/
1514static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1515  int i;
1516  char *zBlob = (char *)pBlob;
1517  raw_printf(out,"X'");
1518  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1519  raw_printf(out,"'");
1520}
1521
1522/*
1523** Find a string that is not found anywhere in z[].  Return a pointer
1524** to that string.
1525**
1526** Try to use zA and zB first.  If both of those are already found in z[]
1527** then make up some string and store it in the buffer zBuf.
1528*/
1529static const char *unused_string(
1530  const char *z,                    /* Result must not appear anywhere in z */
1531  const char *zA, const char *zB,   /* Try these first */
1532  char *zBuf                        /* Space to store a generated string */
1533){
1534  unsigned i = 0;
1535  if( strstr(z, zA)==0 ) return zA;
1536  if( strstr(z, zB)==0 ) return zB;
1537  do{
1538    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1539  }while( strstr(z,zBuf)!=0 );
1540  return zBuf;
1541}
1542
1543/*
1544** Output the given string as a quoted string using SQL quoting conventions.
1545**
1546** See also: output_quoted_escaped_string()
1547*/
1548static void output_quoted_string(FILE *out, const char *z){
1549  int i;
1550  char c;
1551  setBinaryMode(out, 1);
1552  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1553  if( c==0 ){
1554    utf8_printf(out,"'%s'",z);
1555  }else{
1556    raw_printf(out, "'");
1557    while( *z ){
1558      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1559      if( c=='\'' ) i++;
1560      if( i ){
1561        utf8_printf(out, "%.*s", i, z);
1562        z += i;
1563      }
1564      if( c=='\'' ){
1565        raw_printf(out, "'");
1566        continue;
1567      }
1568      if( c==0 ){
1569        break;
1570      }
1571      z++;
1572    }
1573    raw_printf(out, "'");
1574  }
1575  setTextMode(out, 1);
1576}
1577
1578/*
1579** Output the given string as a quoted string using SQL quoting conventions.
1580** Additionallly , escape the "\n" and "\r" characters so that they do not
1581** get corrupted by end-of-line translation facilities in some operating
1582** systems.
1583**
1584** This is like output_quoted_string() but with the addition of the \r\n
1585** escape mechanism.
1586*/
1587static void output_quoted_escaped_string(FILE *out, const char *z){
1588  int i;
1589  char c;
1590  setBinaryMode(out, 1);
1591  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1592  if( c==0 ){
1593    utf8_printf(out,"'%s'",z);
1594  }else{
1595    const char *zNL = 0;
1596    const char *zCR = 0;
1597    int nNL = 0;
1598    int nCR = 0;
1599    char zBuf1[20], zBuf2[20];
1600    for(i=0; z[i]; i++){
1601      if( z[i]=='\n' ) nNL++;
1602      if( z[i]=='\r' ) nCR++;
1603    }
1604    if( nNL ){
1605      raw_printf(out, "replace(");
1606      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1607    }
1608    if( nCR ){
1609      raw_printf(out, "replace(");
1610      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1611    }
1612    raw_printf(out, "'");
1613    while( *z ){
1614      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1615      if( c=='\'' ) i++;
1616      if( i ){
1617        utf8_printf(out, "%.*s", i, z);
1618        z += i;
1619      }
1620      if( c=='\'' ){
1621        raw_printf(out, "'");
1622        continue;
1623      }
1624      if( c==0 ){
1625        break;
1626      }
1627      z++;
1628      if( c=='\n' ){
1629        raw_printf(out, "%s", zNL);
1630        continue;
1631      }
1632      raw_printf(out, "%s", zCR);
1633    }
1634    raw_printf(out, "'");
1635    if( nCR ){
1636      raw_printf(out, ",'%s',char(13))", zCR);
1637    }
1638    if( nNL ){
1639      raw_printf(out, ",'%s',char(10))", zNL);
1640    }
1641  }
1642  setTextMode(out, 1);
1643}
1644
1645/*
1646** Output the given string as a quoted according to C or TCL quoting rules.
1647*/
1648static void output_c_string(FILE *out, const char *z){
1649  unsigned int c;
1650  fputc('"', out);
1651  while( (c = *(z++))!=0 ){
1652    if( c=='\\' ){
1653      fputc(c, out);
1654      fputc(c, out);
1655    }else if( c=='"' ){
1656      fputc('\\', out);
1657      fputc('"', out);
1658    }else if( c=='\t' ){
1659      fputc('\\', out);
1660      fputc('t', out);
1661    }else if( c=='\n' ){
1662      fputc('\\', out);
1663      fputc('n', out);
1664    }else if( c=='\r' ){
1665      fputc('\\', out);
1666      fputc('r', out);
1667    }else if( !isprint(c&0xff) ){
1668      raw_printf(out, "\\%03o", c&0xff);
1669    }else{
1670      fputc(c, out);
1671    }
1672  }
1673  fputc('"', out);
1674}
1675
1676/*
1677** Output the given string as a quoted according to JSON quoting rules.
1678*/
1679static void output_json_string(FILE *out, const char *z, int n){
1680  unsigned int c;
1681  if( n<0 ) n = (int)strlen(z);
1682  fputc('"', out);
1683  while( n-- ){
1684    c = *(z++);
1685    if( c=='\\' || c=='"' ){
1686      fputc('\\', out);
1687      fputc(c, out);
1688    }else if( c<=0x1f ){
1689      fputc('\\', out);
1690      if( c=='\b' ){
1691        fputc('b', out);
1692      }else if( c=='\f' ){
1693        fputc('f', out);
1694      }else if( c=='\n' ){
1695        fputc('n', out);
1696      }else if( c=='\r' ){
1697        fputc('r', out);
1698      }else if( c=='\t' ){
1699        fputc('t', out);
1700      }else{
1701         raw_printf(out, "u%04x",c);
1702      }
1703    }else{
1704      fputc(c, out);
1705    }
1706  }
1707  fputc('"', out);
1708}
1709
1710/*
1711** Output the given string with characters that are special to
1712** HTML escaped.
1713*/
1714static void output_html_string(FILE *out, const char *z){
1715  int i;
1716  if( z==0 ) z = "";
1717  while( *z ){
1718    for(i=0;   z[i]
1719            && z[i]!='<'
1720            && z[i]!='&'
1721            && z[i]!='>'
1722            && z[i]!='\"'
1723            && z[i]!='\'';
1724        i++){}
1725    if( i>0 ){
1726      utf8_printf(out,"%.*s",i,z);
1727    }
1728    if( z[i]=='<' ){
1729      raw_printf(out,"&lt;");
1730    }else if( z[i]=='&' ){
1731      raw_printf(out,"&amp;");
1732    }else if( z[i]=='>' ){
1733      raw_printf(out,"&gt;");
1734    }else if( z[i]=='\"' ){
1735      raw_printf(out,"&quot;");
1736    }else if( z[i]=='\'' ){
1737      raw_printf(out,"&#39;");
1738    }else{
1739      break;
1740    }
1741    z += i + 1;
1742  }
1743}
1744
1745/*
1746** If a field contains any character identified by a 1 in the following
1747** array, then the string must be quoted for CSV.
1748*/
1749static const char needCsvQuote[] = {
1750  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1751  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1752  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1753  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1754  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1755  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1756  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1757  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1758  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1759  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1760  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1761  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1762  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1763  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1764  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1765  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1766};
1767
1768/*
1769** Output a single term of CSV.  Actually, p->colSeparator is used for
1770** the separator, which may or may not be a comma.  p->nullValue is
1771** the null value.  Strings are quoted if necessary.  The separator
1772** is only issued if bSep is true.
1773*/
1774static void output_csv(ShellState *p, const char *z, int bSep){
1775  FILE *out = p->out;
1776  if( z==0 ){
1777    utf8_printf(out,"%s",p->nullValue);
1778  }else{
1779    unsigned i;
1780    for(i=0; z[i]; i++){
1781      if( needCsvQuote[((unsigned char*)z)[i]] ){
1782        i = 0;
1783        break;
1784      }
1785    }
1786    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1787      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1788      shell_check_oom(zQuoted);
1789      utf8_printf(out, "%s", zQuoted);
1790      sqlite3_free(zQuoted);
1791    }else{
1792      utf8_printf(out, "%s", z);
1793    }
1794  }
1795  if( bSep ){
1796    utf8_printf(p->out, "%s", p->colSeparator);
1797  }
1798}
1799
1800/*
1801** This routine runs when the user presses Ctrl-C
1802*/
1803static void interrupt_handler(int NotUsed){
1804  UNUSED_PARAMETER(NotUsed);
1805  seenInterrupt++;
1806  if( seenInterrupt>2 ) exit(1);
1807  if( globalDb ) sqlite3_interrupt(globalDb);
1808}
1809
1810#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1811/*
1812** This routine runs for console events (e.g. Ctrl-C) on Win32
1813*/
1814static BOOL WINAPI ConsoleCtrlHandler(
1815  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1816){
1817  if( dwCtrlType==CTRL_C_EVENT ){
1818    interrupt_handler(0);
1819    return TRUE;
1820  }
1821  return FALSE;
1822}
1823#endif
1824
1825#ifndef SQLITE_OMIT_AUTHORIZATION
1826/*
1827** This authorizer runs in safe mode.
1828*/
1829static int safeModeAuth(
1830  void *pClientData,
1831  int op,
1832  const char *zA1,
1833  const char *zA2,
1834  const char *zA3,
1835  const char *zA4
1836){
1837  ShellState *p = (ShellState*)pClientData;
1838  static const char *azProhibitedFunctions[] = {
1839    "edit",
1840    "fts3_tokenizer",
1841    "load_extension",
1842    "readfile",
1843    "writefile",
1844    "zipfile",
1845    "zipfile_cds",
1846  };
1847  UNUSED_PARAMETER(zA2);
1848  UNUSED_PARAMETER(zA3);
1849  UNUSED_PARAMETER(zA4);
1850  switch( op ){
1851    case SQLITE_ATTACH: {
1852      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1853      break;
1854    }
1855    case SQLITE_FUNCTION: {
1856      int i;
1857      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1858        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1859          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1860                         azProhibitedFunctions[i]);
1861        }
1862      }
1863      break;
1864    }
1865  }
1866  return SQLITE_OK;
1867}
1868
1869/*
1870** When the ".auth ON" is set, the following authorizer callback is
1871** invoked.  It always returns SQLITE_OK.
1872*/
1873static int shellAuth(
1874  void *pClientData,
1875  int op,
1876  const char *zA1,
1877  const char *zA2,
1878  const char *zA3,
1879  const char *zA4
1880){
1881  ShellState *p = (ShellState*)pClientData;
1882  static const char *azAction[] = { 0,
1883     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1884     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1885     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1886     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1887     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1888     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1889     "PRAGMA",               "READ",                 "SELECT",
1890     "TRANSACTION",          "UPDATE",               "ATTACH",
1891     "DETACH",               "ALTER_TABLE",          "REINDEX",
1892     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1893     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1894  };
1895  int i;
1896  const char *az[4];
1897  az[0] = zA1;
1898  az[1] = zA2;
1899  az[2] = zA3;
1900  az[3] = zA4;
1901  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1902  for(i=0; i<4; i++){
1903    raw_printf(p->out, " ");
1904    if( az[i] ){
1905      output_c_string(p->out, az[i]);
1906    }else{
1907      raw_printf(p->out, "NULL");
1908    }
1909  }
1910  raw_printf(p->out, "\n");
1911  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1912  return SQLITE_OK;
1913}
1914#endif
1915
1916/*
1917** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1918**
1919** This routine converts some CREATE TABLE statements for shadow tables
1920** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1921*/
1922static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1923  if( z==0 ) return;
1924  if( zTail==0 ) return;
1925  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1926    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1927  }else{
1928    utf8_printf(out, "%s%s", z, zTail);
1929  }
1930}
1931static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1932  char c = z[n];
1933  z[n] = 0;
1934  printSchemaLine(out, z, zTail);
1935  z[n] = c;
1936}
1937
1938/*
1939** Return true if string z[] has nothing but whitespace and comments to the
1940** end of the first line.
1941*/
1942static int wsToEol(const char *z){
1943  int i;
1944  for(i=0; z[i]; i++){
1945    if( z[i]=='\n' ) return 1;
1946    if( IsSpace(z[i]) ) continue;
1947    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1948    return 0;
1949  }
1950  return 1;
1951}
1952
1953/*
1954** Add a new entry to the EXPLAIN QUERY PLAN data
1955*/
1956static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1957  EQPGraphRow *pNew;
1958  int nText = strlen30(zText);
1959  if( p->autoEQPtest ){
1960    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1961  }
1962  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1963  shell_check_oom(pNew);
1964  pNew->iEqpId = iEqpId;
1965  pNew->iParentId = p2;
1966  memcpy(pNew->zText, zText, nText+1);
1967  pNew->pNext = 0;
1968  if( p->sGraph.pLast ){
1969    p->sGraph.pLast->pNext = pNew;
1970  }else{
1971    p->sGraph.pRow = pNew;
1972  }
1973  p->sGraph.pLast = pNew;
1974}
1975
1976/*
1977** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1978** in p->sGraph.
1979*/
1980static void eqp_reset(ShellState *p){
1981  EQPGraphRow *pRow, *pNext;
1982  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1983    pNext = pRow->pNext;
1984    sqlite3_free(pRow);
1985  }
1986  memset(&p->sGraph, 0, sizeof(p->sGraph));
1987}
1988
1989/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1990** pOld, or return the first such line if pOld is NULL
1991*/
1992static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1993  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1994  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1995  return pRow;
1996}
1997
1998/* Render a single level of the graph that has iEqpId as its parent.  Called
1999** recursively to render sublevels.
2000*/
2001static void eqp_render_level(ShellState *p, int iEqpId){
2002  EQPGraphRow *pRow, *pNext;
2003  int n = strlen30(p->sGraph.zPrefix);
2004  char *z;
2005  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2006    pNext = eqp_next_row(p, iEqpId, pRow);
2007    z = pRow->zText;
2008    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2009                pNext ? "|--" : "`--", z);
2010    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2011      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2012      eqp_render_level(p, pRow->iEqpId);
2013      p->sGraph.zPrefix[n] = 0;
2014    }
2015  }
2016}
2017
2018/*
2019** Display and reset the EXPLAIN QUERY PLAN data
2020*/
2021static void eqp_render(ShellState *p){
2022  EQPGraphRow *pRow = p->sGraph.pRow;
2023  if( pRow ){
2024    if( pRow->zText[0]=='-' ){
2025      if( pRow->pNext==0 ){
2026        eqp_reset(p);
2027        return;
2028      }
2029      utf8_printf(p->out, "%s\n", pRow->zText+3);
2030      p->sGraph.pRow = pRow->pNext;
2031      sqlite3_free(pRow);
2032    }else{
2033      utf8_printf(p->out, "QUERY PLAN\n");
2034    }
2035    p->sGraph.zPrefix[0] = 0;
2036    eqp_render_level(p, 0);
2037    eqp_reset(p);
2038  }
2039}
2040
2041#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2042/*
2043** Progress handler callback.
2044*/
2045static int progress_handler(void *pClientData) {
2046  ShellState *p = (ShellState*)pClientData;
2047  p->nProgress++;
2048  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2049    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2050    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2051    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2052    return 1;
2053  }
2054  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2055    raw_printf(p->out, "Progress %u\n", p->nProgress);
2056  }
2057  return 0;
2058}
2059#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2060
2061/*
2062** Print N dashes
2063*/
2064static void print_dashes(FILE *out, int N){
2065  const char zDash[] = "--------------------------------------------------";
2066  const int nDash = sizeof(zDash) - 1;
2067  while( N>nDash ){
2068    fputs(zDash, out);
2069    N -= nDash;
2070  }
2071  raw_printf(out, "%.*s", N, zDash);
2072}
2073
2074/*
2075** Print a markdown or table-style row separator using ascii-art
2076*/
2077static void print_row_separator(
2078  ShellState *p,
2079  int nArg,
2080  const char *zSep
2081){
2082  int i;
2083  if( nArg>0 ){
2084    fputs(zSep, p->out);
2085    print_dashes(p->out, p->actualWidth[0]+2);
2086    for(i=1; i<nArg; i++){
2087      fputs(zSep, p->out);
2088      print_dashes(p->out, p->actualWidth[i]+2);
2089    }
2090    fputs(zSep, p->out);
2091  }
2092  fputs("\n", p->out);
2093}
2094
2095/*
2096** This is the callback routine that the shell
2097** invokes for each row of a query result.
2098*/
2099static int shell_callback(
2100  void *pArg,
2101  int nArg,        /* Number of result columns */
2102  char **azArg,    /* Text of each result column */
2103  char **azCol,    /* Column names */
2104  int *aiType      /* Column types.  Might be NULL */
2105){
2106  int i;
2107  ShellState *p = (ShellState*)pArg;
2108
2109  if( azArg==0 ) return 0;
2110  switch( p->cMode ){
2111    case MODE_Count:
2112    case MODE_Off: {
2113      break;
2114    }
2115    case MODE_Line: {
2116      int w = 5;
2117      if( azArg==0 ) break;
2118      for(i=0; i<nArg; i++){
2119        int len = strlen30(azCol[i] ? azCol[i] : "");
2120        if( len>w ) w = len;
2121      }
2122      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2123      for(i=0; i<nArg; i++){
2124        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2125                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2126      }
2127      break;
2128    }
2129    case MODE_Explain: {
2130      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2131      if( nArg>ArraySize(aExplainWidth) ){
2132        nArg = ArraySize(aExplainWidth);
2133      }
2134      if( p->cnt++==0 ){
2135        for(i=0; i<nArg; i++){
2136          int w = aExplainWidth[i];
2137          utf8_width_print(p->out, w, azCol[i]);
2138          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2139        }
2140        for(i=0; i<nArg; i++){
2141          int w = aExplainWidth[i];
2142          print_dashes(p->out, w);
2143          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2144        }
2145      }
2146      if( azArg==0 ) break;
2147      for(i=0; i<nArg; i++){
2148        int w = aExplainWidth[i];
2149        if( i==nArg-1 ) w = 0;
2150        if( azArg[i] && strlenChar(azArg[i])>w ){
2151          w = strlenChar(azArg[i]);
2152        }
2153        if( i==1 && p->aiIndent && p->pStmt ){
2154          if( p->iIndent<p->nIndent ){
2155            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2156          }
2157          p->iIndent++;
2158        }
2159        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2160        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2161      }
2162      break;
2163    }
2164    case MODE_Semi: {   /* .schema and .fullschema output */
2165      printSchemaLine(p->out, azArg[0], ";\n");
2166      break;
2167    }
2168    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2169      char *z;
2170      int j;
2171      int nParen = 0;
2172      char cEnd = 0;
2173      char c;
2174      int nLine = 0;
2175      assert( nArg==1 );
2176      if( azArg[0]==0 ) break;
2177      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2178       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2179      ){
2180        utf8_printf(p->out, "%s;\n", azArg[0]);
2181        break;
2182      }
2183      z = sqlite3_mprintf("%s", azArg[0]);
2184      shell_check_oom(z);
2185      j = 0;
2186      for(i=0; IsSpace(z[i]); i++){}
2187      for(; (c = z[i])!=0; i++){
2188        if( IsSpace(c) ){
2189          if( z[j-1]=='\r' ) z[j-1] = '\n';
2190          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2191        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2192          j--;
2193        }
2194        z[j++] = c;
2195      }
2196      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2197      z[j] = 0;
2198      if( strlen30(z)>=79 ){
2199        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2200          if( c==cEnd ){
2201            cEnd = 0;
2202          }else if( c=='"' || c=='\'' || c=='`' ){
2203            cEnd = c;
2204          }else if( c=='[' ){
2205            cEnd = ']';
2206          }else if( c=='-' && z[i+1]=='-' ){
2207            cEnd = '\n';
2208          }else if( c=='(' ){
2209            nParen++;
2210          }else if( c==')' ){
2211            nParen--;
2212            if( nLine>0 && nParen==0 && j>0 ){
2213              printSchemaLineN(p->out, z, j, "\n");
2214              j = 0;
2215            }
2216          }
2217          z[j++] = c;
2218          if( nParen==1 && cEnd==0
2219           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2220          ){
2221            if( c=='\n' ) j--;
2222            printSchemaLineN(p->out, z, j, "\n  ");
2223            j = 0;
2224            nLine++;
2225            while( IsSpace(z[i+1]) ){ i++; }
2226          }
2227        }
2228        z[j] = 0;
2229      }
2230      printSchemaLine(p->out, z, ";\n");
2231      sqlite3_free(z);
2232      break;
2233    }
2234    case MODE_List: {
2235      if( p->cnt++==0 && p->showHeader ){
2236        for(i=0; i<nArg; i++){
2237          utf8_printf(p->out,"%s%s",azCol[i],
2238                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2239        }
2240      }
2241      if( azArg==0 ) break;
2242      for(i=0; i<nArg; i++){
2243        char *z = azArg[i];
2244        if( z==0 ) z = p->nullValue;
2245        utf8_printf(p->out, "%s", z);
2246        if( i<nArg-1 ){
2247          utf8_printf(p->out, "%s", p->colSeparator);
2248        }else{
2249          utf8_printf(p->out, "%s", p->rowSeparator);
2250        }
2251      }
2252      break;
2253    }
2254    case MODE_Html: {
2255      if( p->cnt++==0 && p->showHeader ){
2256        raw_printf(p->out,"<TR>");
2257        for(i=0; i<nArg; i++){
2258          raw_printf(p->out,"<TH>");
2259          output_html_string(p->out, azCol[i]);
2260          raw_printf(p->out,"</TH>\n");
2261        }
2262        raw_printf(p->out,"</TR>\n");
2263      }
2264      if( azArg==0 ) break;
2265      raw_printf(p->out,"<TR>");
2266      for(i=0; i<nArg; i++){
2267        raw_printf(p->out,"<TD>");
2268        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2269        raw_printf(p->out,"</TD>\n");
2270      }
2271      raw_printf(p->out,"</TR>\n");
2272      break;
2273    }
2274    case MODE_Tcl: {
2275      if( p->cnt++==0 && p->showHeader ){
2276        for(i=0; i<nArg; i++){
2277          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2278          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2279        }
2280        utf8_printf(p->out, "%s", p->rowSeparator);
2281      }
2282      if( azArg==0 ) break;
2283      for(i=0; i<nArg; i++){
2284        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2285        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2286      }
2287      utf8_printf(p->out, "%s", p->rowSeparator);
2288      break;
2289    }
2290    case MODE_Csv: {
2291      setBinaryMode(p->out, 1);
2292      if( p->cnt++==0 && p->showHeader ){
2293        for(i=0; i<nArg; i++){
2294          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2295        }
2296        utf8_printf(p->out, "%s", p->rowSeparator);
2297      }
2298      if( nArg>0 ){
2299        for(i=0; i<nArg; i++){
2300          output_csv(p, azArg[i], i<nArg-1);
2301        }
2302        utf8_printf(p->out, "%s", p->rowSeparator);
2303      }
2304      setTextMode(p->out, 1);
2305      break;
2306    }
2307    case MODE_Insert: {
2308      if( azArg==0 ) break;
2309      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2310      if( p->showHeader ){
2311        raw_printf(p->out,"(");
2312        for(i=0; i<nArg; i++){
2313          if( i>0 ) raw_printf(p->out, ",");
2314          if( quoteChar(azCol[i]) ){
2315            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2316            shell_check_oom(z);
2317            utf8_printf(p->out, "%s", z);
2318            sqlite3_free(z);
2319          }else{
2320            raw_printf(p->out, "%s", azCol[i]);
2321          }
2322        }
2323        raw_printf(p->out,")");
2324      }
2325      p->cnt++;
2326      for(i=0; i<nArg; i++){
2327        raw_printf(p->out, i>0 ? "," : " VALUES(");
2328        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2329          utf8_printf(p->out,"NULL");
2330        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2331          if( ShellHasFlag(p, SHFLG_Newlines) ){
2332            output_quoted_string(p->out, azArg[i]);
2333          }else{
2334            output_quoted_escaped_string(p->out, azArg[i]);
2335          }
2336        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2337          utf8_printf(p->out,"%s", azArg[i]);
2338        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2339          char z[50];
2340          double r = sqlite3_column_double(p->pStmt, i);
2341          sqlite3_uint64 ur;
2342          memcpy(&ur,&r,sizeof(r));
2343          if( ur==0x7ff0000000000000LL ){
2344            raw_printf(p->out, "1e999");
2345          }else if( ur==0xfff0000000000000LL ){
2346            raw_printf(p->out, "-1e999");
2347          }else{
2348            sqlite3_snprintf(50,z,"%!.20g", r);
2349            raw_printf(p->out, "%s", z);
2350          }
2351        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2352          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2353          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2354          output_hex_blob(p->out, pBlob, nBlob);
2355        }else if( isNumber(azArg[i], 0) ){
2356          utf8_printf(p->out,"%s", azArg[i]);
2357        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2358          output_quoted_string(p->out, azArg[i]);
2359        }else{
2360          output_quoted_escaped_string(p->out, azArg[i]);
2361        }
2362      }
2363      raw_printf(p->out,");\n");
2364      break;
2365    }
2366    case MODE_Json: {
2367      if( azArg==0 ) break;
2368      if( p->cnt==0 ){
2369        fputs("[{", p->out);
2370      }else{
2371        fputs(",\n{", p->out);
2372      }
2373      p->cnt++;
2374      for(i=0; i<nArg; i++){
2375        output_json_string(p->out, azCol[i], -1);
2376        putc(':', p->out);
2377        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2378          fputs("null",p->out);
2379        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2380          char z[50];
2381          double r = sqlite3_column_double(p->pStmt, i);
2382          sqlite3_uint64 ur;
2383          memcpy(&ur,&r,sizeof(r));
2384          if( ur==0x7ff0000000000000LL ){
2385            raw_printf(p->out, "1e999");
2386          }else if( ur==0xfff0000000000000LL ){
2387            raw_printf(p->out, "-1e999");
2388          }else{
2389            sqlite3_snprintf(50,z,"%!.20g", r);
2390            raw_printf(p->out, "%s", z);
2391          }
2392        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2393          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2394          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2395          output_json_string(p->out, pBlob, nBlob);
2396        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2397          output_json_string(p->out, azArg[i], -1);
2398        }else{
2399          utf8_printf(p->out,"%s", azArg[i]);
2400        }
2401        if( i<nArg-1 ){
2402          putc(',', p->out);
2403        }
2404      }
2405      putc('}', p->out);
2406      break;
2407    }
2408    case MODE_Quote: {
2409      if( azArg==0 ) break;
2410      if( p->cnt==0 && p->showHeader ){
2411        for(i=0; i<nArg; i++){
2412          if( i>0 ) fputs(p->colSeparator, p->out);
2413          output_quoted_string(p->out, azCol[i]);
2414        }
2415        fputs(p->rowSeparator, p->out);
2416      }
2417      p->cnt++;
2418      for(i=0; i<nArg; i++){
2419        if( i>0 ) fputs(p->colSeparator, p->out);
2420        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2421          utf8_printf(p->out,"NULL");
2422        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2423          output_quoted_string(p->out, azArg[i]);
2424        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2425          utf8_printf(p->out,"%s", azArg[i]);
2426        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2427          char z[50];
2428          double r = sqlite3_column_double(p->pStmt, i);
2429          sqlite3_snprintf(50,z,"%!.20g", r);
2430          raw_printf(p->out, "%s", z);
2431        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2432          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2433          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2434          output_hex_blob(p->out, pBlob, nBlob);
2435        }else if( isNumber(azArg[i], 0) ){
2436          utf8_printf(p->out,"%s", azArg[i]);
2437        }else{
2438          output_quoted_string(p->out, azArg[i]);
2439        }
2440      }
2441      fputs(p->rowSeparator, p->out);
2442      break;
2443    }
2444    case MODE_Ascii: {
2445      if( p->cnt++==0 && p->showHeader ){
2446        for(i=0; i<nArg; i++){
2447          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2448          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2449        }
2450        utf8_printf(p->out, "%s", p->rowSeparator);
2451      }
2452      if( azArg==0 ) break;
2453      for(i=0; i<nArg; i++){
2454        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2455        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2456      }
2457      utf8_printf(p->out, "%s", p->rowSeparator);
2458      break;
2459    }
2460    case MODE_EQP: {
2461      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2462      break;
2463    }
2464  }
2465  return 0;
2466}
2467
2468/*
2469** This is the callback routine that the SQLite library
2470** invokes for each row of a query result.
2471*/
2472static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2473  /* since we don't have type info, call the shell_callback with a NULL value */
2474  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2475}
2476
2477/*
2478** This is the callback routine from sqlite3_exec() that appends all
2479** output onto the end of a ShellText object.
2480*/
2481static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2482  ShellText *p = (ShellText*)pArg;
2483  int i;
2484  UNUSED_PARAMETER(az);
2485  if( azArg==0 ) return 0;
2486  if( p->n ) appendText(p, "|", 0);
2487  for(i=0; i<nArg; i++){
2488    if( i ) appendText(p, ",", 0);
2489    if( azArg[i] ) appendText(p, azArg[i], 0);
2490  }
2491  return 0;
2492}
2493
2494/*
2495** Generate an appropriate SELFTEST table in the main database.
2496*/
2497static void createSelftestTable(ShellState *p){
2498  char *zErrMsg = 0;
2499  sqlite3_exec(p->db,
2500    "SAVEPOINT selftest_init;\n"
2501    "CREATE TABLE IF NOT EXISTS selftest(\n"
2502    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2503    "  op TEXT,\n"                   /* Operator:  memo run */
2504    "  cmd TEXT,\n"                  /* Command text */
2505    "  ans TEXT\n"                   /* Desired answer */
2506    ");"
2507    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2508    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2509    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2510    "         'memo','Tests generated by --init');\n"
2511    "INSERT INTO [_shell$self]\n"
2512    "  SELECT 'run',\n"
2513    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2514                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2515    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2516                          "FROM sqlite_schema ORDER BY 2',224));\n"
2517    "INSERT INTO [_shell$self]\n"
2518    "  SELECT 'run',"
2519    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2520    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2521    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2522    "  FROM (\n"
2523    "    SELECT name FROM sqlite_schema\n"
2524    "     WHERE type='table'\n"
2525    "       AND name<>'selftest'\n"
2526    "       AND coalesce(rootpage,0)>0\n"
2527    "  )\n"
2528    " ORDER BY name;\n"
2529    "INSERT INTO [_shell$self]\n"
2530    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2531    "INSERT INTO selftest(tno,op,cmd,ans)"
2532    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2533    "DROP TABLE [_shell$self];"
2534    ,0,0,&zErrMsg);
2535  if( zErrMsg ){
2536    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2537    sqlite3_free(zErrMsg);
2538  }
2539  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2540}
2541
2542
2543/*
2544** Set the destination table field of the ShellState structure to
2545** the name of the table given.  Escape any quote characters in the
2546** table name.
2547*/
2548static void set_table_name(ShellState *p, const char *zName){
2549  int i, n;
2550  char cQuote;
2551  char *z;
2552
2553  if( p->zDestTable ){
2554    free(p->zDestTable);
2555    p->zDestTable = 0;
2556  }
2557  if( zName==0 ) return;
2558  cQuote = quoteChar(zName);
2559  n = strlen30(zName);
2560  if( cQuote ) n += n+2;
2561  z = p->zDestTable = malloc( n+1 );
2562  shell_check_oom(z);
2563  n = 0;
2564  if( cQuote ) z[n++] = cQuote;
2565  for(i=0; zName[i]; i++){
2566    z[n++] = zName[i];
2567    if( zName[i]==cQuote ) z[n++] = cQuote;
2568  }
2569  if( cQuote ) z[n++] = cQuote;
2570  z[n] = 0;
2571}
2572
2573
2574/*
2575** Execute a query statement that will generate SQL output.  Print
2576** the result columns, comma-separated, on a line and then add a
2577** semicolon terminator to the end of that line.
2578**
2579** If the number of columns is 1 and that column contains text "--"
2580** then write the semicolon on a separate line.  That way, if a
2581** "--" comment occurs at the end of the statement, the comment
2582** won't consume the semicolon terminator.
2583*/
2584static int run_table_dump_query(
2585  ShellState *p,           /* Query context */
2586  const char *zSelect      /* SELECT statement to extract content */
2587){
2588  sqlite3_stmt *pSelect;
2589  int rc;
2590  int nResult;
2591  int i;
2592  const char *z;
2593  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2594  if( rc!=SQLITE_OK || !pSelect ){
2595    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2596                sqlite3_errmsg(p->db));
2597    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2598    return rc;
2599  }
2600  rc = sqlite3_step(pSelect);
2601  nResult = sqlite3_column_count(pSelect);
2602  while( rc==SQLITE_ROW ){
2603    z = (const char*)sqlite3_column_text(pSelect, 0);
2604    utf8_printf(p->out, "%s", z);
2605    for(i=1; i<nResult; i++){
2606      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2607    }
2608    if( z==0 ) z = "";
2609    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2610    if( z[0] ){
2611      raw_printf(p->out, "\n;\n");
2612    }else{
2613      raw_printf(p->out, ";\n");
2614    }
2615    rc = sqlite3_step(pSelect);
2616  }
2617  rc = sqlite3_finalize(pSelect);
2618  if( rc!=SQLITE_OK ){
2619    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2620                sqlite3_errmsg(p->db));
2621    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2622  }
2623  return rc;
2624}
2625
2626/*
2627** Allocate space and save off string indicating current error.
2628*/
2629static char *save_err_msg(
2630  sqlite3 *db,           /* Database to query */
2631  const char *zWhen,     /* Qualifier (format) wrapper */
2632  int rc                 /* Error code returned from API */
2633){
2634  char *zErr;
2635  if( zWhen==0 ) zWhen = "%s (%d)";
2636  zErr = sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc);
2637  shell_check_oom(zErr);
2638  return zErr;
2639}
2640
2641#ifdef __linux__
2642/*
2643** Attempt to display I/O stats on Linux using /proc/PID/io
2644*/
2645static void displayLinuxIoStats(FILE *out){
2646  FILE *in;
2647  char z[200];
2648  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2649  in = fopen(z, "rb");
2650  if( in==0 ) return;
2651  while( fgets(z, sizeof(z), in)!=0 ){
2652    static const struct {
2653      const char *zPattern;
2654      const char *zDesc;
2655    } aTrans[] = {
2656      { "rchar: ",                  "Bytes received by read():" },
2657      { "wchar: ",                  "Bytes sent to write():"    },
2658      { "syscr: ",                  "Read() system calls:"      },
2659      { "syscw: ",                  "Write() system calls:"     },
2660      { "read_bytes: ",             "Bytes read from storage:"  },
2661      { "write_bytes: ",            "Bytes written to storage:" },
2662      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2663    };
2664    int i;
2665    for(i=0; i<ArraySize(aTrans); i++){
2666      int n = strlen30(aTrans[i].zPattern);
2667      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2668        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2669        break;
2670      }
2671    }
2672  }
2673  fclose(in);
2674}
2675#endif
2676
2677/*
2678** Display a single line of status using 64-bit values.
2679*/
2680static void displayStatLine(
2681  ShellState *p,            /* The shell context */
2682  char *zLabel,             /* Label for this one line */
2683  char *zFormat,            /* Format for the result */
2684  int iStatusCtrl,          /* Which status to display */
2685  int bReset                /* True to reset the stats */
2686){
2687  sqlite3_int64 iCur = -1;
2688  sqlite3_int64 iHiwtr = -1;
2689  int i, nPercent;
2690  char zLine[200];
2691  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2692  for(i=0, nPercent=0; zFormat[i]; i++){
2693    if( zFormat[i]=='%' ) nPercent++;
2694  }
2695  if( nPercent>1 ){
2696    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2697  }else{
2698    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2699  }
2700  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2701}
2702
2703/*
2704** Display memory stats.
2705*/
2706static int display_stats(
2707  sqlite3 *db,                /* Database to query */
2708  ShellState *pArg,           /* Pointer to ShellState */
2709  int bReset                  /* True to reset the stats */
2710){
2711  int iCur;
2712  int iHiwtr;
2713  FILE *out;
2714  if( pArg==0 || pArg->out==0 ) return 0;
2715  out = pArg->out;
2716
2717  if( pArg->pStmt && pArg->statsOn==2 ){
2718    int nCol, i, x;
2719    sqlite3_stmt *pStmt = pArg->pStmt;
2720    char z[100];
2721    nCol = sqlite3_column_count(pStmt);
2722    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2723    for(i=0; i<nCol; i++){
2724      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2725      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2726#ifndef SQLITE_OMIT_DECLTYPE
2727      sqlite3_snprintf(30, z+x, "declared type:");
2728      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2729#endif
2730#ifdef SQLITE_ENABLE_COLUMN_METADATA
2731      sqlite3_snprintf(30, z+x, "database name:");
2732      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2733      sqlite3_snprintf(30, z+x, "table name:");
2734      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2735      sqlite3_snprintf(30, z+x, "origin name:");
2736      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2737#endif
2738    }
2739  }
2740
2741  if( pArg->statsOn==3 ){
2742    if( pArg->pStmt ){
2743      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2744      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2745    }
2746    return 0;
2747  }
2748
2749  displayStatLine(pArg, "Memory Used:",
2750     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2751  displayStatLine(pArg, "Number of Outstanding Allocations:",
2752     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2753  if( pArg->shellFlgs & SHFLG_Pagecache ){
2754    displayStatLine(pArg, "Number of Pcache Pages Used:",
2755       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2756  }
2757  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2758     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2759  displayStatLine(pArg, "Largest Allocation:",
2760     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2761  displayStatLine(pArg, "Largest Pcache Allocation:",
2762     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2763#ifdef YYTRACKMAXSTACKDEPTH
2764  displayStatLine(pArg, "Deepest Parser Stack:",
2765     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2766#endif
2767
2768  if( db ){
2769    if( pArg->shellFlgs & SHFLG_Lookaside ){
2770      iHiwtr = iCur = -1;
2771      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2772                        &iCur, &iHiwtr, bReset);
2773      raw_printf(pArg->out,
2774              "Lookaside Slots Used:                %d (max %d)\n",
2775              iCur, iHiwtr);
2776      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2777                        &iCur, &iHiwtr, bReset);
2778      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2779              iHiwtr);
2780      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2781                        &iCur, &iHiwtr, bReset);
2782      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2783              iHiwtr);
2784      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2785                        &iCur, &iHiwtr, bReset);
2786      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2787              iHiwtr);
2788    }
2789    iHiwtr = iCur = -1;
2790    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2791    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2792            iCur);
2793    iHiwtr = iCur = -1;
2794    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2795    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2796    iHiwtr = iCur = -1;
2797    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2798    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2799    iHiwtr = iCur = -1;
2800    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2801    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2802    iHiwtr = iCur = -1;
2803    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2804    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2805    iHiwtr = iCur = -1;
2806    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2807    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2808            iCur);
2809    iHiwtr = iCur = -1;
2810    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2811    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2812            iCur);
2813  }
2814
2815  if( pArg->pStmt ){
2816    int iHit, iMiss;
2817    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2818                               bReset);
2819    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2820    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2821    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2822    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2823    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2824    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2825    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2826    if( iHit || iMiss ){
2827      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2828            iHit, iHit+iMiss);
2829    }
2830    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2831    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2832    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2833    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2834    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2835    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2836    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2837    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2838  }
2839
2840#ifdef __linux__
2841  displayLinuxIoStats(pArg->out);
2842#endif
2843
2844  /* Do not remove this machine readable comment: extra-stats-output-here */
2845
2846  return 0;
2847}
2848
2849/*
2850** Display scan stats.
2851*/
2852static void display_scanstats(
2853  sqlite3 *db,                    /* Database to query */
2854  ShellState *pArg                /* Pointer to ShellState */
2855){
2856#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2857  UNUSED_PARAMETER(db);
2858  UNUSED_PARAMETER(pArg);
2859#else
2860  int i, k, n, mx;
2861  raw_printf(pArg->out, "-------- scanstats --------\n");
2862  mx = 0;
2863  for(k=0; k<=mx; k++){
2864    double rEstLoop = 1.0;
2865    for(i=n=0; 1; i++){
2866      sqlite3_stmt *p = pArg->pStmt;
2867      sqlite3_int64 nLoop, nVisit;
2868      double rEst;
2869      int iSid;
2870      const char *zExplain;
2871      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2872        break;
2873      }
2874      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2875      if( iSid>mx ) mx = iSid;
2876      if( iSid!=k ) continue;
2877      if( n==0 ){
2878        rEstLoop = (double)nLoop;
2879        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2880      }
2881      n++;
2882      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2883      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2884      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2885      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2886      rEstLoop *= rEst;
2887      raw_printf(pArg->out,
2888          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2889          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2890      );
2891    }
2892  }
2893  raw_printf(pArg->out, "---------------------------\n");
2894#endif
2895}
2896
2897/*
2898** Parameter azArray points to a zero-terminated array of strings. zStr
2899** points to a single nul-terminated string. Return non-zero if zStr
2900** is equal, according to strcmp(), to any of the strings in the array.
2901** Otherwise, return zero.
2902*/
2903static int str_in_array(const char *zStr, const char **azArray){
2904  int i;
2905  for(i=0; azArray[i]; i++){
2906    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2907  }
2908  return 0;
2909}
2910
2911/*
2912** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2913** and populate the ShellState.aiIndent[] array with the number of
2914** spaces each opcode should be indented before it is output.
2915**
2916** The indenting rules are:
2917**
2918**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2919**       all opcodes that occur between the p2 jump destination and the opcode
2920**       itself by 2 spaces.
2921**
2922**     * For each "Goto", if the jump destination is earlier in the program
2923**       and ends on one of:
2924**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2925**       or if the P1 parameter is one instead of zero,
2926**       then indent all opcodes between the earlier instruction
2927**       and "Goto" by 2 spaces.
2928*/
2929static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2930  const char *zSql;               /* The text of the SQL statement */
2931  const char *z;                  /* Used to check if this is an EXPLAIN */
2932  int *abYield = 0;               /* True if op is an OP_Yield */
2933  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2934  int iOp;                        /* Index of operation in p->aiIndent[] */
2935
2936  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2937  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2938                            "Rewind", 0 };
2939  const char *azGoto[] = { "Goto", 0 };
2940
2941  /* Try to figure out if this is really an EXPLAIN statement. If this
2942  ** cannot be verified, return early.  */
2943  if( sqlite3_column_count(pSql)!=8 ){
2944    p->cMode = p->mode;
2945    return;
2946  }
2947  zSql = sqlite3_sql(pSql);
2948  if( zSql==0 ) return;
2949  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2950  if( sqlite3_strnicmp(z, "explain", 7) ){
2951    p->cMode = p->mode;
2952    return;
2953  }
2954
2955  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2956    int i;
2957    int iAddr = sqlite3_column_int(pSql, 0);
2958    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2959
2960    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2961    ** p2 is an instruction address, set variable p2op to the index of that
2962    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2963    ** the current instruction is part of a sub-program generated by an
2964    ** SQL trigger or foreign key.  */
2965    int p2 = sqlite3_column_int(pSql, 3);
2966    int p2op = (p2 + (iOp-iAddr));
2967
2968    /* Grow the p->aiIndent array as required */
2969    if( iOp>=nAlloc ){
2970      if( iOp==0 ){
2971        /* Do further verfication that this is explain output.  Abort if
2972        ** it is not */
2973        static const char *explainCols[] = {
2974           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2975        int jj;
2976        for(jj=0; jj<ArraySize(explainCols); jj++){
2977          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2978            p->cMode = p->mode;
2979            sqlite3_reset(pSql);
2980            return;
2981          }
2982        }
2983      }
2984      nAlloc += 100;
2985      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2986      shell_check_oom(p->aiIndent);
2987      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2988      shell_check_oom(abYield);
2989    }
2990    abYield[iOp] = str_in_array(zOp, azYield);
2991    p->aiIndent[iOp] = 0;
2992    p->nIndent = iOp+1;
2993
2994    if( str_in_array(zOp, azNext) ){
2995      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2996    }
2997    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2998     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2999    ){
3000      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3001    }
3002  }
3003
3004  p->iIndent = 0;
3005  sqlite3_free(abYield);
3006  sqlite3_reset(pSql);
3007}
3008
3009/*
3010** Free the array allocated by explain_data_prepare().
3011*/
3012static void explain_data_delete(ShellState *p){
3013  sqlite3_free(p->aiIndent);
3014  p->aiIndent = 0;
3015  p->nIndent = 0;
3016  p->iIndent = 0;
3017}
3018
3019/*
3020** Disable and restore .wheretrace and .selecttrace settings.
3021*/
3022static unsigned int savedSelectTrace;
3023static unsigned int savedWhereTrace;
3024static void disable_debug_trace_modes(void){
3025  unsigned int zero = 0;
3026  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3027  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3028  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3029  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3030}
3031static void restore_debug_trace_modes(void){
3032  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3033  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3034}
3035
3036/* Create the TEMP table used to store parameter bindings */
3037static void bind_table_init(ShellState *p){
3038  int wrSchema = 0;
3039  int defensiveMode = 0;
3040  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3041  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3042  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3043  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3044  sqlite3_exec(p->db,
3045    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3046    "  key TEXT PRIMARY KEY,\n"
3047    "  value\n"
3048    ") WITHOUT ROWID;",
3049    0, 0, 0);
3050  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3051  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3052}
3053
3054/*
3055** Bind parameters on a prepared statement.
3056**
3057** Parameter bindings are taken from a TEMP table of the form:
3058**
3059**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3060**    WITHOUT ROWID;
3061**
3062** No bindings occur if this table does not exist.  The name of the table
3063** begins with "sqlite_" so that it will not collide with ordinary application
3064** tables.  The table must be in the TEMP schema.
3065*/
3066static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3067  int nVar;
3068  int i;
3069  int rc;
3070  sqlite3_stmt *pQ = 0;
3071
3072  nVar = sqlite3_bind_parameter_count(pStmt);
3073  if( nVar==0 ) return;  /* Nothing to do */
3074  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3075                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3076    return; /* Parameter table does not exist */
3077  }
3078  rc = sqlite3_prepare_v2(pArg->db,
3079          "SELECT value FROM temp.sqlite_parameters"
3080          " WHERE key=?1", -1, &pQ, 0);
3081  if( rc || pQ==0 ) return;
3082  for(i=1; i<=nVar; i++){
3083    char zNum[30];
3084    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3085    if( zVar==0 ){
3086      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3087      zVar = zNum;
3088    }
3089    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3090    if( sqlite3_step(pQ)==SQLITE_ROW ){
3091      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3092    }else{
3093      sqlite3_bind_null(pStmt, i);
3094    }
3095    sqlite3_reset(pQ);
3096  }
3097  sqlite3_finalize(pQ);
3098}
3099
3100/*
3101** UTF8 box-drawing characters.  Imagine box lines like this:
3102**
3103**           1
3104**           |
3105**       4 --+-- 2
3106**           |
3107**           3
3108**
3109** Each box characters has between 2 and 4 of the lines leading from
3110** the center.  The characters are here identified by the numbers of
3111** their corresponding lines.
3112*/
3113#define BOX_24   "\342\224\200"  /* U+2500 --- */
3114#define BOX_13   "\342\224\202"  /* U+2502  |  */
3115#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3116#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3117#define BOX_12   "\342\224\224"  /* U+2514  '- */
3118#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3119#define BOX_123  "\342\224\234"  /* U+251c  |- */
3120#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3121#define BOX_234  "\342\224\254"  /* U+252c -,- */
3122#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3123#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3124
3125/* Draw horizontal line N characters long using unicode box
3126** characters
3127*/
3128static void print_box_line(FILE *out, int N){
3129  const char zDash[] =
3130      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3131      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3132  const int nDash = sizeof(zDash) - 1;
3133  N *= 3;
3134  while( N>nDash ){
3135    utf8_printf(out, zDash);
3136    N -= nDash;
3137  }
3138  utf8_printf(out, "%.*s", N, zDash);
3139}
3140
3141/*
3142** Draw a horizontal separator for a MODE_Box table.
3143*/
3144static void print_box_row_separator(
3145  ShellState *p,
3146  int nArg,
3147  const char *zSep1,
3148  const char *zSep2,
3149  const char *zSep3
3150){
3151  int i;
3152  if( nArg>0 ){
3153    utf8_printf(p->out, "%s", zSep1);
3154    print_box_line(p->out, p->actualWidth[0]+2);
3155    for(i=1; i<nArg; i++){
3156      utf8_printf(p->out, "%s", zSep2);
3157      print_box_line(p->out, p->actualWidth[i]+2);
3158    }
3159    utf8_printf(p->out, "%s", zSep3);
3160  }
3161  fputs("\n", p->out);
3162}
3163
3164
3165
3166/*
3167** Run a prepared statement and output the result in one of the
3168** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3169** or MODE_Box.
3170**
3171** This is different from ordinary exec_prepared_stmt() in that
3172** it has to run the entire query and gather the results into memory
3173** first, in order to determine column widths, before providing
3174** any output.
3175*/
3176static void exec_prepared_stmt_columnar(
3177  ShellState *p,                        /* Pointer to ShellState */
3178  sqlite3_stmt *pStmt                   /* Statment to run */
3179){
3180  sqlite3_int64 nRow = 0;
3181  int nColumn = 0;
3182  char **azData = 0;
3183  sqlite3_int64 nAlloc = 0;
3184  const char *z;
3185  int rc;
3186  sqlite3_int64 i, nData;
3187  int j, nTotal, w, n;
3188  const char *colSep = 0;
3189  const char *rowSep = 0;
3190
3191  rc = sqlite3_step(pStmt);
3192  if( rc!=SQLITE_ROW ) return;
3193  nColumn = sqlite3_column_count(pStmt);
3194  nAlloc = nColumn*4;
3195  if( nAlloc<=0 ) nAlloc = 1;
3196  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3197  shell_check_oom(azData);
3198  for(i=0; i<nColumn; i++){
3199    azData[i] = strdup(sqlite3_column_name(pStmt,i));
3200  }
3201  do{
3202    if( (nRow+2)*nColumn >= nAlloc ){
3203      nAlloc *= 2;
3204      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3205      shell_check_oom(azData);
3206    }
3207    nRow++;
3208    for(i=0; i<nColumn; i++){
3209      z = (const char*)sqlite3_column_text(pStmt,i);
3210      azData[nRow*nColumn + i] = z ? strdup(z) : 0;
3211    }
3212  }while( sqlite3_step(pStmt)==SQLITE_ROW );
3213  if( nColumn>p->nWidth ){
3214    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3215    shell_check_oom(p->colWidth);
3216    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3217    p->nWidth = nColumn;
3218    p->actualWidth = &p->colWidth[nColumn];
3219  }
3220  memset(p->actualWidth, 0, nColumn*sizeof(int));
3221  for(i=0; i<nColumn; i++){
3222    w = p->colWidth[i];
3223    if( w<0 ) w = -w;
3224    p->actualWidth[i] = w;
3225  }
3226  nTotal = nColumn*(nRow+1);
3227  for(i=0; i<nTotal; i++){
3228    z = azData[i];
3229    if( z==0 ) z = p->nullValue;
3230    n = strlenChar(z);
3231    j = i%nColumn;
3232    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3233  }
3234  if( seenInterrupt ) goto columnar_end;
3235  if( nColumn==0 ) goto columnar_end;
3236  switch( p->cMode ){
3237    case MODE_Column: {
3238      colSep = "  ";
3239      rowSep = "\n";
3240      if( p->showHeader ){
3241        for(i=0; i<nColumn; i++){
3242          w = p->actualWidth[i];
3243          if( p->colWidth[i]<0 ) w = -w;
3244          utf8_width_print(p->out, w, azData[i]);
3245          fputs(i==nColumn-1?"\n":"  ", p->out);
3246        }
3247        for(i=0; i<nColumn; i++){
3248          print_dashes(p->out, p->actualWidth[i]);
3249          fputs(i==nColumn-1?"\n":"  ", p->out);
3250        }
3251      }
3252      break;
3253    }
3254    case MODE_Table: {
3255      colSep = " | ";
3256      rowSep = " |\n";
3257      print_row_separator(p, nColumn, "+");
3258      fputs("| ", p->out);
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", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3263        fputs(i==nColumn-1?" |\n":" | ", p->out);
3264      }
3265      print_row_separator(p, nColumn, "+");
3266      break;
3267    }
3268    case MODE_Markdown: {
3269      colSep = " | ";
3270      rowSep = " |\n";
3271      fputs("| ", p->out);
3272      for(i=0; i<nColumn; i++){
3273        w = p->actualWidth[i];
3274        n = strlenChar(azData[i]);
3275        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3276        fputs(i==nColumn-1?" |\n":" | ", p->out);
3277      }
3278      print_row_separator(p, nColumn, "|");
3279      break;
3280    }
3281    case MODE_Box: {
3282      colSep = " " BOX_13 " ";
3283      rowSep = " " BOX_13 "\n";
3284      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3285      utf8_printf(p->out, BOX_13 " ");
3286      for(i=0; i<nColumn; i++){
3287        w = p->actualWidth[i];
3288        n = strlenChar(azData[i]);
3289        utf8_printf(p->out, "%*s%s%*s%s",
3290            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3291            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3292      }
3293      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3294      break;
3295    }
3296  }
3297  for(i=nColumn, j=0; i<nTotal; i++, j++){
3298    if( j==0 && p->cMode!=MODE_Column ){
3299      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3300    }
3301    z = azData[i];
3302    if( z==0 ) z = p->nullValue;
3303    w = p->actualWidth[j];
3304    if( p->colWidth[j]<0 ) w = -w;
3305    utf8_width_print(p->out, w, z);
3306    if( j==nColumn-1 ){
3307      utf8_printf(p->out, "%s", rowSep);
3308      j = -1;
3309      if( seenInterrupt ) goto columnar_end;
3310    }else{
3311      utf8_printf(p->out, "%s", colSep);
3312    }
3313  }
3314  if( p->cMode==MODE_Table ){
3315    print_row_separator(p, nColumn, "+");
3316  }else if( p->cMode==MODE_Box ){
3317    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3318  }
3319columnar_end:
3320  if( seenInterrupt ){
3321    utf8_printf(p->out, "Interrupt\n");
3322  }
3323  nData = (nRow+1)*nColumn;
3324  for(i=0; i<nData; i++) free(azData[i]);
3325  sqlite3_free(azData);
3326}
3327
3328/*
3329** Run a prepared statement
3330*/
3331static void exec_prepared_stmt(
3332  ShellState *pArg,                                /* Pointer to ShellState */
3333  sqlite3_stmt *pStmt                              /* Statment to run */
3334){
3335  int rc;
3336  sqlite3_uint64 nRow = 0;
3337
3338  if( pArg->cMode==MODE_Column
3339   || pArg->cMode==MODE_Table
3340   || pArg->cMode==MODE_Box
3341   || pArg->cMode==MODE_Markdown
3342  ){
3343    exec_prepared_stmt_columnar(pArg, pStmt);
3344    return;
3345  }
3346
3347  /* perform the first step.  this will tell us if we
3348  ** have a result set or not and how wide it is.
3349  */
3350  rc = sqlite3_step(pStmt);
3351  /* if we have a result set... */
3352  if( SQLITE_ROW == rc ){
3353    /* allocate space for col name ptr, value ptr, and type */
3354    int nCol = sqlite3_column_count(pStmt);
3355    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3356    if( !pData ){
3357      shell_out_of_memory();
3358    }else{
3359      char **azCols = (char **)pData;      /* Names of result columns */
3360      char **azVals = &azCols[nCol];       /* Results */
3361      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3362      int i, x;
3363      assert(sizeof(int) <= sizeof(char *));
3364      /* save off ptrs to column names */
3365      for(i=0; i<nCol; i++){
3366        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3367      }
3368      do{
3369        nRow++;
3370        /* extract the data and data types */
3371        for(i=0; i<nCol; i++){
3372          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3373          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3374            azVals[i] = "";
3375          }else{
3376            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3377          }
3378          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3379            rc = SQLITE_NOMEM;
3380            break; /* from for */
3381          }
3382        } /* end for */
3383
3384        /* if data and types extracted successfully... */
3385        if( SQLITE_ROW == rc ){
3386          /* call the supplied callback with the result row data */
3387          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3388            rc = SQLITE_ABORT;
3389          }else{
3390            rc = sqlite3_step(pStmt);
3391          }
3392        }
3393      } while( SQLITE_ROW == rc );
3394      sqlite3_free(pData);
3395      if( pArg->cMode==MODE_Json ){
3396        fputs("]\n", pArg->out);
3397      }else if( pArg->cMode==MODE_Count ){
3398        printf("%llu row%s\n", nRow, nRow!=1 ? "s" : "");
3399      }
3400    }
3401  }
3402}
3403
3404#ifndef SQLITE_OMIT_VIRTUALTABLE
3405/*
3406** This function is called to process SQL if the previous shell command
3407** was ".expert". It passes the SQL in the second argument directly to
3408** the sqlite3expert object.
3409**
3410** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3411** code. In this case, (*pzErr) may be set to point to a buffer containing
3412** an English language error message. It is the responsibility of the
3413** caller to eventually free this buffer using sqlite3_free().
3414*/
3415static int expertHandleSQL(
3416  ShellState *pState,
3417  const char *zSql,
3418  char **pzErr
3419){
3420  assert( pState->expert.pExpert );
3421  assert( pzErr==0 || *pzErr==0 );
3422  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3423}
3424
3425/*
3426** This function is called either to silently clean up the object
3427** created by the ".expert" command (if bCancel==1), or to generate a
3428** report from it and then clean it up (if bCancel==0).
3429**
3430** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3431** code. In this case, (*pzErr) may be set to point to a buffer containing
3432** an English language error message. It is the responsibility of the
3433** caller to eventually free this buffer using sqlite3_free().
3434*/
3435static int expertFinish(
3436  ShellState *pState,
3437  int bCancel,
3438  char **pzErr
3439){
3440  int rc = SQLITE_OK;
3441  sqlite3expert *p = pState->expert.pExpert;
3442  assert( p );
3443  assert( bCancel || pzErr==0 || *pzErr==0 );
3444  if( bCancel==0 ){
3445    FILE *out = pState->out;
3446    int bVerbose = pState->expert.bVerbose;
3447
3448    rc = sqlite3_expert_analyze(p, pzErr);
3449    if( rc==SQLITE_OK ){
3450      int nQuery = sqlite3_expert_count(p);
3451      int i;
3452
3453      if( bVerbose ){
3454        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3455        raw_printf(out, "-- Candidates -----------------------------\n");
3456        raw_printf(out, "%s\n", zCand);
3457      }
3458      for(i=0; i<nQuery; i++){
3459        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3460        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3461        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3462        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3463        if( bVerbose ){
3464          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3465          raw_printf(out, "%s\n\n", zSql);
3466        }
3467        raw_printf(out, "%s\n", zIdx);
3468        raw_printf(out, "%s\n", zEQP);
3469      }
3470    }
3471  }
3472  sqlite3_expert_destroy(p);
3473  pState->expert.pExpert = 0;
3474  return rc;
3475}
3476
3477/*
3478** Implementation of ".expert" dot command.
3479*/
3480static int expertDotCommand(
3481  ShellState *pState,             /* Current shell tool state */
3482  char **azArg,                   /* Array of arguments passed to dot command */
3483  int nArg                        /* Number of entries in azArg[] */
3484){
3485  int rc = SQLITE_OK;
3486  char *zErr = 0;
3487  int i;
3488  int iSample = 0;
3489
3490  assert( pState->expert.pExpert==0 );
3491  memset(&pState->expert, 0, sizeof(ExpertInfo));
3492
3493  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3494    char *z = azArg[i];
3495    int n;
3496    if( z[0]=='-' && z[1]=='-' ) z++;
3497    n = strlen30(z);
3498    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3499      pState->expert.bVerbose = 1;
3500    }
3501    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3502      if( i==(nArg-1) ){
3503        raw_printf(stderr, "option requires an argument: %s\n", z);
3504        rc = SQLITE_ERROR;
3505      }else{
3506        iSample = (int)integerValue(azArg[++i]);
3507        if( iSample<0 || iSample>100 ){
3508          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3509          rc = SQLITE_ERROR;
3510        }
3511      }
3512    }
3513    else{
3514      raw_printf(stderr, "unknown option: %s\n", z);
3515      rc = SQLITE_ERROR;
3516    }
3517  }
3518
3519  if( rc==SQLITE_OK ){
3520    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3521    if( pState->expert.pExpert==0 ){
3522      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3523      rc = SQLITE_ERROR;
3524    }else{
3525      sqlite3_expert_config(
3526          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3527      );
3528    }
3529  }
3530  sqlite3_free(zErr);
3531
3532  return rc;
3533}
3534#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3535
3536/*
3537** Execute a statement or set of statements.  Print
3538** any result rows/columns depending on the current mode
3539** set via the supplied callback.
3540**
3541** This is very similar to SQLite's built-in sqlite3_exec()
3542** function except it takes a slightly different callback
3543** and callback data argument.
3544*/
3545static int shell_exec(
3546  ShellState *pArg,                         /* Pointer to ShellState */
3547  const char *zSql,                         /* SQL to be evaluated */
3548  char **pzErrMsg                           /* Error msg written here */
3549){
3550  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3551  int rc = SQLITE_OK;             /* Return Code */
3552  int rc2;
3553  const char *zLeftover;          /* Tail of unprocessed SQL */
3554  sqlite3 *db = pArg->db;
3555
3556  if( pzErrMsg ){
3557    *pzErrMsg = NULL;
3558  }
3559
3560#ifndef SQLITE_OMIT_VIRTUALTABLE
3561  if( pArg->expert.pExpert ){
3562    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3563    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3564  }
3565#endif
3566
3567  while( zSql[0] && (SQLITE_OK == rc) ){
3568    static const char *zStmtSql;
3569    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3570    if( SQLITE_OK != rc ){
3571      if( pzErrMsg ){
3572        *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)", rc);
3573      }
3574    }else{
3575      if( !pStmt ){
3576        /* this happens for a comment or white-space */
3577        zSql = zLeftover;
3578        while( IsSpace(zSql[0]) ) zSql++;
3579        continue;
3580      }
3581      zStmtSql = sqlite3_sql(pStmt);
3582      if( zStmtSql==0 ) zStmtSql = "";
3583      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3584
3585      /* save off the prepared statment handle and reset row count */
3586      if( pArg ){
3587        pArg->pStmt = pStmt;
3588        pArg->cnt = 0;
3589      }
3590
3591      /* echo the sql statement if echo on */
3592      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3593        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3594      }
3595
3596      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3597      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3598        sqlite3_stmt *pExplain;
3599        char *zEQP;
3600        int triggerEQP = 0;
3601        disable_debug_trace_modes();
3602        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3603        if( pArg->autoEQP>=AUTOEQP_trigger ){
3604          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3605        }
3606        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3607        shell_check_oom(zEQP);
3608        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3609        if( rc==SQLITE_OK ){
3610          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3611            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3612            int iEqpId = sqlite3_column_int(pExplain, 0);
3613            int iParentId = sqlite3_column_int(pExplain, 1);
3614            if( zEQPLine==0 ) zEQPLine = "";
3615            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3616            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3617          }
3618          eqp_render(pArg);
3619        }
3620        sqlite3_finalize(pExplain);
3621        sqlite3_free(zEQP);
3622        if( pArg->autoEQP>=AUTOEQP_full ){
3623          /* Also do an EXPLAIN for ".eqp full" mode */
3624          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3625          shell_check_oom(zEQP);
3626          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3627          if( rc==SQLITE_OK ){
3628            pArg->cMode = MODE_Explain;
3629            explain_data_prepare(pArg, pExplain);
3630            exec_prepared_stmt(pArg, pExplain);
3631            explain_data_delete(pArg);
3632          }
3633          sqlite3_finalize(pExplain);
3634          sqlite3_free(zEQP);
3635        }
3636        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3637          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3638          /* Reprepare pStmt before reactiving trace modes */
3639          sqlite3_finalize(pStmt);
3640          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3641          if( pArg ) pArg->pStmt = pStmt;
3642        }
3643        restore_debug_trace_modes();
3644      }
3645
3646      if( pArg ){
3647        pArg->cMode = pArg->mode;
3648        if( pArg->autoExplain ){
3649          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3650            pArg->cMode = MODE_Explain;
3651          }
3652          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3653            pArg->cMode = MODE_EQP;
3654          }
3655        }
3656
3657        /* If the shell is currently in ".explain" mode, gather the extra
3658        ** data required to add indents to the output.*/
3659        if( pArg->cMode==MODE_Explain ){
3660          explain_data_prepare(pArg, pStmt);
3661        }
3662      }
3663
3664      bind_prepared_stmt(pArg, pStmt);
3665      exec_prepared_stmt(pArg, pStmt);
3666      explain_data_delete(pArg);
3667      eqp_render(pArg);
3668
3669      /* print usage stats if stats on */
3670      if( pArg && pArg->statsOn ){
3671        display_stats(db, pArg, 0);
3672      }
3673
3674      /* print loop-counters if required */
3675      if( pArg && pArg->scanstatsOn ){
3676        display_scanstats(db, pArg);
3677      }
3678
3679      /* Finalize the statement just executed. If this fails, save a
3680      ** copy of the error message. Otherwise, set zSql to point to the
3681      ** next statement to execute. */
3682      rc2 = sqlite3_finalize(pStmt);
3683      if( rc!=SQLITE_NOMEM ) rc = rc2;
3684      if( rc==SQLITE_OK ){
3685        zSql = zLeftover;
3686        while( IsSpace(zSql[0]) ) zSql++;
3687      }else if( pzErrMsg ){
3688        *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc);
3689      }
3690
3691      /* clear saved stmt handle */
3692      if( pArg ){
3693        pArg->pStmt = NULL;
3694      }
3695    }
3696  } /* end while */
3697
3698  return rc;
3699}
3700
3701/*
3702** Release memory previously allocated by tableColumnList().
3703*/
3704static void freeColumnList(char **azCol){
3705  int i;
3706  for(i=1; azCol[i]; i++){
3707    sqlite3_free(azCol[i]);
3708  }
3709  /* azCol[0] is a static string */
3710  sqlite3_free(azCol);
3711}
3712
3713/*
3714** Return a list of pointers to strings which are the names of all
3715** columns in table zTab.   The memory to hold the names is dynamically
3716** allocated and must be released by the caller using a subsequent call
3717** to freeColumnList().
3718**
3719** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3720** value that needs to be preserved, then azCol[0] is filled in with the
3721** name of the rowid column.
3722**
3723** The first regular column in the table is azCol[1].  The list is terminated
3724** by an entry with azCol[i]==0.
3725*/
3726static char **tableColumnList(ShellState *p, const char *zTab){
3727  char **azCol = 0;
3728  sqlite3_stmt *pStmt;
3729  char *zSql;
3730  int nCol = 0;
3731  int nAlloc = 0;
3732  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3733  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3734  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3735  int rc;
3736
3737  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3738  shell_check_oom(zSql);
3739  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3740  sqlite3_free(zSql);
3741  if( rc ) return 0;
3742  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3743    if( nCol>=nAlloc-2 ){
3744      nAlloc = nAlloc*2 + nCol + 10;
3745      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3746      shell_check_oom(azCol);
3747    }
3748    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3749    shell_check_oom(azCol[nCol]);
3750    if( sqlite3_column_int(pStmt, 5) ){
3751      nPK++;
3752      if( nPK==1
3753       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3754                          "INTEGER")==0
3755      ){
3756        isIPK = 1;
3757      }else{
3758        isIPK = 0;
3759      }
3760    }
3761  }
3762  sqlite3_finalize(pStmt);
3763  if( azCol==0 ) return 0;
3764  azCol[0] = 0;
3765  azCol[nCol+1] = 0;
3766
3767  /* The decision of whether or not a rowid really needs to be preserved
3768  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3769  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3770  ** rowids on tables where the rowid is inaccessible because there are other
3771  ** columns in the table named "rowid", "_rowid_", and "oid".
3772  */
3773  if( preserveRowid && isIPK ){
3774    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3775    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3776    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3777    ** ROWID aliases.  To distinguish these cases, check to see if
3778    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3779    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3780    */
3781    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3782                           " WHERE origin='pk'", zTab);
3783    shell_check_oom(zSql);
3784    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3785    sqlite3_free(zSql);
3786    if( rc ){
3787      freeColumnList(azCol);
3788      return 0;
3789    }
3790    rc = sqlite3_step(pStmt);
3791    sqlite3_finalize(pStmt);
3792    preserveRowid = rc==SQLITE_ROW;
3793  }
3794  if( preserveRowid ){
3795    /* Only preserve the rowid if we can find a name to use for the
3796    ** rowid */
3797    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3798    int i, j;
3799    for(j=0; j<3; j++){
3800      for(i=1; i<=nCol; i++){
3801        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3802      }
3803      if( i>nCol ){
3804        /* At this point, we know that azRowid[j] is not the name of any
3805        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3806        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3807        ** tables will fail this last check */
3808        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3809        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3810        break;
3811      }
3812    }
3813  }
3814  return azCol;
3815}
3816
3817/*
3818** Toggle the reverse_unordered_selects setting.
3819*/
3820static void toggleSelectOrder(sqlite3 *db){
3821  sqlite3_stmt *pStmt = 0;
3822  int iSetting = 0;
3823  char zStmt[100];
3824  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3825  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3826    iSetting = sqlite3_column_int(pStmt, 0);
3827  }
3828  sqlite3_finalize(pStmt);
3829  sqlite3_snprintf(sizeof(zStmt), zStmt,
3830       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3831  sqlite3_exec(db, zStmt, 0, 0, 0);
3832}
3833
3834/*
3835** This is a different callback routine used for dumping the database.
3836** Each row received by this callback consists of a table name,
3837** the table type ("index" or "table") and SQL to create the table.
3838** This routine should print text sufficient to recreate the table.
3839*/
3840static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3841  int rc;
3842  const char *zTable;
3843  const char *zType;
3844  const char *zSql;
3845  ShellState *p = (ShellState *)pArg;
3846  int dataOnly;
3847  int noSys;
3848
3849  UNUSED_PARAMETER(azNotUsed);
3850  if( nArg!=3 || azArg==0 ) return 0;
3851  zTable = azArg[0];
3852  zType = azArg[1];
3853  zSql = azArg[2];
3854  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
3855  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
3856
3857  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
3858    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3859  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
3860    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3861  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3862    return 0;
3863  }else if( dataOnly ){
3864    /* no-op */
3865  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3866    char *zIns;
3867    if( !p->writableSchema ){
3868      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3869      p->writableSchema = 1;
3870    }
3871    zIns = sqlite3_mprintf(
3872       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3873       "VALUES('table','%q','%q',0,'%q');",
3874       zTable, zTable, zSql);
3875    shell_check_oom(zIns);
3876    utf8_printf(p->out, "%s\n", zIns);
3877    sqlite3_free(zIns);
3878    return 0;
3879  }else{
3880    printSchemaLine(p->out, zSql, ";\n");
3881  }
3882
3883  if( strcmp(zType, "table")==0 ){
3884    ShellText sSelect;
3885    ShellText sTable;
3886    char **azCol;
3887    int i;
3888    char *savedDestTable;
3889    int savedMode;
3890
3891    azCol = tableColumnList(p, zTable);
3892    if( azCol==0 ){
3893      p->nErr++;
3894      return 0;
3895    }
3896
3897    /* Always quote the table name, even if it appears to be pure ascii,
3898    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3899    initText(&sTable);
3900    appendText(&sTable, zTable, quoteChar(zTable));
3901    /* If preserving the rowid, add a column list after the table name.
3902    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3903    ** instead of the usual "INSERT INTO tab VALUES(...)".
3904    */
3905    if( azCol[0] ){
3906      appendText(&sTable, "(", 0);
3907      appendText(&sTable, azCol[0], 0);
3908      for(i=1; azCol[i]; i++){
3909        appendText(&sTable, ",", 0);
3910        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3911      }
3912      appendText(&sTable, ")", 0);
3913    }
3914
3915    /* Build an appropriate SELECT statement */
3916    initText(&sSelect);
3917    appendText(&sSelect, "SELECT ", 0);
3918    if( azCol[0] ){
3919      appendText(&sSelect, azCol[0], 0);
3920      appendText(&sSelect, ",", 0);
3921    }
3922    for(i=1; azCol[i]; i++){
3923      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3924      if( azCol[i+1] ){
3925        appendText(&sSelect, ",", 0);
3926      }
3927    }
3928    freeColumnList(azCol);
3929    appendText(&sSelect, " FROM ", 0);
3930    appendText(&sSelect, zTable, quoteChar(zTable));
3931
3932    savedDestTable = p->zDestTable;
3933    savedMode = p->mode;
3934    p->zDestTable = sTable.z;
3935    p->mode = p->cMode = MODE_Insert;
3936    rc = shell_exec(p, sSelect.z, 0);
3937    if( (rc&0xff)==SQLITE_CORRUPT ){
3938      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3939      toggleSelectOrder(p->db);
3940      shell_exec(p, sSelect.z, 0);
3941      toggleSelectOrder(p->db);
3942    }
3943    p->zDestTable = savedDestTable;
3944    p->mode = savedMode;
3945    freeText(&sTable);
3946    freeText(&sSelect);
3947    if( rc ) p->nErr++;
3948  }
3949  return 0;
3950}
3951
3952/*
3953** Run zQuery.  Use dump_callback() as the callback routine so that
3954** the contents of the query are output as SQL statements.
3955**
3956** If we get a SQLITE_CORRUPT error, rerun the query after appending
3957** "ORDER BY rowid DESC" to the end.
3958*/
3959static int run_schema_dump_query(
3960  ShellState *p,
3961  const char *zQuery
3962){
3963  int rc;
3964  char *zErr = 0;
3965  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3966  if( rc==SQLITE_CORRUPT ){
3967    char *zQ2;
3968    int len = strlen30(zQuery);
3969    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3970    if( zErr ){
3971      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3972      sqlite3_free(zErr);
3973      zErr = 0;
3974    }
3975    zQ2 = malloc( len+100 );
3976    if( zQ2==0 ) return rc;
3977    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3978    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3979    if( rc ){
3980      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3981    }else{
3982      rc = SQLITE_CORRUPT;
3983    }
3984    sqlite3_free(zErr);
3985    free(zQ2);
3986  }
3987  return rc;
3988}
3989
3990/*
3991** Text of help messages.
3992**
3993** The help text for each individual command begins with a line that starts
3994** with ".".  Subsequent lines are supplimental information.
3995**
3996** There must be two or more spaces between the end of the command and the
3997** start of the description of what that command does.
3998*/
3999static const char *(azHelp[]) = {
4000#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
4001  ".archive ...             Manage SQL archives",
4002  "   Each command must have exactly one of the following options:",
4003  "     -c, --create               Create a new archive",
4004  "     -u, --update               Add or update files with changed mtime",
4005  "     -i, --insert               Like -u but always add even if unchanged",
4006  "     -r, --remove               Remove files from archive",
4007  "     -t, --list                 List contents of archive",
4008  "     -x, --extract              Extract files from archive",
4009  "   Optional arguments:",
4010  "     -v, --verbose              Print each filename as it is processed",
4011  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4012  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4013  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4014  "     -g, --glob                 Use glob matching for names in archive",
4015  "     -n, --dryrun               Show the SQL that would have occurred",
4016  "   Examples:",
4017  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4018  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4019  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4020  "   See also:",
4021  "      http://sqlite.org/cli.html#sqlite_archive_support",
4022#endif
4023#ifndef SQLITE_OMIT_AUTHORIZATION
4024  ".auth ON|OFF             Show authorizer callbacks",
4025#endif
4026  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4027  "       --append            Use the appendvfs",
4028  "       --async             Write to FILE without journal and fsync()",
4029  ".bail on|off             Stop after hitting an error.  Default OFF",
4030  ".binary on|off           Turn binary output on or off.  Default OFF",
4031  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4032  ".changes on|off          Show number of rows changed by SQL",
4033  ".check GLOB              Fail if output since .testcase does not match",
4034  ".clone NEWDB             Clone data into NEWDB from the existing database",
4035  ".connection [close] [#]  Open or close an auxiliary database connection",
4036  ".databases               List names and files of attached databases",
4037  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4038  ".dbinfo ?DB?             Show status information about the database",
4039  ".dump ?OBJECTS?          Render database content as SQL",
4040  "   Options:",
4041  "     --data-only            Output only INSERT statements",
4042  "     --newlines             Allow unescaped newline characters in output",
4043  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4044  "     --preserve-rowids      Include ROWID values in the output",
4045  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4046  "   Additional LIKE patterns can be given in subsequent arguments",
4047  ".echo on|off             Turn command echo on or off",
4048  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4049  "   Other Modes:",
4050#ifdef SQLITE_DEBUG
4051  "      test                  Show raw EXPLAIN QUERY PLAN output",
4052  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4053#endif
4054  "      trigger               Like \"full\" but also show trigger bytecode",
4055  ".excel                   Display the output of next command in spreadsheet",
4056  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4057  ".exit ?CODE?             Exit this program with return-code CODE",
4058  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4059  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4060  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4061  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4062  "   --help                  Show CMD details",
4063  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4064  ".headers on|off          Turn display of headers on or off",
4065  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4066  ".import FILE TABLE       Import data from FILE into TABLE",
4067  "   Options:",
4068  "     --ascii               Use \\037 and \\036 as column and row separators",
4069  "     --csv                 Use , and \\n as column and row separators",
4070  "     --skip N              Skip the first N rows of input",
4071  "     -v                    \"Verbose\" - increase auxiliary output",
4072  "   Notes:",
4073  "     *  If TABLE does not exist, it is created.  The first row of input",
4074  "        determines the column names.",
4075  "     *  If neither --csv or --ascii are used, the input mode is derived",
4076  "        from the \".mode\" output mode",
4077  "     *  If FILE begins with \"|\" then it is a command that generates the",
4078  "        input text.",
4079#ifndef SQLITE_OMIT_TEST_CONTROL
4080  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4081#endif
4082  ".indexes ?TABLE?         Show names of indexes",
4083  "                           If TABLE is specified, only show indexes for",
4084  "                           tables matching TABLE using the LIKE operator.",
4085#ifdef SQLITE_ENABLE_IOTRACE
4086  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4087#endif
4088  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4089  ".lint OPTIONS            Report potential schema issues.",
4090  "     Options:",
4091  "        fkey-indexes     Find missing foreign key indexes",
4092#ifndef SQLITE_OMIT_LOAD_EXTENSION
4093  ".load FILE ?ENTRY?       Load an extension library",
4094#endif
4095  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4096  ".mode MODE ?TABLE?       Set output mode",
4097  "   MODE is one of:",
4098  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
4099  "     box       Tables using unicode box-drawing characters",
4100  "     csv       Comma-separated values",
4101  "     column    Output in columns.  (See .width)",
4102  "     html      HTML <table> code",
4103  "     insert    SQL insert statements for TABLE",
4104  "     json      Results in a JSON array",
4105  "     line      One value per line",
4106  "     list      Values delimited by \"|\"",
4107  "     markdown  Markdown table format",
4108  "     quote     Escape answers as for SQL",
4109  "     table     ASCII-art table",
4110  "     tabs      Tab-separated values",
4111  "     tcl       TCL list elements",
4112  ".nonce STRING            Disable safe mode for one command if the nonce matches",
4113  ".nullvalue STRING        Use STRING in place of NULL values",
4114  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4115  "     If FILE begins with '|' then open as a pipe",
4116  "       --bom  Put a UTF8 byte-order mark at the beginning",
4117  "       -e     Send output to the system text editor",
4118  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4119#ifdef SQLITE_DEBUG
4120  ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
4121#endif
4122  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4123  "     Options:",
4124  "        --append        Use appendvfs to append database to the end of FILE",
4125#ifndef SQLITE_OMIT_DESERIALIZE
4126  "        --deserialize   Load into memory using sqlite3_deserialize()",
4127  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4128  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4129#endif
4130  "        --new           Initialize FILE to an empty database",
4131  "        --nofollow      Do not follow symbolic links",
4132  "        --readonly      Open FILE readonly",
4133  "        --zip           FILE is a ZIP archive",
4134  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4135  "   If FILE begins with '|' then open it as a pipe.",
4136  "   Options:",
4137  "     --bom                 Prefix output with a UTF8 byte-order mark",
4138  "     -e                    Send output to the system text editor",
4139  "     -x                    Send output as CSV to a spreadsheet",
4140  ".parameter CMD ...       Manage SQL parameter bindings",
4141  "   clear                   Erase all bindings",
4142  "   init                    Initialize the TEMP table that holds bindings",
4143  "   list                    List the current parameter bindings",
4144  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4145  "                           PARAMETER should start with one of: $ : @ ?",
4146  "   unset PARAMETER         Remove PARAMETER from the binding table",
4147  ".print STRING...         Print literal STRING",
4148#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4149  ".progress N              Invoke progress handler after every N opcodes",
4150  "   --limit N                 Interrupt after N progress callbacks",
4151  "   --once                    Do no more than one progress interrupt",
4152  "   --quiet|-q                No output except at interrupts",
4153  "   --reset                   Reset the count for each input and interrupt",
4154#endif
4155  ".prompt MAIN CONTINUE    Replace the standard prompts",
4156  ".quit                    Exit this program",
4157  ".read FILE               Read input from FILE",
4158#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4159  ".recover                 Recover as much data as possible from corrupt db.",
4160  "   --freelist-corrupt       Assume the freelist is corrupt",
4161  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4162  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4163  "   --no-rowids              Do not attempt to recover rowid values",
4164  "                            that are not also INTEGER PRIMARY KEYs",
4165#endif
4166  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4167  ".save FILE               Write in-memory database into FILE",
4168  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4169  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4170  "   Options:",
4171  "      --indent             Try to pretty-print the schema",
4172  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4173  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4174  "    Options:",
4175  "       --init               Create a new SELFTEST table",
4176  "       -v                   Verbose output",
4177  ".separator COL ?ROW?     Change the column and row separators",
4178#if defined(SQLITE_ENABLE_SESSION)
4179  ".session ?NAME? CMD ...  Create or control sessions",
4180  "   Subcommands:",
4181  "     attach TABLE             Attach TABLE",
4182  "     changeset FILE           Write a changeset into FILE",
4183  "     close                    Close one session",
4184  "     enable ?BOOLEAN?         Set or query the enable bit",
4185  "     filter GLOB...           Reject tables matching GLOBs",
4186  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4187  "     isempty                  Query whether the session is empty",
4188  "     list                     List currently open session names",
4189  "     open DB NAME             Open a new session on DB",
4190  "     patchset FILE            Write a patchset into FILE",
4191  "   If ?NAME? is omitted, the first defined session is used.",
4192#endif
4193  ".sha3sum ...             Compute a SHA3 hash of database content",
4194  "    Options:",
4195  "      --schema              Also hash the sqlite_schema table",
4196  "      --sha3-224            Use the sha3-224 algorithm",
4197  "      --sha3-256            Use the sha3-256 algorithm (default)",
4198  "      --sha3-384            Use the sha3-384 algorithm",
4199  "      --sha3-512            Use the sha3-512 algorithm",
4200  "    Any other argument is a LIKE pattern for tables to hash",
4201#ifndef SQLITE_NOHAVE_SYSTEM
4202  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4203#endif
4204  ".show                    Show the current values for various settings",
4205  ".stats ?ARG?             Show stats or turn stats on or off",
4206  "   off                      Turn off automatic stat display",
4207  "   on                       Turn on automatic stat display",
4208  "   stmt                     Show statement stats",
4209  "   vmstep                   Show the virtual machine step count only",
4210#ifndef SQLITE_NOHAVE_SYSTEM
4211  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4212#endif
4213  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4214  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4215  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4216  "                           Run \".testctrl\" with no arguments for details",
4217  ".timeout MS              Try opening locked tables for MS milliseconds",
4218  ".timer on|off            Turn SQL timer on or off",
4219#ifndef SQLITE_OMIT_TRACE
4220  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4221  "    FILE                    Send output to FILE",
4222  "    stdout                  Send output to stdout",
4223  "    stderr                  Send output to stderr",
4224  "    off                     Disable tracing",
4225  "    --expanded              Expand query parameters",
4226#ifdef SQLITE_ENABLE_NORMALIZE
4227  "    --normalized            Normal the SQL statements",
4228#endif
4229  "    --plain                 Show SQL as it is input",
4230  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4231  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4232  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4233  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4234#endif /* SQLITE_OMIT_TRACE */
4235#ifdef SQLITE_DEBUG
4236  ".unmodule NAME ...       Unregister virtual table modules",
4237  "    --allexcept             Unregister everything except those named",
4238#endif
4239  ".vfsinfo ?AUX?           Information about the top-level VFS",
4240  ".vfslist                 List all available VFSes",
4241  ".vfsname ?AUX?           Print the name of the VFS stack",
4242  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4243  "     Negative values right-justify",
4244};
4245
4246/*
4247** Output help text.
4248**
4249** zPattern describes the set of commands for which help text is provided.
4250** If zPattern is NULL, then show all commands, but only give a one-line
4251** description of each.
4252**
4253** Return the number of matches.
4254*/
4255static int showHelp(FILE *out, const char *zPattern){
4256  int i = 0;
4257  int j = 0;
4258  int n = 0;
4259  char *zPat;
4260  if( zPattern==0
4261   || zPattern[0]=='0'
4262   || strcmp(zPattern,"-a")==0
4263   || strcmp(zPattern,"-all")==0
4264   || strcmp(zPattern,"--all")==0
4265  ){
4266    /* Show all commands, but only one line per command */
4267    if( zPattern==0 ) zPattern = "";
4268    for(i=0; i<ArraySize(azHelp); i++){
4269      if( azHelp[i][0]=='.' || zPattern[0] ){
4270        utf8_printf(out, "%s\n", azHelp[i]);
4271        n++;
4272      }
4273    }
4274  }else{
4275    /* Look for commands that for which zPattern is an exact prefix */
4276    zPat = sqlite3_mprintf(".%s*", zPattern);
4277    shell_check_oom(zPat);
4278    for(i=0; i<ArraySize(azHelp); i++){
4279      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4280        utf8_printf(out, "%s\n", azHelp[i]);
4281        j = i+1;
4282        n++;
4283      }
4284    }
4285    sqlite3_free(zPat);
4286    if( n ){
4287      if( n==1 ){
4288        /* when zPattern is a prefix of exactly one command, then include the
4289        ** details of that command, which should begin at offset j */
4290        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4291          utf8_printf(out, "%s\n", azHelp[j]);
4292          j++;
4293        }
4294      }
4295      return n;
4296    }
4297    /* Look for commands that contain zPattern anywhere.  Show the complete
4298    ** text of all commands that match. */
4299    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4300    shell_check_oom(zPat);
4301    for(i=0; i<ArraySize(azHelp); i++){
4302      if( azHelp[i][0]=='.' ) j = i;
4303      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4304        utf8_printf(out, "%s\n", azHelp[j]);
4305        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4306          j++;
4307          utf8_printf(out, "%s\n", azHelp[j]);
4308        }
4309        i = j;
4310        n++;
4311      }
4312    }
4313    sqlite3_free(zPat);
4314  }
4315  return n;
4316}
4317
4318/* Forward reference */
4319static int process_input(ShellState *p);
4320
4321/*
4322** Read the content of file zName into memory obtained from sqlite3_malloc64()
4323** and return a pointer to the buffer. The caller is responsible for freeing
4324** the memory.
4325**
4326** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4327** read.
4328**
4329** For convenience, a nul-terminator byte is always appended to the data read
4330** from the file before the buffer is returned. This byte is not included in
4331** the final value of (*pnByte), if applicable.
4332**
4333** NULL is returned if any error is encountered. The final value of *pnByte
4334** is undefined in this case.
4335*/
4336static char *readFile(const char *zName, int *pnByte){
4337  FILE *in = fopen(zName, "rb");
4338  long nIn;
4339  size_t nRead;
4340  char *pBuf;
4341  if( in==0 ) return 0;
4342  fseek(in, 0, SEEK_END);
4343  nIn = ftell(in);
4344  rewind(in);
4345  pBuf = sqlite3_malloc64( nIn+1 );
4346  if( pBuf==0 ){ fclose(in); return 0; }
4347  nRead = fread(pBuf, nIn, 1, in);
4348  fclose(in);
4349  if( nRead!=1 ){
4350    sqlite3_free(pBuf);
4351    return 0;
4352  }
4353  pBuf[nIn] = 0;
4354  if( pnByte ) *pnByte = nIn;
4355  return pBuf;
4356}
4357
4358#if defined(SQLITE_ENABLE_SESSION)
4359/*
4360** Close a single OpenSession object and release all of its associated
4361** resources.
4362*/
4363static void session_close(OpenSession *pSession){
4364  int i;
4365  sqlite3session_delete(pSession->p);
4366  sqlite3_free(pSession->zName);
4367  for(i=0; i<pSession->nFilter; i++){
4368    sqlite3_free(pSession->azFilter[i]);
4369  }
4370  sqlite3_free(pSession->azFilter);
4371  memset(pSession, 0, sizeof(OpenSession));
4372}
4373#endif
4374
4375/*
4376** Close all OpenSession objects and release all associated resources.
4377*/
4378#if defined(SQLITE_ENABLE_SESSION)
4379static void session_close_all(ShellState *p, int i){
4380  int j;
4381  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4382  for(j=0; j<pAuxDb->nSession; j++){
4383    session_close(&pAuxDb->aSession[j]);
4384  }
4385  pAuxDb->nSession = 0;
4386}
4387#else
4388# define session_close_all(X,Y)
4389#endif
4390
4391/*
4392** Implementation of the xFilter function for an open session.  Omit
4393** any tables named by ".session filter" but let all other table through.
4394*/
4395#if defined(SQLITE_ENABLE_SESSION)
4396static int session_filter(void *pCtx, const char *zTab){
4397  OpenSession *pSession = (OpenSession*)pCtx;
4398  int i;
4399  for(i=0; i<pSession->nFilter; i++){
4400    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4401  }
4402  return 1;
4403}
4404#endif
4405
4406/*
4407** Try to deduce the type of file for zName based on its content.  Return
4408** one of the SHELL_OPEN_* constants.
4409**
4410** If the file does not exist or is empty but its name looks like a ZIP
4411** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4412** Otherwise, assume an ordinary database regardless of the filename if
4413** the type cannot be determined from content.
4414*/
4415int deduceDatabaseType(const char *zName, int dfltZip){
4416  FILE *f = fopen(zName, "rb");
4417  size_t n;
4418  int rc = SHELL_OPEN_UNSPEC;
4419  char zBuf[100];
4420  if( f==0 ){
4421    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4422       return SHELL_OPEN_ZIPFILE;
4423    }else{
4424       return SHELL_OPEN_NORMAL;
4425    }
4426  }
4427  n = fread(zBuf, 16, 1, f);
4428  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4429    fclose(f);
4430    return SHELL_OPEN_NORMAL;
4431  }
4432  fseek(f, -25, SEEK_END);
4433  n = fread(zBuf, 25, 1, f);
4434  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4435    rc = SHELL_OPEN_APPENDVFS;
4436  }else{
4437    fseek(f, -22, SEEK_END);
4438    n = fread(zBuf, 22, 1, f);
4439    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4440       && zBuf[3]==0x06 ){
4441      rc = SHELL_OPEN_ZIPFILE;
4442    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4443      rc = SHELL_OPEN_ZIPFILE;
4444    }
4445  }
4446  fclose(f);
4447  return rc;
4448}
4449
4450#ifndef SQLITE_OMIT_DESERIALIZE
4451/*
4452** Reconstruct an in-memory database using the output from the "dbtotxt"
4453** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4454** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4455*/
4456static unsigned char *readHexDb(ShellState *p, int *pnData){
4457  unsigned char *a = 0;
4458  int nLine;
4459  int n = 0;
4460  int pgsz = 0;
4461  int iOffset = 0;
4462  int j, k;
4463  int rc;
4464  FILE *in;
4465  const char *zDbFilename = p->pAuxDb->zDbFilename;
4466  unsigned int x[16];
4467  char zLine[1000];
4468  if( zDbFilename ){
4469    in = fopen(zDbFilename, "r");
4470    if( in==0 ){
4471      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4472      return 0;
4473    }
4474    nLine = 0;
4475  }else{
4476    in = p->in;
4477    nLine = p->lineno;
4478    if( in==0 ) in = stdin;
4479  }
4480  *pnData = 0;
4481  nLine++;
4482  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4483  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4484  if( rc!=2 ) goto readHexDb_error;
4485  if( n<0 ) goto readHexDb_error;
4486  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4487  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4488  a = sqlite3_malloc( n ? n : 1 );
4489  shell_check_oom(a);
4490  memset(a, 0, n);
4491  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4492    utf8_printf(stderr, "invalid pagesize\n");
4493    goto readHexDb_error;
4494  }
4495  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4496    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4497    if( rc==2 ){
4498      iOffset = k;
4499      continue;
4500    }
4501    if( strncmp(zLine, "| end ", 6)==0 ){
4502      break;
4503    }
4504    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4505                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4506                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4507    if( rc==17 ){
4508      k = iOffset+j;
4509      if( k+16<=n && k>=0 ){
4510        int ii;
4511        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4512      }
4513    }
4514  }
4515  *pnData = n;
4516  if( in!=p->in ){
4517    fclose(in);
4518  }else{
4519    p->lineno = nLine;
4520  }
4521  return a;
4522
4523readHexDb_error:
4524  if( in!=p->in ){
4525    fclose(in);
4526  }else{
4527    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4528      nLine++;
4529      if(strncmp(zLine, "| end ", 6)==0 ) break;
4530    }
4531    p->lineno = nLine;
4532  }
4533  sqlite3_free(a);
4534  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4535  return 0;
4536}
4537#endif /* SQLITE_OMIT_DESERIALIZE */
4538
4539/*
4540** Scalar function "shell_int32". The first argument to this function
4541** must be a blob. The second a non-negative integer. This function
4542** reads and returns a 32-bit big-endian integer from byte
4543** offset (4*<arg2>) of the blob.
4544*/
4545static void shellInt32(
4546  sqlite3_context *context,
4547  int argc,
4548  sqlite3_value **argv
4549){
4550  const unsigned char *pBlob;
4551  int nBlob;
4552  int iInt;
4553
4554  UNUSED_PARAMETER(argc);
4555  nBlob = sqlite3_value_bytes(argv[0]);
4556  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4557  iInt = sqlite3_value_int(argv[1]);
4558
4559  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4560    const unsigned char *a = &pBlob[iInt*4];
4561    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4562                       + ((sqlite3_int64)a[1]<<16)
4563                       + ((sqlite3_int64)a[2]<< 8)
4564                       + ((sqlite3_int64)a[3]<< 0);
4565    sqlite3_result_int64(context, iVal);
4566  }
4567}
4568
4569/*
4570** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4571** using "..." with internal double-quote characters doubled.
4572*/
4573static void shellIdQuote(
4574  sqlite3_context *context,
4575  int argc,
4576  sqlite3_value **argv
4577){
4578  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4579  UNUSED_PARAMETER(argc);
4580  if( zName ){
4581    char *z = sqlite3_mprintf("\"%w\"", zName);
4582    sqlite3_result_text(context, z, -1, sqlite3_free);
4583  }
4584}
4585
4586/*
4587** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4588*/
4589static void shellUSleepFunc(
4590  sqlite3_context *context,
4591  int argcUnused,
4592  sqlite3_value **argv
4593){
4594  int sleep = sqlite3_value_int(argv[0]);
4595  (void)argcUnused;
4596  sqlite3_sleep(sleep/1000);
4597  sqlite3_result_int(context, sleep);
4598}
4599
4600/*
4601** Scalar function "shell_escape_crnl" used by the .recover command.
4602** The argument passed to this function is the output of built-in
4603** function quote(). If the first character of the input is "'",
4604** indicating that the value passed to quote() was a text value,
4605** then this function searches the input for "\n" and "\r" characters
4606** and adds a wrapper similar to the following:
4607**
4608**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4609**
4610** Or, if the first character of the input is not "'", then a copy
4611** of the input is returned.
4612*/
4613static void shellEscapeCrnl(
4614  sqlite3_context *context,
4615  int argc,
4616  sqlite3_value **argv
4617){
4618  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4619  UNUSED_PARAMETER(argc);
4620  if( zText[0]=='\'' ){
4621    int nText = sqlite3_value_bytes(argv[0]);
4622    int i;
4623    char zBuf1[20];
4624    char zBuf2[20];
4625    const char *zNL = 0;
4626    const char *zCR = 0;
4627    int nCR = 0;
4628    int nNL = 0;
4629
4630    for(i=0; zText[i]; i++){
4631      if( zNL==0 && zText[i]=='\n' ){
4632        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4633        nNL = (int)strlen(zNL);
4634      }
4635      if( zCR==0 && zText[i]=='\r' ){
4636        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4637        nCR = (int)strlen(zCR);
4638      }
4639    }
4640
4641    if( zNL || zCR ){
4642      int iOut = 0;
4643      i64 nMax = (nNL > nCR) ? nNL : nCR;
4644      i64 nAlloc = nMax * nText + (nMax+64)*2;
4645      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4646      if( zOut==0 ){
4647        sqlite3_result_error_nomem(context);
4648        return;
4649      }
4650
4651      if( zNL && zCR ){
4652        memcpy(&zOut[iOut], "replace(replace(", 16);
4653        iOut += 16;
4654      }else{
4655        memcpy(&zOut[iOut], "replace(", 8);
4656        iOut += 8;
4657      }
4658      for(i=0; zText[i]; i++){
4659        if( zText[i]=='\n' ){
4660          memcpy(&zOut[iOut], zNL, nNL);
4661          iOut += nNL;
4662        }else if( zText[i]=='\r' ){
4663          memcpy(&zOut[iOut], zCR, nCR);
4664          iOut += nCR;
4665        }else{
4666          zOut[iOut] = zText[i];
4667          iOut++;
4668        }
4669      }
4670
4671      if( zNL ){
4672        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4673        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4674        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4675      }
4676      if( zCR ){
4677        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4678        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4679        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4680      }
4681
4682      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4683      sqlite3_free(zOut);
4684      return;
4685    }
4686  }
4687
4688  sqlite3_result_value(context, argv[0]);
4689}
4690
4691/* Flags for open_db().
4692**
4693** The default behavior of open_db() is to exit(1) if the database fails to
4694** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4695** but still returns without calling exit.
4696**
4697** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4698** ZIP archive if the file does not exist or is empty and its name matches
4699** the *.zip pattern.
4700*/
4701#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4702#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4703
4704/*
4705** Make sure the database is open.  If it is not, then open it.  If
4706** the database fails to open, print an error message and exit.
4707*/
4708static void open_db(ShellState *p, int openFlags){
4709  if( p->db==0 ){
4710    const char *zDbFilename = p->pAuxDb->zDbFilename;
4711    if( p->openMode==SHELL_OPEN_UNSPEC ){
4712      if( zDbFilename==0 || zDbFilename[0]==0 ){
4713        p->openMode = SHELL_OPEN_NORMAL;
4714      }else{
4715        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4716                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4717      }
4718    }
4719    switch( p->openMode ){
4720      case SHELL_OPEN_APPENDVFS: {
4721        sqlite3_open_v2(zDbFilename, &p->db,
4722           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4723        break;
4724      }
4725      case SHELL_OPEN_HEXDB:
4726      case SHELL_OPEN_DESERIALIZE: {
4727        sqlite3_open(0, &p->db);
4728        break;
4729      }
4730      case SHELL_OPEN_ZIPFILE: {
4731        sqlite3_open(":memory:", &p->db);
4732        break;
4733      }
4734      case SHELL_OPEN_READONLY: {
4735        sqlite3_open_v2(zDbFilename, &p->db,
4736            SQLITE_OPEN_READONLY|p->openFlags, 0);
4737        break;
4738      }
4739      case SHELL_OPEN_UNSPEC:
4740      case SHELL_OPEN_NORMAL: {
4741        sqlite3_open_v2(zDbFilename, &p->db,
4742           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4743        break;
4744      }
4745    }
4746    globalDb = p->db;
4747    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4748      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4749          zDbFilename, sqlite3_errmsg(p->db));
4750      if( openFlags & OPEN_DB_KEEPALIVE ){
4751        sqlite3_open(":memory:", &p->db);
4752        return;
4753      }
4754      exit(1);
4755    }
4756#ifndef SQLITE_OMIT_LOAD_EXTENSION
4757    sqlite3_enable_load_extension(p->db, 1);
4758#endif
4759    sqlite3_fileio_init(p->db, 0, 0);
4760    sqlite3_shathree_init(p->db, 0, 0);
4761    sqlite3_completion_init(p->db, 0, 0);
4762    sqlite3_uint_init(p->db, 0, 0);
4763    sqlite3_decimal_init(p->db, 0, 0);
4764    sqlite3_regexp_init(p->db, 0, 0);
4765    sqlite3_ieee_init(p->db, 0, 0);
4766    sqlite3_series_init(p->db, 0, 0);
4767#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4768    sqlite3_dbdata_init(p->db, 0, 0);
4769#endif
4770#ifdef SQLITE_HAVE_ZLIB
4771    sqlite3_zipfile_init(p->db, 0, 0);
4772    sqlite3_sqlar_init(p->db, 0, 0);
4773#endif
4774    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4775                            shellAddSchemaName, 0, 0);
4776    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4777                            shellModuleSchema, 0, 0);
4778    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4779                            shellPutsFunc, 0, 0);
4780    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4781                            shellEscapeCrnl, 0, 0);
4782    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4783                            shellInt32, 0, 0);
4784    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4785                            shellIdQuote, 0, 0);
4786    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
4787                            shellUSleepFunc, 0, 0);
4788#ifndef SQLITE_NOHAVE_SYSTEM
4789    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4790                            editFunc, 0, 0);
4791    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4792                            editFunc, 0, 0);
4793#endif
4794    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4795      char *zSql = sqlite3_mprintf(
4796         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
4797      shell_check_oom(zSql);
4798      sqlite3_exec(p->db, zSql, 0, 0, 0);
4799      sqlite3_free(zSql);
4800    }
4801#ifndef SQLITE_OMIT_DESERIALIZE
4802    else
4803    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4804      int rc;
4805      int nData = 0;
4806      unsigned char *aData;
4807      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4808        aData = (unsigned char*)readFile(zDbFilename, &nData);
4809      }else{
4810        aData = readHexDb(p, &nData);
4811        if( aData==0 ){
4812          return;
4813        }
4814      }
4815      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4816                   SQLITE_DESERIALIZE_RESIZEABLE |
4817                   SQLITE_DESERIALIZE_FREEONCLOSE);
4818      if( rc ){
4819        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4820      }
4821      if( p->szMax>0 ){
4822        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4823      }
4824    }
4825#endif
4826  }
4827  if( p->bSafeModePersist && p->db!=0 ){
4828    sqlite3_set_authorizer(p->db, safeModeAuth, p);
4829  }
4830}
4831
4832/*
4833** Attempt to close the databaes connection.  Report errors.
4834*/
4835void close_db(sqlite3 *db){
4836  int rc = sqlite3_close(db);
4837  if( rc ){
4838    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4839        rc, sqlite3_errmsg(db));
4840  }
4841}
4842
4843#if HAVE_READLINE || HAVE_EDITLINE
4844/*
4845** Readline completion callbacks
4846*/
4847static char *readline_completion_generator(const char *text, int state){
4848  static sqlite3_stmt *pStmt = 0;
4849  char *zRet;
4850  if( state==0 ){
4851    char *zSql;
4852    sqlite3_finalize(pStmt);
4853    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4854                           "  FROM completion(%Q) ORDER BY 1", text);
4855    shell_check_oom(zSql);
4856    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4857    sqlite3_free(zSql);
4858  }
4859  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4860    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4861  }else{
4862    sqlite3_finalize(pStmt);
4863    pStmt = 0;
4864    zRet = 0;
4865  }
4866  return zRet;
4867}
4868static char **readline_completion(const char *zText, int iStart, int iEnd){
4869  rl_attempted_completion_over = 1;
4870  return rl_completion_matches(zText, readline_completion_generator);
4871}
4872
4873#elif HAVE_LINENOISE
4874/*
4875** Linenoise completion callback
4876*/
4877static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4878  int nLine = strlen30(zLine);
4879  int i, iStart;
4880  sqlite3_stmt *pStmt = 0;
4881  char *zSql;
4882  char zBuf[1000];
4883
4884  if( nLine>sizeof(zBuf)-30 ) return;
4885  if( zLine[0]=='.' || zLine[0]=='#') return;
4886  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4887  if( i==nLine-1 ) return;
4888  iStart = i+1;
4889  memcpy(zBuf, zLine, iStart);
4890  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4891                         "  FROM completion(%Q,%Q) ORDER BY 1",
4892                         &zLine[iStart], zLine);
4893  shell_check_oom(zSql);
4894  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4895  sqlite3_free(zSql);
4896  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4897  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4898    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4899    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4900    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4901      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4902      linenoiseAddCompletion(lc, zBuf);
4903    }
4904  }
4905  sqlite3_finalize(pStmt);
4906}
4907#endif
4908
4909/*
4910** Do C-language style dequoting.
4911**
4912**    \a    -> alarm
4913**    \b    -> backspace
4914**    \t    -> tab
4915**    \n    -> newline
4916**    \v    -> vertical tab
4917**    \f    -> form feed
4918**    \r    -> carriage return
4919**    \s    -> space
4920**    \"    -> "
4921**    \'    -> '
4922**    \\    -> backslash
4923**    \NNN  -> ascii character NNN in octal
4924*/
4925static void resolve_backslashes(char *z){
4926  int i, j;
4927  char c;
4928  while( *z && *z!='\\' ) z++;
4929  for(i=j=0; (c = z[i])!=0; i++, j++){
4930    if( c=='\\' && z[i+1]!=0 ){
4931      c = z[++i];
4932      if( c=='a' ){
4933        c = '\a';
4934      }else if( c=='b' ){
4935        c = '\b';
4936      }else if( c=='t' ){
4937        c = '\t';
4938      }else if( c=='n' ){
4939        c = '\n';
4940      }else if( c=='v' ){
4941        c = '\v';
4942      }else if( c=='f' ){
4943        c = '\f';
4944      }else if( c=='r' ){
4945        c = '\r';
4946      }else if( c=='"' ){
4947        c = '"';
4948      }else if( c=='\'' ){
4949        c = '\'';
4950      }else if( c=='\\' ){
4951        c = '\\';
4952      }else if( c>='0' && c<='7' ){
4953        c -= '0';
4954        if( z[i+1]>='0' && z[i+1]<='7' ){
4955          i++;
4956          c = (c<<3) + z[i] - '0';
4957          if( z[i+1]>='0' && z[i+1]<='7' ){
4958            i++;
4959            c = (c<<3) + z[i] - '0';
4960          }
4961        }
4962      }
4963    }
4964    z[j] = c;
4965  }
4966  if( j<i ) z[j] = 0;
4967}
4968
4969/*
4970** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4971** for TRUE and FALSE.  Return the integer value if appropriate.
4972*/
4973static int booleanValue(const char *zArg){
4974  int i;
4975  if( zArg[0]=='0' && zArg[1]=='x' ){
4976    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4977  }else{
4978    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4979  }
4980  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4981  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4982    return 1;
4983  }
4984  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4985    return 0;
4986  }
4987  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4988          zArg);
4989  return 0;
4990}
4991
4992/*
4993** Set or clear a shell flag according to a boolean value.
4994*/
4995static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4996  if( booleanValue(zArg) ){
4997    ShellSetFlag(p, mFlag);
4998  }else{
4999    ShellClearFlag(p, mFlag);
5000  }
5001}
5002
5003/*
5004** Close an output file, assuming it is not stderr or stdout
5005*/
5006static void output_file_close(FILE *f){
5007  if( f && f!=stdout && f!=stderr ) fclose(f);
5008}
5009
5010/*
5011** Try to open an output file.   The names "stdout" and "stderr" are
5012** recognized and do the right thing.  NULL is returned if the output
5013** filename is "off".
5014*/
5015static FILE *output_file_open(const char *zFile, int bTextMode){
5016  FILE *f;
5017  if( strcmp(zFile,"stdout")==0 ){
5018    f = stdout;
5019  }else if( strcmp(zFile, "stderr")==0 ){
5020    f = stderr;
5021  }else if( strcmp(zFile, "off")==0 ){
5022    f = 0;
5023  }else{
5024    f = fopen(zFile, bTextMode ? "w" : "wb");
5025    if( f==0 ){
5026      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5027    }
5028  }
5029  return f;
5030}
5031
5032#ifndef SQLITE_OMIT_TRACE
5033/*
5034** A routine for handling output from sqlite3_trace().
5035*/
5036static int sql_trace_callback(
5037  unsigned mType,         /* The trace type */
5038  void *pArg,             /* The ShellState pointer */
5039  void *pP,               /* Usually a pointer to sqlite_stmt */
5040  void *pX                /* Auxiliary output */
5041){
5042  ShellState *p = (ShellState*)pArg;
5043  sqlite3_stmt *pStmt;
5044  const char *zSql;
5045  int nSql;
5046  if( p->traceOut==0 ) return 0;
5047  if( mType==SQLITE_TRACE_CLOSE ){
5048    utf8_printf(p->traceOut, "-- closing database connection\n");
5049    return 0;
5050  }
5051  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5052    zSql = (const char*)pX;
5053  }else{
5054    pStmt = (sqlite3_stmt*)pP;
5055    switch( p->eTraceType ){
5056      case SHELL_TRACE_EXPANDED: {
5057        zSql = sqlite3_expanded_sql(pStmt);
5058        break;
5059      }
5060#ifdef SQLITE_ENABLE_NORMALIZE
5061      case SHELL_TRACE_NORMALIZED: {
5062        zSql = sqlite3_normalized_sql(pStmt);
5063        break;
5064      }
5065#endif
5066      default: {
5067        zSql = sqlite3_sql(pStmt);
5068        break;
5069      }
5070    }
5071  }
5072  if( zSql==0 ) return 0;
5073  nSql = strlen30(zSql);
5074  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5075  switch( mType ){
5076    case SQLITE_TRACE_ROW:
5077    case SQLITE_TRACE_STMT: {
5078      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5079      break;
5080    }
5081    case SQLITE_TRACE_PROFILE: {
5082      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5083      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5084      break;
5085    }
5086  }
5087  return 0;
5088}
5089#endif
5090
5091/*
5092** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5093** a useful spot to set a debugger breakpoint.
5094*/
5095static void test_breakpoint(void){
5096  static int nCall = 0;
5097  nCall++;
5098}
5099
5100/*
5101** An object used to read a CSV and other files for import.
5102*/
5103typedef struct ImportCtx ImportCtx;
5104struct ImportCtx {
5105  const char *zFile;  /* Name of the input file */
5106  FILE *in;           /* Read the CSV text from this input stream */
5107  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5108  char *z;            /* Accumulated text for a field */
5109  int n;              /* Number of bytes in z */
5110  int nAlloc;         /* Space allocated for z[] */
5111  int nLine;          /* Current line number */
5112  int nRow;           /* Number of rows imported */
5113  int nErr;           /* Number of errors encountered */
5114  int bNotFirst;      /* True if one or more bytes already read */
5115  int cTerm;          /* Character that terminated the most recent field */
5116  int cColSep;        /* The column separator character.  (Usually ",") */
5117  int cRowSep;        /* The row separator character.  (Usually "\n") */
5118};
5119
5120/* Clean up resourced used by an ImportCtx */
5121static void import_cleanup(ImportCtx *p){
5122  if( p->in!=0 && p->xCloser!=0 ){
5123    p->xCloser(p->in);
5124    p->in = 0;
5125  }
5126  sqlite3_free(p->z);
5127  p->z = 0;
5128}
5129
5130/* Append a single byte to z[] */
5131static void import_append_char(ImportCtx *p, int c){
5132  if( p->n+1>=p->nAlloc ){
5133    p->nAlloc += p->nAlloc + 100;
5134    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5135    shell_check_oom(p->z);
5136  }
5137  p->z[p->n++] = (char)c;
5138}
5139
5140/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5141** with the option of having a separator other than ",".
5142**
5143**   +  Input comes from p->in.
5144**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5145**      from sqlite3_malloc64().
5146**   +  Use p->cSep as the column separator.  The default is ",".
5147**   +  Use p->rSep as the row separator.  The default is "\n".
5148**   +  Keep track of the line number in p->nLine.
5149**   +  Store the character that terminates the field in p->cTerm.  Store
5150**      EOF on end-of-file.
5151**   +  Report syntax errors on stderr
5152*/
5153static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5154  int c;
5155  int cSep = p->cColSep;
5156  int rSep = p->cRowSep;
5157  p->n = 0;
5158  c = fgetc(p->in);
5159  if( c==EOF || seenInterrupt ){
5160    p->cTerm = EOF;
5161    return 0;
5162  }
5163  if( c=='"' ){
5164    int pc, ppc;
5165    int startLine = p->nLine;
5166    int cQuote = c;
5167    pc = ppc = 0;
5168    while( 1 ){
5169      c = fgetc(p->in);
5170      if( c==rSep ) p->nLine++;
5171      if( c==cQuote ){
5172        if( pc==cQuote ){
5173          pc = 0;
5174          continue;
5175        }
5176      }
5177      if( (c==cSep && pc==cQuote)
5178       || (c==rSep && pc==cQuote)
5179       || (c==rSep && pc=='\r' && ppc==cQuote)
5180       || (c==EOF && pc==cQuote)
5181      ){
5182        do{ p->n--; }while( p->z[p->n]!=cQuote );
5183        p->cTerm = c;
5184        break;
5185      }
5186      if( pc==cQuote && c!='\r' ){
5187        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5188                p->zFile, p->nLine, cQuote);
5189      }
5190      if( c==EOF ){
5191        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5192                p->zFile, startLine, cQuote);
5193        p->cTerm = c;
5194        break;
5195      }
5196      import_append_char(p, c);
5197      ppc = pc;
5198      pc = c;
5199    }
5200  }else{
5201    /* If this is the first field being parsed and it begins with the
5202    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5203    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5204      import_append_char(p, c);
5205      c = fgetc(p->in);
5206      if( (c&0xff)==0xbb ){
5207        import_append_char(p, c);
5208        c = fgetc(p->in);
5209        if( (c&0xff)==0xbf ){
5210          p->bNotFirst = 1;
5211          p->n = 0;
5212          return csv_read_one_field(p);
5213        }
5214      }
5215    }
5216    while( c!=EOF && c!=cSep && c!=rSep ){
5217      import_append_char(p, c);
5218      c = fgetc(p->in);
5219    }
5220    if( c==rSep ){
5221      p->nLine++;
5222      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5223    }
5224    p->cTerm = c;
5225  }
5226  if( p->z ) p->z[p->n] = 0;
5227  p->bNotFirst = 1;
5228  return p->z;
5229}
5230
5231/* Read a single field of ASCII delimited text.
5232**
5233**   +  Input comes from p->in.
5234**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5235**      from sqlite3_malloc64().
5236**   +  Use p->cSep as the column separator.  The default is "\x1F".
5237**   +  Use p->rSep as the row separator.  The default is "\x1E".
5238**   +  Keep track of the row number in p->nLine.
5239**   +  Store the character that terminates the field in p->cTerm.  Store
5240**      EOF on end-of-file.
5241**   +  Report syntax errors on stderr
5242*/
5243static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5244  int c;
5245  int cSep = p->cColSep;
5246  int rSep = p->cRowSep;
5247  p->n = 0;
5248  c = fgetc(p->in);
5249  if( c==EOF || seenInterrupt ){
5250    p->cTerm = EOF;
5251    return 0;
5252  }
5253  while( c!=EOF && c!=cSep && c!=rSep ){
5254    import_append_char(p, c);
5255    c = fgetc(p->in);
5256  }
5257  if( c==rSep ){
5258    p->nLine++;
5259  }
5260  p->cTerm = c;
5261  if( p->z ) p->z[p->n] = 0;
5262  return p->z;
5263}
5264
5265/*
5266** Try to transfer data for table zTable.  If an error is seen while
5267** moving forward, try to go backwards.  The backwards movement won't
5268** work for WITHOUT ROWID tables.
5269*/
5270static void tryToCloneData(
5271  ShellState *p,
5272  sqlite3 *newDb,
5273  const char *zTable
5274){
5275  sqlite3_stmt *pQuery = 0;
5276  sqlite3_stmt *pInsert = 0;
5277  char *zQuery = 0;
5278  char *zInsert = 0;
5279  int rc;
5280  int i, j, n;
5281  int nTable = strlen30(zTable);
5282  int k = 0;
5283  int cnt = 0;
5284  const int spinRate = 10000;
5285
5286  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5287  shell_check_oom(zQuery);
5288  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5289  if( rc ){
5290    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5291            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5292            zQuery);
5293    goto end_data_xfer;
5294  }
5295  n = sqlite3_column_count(pQuery);
5296  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5297  shell_check_oom(zInsert);
5298  sqlite3_snprintf(200+nTable,zInsert,
5299                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5300  i = strlen30(zInsert);
5301  for(j=1; j<n; j++){
5302    memcpy(zInsert+i, ",?", 2);
5303    i += 2;
5304  }
5305  memcpy(zInsert+i, ");", 3);
5306  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5307  if( rc ){
5308    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5309            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5310            zQuery);
5311    goto end_data_xfer;
5312  }
5313  for(k=0; k<2; k++){
5314    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5315      for(i=0; i<n; i++){
5316        switch( sqlite3_column_type(pQuery, i) ){
5317          case SQLITE_NULL: {
5318            sqlite3_bind_null(pInsert, i+1);
5319            break;
5320          }
5321          case SQLITE_INTEGER: {
5322            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5323            break;
5324          }
5325          case SQLITE_FLOAT: {
5326            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5327            break;
5328          }
5329          case SQLITE_TEXT: {
5330            sqlite3_bind_text(pInsert, i+1,
5331                             (const char*)sqlite3_column_text(pQuery,i),
5332                             -1, SQLITE_STATIC);
5333            break;
5334          }
5335          case SQLITE_BLOB: {
5336            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5337                                            sqlite3_column_bytes(pQuery,i),
5338                                            SQLITE_STATIC);
5339            break;
5340          }
5341        }
5342      } /* End for */
5343      rc = sqlite3_step(pInsert);
5344      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5345        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5346                        sqlite3_errmsg(newDb));
5347      }
5348      sqlite3_reset(pInsert);
5349      cnt++;
5350      if( (cnt%spinRate)==0 ){
5351        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5352        fflush(stdout);
5353      }
5354    } /* End while */
5355    if( rc==SQLITE_DONE ) break;
5356    sqlite3_finalize(pQuery);
5357    sqlite3_free(zQuery);
5358    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5359                             zTable);
5360    shell_check_oom(zQuery);
5361    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5362    if( rc ){
5363      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5364      break;
5365    }
5366  } /* End for(k=0...) */
5367
5368end_data_xfer:
5369  sqlite3_finalize(pQuery);
5370  sqlite3_finalize(pInsert);
5371  sqlite3_free(zQuery);
5372  sqlite3_free(zInsert);
5373}
5374
5375
5376/*
5377** Try to transfer all rows of the schema that match zWhere.  For
5378** each row, invoke xForEach() on the object defined by that row.
5379** If an error is encountered while moving forward through the
5380** sqlite_schema table, try again moving backwards.
5381*/
5382static void tryToCloneSchema(
5383  ShellState *p,
5384  sqlite3 *newDb,
5385  const char *zWhere,
5386  void (*xForEach)(ShellState*,sqlite3*,const char*)
5387){
5388  sqlite3_stmt *pQuery = 0;
5389  char *zQuery = 0;
5390  int rc;
5391  const unsigned char *zName;
5392  const unsigned char *zSql;
5393  char *zErrMsg = 0;
5394
5395  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5396                           " WHERE %s", zWhere);
5397  shell_check_oom(zQuery);
5398  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5399  if( rc ){
5400    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5401                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5402                    zQuery);
5403    goto end_schema_xfer;
5404  }
5405  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5406    zName = sqlite3_column_text(pQuery, 0);
5407    zSql = sqlite3_column_text(pQuery, 1);
5408    printf("%s... ", zName); fflush(stdout);
5409    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5410    if( zErrMsg ){
5411      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5412      sqlite3_free(zErrMsg);
5413      zErrMsg = 0;
5414    }
5415    if( xForEach ){
5416      xForEach(p, newDb, (const char*)zName);
5417    }
5418    printf("done\n");
5419  }
5420  if( rc!=SQLITE_DONE ){
5421    sqlite3_finalize(pQuery);
5422    sqlite3_free(zQuery);
5423    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5424                             " WHERE %s ORDER BY rowid DESC", zWhere);
5425    shell_check_oom(zQuery);
5426    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5427    if( rc ){
5428      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5429                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5430                      zQuery);
5431      goto end_schema_xfer;
5432    }
5433    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5434      zName = sqlite3_column_text(pQuery, 0);
5435      zSql = sqlite3_column_text(pQuery, 1);
5436      printf("%s... ", zName); fflush(stdout);
5437      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5438      if( zErrMsg ){
5439        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5440        sqlite3_free(zErrMsg);
5441        zErrMsg = 0;
5442      }
5443      if( xForEach ){
5444        xForEach(p, newDb, (const char*)zName);
5445      }
5446      printf("done\n");
5447    }
5448  }
5449end_schema_xfer:
5450  sqlite3_finalize(pQuery);
5451  sqlite3_free(zQuery);
5452}
5453
5454/*
5455** Open a new database file named "zNewDb".  Try to recover as much information
5456** as possible out of the main database (which might be corrupt) and write it
5457** into zNewDb.
5458*/
5459static void tryToClone(ShellState *p, const char *zNewDb){
5460  int rc;
5461  sqlite3 *newDb = 0;
5462  if( access(zNewDb,0)==0 ){
5463    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5464    return;
5465  }
5466  rc = sqlite3_open(zNewDb, &newDb);
5467  if( rc ){
5468    utf8_printf(stderr, "Cannot create output database: %s\n",
5469            sqlite3_errmsg(newDb));
5470  }else{
5471    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5472    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5473    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5474    tryToCloneSchema(p, newDb, "type!='table'", 0);
5475    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5476    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5477  }
5478  close_db(newDb);
5479}
5480
5481/*
5482** Change the output file back to stdout.
5483**
5484** If the p->doXdgOpen flag is set, that means the output was being
5485** redirected to a temporary file named by p->zTempFile.  In that case,
5486** launch start/open/xdg-open on that temporary file.
5487*/
5488static void output_reset(ShellState *p){
5489  if( p->outfile[0]=='|' ){
5490#ifndef SQLITE_OMIT_POPEN
5491    pclose(p->out);
5492#endif
5493  }else{
5494    output_file_close(p->out);
5495#ifndef SQLITE_NOHAVE_SYSTEM
5496    if( p->doXdgOpen ){
5497      const char *zXdgOpenCmd =
5498#if defined(_WIN32)
5499      "start";
5500#elif defined(__APPLE__)
5501      "open";
5502#else
5503      "xdg-open";
5504#endif
5505      char *zCmd;
5506      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5507      if( system(zCmd) ){
5508        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5509      }else{
5510        /* Give the start/open/xdg-open command some time to get
5511        ** going before we continue, and potential delete the
5512        ** p->zTempFile data file out from under it */
5513        sqlite3_sleep(2000);
5514      }
5515      sqlite3_free(zCmd);
5516      outputModePop(p);
5517      p->doXdgOpen = 0;
5518    }
5519#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5520  }
5521  p->outfile[0] = 0;
5522  p->out = stdout;
5523}
5524
5525/*
5526** Run an SQL command and return the single integer result.
5527*/
5528static int db_int(ShellState *p, const char *zSql){
5529  sqlite3_stmt *pStmt;
5530  int res = 0;
5531  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5532  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5533    res = sqlite3_column_int(pStmt,0);
5534  }
5535  sqlite3_finalize(pStmt);
5536  return res;
5537}
5538
5539/*
5540** Convert a 2-byte or 4-byte big-endian integer into a native integer
5541*/
5542static unsigned int get2byteInt(unsigned char *a){
5543  return (a[0]<<8) + a[1];
5544}
5545static unsigned int get4byteInt(unsigned char *a){
5546  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5547}
5548
5549/*
5550** Implementation of the ".dbinfo" command.
5551**
5552** Return 1 on error, 2 to exit, and 0 otherwise.
5553*/
5554static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5555  static const struct { const char *zName; int ofst; } aField[] = {
5556     { "file change counter:",  24  },
5557     { "database page count:",  28  },
5558     { "freelist page count:",  36  },
5559     { "schema cookie:",        40  },
5560     { "schema format:",        44  },
5561     { "default cache size:",   48  },
5562     { "autovacuum top root:",  52  },
5563     { "incremental vacuum:",   64  },
5564     { "text encoding:",        56  },
5565     { "user version:",         60  },
5566     { "application id:",       68  },
5567     { "software version:",     96  },
5568  };
5569  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5570     { "number of tables:",
5571       "SELECT count(*) FROM %s WHERE type='table'" },
5572     { "number of indexes:",
5573       "SELECT count(*) FROM %s WHERE type='index'" },
5574     { "number of triggers:",
5575       "SELECT count(*) FROM %s WHERE type='trigger'" },
5576     { "number of views:",
5577       "SELECT count(*) FROM %s WHERE type='view'" },
5578     { "schema size:",
5579       "SELECT total(length(sql)) FROM %s" },
5580  };
5581  int i, rc;
5582  unsigned iDataVersion;
5583  char *zSchemaTab;
5584  char *zDb = nArg>=2 ? azArg[1] : "main";
5585  sqlite3_stmt *pStmt = 0;
5586  unsigned char aHdr[100];
5587  open_db(p, 0);
5588  if( p->db==0 ) return 1;
5589  rc = sqlite3_prepare_v2(p->db,
5590             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5591             -1, &pStmt, 0);
5592  if( rc ){
5593    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5594    sqlite3_finalize(pStmt);
5595    return 1;
5596  }
5597  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5598  if( sqlite3_step(pStmt)==SQLITE_ROW
5599   && sqlite3_column_bytes(pStmt,0)>100
5600  ){
5601    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5602    sqlite3_finalize(pStmt);
5603  }else{
5604    raw_printf(stderr, "unable to read database header\n");
5605    sqlite3_finalize(pStmt);
5606    return 1;
5607  }
5608  i = get2byteInt(aHdr+16);
5609  if( i==1 ) i = 65536;
5610  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5611  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5612  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5613  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5614  for(i=0; i<ArraySize(aField); i++){
5615    int ofst = aField[i].ofst;
5616    unsigned int val = get4byteInt(aHdr + ofst);
5617    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5618    switch( ofst ){
5619      case 56: {
5620        if( val==1 ) raw_printf(p->out, " (utf8)");
5621        if( val==2 ) raw_printf(p->out, " (utf16le)");
5622        if( val==3 ) raw_printf(p->out, " (utf16be)");
5623      }
5624    }
5625    raw_printf(p->out, "\n");
5626  }
5627  if( zDb==0 ){
5628    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5629  }else if( strcmp(zDb,"temp")==0 ){
5630    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5631  }else{
5632    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5633  }
5634  for(i=0; i<ArraySize(aQuery); i++){
5635    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5636    int val = db_int(p, zSql);
5637    sqlite3_free(zSql);
5638    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5639  }
5640  sqlite3_free(zSchemaTab);
5641  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5642  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5643  return 0;
5644}
5645
5646/*
5647** Print the current sqlite3_errmsg() value to stderr and return 1.
5648*/
5649static int shellDatabaseError(sqlite3 *db){
5650  const char *zErr = sqlite3_errmsg(db);
5651  utf8_printf(stderr, "Error: %s\n", zErr);
5652  return 1;
5653}
5654
5655/*
5656** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5657** if they match and FALSE (0) if they do not match.
5658**
5659** Globbing rules:
5660**
5661**      '*'       Matches any sequence of zero or more characters.
5662**
5663**      '?'       Matches exactly one character.
5664**
5665**     [...]      Matches one character from the enclosed list of
5666**                characters.
5667**
5668**     [^...]     Matches one character not in the enclosed list.
5669**
5670**      '#'       Matches any sequence of one or more digits with an
5671**                optional + or - sign in front
5672**
5673**      ' '       Any span of whitespace matches any other span of
5674**                whitespace.
5675**
5676** Extra whitespace at the end of z[] is ignored.
5677*/
5678static int testcase_glob(const char *zGlob, const char *z){
5679  int c, c2;
5680  int invert;
5681  int seen;
5682
5683  while( (c = (*(zGlob++)))!=0 ){
5684    if( IsSpace(c) ){
5685      if( !IsSpace(*z) ) return 0;
5686      while( IsSpace(*zGlob) ) zGlob++;
5687      while( IsSpace(*z) ) z++;
5688    }else if( c=='*' ){
5689      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5690        if( c=='?' && (*(z++))==0 ) return 0;
5691      }
5692      if( c==0 ){
5693        return 1;
5694      }else if( c=='[' ){
5695        while( *z && testcase_glob(zGlob-1,z)==0 ){
5696          z++;
5697        }
5698        return (*z)!=0;
5699      }
5700      while( (c2 = (*(z++)))!=0 ){
5701        while( c2!=c ){
5702          c2 = *(z++);
5703          if( c2==0 ) return 0;
5704        }
5705        if( testcase_glob(zGlob,z) ) return 1;
5706      }
5707      return 0;
5708    }else if( c=='?' ){
5709      if( (*(z++))==0 ) return 0;
5710    }else if( c=='[' ){
5711      int prior_c = 0;
5712      seen = 0;
5713      invert = 0;
5714      c = *(z++);
5715      if( c==0 ) return 0;
5716      c2 = *(zGlob++);
5717      if( c2=='^' ){
5718        invert = 1;
5719        c2 = *(zGlob++);
5720      }
5721      if( c2==']' ){
5722        if( c==']' ) seen = 1;
5723        c2 = *(zGlob++);
5724      }
5725      while( c2 && c2!=']' ){
5726        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5727          c2 = *(zGlob++);
5728          if( c>=prior_c && c<=c2 ) seen = 1;
5729          prior_c = 0;
5730        }else{
5731          if( c==c2 ){
5732            seen = 1;
5733          }
5734          prior_c = c2;
5735        }
5736        c2 = *(zGlob++);
5737      }
5738      if( c2==0 || (seen ^ invert)==0 ) return 0;
5739    }else if( c=='#' ){
5740      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5741      if( !IsDigit(z[0]) ) return 0;
5742      z++;
5743      while( IsDigit(z[0]) ){ z++; }
5744    }else{
5745      if( c!=(*(z++)) ) return 0;
5746    }
5747  }
5748  while( IsSpace(*z) ){ z++; }
5749  return *z==0;
5750}
5751
5752
5753/*
5754** Compare the string as a command-line option with either one or two
5755** initial "-" characters.
5756*/
5757static int optionMatch(const char *zStr, const char *zOpt){
5758  if( zStr[0]!='-' ) return 0;
5759  zStr++;
5760  if( zStr[0]=='-' ) zStr++;
5761  return strcmp(zStr, zOpt)==0;
5762}
5763
5764/*
5765** Delete a file.
5766*/
5767int shellDeleteFile(const char *zFilename){
5768  int rc;
5769#ifdef _WIN32
5770  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5771  rc = _wunlink(z);
5772  sqlite3_free(z);
5773#else
5774  rc = unlink(zFilename);
5775#endif
5776  return rc;
5777}
5778
5779/*
5780** Try to delete the temporary file (if there is one) and free the
5781** memory used to hold the name of the temp file.
5782*/
5783static void clearTempFile(ShellState *p){
5784  if( p->zTempFile==0 ) return;
5785  if( p->doXdgOpen ) return;
5786  if( shellDeleteFile(p->zTempFile) ) return;
5787  sqlite3_free(p->zTempFile);
5788  p->zTempFile = 0;
5789}
5790
5791/*
5792** Create a new temp file name with the given suffix.
5793*/
5794static void newTempFile(ShellState *p, const char *zSuffix){
5795  clearTempFile(p);
5796  sqlite3_free(p->zTempFile);
5797  p->zTempFile = 0;
5798  if( p->db ){
5799    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5800  }
5801  if( p->zTempFile==0 ){
5802    /* If p->db is an in-memory database then the TEMPFILENAME file-control
5803    ** will not work and we will need to fallback to guessing */
5804    char *zTemp;
5805    sqlite3_uint64 r;
5806    sqlite3_randomness(sizeof(r), &r);
5807    zTemp = getenv("TEMP");
5808    if( zTemp==0 ) zTemp = getenv("TMP");
5809    if( zTemp==0 ){
5810#ifdef _WIN32
5811      zTemp = "\\tmp";
5812#else
5813      zTemp = "/tmp";
5814#endif
5815    }
5816    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5817  }else{
5818    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5819  }
5820  shell_check_oom(p->zTempFile);
5821}
5822
5823
5824/*
5825** The implementation of SQL scalar function fkey_collate_clause(), used
5826** by the ".lint fkey-indexes" command. This scalar function is always
5827** called with four arguments - the parent table name, the parent column name,
5828** the child table name and the child column name.
5829**
5830**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5831**
5832** If either of the named tables or columns do not exist, this function
5833** returns an empty string. An empty string is also returned if both tables
5834** and columns exist but have the same default collation sequence. Or,
5835** if both exist but the default collation sequences are different, this
5836** function returns the string " COLLATE <parent-collation>", where
5837** <parent-collation> is the default collation sequence of the parent column.
5838*/
5839static void shellFkeyCollateClause(
5840  sqlite3_context *pCtx,
5841  int nVal,
5842  sqlite3_value **apVal
5843){
5844  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5845  const char *zParent;
5846  const char *zParentCol;
5847  const char *zParentSeq;
5848  const char *zChild;
5849  const char *zChildCol;
5850  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5851  int rc;
5852
5853  assert( nVal==4 );
5854  zParent = (const char*)sqlite3_value_text(apVal[0]);
5855  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5856  zChild = (const char*)sqlite3_value_text(apVal[2]);
5857  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5858
5859  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5860  rc = sqlite3_table_column_metadata(
5861      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5862  );
5863  if( rc==SQLITE_OK ){
5864    rc = sqlite3_table_column_metadata(
5865        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5866    );
5867  }
5868
5869  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5870    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5871    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5872    sqlite3_free(z);
5873  }
5874}
5875
5876
5877/*
5878** The implementation of dot-command ".lint fkey-indexes".
5879*/
5880static int lintFkeyIndexes(
5881  ShellState *pState,             /* Current shell tool state */
5882  char **azArg,                   /* Array of arguments passed to dot command */
5883  int nArg                        /* Number of entries in azArg[] */
5884){
5885  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5886  FILE *out = pState->out;        /* Stream to write non-error output to */
5887  int bVerbose = 0;               /* If -verbose is present */
5888  int bGroupByParent = 0;         /* If -groupbyparent is present */
5889  int i;                          /* To iterate through azArg[] */
5890  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5891  int rc;                         /* Return code */
5892  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5893
5894  /*
5895  ** This SELECT statement returns one row for each foreign key constraint
5896  ** in the schema of the main database. The column values are:
5897  **
5898  ** 0. The text of an SQL statement similar to:
5899  **
5900  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5901  **
5902  **    This SELECT is similar to the one that the foreign keys implementation
5903  **    needs to run internally on child tables. If there is an index that can
5904  **    be used to optimize this query, then it can also be used by the FK
5905  **    implementation to optimize DELETE or UPDATE statements on the parent
5906  **    table.
5907  **
5908  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5909  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5910  **    contains an index that can be used to optimize the query.
5911  **
5912  ** 2. Human readable text that describes the child table and columns. e.g.
5913  **
5914  **       "child_table(child_key1, child_key2)"
5915  **
5916  ** 3. Human readable text that describes the parent table and columns. e.g.
5917  **
5918  **       "parent_table(parent_key1, parent_key2)"
5919  **
5920  ** 4. A full CREATE INDEX statement for an index that could be used to
5921  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5922  **
5923  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5924  **
5925  ** 5. The name of the parent table.
5926  **
5927  ** These six values are used by the C logic below to generate the report.
5928  */
5929  const char *zSql =
5930  "SELECT "
5931    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5932    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5933    "  || fkey_collate_clause("
5934    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5935    ", "
5936    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
5937    "  || group_concat('*=?', ' AND ') || ')'"
5938    ", "
5939    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5940    ", "
5941    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5942    ", "
5943    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5944    "  || ' ON ' || quote(s.name) || '('"
5945    "  || group_concat(quote(f.[from]) ||"
5946    "        fkey_collate_clause("
5947    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5948    "  || ');'"
5949    ", "
5950    "     f.[table] "
5951    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5952    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5953    "GROUP BY s.name, f.id "
5954    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5955  ;
5956  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
5957
5958  for(i=2; i<nArg; i++){
5959    int n = strlen30(azArg[i]);
5960    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5961      bVerbose = 1;
5962    }
5963    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5964      bGroupByParent = 1;
5965      zIndent = "    ";
5966    }
5967    else{
5968      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5969          azArg[0], azArg[1]
5970      );
5971      return SQLITE_ERROR;
5972    }
5973  }
5974
5975  /* Register the fkey_collate_clause() SQL function */
5976  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5977      0, shellFkeyCollateClause, 0, 0
5978  );
5979
5980
5981  if( rc==SQLITE_OK ){
5982    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5983  }
5984  if( rc==SQLITE_OK ){
5985    sqlite3_bind_int(pSql, 1, bGroupByParent);
5986  }
5987
5988  if( rc==SQLITE_OK ){
5989    int rc2;
5990    char *zPrev = 0;
5991    while( SQLITE_ROW==sqlite3_step(pSql) ){
5992      int res = -1;
5993      sqlite3_stmt *pExplain = 0;
5994      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5995      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5996      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5997      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5998      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5999      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6000
6001      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6002      if( rc!=SQLITE_OK ) break;
6003      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6004        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6005        res = (
6006              0==sqlite3_strglob(zGlob, zPlan)
6007           || 0==sqlite3_strglob(zGlobIPK, zPlan)
6008        );
6009      }
6010      rc = sqlite3_finalize(pExplain);
6011      if( rc!=SQLITE_OK ) break;
6012
6013      if( res<0 ){
6014        raw_printf(stderr, "Error: internal error");
6015        break;
6016      }else{
6017        if( bGroupByParent
6018        && (bVerbose || res==0)
6019        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6020        ){
6021          raw_printf(out, "-- Parent table %s\n", zParent);
6022          sqlite3_free(zPrev);
6023          zPrev = sqlite3_mprintf("%s", zParent);
6024        }
6025
6026        if( res==0 ){
6027          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6028        }else if( bVerbose ){
6029          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6030              zIndent, zFrom, zTarget
6031          );
6032        }
6033      }
6034    }
6035    sqlite3_free(zPrev);
6036
6037    if( rc!=SQLITE_OK ){
6038      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6039    }
6040
6041    rc2 = sqlite3_finalize(pSql);
6042    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6043      rc = rc2;
6044      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6045    }
6046  }else{
6047    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6048  }
6049
6050  return rc;
6051}
6052
6053/*
6054** Implementation of ".lint" dot command.
6055*/
6056static int lintDotCommand(
6057  ShellState *pState,             /* Current shell tool state */
6058  char **azArg,                   /* Array of arguments passed to dot command */
6059  int nArg                        /* Number of entries in azArg[] */
6060){
6061  int n;
6062  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6063  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6064  return lintFkeyIndexes(pState, azArg, nArg);
6065
6066 usage:
6067  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6068  raw_printf(stderr, "Where sub-commands are:\n");
6069  raw_printf(stderr, "    fkey-indexes\n");
6070  return SQLITE_ERROR;
6071}
6072
6073#if !defined SQLITE_OMIT_VIRTUALTABLE
6074static void shellPrepare(
6075  sqlite3 *db,
6076  int *pRc,
6077  const char *zSql,
6078  sqlite3_stmt **ppStmt
6079){
6080  *ppStmt = 0;
6081  if( *pRc==SQLITE_OK ){
6082    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6083    if( rc!=SQLITE_OK ){
6084      raw_printf(stderr, "sql error: %s (%d)\n",
6085          sqlite3_errmsg(db), sqlite3_errcode(db)
6086      );
6087      *pRc = rc;
6088    }
6089  }
6090}
6091
6092/*
6093** Create a prepared statement using printf-style arguments for the SQL.
6094**
6095** This routine is could be marked "static".  But it is not always used,
6096** depending on compile-time options.  By omitting the "static", we avoid
6097** nuisance compiler warnings about "defined but not used".
6098*/
6099void shellPreparePrintf(
6100  sqlite3 *db,
6101  int *pRc,
6102  sqlite3_stmt **ppStmt,
6103  const char *zFmt,
6104  ...
6105){
6106  *ppStmt = 0;
6107  if( *pRc==SQLITE_OK ){
6108    va_list ap;
6109    char *z;
6110    va_start(ap, zFmt);
6111    z = sqlite3_vmprintf(zFmt, ap);
6112    va_end(ap);
6113    if( z==0 ){
6114      *pRc = SQLITE_NOMEM;
6115    }else{
6116      shellPrepare(db, pRc, z, ppStmt);
6117      sqlite3_free(z);
6118    }
6119  }
6120}
6121
6122/* Finalize the prepared statement created using shellPreparePrintf().
6123**
6124** This routine is could be marked "static".  But it is not always used,
6125** depending on compile-time options.  By omitting the "static", we avoid
6126** nuisance compiler warnings about "defined but not used".
6127*/
6128void shellFinalize(
6129  int *pRc,
6130  sqlite3_stmt *pStmt
6131){
6132  if( pStmt ){
6133    sqlite3 *db = sqlite3_db_handle(pStmt);
6134    int rc = sqlite3_finalize(pStmt);
6135    if( *pRc==SQLITE_OK ){
6136      if( rc!=SQLITE_OK ){
6137        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6138      }
6139      *pRc = rc;
6140    }
6141  }
6142}
6143
6144/* Reset the prepared statement created using shellPreparePrintf().
6145**
6146** This routine is could be marked "static".  But it is not always used,
6147** depending on compile-time options.  By omitting the "static", we avoid
6148** nuisance compiler warnings about "defined but not used".
6149*/
6150void shellReset(
6151  int *pRc,
6152  sqlite3_stmt *pStmt
6153){
6154  int rc = sqlite3_reset(pStmt);
6155  if( *pRc==SQLITE_OK ){
6156    if( rc!=SQLITE_OK ){
6157      sqlite3 *db = sqlite3_db_handle(pStmt);
6158      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6159    }
6160    *pRc = rc;
6161  }
6162}
6163#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6164
6165#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6166/******************************************************************************
6167** The ".archive" or ".ar" command.
6168*/
6169/*
6170** Structure representing a single ".ar" command.
6171*/
6172typedef struct ArCommand ArCommand;
6173struct ArCommand {
6174  u8 eCmd;                        /* An AR_CMD_* value */
6175  u8 bVerbose;                    /* True if --verbose */
6176  u8 bZip;                        /* True if the archive is a ZIP */
6177  u8 bDryRun;                     /* True if --dry-run */
6178  u8 bAppend;                     /* True if --append */
6179  u8 bGlob;                       /* True if --glob */
6180  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6181  int nArg;                       /* Number of command arguments */
6182  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6183  const char *zFile;              /* --file argument, or NULL */
6184  const char *zDir;               /* --directory argument, or NULL */
6185  char **azArg;                   /* Array of command arguments */
6186  ShellState *p;                  /* Shell state */
6187  sqlite3 *db;                    /* Database containing the archive */
6188};
6189
6190/*
6191** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6192*/
6193static int arUsage(FILE *f){
6194  showHelp(f,"archive");
6195  return SQLITE_ERROR;
6196}
6197
6198/*
6199** Print an error message for the .ar command to stderr and return
6200** SQLITE_ERROR.
6201*/
6202static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6203  va_list ap;
6204  char *z;
6205  va_start(ap, zFmt);
6206  z = sqlite3_vmprintf(zFmt, ap);
6207  va_end(ap);
6208  utf8_printf(stderr, "Error: %s\n", z);
6209  if( pAr->fromCmdLine ){
6210    utf8_printf(stderr, "Use \"-A\" for more help\n");
6211  }else{
6212    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6213  }
6214  sqlite3_free(z);
6215  return SQLITE_ERROR;
6216}
6217
6218/*
6219** Values for ArCommand.eCmd.
6220*/
6221#define AR_CMD_CREATE       1
6222#define AR_CMD_UPDATE       2
6223#define AR_CMD_INSERT       3
6224#define AR_CMD_EXTRACT      4
6225#define AR_CMD_LIST         5
6226#define AR_CMD_HELP         6
6227#define AR_CMD_REMOVE       7
6228
6229/*
6230** Other (non-command) switches.
6231*/
6232#define AR_SWITCH_VERBOSE     8
6233#define AR_SWITCH_FILE        9
6234#define AR_SWITCH_DIRECTORY  10
6235#define AR_SWITCH_APPEND     11
6236#define AR_SWITCH_DRYRUN     12
6237#define AR_SWITCH_GLOB       13
6238
6239static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6240  switch( eSwitch ){
6241    case AR_CMD_CREATE:
6242    case AR_CMD_EXTRACT:
6243    case AR_CMD_LIST:
6244    case AR_CMD_REMOVE:
6245    case AR_CMD_UPDATE:
6246    case AR_CMD_INSERT:
6247    case AR_CMD_HELP:
6248      if( pAr->eCmd ){
6249        return arErrorMsg(pAr, "multiple command options");
6250      }
6251      pAr->eCmd = eSwitch;
6252      break;
6253
6254    case AR_SWITCH_DRYRUN:
6255      pAr->bDryRun = 1;
6256      break;
6257    case AR_SWITCH_GLOB:
6258      pAr->bGlob = 1;
6259      break;
6260    case AR_SWITCH_VERBOSE:
6261      pAr->bVerbose = 1;
6262      break;
6263    case AR_SWITCH_APPEND:
6264      pAr->bAppend = 1;
6265      /* Fall thru into --file */
6266    case AR_SWITCH_FILE:
6267      pAr->zFile = zArg;
6268      break;
6269    case AR_SWITCH_DIRECTORY:
6270      pAr->zDir = zArg;
6271      break;
6272  }
6273
6274  return SQLITE_OK;
6275}
6276
6277/*
6278** Parse the command line for an ".ar" command. The results are written into
6279** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6280** successfully, otherwise an error message is written to stderr and
6281** SQLITE_ERROR returned.
6282*/
6283static int arParseCommand(
6284  char **azArg,                   /* Array of arguments passed to dot command */
6285  int nArg,                       /* Number of entries in azArg[] */
6286  ArCommand *pAr                  /* Populate this object */
6287){
6288  struct ArSwitch {
6289    const char *zLong;
6290    char cShort;
6291    u8 eSwitch;
6292    u8 bArg;
6293  } aSwitch[] = {
6294    { "create",    'c', AR_CMD_CREATE,       0 },
6295    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6296    { "insert",    'i', AR_CMD_INSERT,       0 },
6297    { "list",      't', AR_CMD_LIST,         0 },
6298    { "remove",    'r', AR_CMD_REMOVE,       0 },
6299    { "update",    'u', AR_CMD_UPDATE,       0 },
6300    { "help",      'h', AR_CMD_HELP,         0 },
6301    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6302    { "file",      'f', AR_SWITCH_FILE,      1 },
6303    { "append",    'a', AR_SWITCH_APPEND,    1 },
6304    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6305    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6306    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6307  };
6308  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6309  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6310
6311  if( nArg<=1 ){
6312    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6313    return arUsage(stderr);
6314  }else{
6315    char *z = azArg[1];
6316    if( z[0]!='-' ){
6317      /* Traditional style [tar] invocation */
6318      int i;
6319      int iArg = 2;
6320      for(i=0; z[i]; i++){
6321        const char *zArg = 0;
6322        struct ArSwitch *pOpt;
6323        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6324          if( z[i]==pOpt->cShort ) break;
6325        }
6326        if( pOpt==pEnd ){
6327          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6328        }
6329        if( pOpt->bArg ){
6330          if( iArg>=nArg ){
6331            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6332          }
6333          zArg = azArg[iArg++];
6334        }
6335        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6336      }
6337      pAr->nArg = nArg-iArg;
6338      if( pAr->nArg>0 ){
6339        pAr->azArg = &azArg[iArg];
6340      }
6341    }else{
6342      /* Non-traditional invocation */
6343      int iArg;
6344      for(iArg=1; iArg<nArg; iArg++){
6345        int n;
6346        z = azArg[iArg];
6347        if( z[0]!='-' ){
6348          /* All remaining command line words are command arguments. */
6349          pAr->azArg = &azArg[iArg];
6350          pAr->nArg = nArg-iArg;
6351          break;
6352        }
6353        n = strlen30(z);
6354
6355        if( z[1]!='-' ){
6356          int i;
6357          /* One or more short options */
6358          for(i=1; i<n; i++){
6359            const char *zArg = 0;
6360            struct ArSwitch *pOpt;
6361            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6362              if( z[i]==pOpt->cShort ) break;
6363            }
6364            if( pOpt==pEnd ){
6365              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6366            }
6367            if( pOpt->bArg ){
6368              if( i<(n-1) ){
6369                zArg = &z[i+1];
6370                i = n;
6371              }else{
6372                if( iArg>=(nArg-1) ){
6373                  return arErrorMsg(pAr, "option requires an argument: %c",
6374                                    z[i]);
6375                }
6376                zArg = azArg[++iArg];
6377              }
6378            }
6379            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6380          }
6381        }else if( z[2]=='\0' ){
6382          /* A -- option, indicating that all remaining command line words
6383          ** are command arguments.  */
6384          pAr->azArg = &azArg[iArg+1];
6385          pAr->nArg = nArg-iArg-1;
6386          break;
6387        }else{
6388          /* A long option */
6389          const char *zArg = 0;             /* Argument for option, if any */
6390          struct ArSwitch *pMatch = 0;      /* Matching option */
6391          struct ArSwitch *pOpt;            /* Iterator */
6392          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6393            const char *zLong = pOpt->zLong;
6394            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6395              if( pMatch ){
6396                return arErrorMsg(pAr, "ambiguous option: %s",z);
6397              }else{
6398                pMatch = pOpt;
6399              }
6400            }
6401          }
6402
6403          if( pMatch==0 ){
6404            return arErrorMsg(pAr, "unrecognized option: %s", z);
6405          }
6406          if( pMatch->bArg ){
6407            if( iArg>=(nArg-1) ){
6408              return arErrorMsg(pAr, "option requires an argument: %s", z);
6409            }
6410            zArg = azArg[++iArg];
6411          }
6412          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6413        }
6414      }
6415    }
6416  }
6417
6418  return SQLITE_OK;
6419}
6420
6421/*
6422** This function assumes that all arguments within the ArCommand.azArg[]
6423** array refer to archive members, as for the --extract, --list or --remove
6424** commands. It checks that each of them are "present". If any specified
6425** file is not present in the archive, an error is printed to stderr and an
6426** error code returned. Otherwise, if all specified arguments are present
6427** in the archive, SQLITE_OK is returned. Here, "present" means either an
6428** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6429** when pAr->bGlob is true.
6430**
6431** This function strips any trailing '/' characters from each argument.
6432** This is consistent with the way the [tar] command seems to work on
6433** Linux.
6434*/
6435static int arCheckEntries(ArCommand *pAr){
6436  int rc = SQLITE_OK;
6437  if( pAr->nArg ){
6438    int i, j;
6439    sqlite3_stmt *pTest = 0;
6440    const char *zSel = (pAr->bGlob)
6441      ? "SELECT name FROM %s WHERE glob($name,name)"
6442      : "SELECT name FROM %s WHERE name=$name";
6443
6444    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6445    j = sqlite3_bind_parameter_index(pTest, "$name");
6446    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6447      char *z = pAr->azArg[i];
6448      int n = strlen30(z);
6449      int bOk = 0;
6450      while( n>0 && z[n-1]=='/' ) n--;
6451      z[n] = '\0';
6452      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6453      if( SQLITE_ROW==sqlite3_step(pTest) ){
6454        bOk = 1;
6455      }
6456      shellReset(&rc, pTest);
6457      if( rc==SQLITE_OK && bOk==0 ){
6458        utf8_printf(stderr, "not found in archive: %s\n", z);
6459        rc = SQLITE_ERROR;
6460      }
6461    }
6462    shellFinalize(&rc, pTest);
6463  }
6464  return rc;
6465}
6466
6467/*
6468** Format a WHERE clause that can be used against the "sqlar" table to
6469** identify all archive members that match the command arguments held
6470** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6471** The caller is responsible for eventually calling sqlite3_free() on
6472** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6473** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6474*/
6475static void arWhereClause(
6476  int *pRc,
6477  ArCommand *pAr,
6478  char **pzWhere                  /* OUT: New WHERE clause */
6479){
6480  char *zWhere = 0;
6481  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6482  if( *pRc==SQLITE_OK ){
6483    if( pAr->nArg==0 ){
6484      zWhere = sqlite3_mprintf("1");
6485    }else{
6486      int i;
6487      const char *zSep = "";
6488      for(i=0; i<pAr->nArg; i++){
6489        const char *z = pAr->azArg[i];
6490        zWhere = sqlite3_mprintf(
6491          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6492          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6493        );
6494        if( zWhere==0 ){
6495          *pRc = SQLITE_NOMEM;
6496          break;
6497        }
6498        zSep = " OR ";
6499      }
6500    }
6501  }
6502  *pzWhere = zWhere;
6503}
6504
6505/*
6506** Implementation of .ar "lisT" command.
6507*/
6508static int arListCommand(ArCommand *pAr){
6509  const char *zSql = "SELECT %s FROM %s WHERE %s";
6510  const char *azCols[] = {
6511    "name",
6512    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6513  };
6514
6515  char *zWhere = 0;
6516  sqlite3_stmt *pSql = 0;
6517  int rc;
6518
6519  rc = arCheckEntries(pAr);
6520  arWhereClause(&rc, pAr, &zWhere);
6521
6522  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6523                     pAr->zSrcTable, zWhere);
6524  if( pAr->bDryRun ){
6525    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6526  }else{
6527    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6528      if( pAr->bVerbose ){
6529        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6530            sqlite3_column_text(pSql, 0),
6531            sqlite3_column_int(pSql, 1),
6532            sqlite3_column_text(pSql, 2),
6533            sqlite3_column_text(pSql, 3)
6534        );
6535      }else{
6536        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6537      }
6538    }
6539  }
6540  shellFinalize(&rc, pSql);
6541  sqlite3_free(zWhere);
6542  return rc;
6543}
6544
6545
6546/*
6547** Implementation of .ar "Remove" command.
6548*/
6549static int arRemoveCommand(ArCommand *pAr){
6550  int rc = 0;
6551  char *zSql = 0;
6552  char *zWhere = 0;
6553
6554  if( pAr->nArg ){
6555    /* Verify that args actually exist within the archive before proceeding.
6556    ** And formulate a WHERE clause to match them.  */
6557    rc = arCheckEntries(pAr);
6558    arWhereClause(&rc, pAr, &zWhere);
6559  }
6560  if( rc==SQLITE_OK ){
6561    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6562                           pAr->zSrcTable, zWhere);
6563    if( pAr->bDryRun ){
6564      utf8_printf(pAr->p->out, "%s\n", zSql);
6565    }else{
6566      char *zErr = 0;
6567      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6568      if( rc==SQLITE_OK ){
6569        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6570        if( rc!=SQLITE_OK ){
6571          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6572        }else{
6573          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6574        }
6575      }
6576      if( zErr ){
6577        utf8_printf(stdout, "ERROR: %s\n", zErr);
6578        sqlite3_free(zErr);
6579      }
6580    }
6581  }
6582  sqlite3_free(zWhere);
6583  sqlite3_free(zSql);
6584  return rc;
6585}
6586
6587/*
6588** Implementation of .ar "eXtract" command.
6589*/
6590static int arExtractCommand(ArCommand *pAr){
6591  const char *zSql1 =
6592    "SELECT "
6593    " ($dir || name),"
6594    " writefile(($dir || name), %s, mode, mtime) "
6595    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6596    " AND name NOT GLOB '*..[/\\]*'";
6597
6598  const char *azExtraArg[] = {
6599    "sqlar_uncompress(data, sz)",
6600    "data"
6601  };
6602
6603  sqlite3_stmt *pSql = 0;
6604  int rc = SQLITE_OK;
6605  char *zDir = 0;
6606  char *zWhere = 0;
6607  int i, j;
6608
6609  /* If arguments are specified, check that they actually exist within
6610  ** the archive before proceeding. And formulate a WHERE clause to
6611  ** match them.  */
6612  rc = arCheckEntries(pAr);
6613  arWhereClause(&rc, pAr, &zWhere);
6614
6615  if( rc==SQLITE_OK ){
6616    if( pAr->zDir ){
6617      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6618    }else{
6619      zDir = sqlite3_mprintf("");
6620    }
6621    if( zDir==0 ) rc = SQLITE_NOMEM;
6622  }
6623
6624  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6625      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6626  );
6627
6628  if( rc==SQLITE_OK ){
6629    j = sqlite3_bind_parameter_index(pSql, "$dir");
6630    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6631
6632    /* Run the SELECT statement twice. The first time, writefile() is called
6633    ** for all archive members that should be extracted. The second time,
6634    ** only for the directories. This is because the timestamps for
6635    ** extracted directories must be reset after they are populated (as
6636    ** populating them changes the timestamp).  */
6637    for(i=0; i<2; i++){
6638      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6639      sqlite3_bind_int(pSql, j, i);
6640      if( pAr->bDryRun ){
6641        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6642      }else{
6643        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6644          if( i==0 && pAr->bVerbose ){
6645            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6646          }
6647        }
6648      }
6649      shellReset(&rc, pSql);
6650    }
6651    shellFinalize(&rc, pSql);
6652  }
6653
6654  sqlite3_free(zDir);
6655  sqlite3_free(zWhere);
6656  return rc;
6657}
6658
6659/*
6660** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6661*/
6662static int arExecSql(ArCommand *pAr, const char *zSql){
6663  int rc;
6664  if( pAr->bDryRun ){
6665    utf8_printf(pAr->p->out, "%s\n", zSql);
6666    rc = SQLITE_OK;
6667  }else{
6668    char *zErr = 0;
6669    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6670    if( zErr ){
6671      utf8_printf(stdout, "ERROR: %s\n", zErr);
6672      sqlite3_free(zErr);
6673    }
6674  }
6675  return rc;
6676}
6677
6678
6679/*
6680** Implementation of .ar "create", "insert", and "update" commands.
6681**
6682**     create    ->     Create a new SQL archive
6683**     insert    ->     Insert or reinsert all files listed
6684**     update    ->     Insert files that have changed or that were not
6685**                      previously in the archive
6686**
6687** Create the "sqlar" table in the database if it does not already exist.
6688** Then add each file in the azFile[] array to the archive. Directories
6689** are added recursively. If argument bVerbose is non-zero, a message is
6690** printed on stdout for each file archived.
6691**
6692** The create command is the same as update, except that it drops
6693** any existing "sqlar" table before beginning.  The "insert" command
6694** always overwrites every file named on the command-line, where as
6695** "update" only overwrites if the size or mtime or mode has changed.
6696*/
6697static int arCreateOrUpdateCommand(
6698  ArCommand *pAr,                 /* Command arguments and options */
6699  int bUpdate,                    /* true for a --create. */
6700  int bOnlyIfChanged              /* Only update if file has changed */
6701){
6702  const char *zCreate =
6703      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6704      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6705      "  mode INT,               -- access permissions\n"
6706      "  mtime INT,              -- last modification time\n"
6707      "  sz INT,                 -- original file size\n"
6708      "  data BLOB               -- compressed content\n"
6709      ")";
6710  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6711  const char *zInsertFmt[2] = {
6712     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6713     "  SELECT\n"
6714     "    %s,\n"
6715     "    mode,\n"
6716     "    mtime,\n"
6717     "    CASE substr(lsmode(mode),1,1)\n"
6718     "      WHEN '-' THEN length(data)\n"
6719     "      WHEN 'd' THEN 0\n"
6720     "      ELSE -1 END,\n"
6721     "    sqlar_compress(data)\n"
6722     "  FROM fsdir(%Q,%Q) AS disk\n"
6723     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6724     ,
6725     "REPLACE INTO %s(name,mode,mtime,data)\n"
6726     "  SELECT\n"
6727     "    %s,\n"
6728     "    mode,\n"
6729     "    mtime,\n"
6730     "    data\n"
6731     "  FROM fsdir(%Q,%Q) AS disk\n"
6732     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6733  };
6734  int i;                          /* For iterating through azFile[] */
6735  int rc;                         /* Return code */
6736  const char *zTab = 0;           /* SQL table into which to insert */
6737  char *zSql;
6738  char zTemp[50];
6739  char *zExists = 0;
6740
6741  arExecSql(pAr, "PRAGMA page_size=512");
6742  rc = arExecSql(pAr, "SAVEPOINT ar;");
6743  if( rc!=SQLITE_OK ) return rc;
6744  zTemp[0] = 0;
6745  if( pAr->bZip ){
6746    /* Initialize the zipfile virtual table, if necessary */
6747    if( pAr->zFile ){
6748      sqlite3_uint64 r;
6749      sqlite3_randomness(sizeof(r),&r);
6750      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6751      zTab = zTemp;
6752      zSql = sqlite3_mprintf(
6753         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6754         zTab, pAr->zFile
6755      );
6756      rc = arExecSql(pAr, zSql);
6757      sqlite3_free(zSql);
6758    }else{
6759      zTab = "zip";
6760    }
6761  }else{
6762    /* Initialize the table for an SQLAR */
6763    zTab = "sqlar";
6764    if( bUpdate==0 ){
6765      rc = arExecSql(pAr, zDrop);
6766      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6767    }
6768    rc = arExecSql(pAr, zCreate);
6769  }
6770  if( bOnlyIfChanged ){
6771    zExists = sqlite3_mprintf(
6772      " AND NOT EXISTS("
6773          "SELECT 1 FROM %s AS mem"
6774          " WHERE mem.name=disk.name"
6775          " AND mem.mtime=disk.mtime"
6776          " AND mem.mode=disk.mode)", zTab);
6777  }else{
6778    zExists = sqlite3_mprintf("");
6779  }
6780  if( zExists==0 ) rc = SQLITE_NOMEM;
6781  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6782    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6783        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6784        pAr->azArg[i], pAr->zDir, zExists);
6785    rc = arExecSql(pAr, zSql2);
6786    sqlite3_free(zSql2);
6787  }
6788end_ar_transaction:
6789  if( rc!=SQLITE_OK ){
6790    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6791  }else{
6792    rc = arExecSql(pAr, "RELEASE ar;");
6793    if( pAr->bZip && pAr->zFile ){
6794      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6795      arExecSql(pAr, zSql);
6796      sqlite3_free(zSql);
6797    }
6798  }
6799  sqlite3_free(zExists);
6800  return rc;
6801}
6802
6803/*
6804** Implementation of ".ar" dot command.
6805*/
6806static int arDotCommand(
6807  ShellState *pState,          /* Current shell tool state */
6808  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
6809  char **azArg,                /* Array of arguments passed to dot command */
6810  int nArg                     /* Number of entries in azArg[] */
6811){
6812  ArCommand cmd;
6813  int rc;
6814  memset(&cmd, 0, sizeof(cmd));
6815  cmd.fromCmdLine = fromCmdLine;
6816  rc = arParseCommand(azArg, nArg, &cmd);
6817  if( rc==SQLITE_OK ){
6818    int eDbType = SHELL_OPEN_UNSPEC;
6819    cmd.p = pState;
6820    cmd.db = pState->db;
6821    if( cmd.zFile ){
6822      eDbType = deduceDatabaseType(cmd.zFile, 1);
6823    }else{
6824      eDbType = pState->openMode;
6825    }
6826    if( eDbType==SHELL_OPEN_ZIPFILE ){
6827      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6828        if( cmd.zFile==0 ){
6829          cmd.zSrcTable = sqlite3_mprintf("zip");
6830        }else{
6831          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6832        }
6833      }
6834      cmd.bZip = 1;
6835    }else if( cmd.zFile ){
6836      int flags;
6837      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6838      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6839           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
6840        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6841      }else{
6842        flags = SQLITE_OPEN_READONLY;
6843      }
6844      cmd.db = 0;
6845      if( cmd.bDryRun ){
6846        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6847             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6848      }
6849      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6850             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6851      if( rc!=SQLITE_OK ){
6852        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6853            cmd.zFile, sqlite3_errmsg(cmd.db)
6854        );
6855        goto end_ar_command;
6856      }
6857      sqlite3_fileio_init(cmd.db, 0, 0);
6858      sqlite3_sqlar_init(cmd.db, 0, 0);
6859      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6860                              shellPutsFunc, 0, 0);
6861
6862    }
6863    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6864      if( cmd.eCmd!=AR_CMD_CREATE
6865       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6866      ){
6867        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6868        rc = SQLITE_ERROR;
6869        goto end_ar_command;
6870      }
6871      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6872    }
6873
6874    switch( cmd.eCmd ){
6875      case AR_CMD_CREATE:
6876        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6877        break;
6878
6879      case AR_CMD_EXTRACT:
6880        rc = arExtractCommand(&cmd);
6881        break;
6882
6883      case AR_CMD_LIST:
6884        rc = arListCommand(&cmd);
6885        break;
6886
6887      case AR_CMD_HELP:
6888        arUsage(pState->out);
6889        break;
6890
6891      case AR_CMD_INSERT:
6892        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6893        break;
6894
6895      case AR_CMD_REMOVE:
6896        rc = arRemoveCommand(&cmd);
6897        break;
6898
6899      default:
6900        assert( cmd.eCmd==AR_CMD_UPDATE );
6901        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6902        break;
6903    }
6904  }
6905end_ar_command:
6906  if( cmd.db!=pState->db ){
6907    close_db(cmd.db);
6908  }
6909  sqlite3_free(cmd.zSrcTable);
6910
6911  return rc;
6912}
6913/* End of the ".archive" or ".ar" command logic
6914*******************************************************************************/
6915#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6916
6917#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6918/*
6919** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6920** Otherwise, the SQL statement or statements in zSql are executed using
6921** database connection db and the error code written to *pRc before
6922** this function returns.
6923*/
6924static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6925  int rc = *pRc;
6926  if( rc==SQLITE_OK ){
6927    char *zErr = 0;
6928    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6929    if( rc!=SQLITE_OK ){
6930      raw_printf(stderr, "SQL error: %s\n", zErr);
6931    }
6932    sqlite3_free(zErr);
6933    *pRc = rc;
6934  }
6935}
6936
6937/*
6938** Like shellExec(), except that zFmt is a printf() style format string.
6939*/
6940static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6941  char *z = 0;
6942  if( *pRc==SQLITE_OK ){
6943    va_list ap;
6944    va_start(ap, zFmt);
6945    z = sqlite3_vmprintf(zFmt, ap);
6946    va_end(ap);
6947    if( z==0 ){
6948      *pRc = SQLITE_NOMEM;
6949    }else{
6950      shellExec(db, pRc, z);
6951    }
6952    sqlite3_free(z);
6953  }
6954}
6955
6956/*
6957** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6958** Otherwise, an attempt is made to allocate, zero and return a pointer
6959** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6960** to SQLITE_NOMEM and NULL returned.
6961*/
6962static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6963  void *pRet = 0;
6964  if( *pRc==SQLITE_OK ){
6965    pRet = sqlite3_malloc64(nByte);
6966    if( pRet==0 ){
6967      *pRc = SQLITE_NOMEM;
6968    }else{
6969      memset(pRet, 0, nByte);
6970    }
6971  }
6972  return pRet;
6973}
6974
6975/*
6976** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6977** Otherwise, zFmt is treated as a printf() style string. The result of
6978** formatting it along with any trailing arguments is written into a
6979** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6980** It is the responsibility of the caller to eventually free this buffer
6981** using a call to sqlite3_free().
6982**
6983** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6984** pointer returned.
6985*/
6986static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6987  char *z = 0;
6988  if( *pRc==SQLITE_OK ){
6989    va_list ap;
6990    va_start(ap, zFmt);
6991    z = sqlite3_vmprintf(zFmt, ap);
6992    va_end(ap);
6993    if( z==0 ){
6994      *pRc = SQLITE_NOMEM;
6995    }
6996  }
6997  return z;
6998}
6999
7000/*
7001** When running the ".recover" command, each output table, and the special
7002** orphaned row table if it is required, is represented by an instance
7003** of the following struct.
7004*/
7005typedef struct RecoverTable RecoverTable;
7006struct RecoverTable {
7007  char *zQuoted;                  /* Quoted version of table name */
7008  int nCol;                       /* Number of columns in table */
7009  char **azlCol;                  /* Array of column lists */
7010  int iPk;                        /* Index of IPK column */
7011};
7012
7013/*
7014** Free a RecoverTable object allocated by recoverFindTable() or
7015** recoverOrphanTable().
7016*/
7017static void recoverFreeTable(RecoverTable *pTab){
7018  if( pTab ){
7019    sqlite3_free(pTab->zQuoted);
7020    if( pTab->azlCol ){
7021      int i;
7022      for(i=0; i<=pTab->nCol; i++){
7023        sqlite3_free(pTab->azlCol[i]);
7024      }
7025      sqlite3_free(pTab->azlCol);
7026    }
7027    sqlite3_free(pTab);
7028  }
7029}
7030
7031/*
7032** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7033** Otherwise, it allocates and returns a RecoverTable object based on the
7034** final four arguments passed to this function. It is the responsibility
7035** of the caller to eventually free the returned object using
7036** recoverFreeTable().
7037*/
7038static RecoverTable *recoverNewTable(
7039  int *pRc,                       /* IN/OUT: Error code */
7040  const char *zName,              /* Name of table */
7041  const char *zSql,               /* CREATE TABLE statement */
7042  int bIntkey,
7043  int nCol
7044){
7045  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7046  int rc = *pRc;
7047  RecoverTable *pTab = 0;
7048
7049  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7050  if( rc==SQLITE_OK ){
7051    int nSqlCol = 0;
7052    int bSqlIntkey = 0;
7053    sqlite3_stmt *pStmt = 0;
7054
7055    rc = sqlite3_open("", &dbtmp);
7056    if( rc==SQLITE_OK ){
7057      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7058                              shellIdQuote, 0, 0);
7059    }
7060    if( rc==SQLITE_OK ){
7061      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7062    }
7063    if( rc==SQLITE_OK ){
7064      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7065      if( rc==SQLITE_ERROR ){
7066        rc = SQLITE_OK;
7067        goto finished;
7068      }
7069    }
7070    shellPreparePrintf(dbtmp, &rc, &pStmt,
7071        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7072    );
7073    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7074      nSqlCol = sqlite3_column_int(pStmt, 0);
7075    }
7076    shellFinalize(&rc, pStmt);
7077
7078    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7079      goto finished;
7080    }
7081
7082    shellPreparePrintf(dbtmp, &rc, &pStmt,
7083      "SELECT ("
7084      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7085      ") FROM sqlite_schema WHERE name = %Q", zName
7086    );
7087    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7088      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7089    }
7090    shellFinalize(&rc, pStmt);
7091
7092    if( bIntkey==bSqlIntkey ){
7093      int i;
7094      const char *zPk = "_rowid_";
7095      sqlite3_stmt *pPkFinder = 0;
7096
7097      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7098      ** set zPk to the name of the PK column, and pTab->iPk to the index
7099      ** of the column, where columns are 0-numbered from left to right.
7100      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7101      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7102      pTab->iPk = -2;
7103      if( bIntkey ){
7104        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7105          "SELECT cid, name FROM pragma_table_info(%Q) "
7106          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7107          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7108          , zName, zName
7109        );
7110        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7111          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7112          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7113        }
7114      }
7115
7116      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7117      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7118      pTab->nCol = nSqlCol;
7119
7120      if( bIntkey ){
7121        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7122      }else{
7123        pTab->azlCol[0] = shellMPrintf(&rc, "");
7124      }
7125      i = 1;
7126      shellPreparePrintf(dbtmp, &rc, &pStmt,
7127          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7128          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7129          "FROM pragma_table_info(%Q)",
7130          bIntkey ? ", " : "", pTab->iPk,
7131          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7132          zName
7133      );
7134      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7135        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7136        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7137        i++;
7138      }
7139      shellFinalize(&rc, pStmt);
7140
7141      shellFinalize(&rc, pPkFinder);
7142    }
7143  }
7144
7145 finished:
7146  sqlite3_close(dbtmp);
7147  *pRc = rc;
7148  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7149    recoverFreeTable(pTab);
7150    pTab = 0;
7151  }
7152  return pTab;
7153}
7154
7155/*
7156** This function is called to search the schema recovered from the
7157** sqlite_schema table of the (possibly) corrupt database as part
7158** of a ".recover" command. Specifically, for a table with root page
7159** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7160** table must be a WITHOUT ROWID table, or if non-zero, not one of
7161** those.
7162**
7163** If a table is found, a (RecoverTable*) object is returned. Or, if
7164** no such table is found, but bIntkey is false and iRoot is the
7165** root page of an index in the recovered schema, then (*pbNoop) is
7166** set to true and NULL returned. Or, if there is no such table or
7167** index, NULL is returned and (*pbNoop) set to 0, indicating that
7168** the caller should write data to the orphans table.
7169*/
7170static RecoverTable *recoverFindTable(
7171  ShellState *pState,             /* Shell state object */
7172  int *pRc,                       /* IN/OUT: Error code */
7173  int iRoot,                      /* Root page of table */
7174  int bIntkey,                    /* True for an intkey table */
7175  int nCol,                       /* Number of columns in table */
7176  int *pbNoop                     /* OUT: True if iRoot is root of index */
7177){
7178  sqlite3_stmt *pStmt = 0;
7179  RecoverTable *pRet = 0;
7180  int bNoop = 0;
7181  const char *zSql = 0;
7182  const char *zName = 0;
7183
7184  /* Search the recovered schema for an object with root page iRoot. */
7185  shellPreparePrintf(pState->db, pRc, &pStmt,
7186      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7187  );
7188  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7189    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7190    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7191      bNoop = 1;
7192      break;
7193    }
7194    if( sqlite3_stricmp(zType, "table")==0 ){
7195      zName = (const char*)sqlite3_column_text(pStmt, 1);
7196      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7197      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7198      break;
7199    }
7200  }
7201
7202  shellFinalize(pRc, pStmt);
7203  *pbNoop = bNoop;
7204  return pRet;
7205}
7206
7207/*
7208** Return a RecoverTable object representing the orphans table.
7209*/
7210static RecoverTable *recoverOrphanTable(
7211  ShellState *pState,             /* Shell state object */
7212  int *pRc,                       /* IN/OUT: Error code */
7213  const char *zLostAndFound,      /* Base name for orphans table */
7214  int nCol                        /* Number of user data columns */
7215){
7216  RecoverTable *pTab = 0;
7217  if( nCol>=0 && *pRc==SQLITE_OK ){
7218    int i;
7219
7220    /* This block determines the name of the orphan table. The prefered
7221    ** name is zLostAndFound. But if that clashes with another name
7222    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7223    ** and so on until a non-clashing name is found.  */
7224    int iTab = 0;
7225    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7226    sqlite3_stmt *pTest = 0;
7227    shellPrepare(pState->db, pRc,
7228        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7229    );
7230    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7231    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7232      shellReset(pRc, pTest);
7233      sqlite3_free(zTab);
7234      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7235      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7236    }
7237    shellFinalize(pRc, pTest);
7238
7239    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7240    if( pTab ){
7241      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7242      pTab->nCol = nCol;
7243      pTab->iPk = -2;
7244      if( nCol>0 ){
7245        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7246        if( pTab->azlCol ){
7247          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7248          for(i=nCol-1; i>=0; i--){
7249            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7250          }
7251        }
7252      }
7253
7254      if( *pRc!=SQLITE_OK ){
7255        recoverFreeTable(pTab);
7256        pTab = 0;
7257      }else{
7258        raw_printf(pState->out,
7259            "CREATE TABLE %s(rootpgno INTEGER, "
7260            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7261        );
7262        for(i=0; i<nCol; i++){
7263          raw_printf(pState->out, ", c%d", i);
7264        }
7265        raw_printf(pState->out, ");\n");
7266      }
7267    }
7268    sqlite3_free(zTab);
7269  }
7270  return pTab;
7271}
7272
7273/*
7274** This function is called to recover data from the database. A script
7275** to construct a new database containing all recovered data is output
7276** on stream pState->out.
7277*/
7278static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7279  int rc = SQLITE_OK;
7280  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7281  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7282  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7283  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7284  const char *zLostAndFound = "lost_and_found";
7285  int i;
7286  int nOrphan = -1;
7287  RecoverTable *pOrphan = 0;
7288
7289  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7290  int bRowids = 1;                /* 0 if --no-rowids */
7291  for(i=1; i<nArg; i++){
7292    char *z = azArg[i];
7293    int n;
7294    if( z[0]=='-' && z[1]=='-' ) z++;
7295    n = strlen30(z);
7296    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7297      bFreelist = 0;
7298    }else
7299    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7300      i++;
7301      zRecoveryDb = azArg[i];
7302    }else
7303    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7304      i++;
7305      zLostAndFound = azArg[i];
7306    }else
7307    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7308      bRowids = 0;
7309    }
7310    else{
7311      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7312      showHelp(pState->out, azArg[0]);
7313      return 1;
7314    }
7315  }
7316
7317  shellExecPrintf(pState->db, &rc,
7318    /* Attach an in-memory database named 'recovery'. Create an indexed
7319    ** cache of the sqlite_dbptr virtual table. */
7320    "PRAGMA writable_schema = on;"
7321    "ATTACH %Q AS recovery;"
7322    "DROP TABLE IF EXISTS recovery.dbptr;"
7323    "DROP TABLE IF EXISTS recovery.freelist;"
7324    "DROP TABLE IF EXISTS recovery.map;"
7325    "DROP TABLE IF EXISTS recovery.schema;"
7326    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7327  );
7328
7329  if( bFreelist ){
7330    shellExec(pState->db, &rc,
7331      "WITH trunk(pgno) AS ("
7332      "  SELECT shell_int32("
7333      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7334      "      WHERE x>0"
7335      "    UNION"
7336      "  SELECT shell_int32("
7337      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7338      "      FROM trunk WHERE x>0"
7339      "),"
7340      "freelist(data, n, freepgno) AS ("
7341      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7342      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7343      "    UNION ALL"
7344      "  SELECT data, n-1, shell_int32(data, 2+n) "
7345      "      FROM freelist WHERE n>=0"
7346      ")"
7347      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7348    );
7349  }
7350
7351  /* If this is an auto-vacuum database, add all pointer-map pages to
7352  ** the freelist table. Do this regardless of whether or not
7353  ** --freelist-corrupt was specified.  */
7354  shellExec(pState->db, &rc,
7355    "WITH ptrmap(pgno) AS ("
7356    "  SELECT 2 WHERE shell_int32("
7357    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7358    "  )"
7359    "    UNION ALL "
7360    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7361    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7362    ")"
7363    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7364  );
7365
7366  shellExec(pState->db, &rc,
7367    "CREATE TABLE recovery.dbptr("
7368    "      pgno, child, PRIMARY KEY(child, pgno)"
7369    ") WITHOUT ROWID;"
7370    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7371    "    SELECT * FROM sqlite_dbptr"
7372    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7373
7374    /* Delete any pointer to page 1. This ensures that page 1 is considered
7375    ** a root page, regardless of how corrupt the db is. */
7376    "DELETE FROM recovery.dbptr WHERE child = 1;"
7377
7378    /* Delete all pointers to any pages that have more than one pointer
7379    ** to them. Such pages will be treated as root pages when recovering
7380    ** data.  */
7381    "DELETE FROM recovery.dbptr WHERE child IN ("
7382    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7383    ");"
7384
7385    /* Create the "map" table that will (eventually) contain instructions
7386    ** for dealing with each page in the db that contains one or more
7387    ** records. */
7388    "CREATE TABLE recovery.map("
7389      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7390    ");"
7391
7392    /* Populate table [map]. If there are circular loops of pages in the
7393    ** database, the following adds all pages in such a loop to the map
7394    ** as individual root pages. This could be handled better.  */
7395    "WITH pages(i, maxlen) AS ("
7396    "  SELECT page_count, ("
7397    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7398    "  ) FROM pragma_page_count WHERE page_count>0"
7399    "    UNION ALL"
7400    "  SELECT i-1, ("
7401    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7402    "  ) FROM pages WHERE i>=2"
7403    ")"
7404    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7405    "  SELECT i, maxlen, NULL, ("
7406    "    WITH p(orig, pgno, parent) AS ("
7407    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7408    "        UNION "
7409    "      SELECT i, p.parent, "
7410    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7411    "    )"
7412    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7413    ") "
7414    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7415    "UPDATE recovery.map AS o SET intkey = ("
7416    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7417    ");"
7418
7419    /* Extract data from page 1 and any linked pages into table
7420    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7421    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7422    "INSERT INTO recovery.schema SELECT "
7423    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7424    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7425    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7426    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7427    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7428    "FROM sqlite_dbdata WHERE pgno IN ("
7429    "  SELECT pgno FROM recovery.map WHERE root=1"
7430    ")"
7431    "GROUP BY pgno, cell;"
7432    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7433  );
7434
7435  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7436  ** CREATE TABLE statements that extracted from the existing schema.  */
7437  if( rc==SQLITE_OK ){
7438    sqlite3_stmt *pStmt = 0;
7439    /* ".recover" might output content in an order which causes immediate
7440    ** foreign key constraints to be violated. So disable foreign-key
7441    ** constraint enforcement to prevent problems when running the output
7442    ** script. */
7443    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7444    raw_printf(pState->out, "BEGIN;\n");
7445    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7446    shellPrepare(pState->db, &rc,
7447        "SELECT sql FROM recovery.schema "
7448        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7449    );
7450    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7451      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7452      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7453          &zCreateTable[12]
7454      );
7455    }
7456    shellFinalize(&rc, pStmt);
7457  }
7458
7459  /* Figure out if an orphan table will be required. And if so, how many
7460  ** user columns it should contain */
7461  shellPrepare(pState->db, &rc,
7462      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7463      , &pLoop
7464  );
7465  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7466    nOrphan = sqlite3_column_int(pLoop, 0);
7467  }
7468  shellFinalize(&rc, pLoop);
7469  pLoop = 0;
7470
7471  shellPrepare(pState->db, &rc,
7472      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7473  );
7474
7475  shellPrepare(pState->db, &rc,
7476      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7477      "(case when (? AND field<0) then NULL else value end)"
7478      "), ', ')"
7479      ", min(field) "
7480      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7481      "GROUP BY cell", &pCells
7482  );
7483
7484  /* Loop through each root page. */
7485  shellPrepare(pState->db, &rc,
7486      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7487      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7488      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7489      ")", &pLoop
7490  );
7491  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7492    int iRoot = sqlite3_column_int(pLoop, 0);
7493    int bIntkey = sqlite3_column_int(pLoop, 1);
7494    int nCol = sqlite3_column_int(pLoop, 2);
7495    int bNoop = 0;
7496    RecoverTable *pTab;
7497
7498    assert( bIntkey==0 || bIntkey==1 );
7499    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7500    if( bNoop || rc ) continue;
7501    if( pTab==0 ){
7502      if( pOrphan==0 ){
7503        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7504      }
7505      pTab = pOrphan;
7506      if( pTab==0 ) break;
7507    }
7508
7509    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7510      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7511    }
7512    sqlite3_bind_int(pPages, 1, iRoot);
7513    if( bRowids==0 && pTab->iPk<0 ){
7514      sqlite3_bind_int(pCells, 1, 1);
7515    }else{
7516      sqlite3_bind_int(pCells, 1, 0);
7517    }
7518    sqlite3_bind_int(pCells, 3, pTab->iPk);
7519
7520    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7521      int iPgno = sqlite3_column_int(pPages, 0);
7522      sqlite3_bind_int(pCells, 2, iPgno);
7523      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7524        int nField = sqlite3_column_int(pCells, 0);
7525        int iMin = sqlite3_column_int(pCells, 2);
7526        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7527
7528        RecoverTable *pTab2 = pTab;
7529        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7530          if( pOrphan==0 ){
7531            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7532          }
7533          pTab2 = pOrphan;
7534          if( pTab2==0 ) break;
7535        }
7536
7537        nField = nField+1;
7538        if( pTab2==pOrphan ){
7539          raw_printf(pState->out,
7540              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7541              pTab2->zQuoted, iRoot, iPgno, nField,
7542              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7543          );
7544        }else{
7545          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7546              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7547          );
7548        }
7549      }
7550      shellReset(&rc, pCells);
7551    }
7552    shellReset(&rc, pPages);
7553    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7554  }
7555  shellFinalize(&rc, pLoop);
7556  shellFinalize(&rc, pPages);
7557  shellFinalize(&rc, pCells);
7558  recoverFreeTable(pOrphan);
7559
7560  /* The rest of the schema */
7561  if( rc==SQLITE_OK ){
7562    sqlite3_stmt *pStmt = 0;
7563    shellPrepare(pState->db, &rc,
7564        "SELECT sql, name FROM recovery.schema "
7565        "WHERE sql NOT LIKE 'create table%'", &pStmt
7566    );
7567    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7568      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7569      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7570        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7571        char *zPrint = shellMPrintf(&rc,
7572          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7573          zName, zName, zSql
7574        );
7575        raw_printf(pState->out, "%s;\n", zPrint);
7576        sqlite3_free(zPrint);
7577      }else{
7578        raw_printf(pState->out, "%s;\n", zSql);
7579      }
7580    }
7581    shellFinalize(&rc, pStmt);
7582  }
7583
7584  if( rc==SQLITE_OK ){
7585    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7586    raw_printf(pState->out, "COMMIT;\n");
7587  }
7588  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7589  return rc;
7590}
7591#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7592
7593/*
7594** If an input line begins with "." then invoke this routine to
7595** process that line.
7596**
7597** Return 1 on error, 2 to exit, and 0 otherwise.
7598*/
7599static int do_meta_command(char *zLine, ShellState *p){
7600  int h = 1;
7601  int nArg = 0;
7602  int n, c;
7603  int rc = 0;
7604  char *azArg[52];
7605
7606#ifndef SQLITE_OMIT_VIRTUALTABLE
7607  if( p->expert.pExpert ){
7608    expertFinish(p, 1, 0);
7609  }
7610#endif
7611
7612  /* Parse the input line into tokens.
7613  */
7614  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7615    while( IsSpace(zLine[h]) ){ h++; }
7616    if( zLine[h]==0 ) break;
7617    if( zLine[h]=='\'' || zLine[h]=='"' ){
7618      int delim = zLine[h++];
7619      azArg[nArg++] = &zLine[h];
7620      while( zLine[h] && zLine[h]!=delim ){
7621        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7622        h++;
7623      }
7624      if( zLine[h]==delim ){
7625        zLine[h++] = 0;
7626      }
7627      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7628    }else{
7629      azArg[nArg++] = &zLine[h];
7630      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7631      if( zLine[h] ) zLine[h++] = 0;
7632      resolve_backslashes(azArg[nArg-1]);
7633    }
7634  }
7635  azArg[nArg] = 0;
7636
7637  /* Process the input line.
7638  */
7639  if( nArg==0 ) return 0; /* no tokens, no error */
7640  n = strlen30(azArg[0]);
7641  c = azArg[0][0];
7642  clearTempFile(p);
7643
7644#ifndef SQLITE_OMIT_AUTHORIZATION
7645  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7646    if( nArg!=2 ){
7647      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7648      rc = 1;
7649      goto meta_command_exit;
7650    }
7651    open_db(p, 0);
7652    if( booleanValue(azArg[1]) ){
7653      sqlite3_set_authorizer(p->db, shellAuth, p);
7654    }else if( p->bSafeModePersist ){
7655      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7656    }else{
7657      sqlite3_set_authorizer(p->db, 0, 0);
7658    }
7659  }else
7660#endif
7661
7662#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7663  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7664    open_db(p, 0);
7665    failIfSafeMode(p, "cannot run .archive in safe mode");
7666    rc = arDotCommand(p, 0, azArg, nArg);
7667  }else
7668#endif
7669
7670  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7671   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7672  ){
7673    const char *zDestFile = 0;
7674    const char *zDb = 0;
7675    sqlite3 *pDest;
7676    sqlite3_backup *pBackup;
7677    int j;
7678    int bAsync = 0;
7679    const char *zVfs = 0;
7680    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7681    for(j=1; j<nArg; j++){
7682      const char *z = azArg[j];
7683      if( z[0]=='-' ){
7684        if( z[1]=='-' ) z++;
7685        if( strcmp(z, "-append")==0 ){
7686          zVfs = "apndvfs";
7687        }else
7688        if( strcmp(z, "-async")==0 ){
7689          bAsync = 1;
7690        }else
7691        {
7692          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7693          return 1;
7694        }
7695      }else if( zDestFile==0 ){
7696        zDestFile = azArg[j];
7697      }else if( zDb==0 ){
7698        zDb = zDestFile;
7699        zDestFile = azArg[j];
7700      }else{
7701        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7702        return 1;
7703      }
7704    }
7705    if( zDestFile==0 ){
7706      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7707      return 1;
7708    }
7709    if( zDb==0 ) zDb = "main";
7710    rc = sqlite3_open_v2(zDestFile, &pDest,
7711                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7712    if( rc!=SQLITE_OK ){
7713      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7714      close_db(pDest);
7715      return 1;
7716    }
7717    if( bAsync ){
7718      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7719                   0, 0, 0);
7720    }
7721    open_db(p, 0);
7722    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7723    if( pBackup==0 ){
7724      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7725      close_db(pDest);
7726      return 1;
7727    }
7728    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7729    sqlite3_backup_finish(pBackup);
7730    if( rc==SQLITE_DONE ){
7731      rc = 0;
7732    }else{
7733      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7734      rc = 1;
7735    }
7736    close_db(pDest);
7737  }else
7738
7739  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7740    if( nArg==2 ){
7741      bail_on_error = booleanValue(azArg[1]);
7742    }else{
7743      raw_printf(stderr, "Usage: .bail on|off\n");
7744      rc = 1;
7745    }
7746  }else
7747
7748  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7749    if( nArg==2 ){
7750      if( booleanValue(azArg[1]) ){
7751        setBinaryMode(p->out, 1);
7752      }else{
7753        setTextMode(p->out, 1);
7754      }
7755    }else{
7756      raw_printf(stderr, "Usage: .binary on|off\n");
7757      rc = 1;
7758    }
7759  }else
7760
7761  /* The undocumented ".breakpoint" command causes a call to the no-op
7762  ** routine named test_breakpoint().
7763  */
7764  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7765    test_breakpoint();
7766  }else
7767
7768  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7769    failIfSafeMode(p, "cannot run .cd in safe mode");
7770    if( nArg==2 ){
7771#if defined(_WIN32) || defined(WIN32)
7772      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7773      rc = !SetCurrentDirectoryW(z);
7774      sqlite3_free(z);
7775#else
7776      rc = chdir(azArg[1]);
7777#endif
7778      if( rc ){
7779        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7780        rc = 1;
7781      }
7782    }else{
7783      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7784      rc = 1;
7785    }
7786  }else
7787
7788  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7789    if( nArg==2 ){
7790      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7791    }else{
7792      raw_printf(stderr, "Usage: .changes on|off\n");
7793      rc = 1;
7794    }
7795  }else
7796
7797  /* Cancel output redirection, if it is currently set (by .testcase)
7798  ** Then read the content of the testcase-out.txt file and compare against
7799  ** azArg[1].  If there are differences, report an error and exit.
7800  */
7801  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7802    char *zRes = 0;
7803    output_reset(p);
7804    if( nArg!=2 ){
7805      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7806      rc = 2;
7807    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7808      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7809      rc = 2;
7810    }else if( testcase_glob(azArg[1],zRes)==0 ){
7811      utf8_printf(stderr,
7812                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7813                 p->zTestcase, azArg[1], zRes);
7814      rc = 1;
7815    }else{
7816      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7817      p->nCheck++;
7818    }
7819    sqlite3_free(zRes);
7820  }else
7821
7822  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7823    failIfSafeMode(p, "cannot run .clone in safe mode");
7824    if( nArg==2 ){
7825      tryToClone(p, azArg[1]);
7826    }else{
7827      raw_printf(stderr, "Usage: .clone FILENAME\n");
7828      rc = 1;
7829    }
7830  }else
7831
7832  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
7833    if( nArg==1 ){
7834      /* List available connections */
7835      int i;
7836      for(i=0; i<ArraySize(p->aAuxDb); i++){
7837        const char *zFile = p->aAuxDb[i].zDbFilename;
7838        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7839          zFile = "(not open)";
7840        }else if( zFile==0 ){
7841          zFile = "(memory)";
7842        }else if( zFile[0]==0 ){
7843          zFile = "(temporary-file)";
7844        }
7845        if( p->pAuxDb == &p->aAuxDb[i] ){
7846          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7847        }else if( p->aAuxDb[i].db!=0 ){
7848          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7849        }
7850      }
7851    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7852      int i = azArg[1][0] - '0';
7853      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7854        p->pAuxDb->db = p->db;
7855        p->pAuxDb = &p->aAuxDb[i];
7856        globalDb = p->db = p->pAuxDb->db;
7857        p->pAuxDb->db = 0;
7858      }
7859    }else if( nArg==3 && strcmp(azArg[1], "close")==0
7860           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7861      int i = azArg[2][0] - '0';
7862      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7863        /* No-op */
7864      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7865        raw_printf(stderr, "cannot close the active database connection\n");
7866        rc = 1;
7867      }else if( p->aAuxDb[i].db ){
7868        session_close_all(p, i);
7869        close_db(p->aAuxDb[i].db);
7870        p->aAuxDb[i].db = 0;
7871      }
7872    }else{
7873      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7874      rc = 1;
7875    }
7876  }else
7877
7878  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7879    char **azName = 0;
7880    int nName = 0;
7881    sqlite3_stmt *pStmt;
7882    int i;
7883    open_db(p, 0);
7884    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7885    if( rc ){
7886      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7887      rc = 1;
7888    }else{
7889      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7890        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7891        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7892        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7893        shell_check_oom(azName);
7894        azName[nName*2] = strdup(zSchema);
7895        azName[nName*2+1] = strdup(zFile);
7896        nName++;
7897      }
7898    }
7899    sqlite3_finalize(pStmt);
7900    for(i=0; i<nName; i++){
7901      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7902      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7903      const char *z = azName[i*2+1];
7904      utf8_printf(p->out, "%s: %s %s%s\n",
7905         azName[i*2],
7906         z && z[0] ? z : "\"\"",
7907         bRdonly ? "r/o" : "r/w",
7908         eTxn==SQLITE_TXN_NONE ? "" :
7909            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7910      free(azName[i*2]);
7911      free(azName[i*2+1]);
7912    }
7913    sqlite3_free(azName);
7914  }else
7915
7916  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7917    static const struct DbConfigChoices {
7918      const char *zName;
7919      int op;
7920    } aDbConfig[] = {
7921        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7922        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7923        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7924        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7925        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7926        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7927        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7928        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7929        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7930        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7931        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7932        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7933        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7934        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7935        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7936        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7937    };
7938    int ii, v;
7939    open_db(p, 0);
7940    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7941      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7942      if( nArg>=3 ){
7943        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7944      }
7945      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7946      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7947      if( nArg>1 ) break;
7948    }
7949    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7950      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7951      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7952    }
7953  }else
7954
7955  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7956    rc = shell_dbinfo_command(p, nArg, azArg);
7957  }else
7958
7959#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7960  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7961    open_db(p, 0);
7962    rc = recoverDatabaseCmd(p, nArg, azArg);
7963  }else
7964#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7965
7966  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7967    char *zLike = 0;
7968    char *zSql;
7969    int i;
7970    int savedShowHeader = p->showHeader;
7971    int savedShellFlags = p->shellFlgs;
7972    ShellClearFlag(p,
7973       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7974       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7975    for(i=1; i<nArg; i++){
7976      if( azArg[i][0]=='-' ){
7977        const char *z = azArg[i]+1;
7978        if( z[0]=='-' ) z++;
7979        if( strcmp(z,"preserve-rowids")==0 ){
7980#ifdef SQLITE_OMIT_VIRTUALTABLE
7981          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7982                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7983          rc = 1;
7984          sqlite3_free(zLike);
7985          goto meta_command_exit;
7986#else
7987          ShellSetFlag(p, SHFLG_PreserveRowid);
7988#endif
7989        }else
7990        if( strcmp(z,"newlines")==0 ){
7991          ShellSetFlag(p, SHFLG_Newlines);
7992        }else
7993        if( strcmp(z,"data-only")==0 ){
7994          ShellSetFlag(p, SHFLG_DumpDataOnly);
7995        }else
7996        if( strcmp(z,"nosys")==0 ){
7997          ShellSetFlag(p, SHFLG_DumpNoSys);
7998        }else
7999        {
8000          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8001          rc = 1;
8002          sqlite3_free(zLike);
8003          goto meta_command_exit;
8004        }
8005      }else{
8006        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8007        ** only dump data for tables for which either the table name matches
8008        ** the LIKE pattern, or the table appears to be a shadow table of
8009        ** a virtual table for which the name matches the LIKE pattern.
8010        */
8011        char *zExpr = sqlite3_mprintf(
8012            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8013            "  SELECT 1 FROM sqlite_schema WHERE "
8014            "    name LIKE %Q ESCAPE '\\' AND"
8015            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8016            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8017            ")", azArg[i], azArg[i]
8018        );
8019
8020        if( zLike ){
8021          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8022        }else{
8023          zLike = zExpr;
8024        }
8025      }
8026    }
8027
8028    open_db(p, 0);
8029
8030    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8031      /* When playing back a "dump", the content might appear in an order
8032      ** which causes immediate foreign key constraints to be violated.
8033      ** So disable foreign-key constraint enforcement to prevent problems. */
8034      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8035      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8036    }
8037    p->writableSchema = 0;
8038    p->showHeader = 0;
8039    /* Set writable_schema=ON since doing so forces SQLite to initialize
8040    ** as much of the schema as it can even if the sqlite_schema table is
8041    ** corrupt. */
8042    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8043    p->nErr = 0;
8044    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8045    zSql = sqlite3_mprintf(
8046      "SELECT name, type, sql FROM sqlite_schema AS o "
8047      "WHERE (%s) AND type=='table'"
8048      "  AND sql NOT NULL"
8049      " ORDER BY tbl_name='sqlite_sequence', rowid",
8050      zLike
8051    );
8052    run_schema_dump_query(p,zSql);
8053    sqlite3_free(zSql);
8054    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8055      zSql = sqlite3_mprintf(
8056        "SELECT sql FROM sqlite_schema AS o "
8057        "WHERE (%s) AND sql NOT NULL"
8058        "  AND type IN ('index','trigger','view')",
8059        zLike
8060      );
8061      run_table_dump_query(p, zSql);
8062      sqlite3_free(zSql);
8063    }
8064    sqlite3_free(zLike);
8065    if( p->writableSchema ){
8066      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8067      p->writableSchema = 0;
8068    }
8069    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8070    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8071    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8072      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8073    }
8074    p->showHeader = savedShowHeader;
8075    p->shellFlgs = savedShellFlags;
8076  }else
8077
8078  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8079    if( nArg==2 ){
8080      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8081    }else{
8082      raw_printf(stderr, "Usage: .echo on|off\n");
8083      rc = 1;
8084    }
8085  }else
8086
8087  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8088    if( nArg==2 ){
8089      p->autoEQPtest = 0;
8090      if( p->autoEQPtrace ){
8091        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8092        p->autoEQPtrace = 0;
8093      }
8094      if( strcmp(azArg[1],"full")==0 ){
8095        p->autoEQP = AUTOEQP_full;
8096      }else if( strcmp(azArg[1],"trigger")==0 ){
8097        p->autoEQP = AUTOEQP_trigger;
8098#ifdef SQLITE_DEBUG
8099      }else if( strcmp(azArg[1],"test")==0 ){
8100        p->autoEQP = AUTOEQP_on;
8101        p->autoEQPtest = 1;
8102      }else if( strcmp(azArg[1],"trace")==0 ){
8103        p->autoEQP = AUTOEQP_full;
8104        p->autoEQPtrace = 1;
8105        open_db(p, 0);
8106        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8107        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8108#endif
8109      }else{
8110        p->autoEQP = (u8)booleanValue(azArg[1]);
8111      }
8112    }else{
8113      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8114      rc = 1;
8115    }
8116  }else
8117
8118  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8119    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8120    rc = 2;
8121  }else
8122
8123  /* The ".explain" command is automatic now.  It is largely pointless.  It
8124  ** retained purely for backwards compatibility */
8125  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8126    int val = 1;
8127    if( nArg>=2 ){
8128      if( strcmp(azArg[1],"auto")==0 ){
8129        val = 99;
8130      }else{
8131        val =  booleanValue(azArg[1]);
8132      }
8133    }
8134    if( val==1 && p->mode!=MODE_Explain ){
8135      p->normalMode = p->mode;
8136      p->mode = MODE_Explain;
8137      p->autoExplain = 0;
8138    }else if( val==0 ){
8139      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8140      p->autoExplain = 0;
8141    }else if( val==99 ){
8142      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8143      p->autoExplain = 1;
8144    }
8145  }else
8146
8147#ifndef SQLITE_OMIT_VIRTUALTABLE
8148  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8149    open_db(p, 0);
8150    expertDotCommand(p, azArg, nArg);
8151  }else
8152#endif
8153
8154  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8155    static const struct {
8156       const char *zCtrlName;   /* Name of a test-control option */
8157       int ctrlCode;            /* Integer code for that option */
8158       const char *zUsage;      /* Usage notes */
8159    } aCtrl[] = {
8160      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8161      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8162      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8163      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8164      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8165   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8166      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8167      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8168      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8169      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8170   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8171    };
8172    int filectrl = -1;
8173    int iCtrl = -1;
8174    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8175    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8176    int n2, i;
8177    const char *zCmd = 0;
8178    const char *zSchema = 0;
8179
8180    open_db(p, 0);
8181    zCmd = nArg>=2 ? azArg[1] : "help";
8182
8183    if( zCmd[0]=='-'
8184     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8185     && nArg>=4
8186    ){
8187      zSchema = azArg[2];
8188      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8189      nArg -= 2;
8190      zCmd = azArg[1];
8191    }
8192
8193    /* The argument can optionally begin with "-" or "--" */
8194    if( zCmd[0]=='-' && zCmd[1] ){
8195      zCmd++;
8196      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8197    }
8198
8199    /* --help lists all file-controls */
8200    if( strcmp(zCmd,"help")==0 ){
8201      utf8_printf(p->out, "Available file-controls:\n");
8202      for(i=0; i<ArraySize(aCtrl); i++){
8203        utf8_printf(p->out, "  .filectrl %s %s\n",
8204                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8205      }
8206      rc = 1;
8207      goto meta_command_exit;
8208    }
8209
8210    /* convert filectrl text option to value. allow any unique prefix
8211    ** of the option name, or a numerical value. */
8212    n2 = strlen30(zCmd);
8213    for(i=0; i<ArraySize(aCtrl); i++){
8214      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8215        if( filectrl<0 ){
8216          filectrl = aCtrl[i].ctrlCode;
8217          iCtrl = i;
8218        }else{
8219          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8220                              "Use \".filectrl --help\" for help\n", zCmd);
8221          rc = 1;
8222          goto meta_command_exit;
8223        }
8224      }
8225    }
8226    if( filectrl<0 ){
8227      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8228                         "Use \".filectrl --help\" for help\n", zCmd);
8229    }else{
8230      switch(filectrl){
8231        case SQLITE_FCNTL_SIZE_LIMIT: {
8232          if( nArg!=2 && nArg!=3 ) break;
8233          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8234          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8235          isOk = 1;
8236          break;
8237        }
8238        case SQLITE_FCNTL_LOCK_TIMEOUT:
8239        case SQLITE_FCNTL_CHUNK_SIZE: {
8240          int x;
8241          if( nArg!=3 ) break;
8242          x = (int)integerValue(azArg[2]);
8243          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8244          isOk = 2;
8245          break;
8246        }
8247        case SQLITE_FCNTL_PERSIST_WAL:
8248        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8249          int x;
8250          if( nArg!=2 && nArg!=3 ) break;
8251          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8252          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8253          iRes = x;
8254          isOk = 1;
8255          break;
8256        }
8257        case SQLITE_FCNTL_DATA_VERSION:
8258        case SQLITE_FCNTL_HAS_MOVED: {
8259          int x;
8260          if( nArg!=2 ) break;
8261          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8262          iRes = x;
8263          isOk = 1;
8264          break;
8265        }
8266        case SQLITE_FCNTL_TEMPFILENAME: {
8267          char *z = 0;
8268          if( nArg!=2 ) break;
8269          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8270          if( z ){
8271            utf8_printf(p->out, "%s\n", z);
8272            sqlite3_free(z);
8273          }
8274          isOk = 2;
8275          break;
8276        }
8277        case SQLITE_FCNTL_RESERVE_BYTES: {
8278          int x;
8279          if( nArg>=3 ){
8280            x = atoi(azArg[2]);
8281            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8282          }
8283          x = -1;
8284          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8285          utf8_printf(p->out,"%d\n", x);
8286          isOk = 2;
8287          break;
8288        }
8289      }
8290    }
8291    if( isOk==0 && iCtrl>=0 ){
8292      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8293      rc = 1;
8294    }else if( isOk==1 ){
8295      char zBuf[100];
8296      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8297      raw_printf(p->out, "%s\n", zBuf);
8298    }
8299  }else
8300
8301  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8302    ShellState data;
8303    int doStats = 0;
8304    memcpy(&data, p, sizeof(data));
8305    data.showHeader = 0;
8306    data.cMode = data.mode = MODE_Semi;
8307    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8308      data.cMode = data.mode = MODE_Pretty;
8309      nArg = 1;
8310    }
8311    if( nArg!=1 ){
8312      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8313      rc = 1;
8314      goto meta_command_exit;
8315    }
8316    open_db(p, 0);
8317    rc = sqlite3_exec(p->db,
8318       "SELECT sql FROM"
8319       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8320       "     FROM sqlite_schema UNION ALL"
8321       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8322       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8323       "ORDER BY x",
8324       callback, &data, 0
8325    );
8326    if( rc==SQLITE_OK ){
8327      sqlite3_stmt *pStmt;
8328      rc = sqlite3_prepare_v2(p->db,
8329               "SELECT rowid FROM sqlite_schema"
8330               " WHERE name GLOB 'sqlite_stat[134]'",
8331               -1, &pStmt, 0);
8332      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8333      sqlite3_finalize(pStmt);
8334    }
8335    if( doStats==0 ){
8336      raw_printf(p->out, "/* No STAT tables available */\n");
8337    }else{
8338      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8339      data.cMode = data.mode = MODE_Insert;
8340      data.zDestTable = "sqlite_stat1";
8341      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8342      data.zDestTable = "sqlite_stat4";
8343      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8344      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8345    }
8346  }else
8347
8348  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8349    if( nArg==2 ){
8350      p->showHeader = booleanValue(azArg[1]);
8351      p->shellFlgs |= SHFLG_HeaderSet;
8352    }else{
8353      raw_printf(stderr, "Usage: .headers on|off\n");
8354      rc = 1;
8355    }
8356  }else
8357
8358  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8359    if( nArg>=2 ){
8360      n = showHelp(p->out, azArg[1]);
8361      if( n==0 ){
8362        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8363      }
8364    }else{
8365      showHelp(p->out, 0);
8366    }
8367  }else
8368
8369  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8370    char *zTable = 0;           /* Insert data into this table */
8371    char *zFile = 0;            /* Name of file to extra content from */
8372    sqlite3_stmt *pStmt = NULL; /* A statement */
8373    int nCol;                   /* Number of columns in the table */
8374    int nByte;                  /* Number of bytes in an SQL string */
8375    int i, j;                   /* Loop counters */
8376    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8377    int nSep;                   /* Number of bytes in p->colSeparator[] */
8378    char *zSql;                 /* An SQL statement */
8379    ImportCtx sCtx;             /* Reader context */
8380    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8381    int eVerbose = 0;           /* Larger for more console output */
8382    int nSkip = 0;              /* Initial lines to skip */
8383    int useOutputMode = 1;      /* Use output mode to determine separators */
8384
8385    failIfSafeMode(p, "cannot run .import in safe mode");
8386    memset(&sCtx, 0, sizeof(sCtx));
8387    sCtx.z = sqlite3_malloc64(120);
8388    if( sCtx.z==0 ){
8389      import_cleanup(&sCtx);
8390      shell_out_of_memory();
8391    }
8392    if( p->mode==MODE_Ascii ){
8393      xRead = ascii_read_one_field;
8394    }else{
8395      xRead = csv_read_one_field;
8396    }
8397    for(i=1; i<nArg; i++){
8398      char *z = azArg[i];
8399      if( z[0]=='-' && z[1]=='-' ) z++;
8400      if( z[0]!='-' ){
8401        if( zFile==0 ){
8402          zFile = z;
8403        }else if( zTable==0 ){
8404          zTable = z;
8405        }else{
8406          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8407          showHelp(p->out, "import");
8408          rc = 1;
8409          goto meta_command_exit;
8410        }
8411      }else if( strcmp(z,"-v")==0 ){
8412        eVerbose++;
8413      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8414        nSkip = integerValue(azArg[++i]);
8415      }else if( strcmp(z,"-ascii")==0 ){
8416        sCtx.cColSep = SEP_Unit[0];
8417        sCtx.cRowSep = SEP_Record[0];
8418        xRead = ascii_read_one_field;
8419        useOutputMode = 0;
8420      }else if( strcmp(z,"-csv")==0 ){
8421        sCtx.cColSep = ',';
8422        sCtx.cRowSep = '\n';
8423        xRead = csv_read_one_field;
8424        useOutputMode = 0;
8425      }else{
8426        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8427        showHelp(p->out, "import");
8428        rc = 1;
8429        goto meta_command_exit;
8430      }
8431    }
8432    if( zTable==0 ){
8433      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8434                  zFile==0 ? "FILE" : "TABLE");
8435      showHelp(p->out, "import");
8436      rc = 1;
8437      goto meta_command_exit;
8438    }
8439    seenInterrupt = 0;
8440    open_db(p, 0);
8441    if( useOutputMode ){
8442      /* If neither the --csv or --ascii options are specified, then set
8443      ** the column and row separator characters from the output mode. */
8444      nSep = strlen30(p->colSeparator);
8445      if( nSep==0 ){
8446        raw_printf(stderr,
8447                   "Error: non-null column separator required for import\n");
8448        rc = 1;
8449        goto meta_command_exit;
8450      }
8451      if( nSep>1 ){
8452        raw_printf(stderr,
8453              "Error: multi-character column separators not allowed"
8454              " for import\n");
8455        rc = 1;
8456        goto meta_command_exit;
8457      }
8458      nSep = strlen30(p->rowSeparator);
8459      if( nSep==0 ){
8460        raw_printf(stderr,
8461            "Error: non-null row separator required for import\n");
8462        rc = 1;
8463        goto meta_command_exit;
8464      }
8465      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8466        /* When importing CSV (only), if the row separator is set to the
8467        ** default output row separator, change it to the default input
8468        ** row separator.  This avoids having to maintain different input
8469        ** and output row separators. */
8470        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8471        nSep = strlen30(p->rowSeparator);
8472      }
8473      if( nSep>1 ){
8474        raw_printf(stderr, "Error: multi-character row separators not allowed"
8475                           " for import\n");
8476        rc = 1;
8477        goto meta_command_exit;
8478      }
8479      sCtx.cColSep = p->colSeparator[0];
8480      sCtx.cRowSep = p->rowSeparator[0];
8481    }
8482    sCtx.zFile = zFile;
8483    sCtx.nLine = 1;
8484    if( sCtx.zFile[0]=='|' ){
8485#ifdef SQLITE_OMIT_POPEN
8486      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8487      rc = 1;
8488      goto meta_command_exit;
8489#else
8490      sCtx.in = popen(sCtx.zFile+1, "r");
8491      sCtx.zFile = "<pipe>";
8492      sCtx.xCloser = pclose;
8493#endif
8494    }else{
8495      sCtx.in = fopen(sCtx.zFile, "rb");
8496      sCtx.xCloser = fclose;
8497    }
8498    if( sCtx.in==0 ){
8499      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8500      rc = 1;
8501      import_cleanup(&sCtx);
8502      goto meta_command_exit;
8503    }
8504    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8505      char zSep[2];
8506      zSep[1] = 0;
8507      zSep[0] = sCtx.cColSep;
8508      utf8_printf(p->out, "Column separator ");
8509      output_c_string(p->out, zSep);
8510      utf8_printf(p->out, ", row separator ");
8511      zSep[0] = sCtx.cRowSep;
8512      output_c_string(p->out, zSep);
8513      utf8_printf(p->out, "\n");
8514    }
8515    while( (nSkip--)>0 ){
8516      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8517    }
8518    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
8519    if( zSql==0 ){
8520      import_cleanup(&sCtx);
8521      shell_out_of_memory();
8522    }
8523    nByte = strlen30(zSql);
8524    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8525    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8526    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8527      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
8528      char cSep = '(';
8529      while( xRead(&sCtx) ){
8530        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
8531        cSep = ',';
8532        if( sCtx.cTerm!=sCtx.cColSep ) break;
8533      }
8534      if( cSep=='(' ){
8535        sqlite3_free(zCreate);
8536        import_cleanup(&sCtx);
8537        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8538        rc = 1;
8539        goto meta_command_exit;
8540      }
8541      zCreate = sqlite3_mprintf("%z\n)", zCreate);
8542      if( eVerbose>=1 ){
8543        utf8_printf(p->out, "%s\n", zCreate);
8544      }
8545      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8546      sqlite3_free(zCreate);
8547      if( rc ){
8548        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
8549                sqlite3_errmsg(p->db));
8550        import_cleanup(&sCtx);
8551        rc = 1;
8552        goto meta_command_exit;
8553      }
8554      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8555    }
8556    sqlite3_free(zSql);
8557    if( rc ){
8558      if (pStmt) sqlite3_finalize(pStmt);
8559      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8560      import_cleanup(&sCtx);
8561      rc = 1;
8562      goto meta_command_exit;
8563    }
8564    nCol = sqlite3_column_count(pStmt);
8565    sqlite3_finalize(pStmt);
8566    pStmt = 0;
8567    if( nCol==0 ) return 0; /* no columns, no error */
8568    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8569    if( zSql==0 ){
8570      import_cleanup(&sCtx);
8571      shell_out_of_memory();
8572    }
8573    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8574    j = strlen30(zSql);
8575    for(i=1; i<nCol; i++){
8576      zSql[j++] = ',';
8577      zSql[j++] = '?';
8578    }
8579    zSql[j++] = ')';
8580    zSql[j] = 0;
8581    if( eVerbose>=2 ){
8582      utf8_printf(p->out, "Insert using: %s\n", zSql);
8583    }
8584    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8585    sqlite3_free(zSql);
8586    if( rc ){
8587      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8588      if (pStmt) sqlite3_finalize(pStmt);
8589      import_cleanup(&sCtx);
8590      rc = 1;
8591      goto meta_command_exit;
8592    }
8593    needCommit = sqlite3_get_autocommit(p->db);
8594    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8595    do{
8596      int startLine = sCtx.nLine;
8597      for(i=0; i<nCol; i++){
8598        char *z = xRead(&sCtx);
8599        /*
8600        ** Did we reach end-of-file before finding any columns?
8601        ** If so, stop instead of NULL filling the remaining columns.
8602        */
8603        if( z==0 && i==0 ) break;
8604        /*
8605        ** Did we reach end-of-file OR end-of-line before finding any
8606        ** columns in ASCII mode?  If so, stop instead of NULL filling
8607        ** the remaining columns.
8608        */
8609        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8610        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8611        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8612          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8613                          "filling the rest with NULL\n",
8614                          sCtx.zFile, startLine, nCol, i+1);
8615          i += 2;
8616          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8617        }
8618      }
8619      if( sCtx.cTerm==sCtx.cColSep ){
8620        do{
8621          xRead(&sCtx);
8622          i++;
8623        }while( sCtx.cTerm==sCtx.cColSep );
8624        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8625                        "extras ignored\n",
8626                        sCtx.zFile, startLine, nCol, i);
8627      }
8628      if( i>=nCol ){
8629        sqlite3_step(pStmt);
8630        rc = sqlite3_reset(pStmt);
8631        if( rc!=SQLITE_OK ){
8632          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8633                      startLine, sqlite3_errmsg(p->db));
8634          sCtx.nErr++;
8635        }else{
8636          sCtx.nRow++;
8637        }
8638      }
8639    }while( sCtx.cTerm!=EOF );
8640
8641    import_cleanup(&sCtx);
8642    sqlite3_finalize(pStmt);
8643    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8644    if( eVerbose>0 ){
8645      utf8_printf(p->out,
8646          "Added %d rows with %d errors using %d lines of input\n",
8647          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8648    }
8649  }else
8650
8651#ifndef SQLITE_UNTESTABLE
8652  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8653    char *zSql;
8654    char *zCollist = 0;
8655    sqlite3_stmt *pStmt;
8656    int tnum = 0;
8657    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8658    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8659    int i;
8660    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8661      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8662                          "       .imposter off\n");
8663      /* Also allowed, but not documented:
8664      **
8665      **    .imposter TABLE IMPOSTER
8666      **
8667      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8668      ** imposter is another WITHOUT ROWID table with the columns in
8669      ** storage order. */
8670      rc = 1;
8671      goto meta_command_exit;
8672    }
8673    open_db(p, 0);
8674    if( nArg==2 ){
8675      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8676      goto meta_command_exit;
8677    }
8678    zSql = sqlite3_mprintf(
8679      "SELECT rootpage, 0 FROM sqlite_schema"
8680      " WHERE name='%q' AND type='index'"
8681      "UNION ALL "
8682      "SELECT rootpage, 1 FROM sqlite_schema"
8683      " WHERE name='%q' AND type='table'"
8684      "   AND sql LIKE '%%without%%rowid%%'",
8685      azArg[1], azArg[1]
8686    );
8687    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8688    sqlite3_free(zSql);
8689    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8690      tnum = sqlite3_column_int(pStmt, 0);
8691      isWO = sqlite3_column_int(pStmt, 1);
8692    }
8693    sqlite3_finalize(pStmt);
8694    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8695    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8696    sqlite3_free(zSql);
8697    i = 0;
8698    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8699      char zLabel[20];
8700      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8701      i++;
8702      if( zCol==0 ){
8703        if( sqlite3_column_int(pStmt,1)==-1 ){
8704          zCol = "_ROWID_";
8705        }else{
8706          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8707          zCol = zLabel;
8708        }
8709      }
8710      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8711        lenPK = (int)strlen(zCollist);
8712      }
8713      if( zCollist==0 ){
8714        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8715      }else{
8716        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8717      }
8718    }
8719    sqlite3_finalize(pStmt);
8720    if( i==0 || tnum==0 ){
8721      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8722      rc = 1;
8723      sqlite3_free(zCollist);
8724      goto meta_command_exit;
8725    }
8726    if( lenPK==0 ) lenPK = 100000;
8727    zSql = sqlite3_mprintf(
8728          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8729          azArg[2], zCollist, lenPK, zCollist);
8730    sqlite3_free(zCollist);
8731    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8732    if( rc==SQLITE_OK ){
8733      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8734      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8735      if( rc ){
8736        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8737      }else{
8738        utf8_printf(stdout, "%s;\n", zSql);
8739        raw_printf(stdout,
8740          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8741          azArg[1], isWO ? "table" : "index"
8742        );
8743      }
8744    }else{
8745      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8746      rc = 1;
8747    }
8748    sqlite3_free(zSql);
8749  }else
8750#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8751
8752#ifdef SQLITE_ENABLE_IOTRACE
8753  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8754    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8755    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8756    iotrace = 0;
8757    if( nArg<2 ){
8758      sqlite3IoTrace = 0;
8759    }else if( strcmp(azArg[1], "-")==0 ){
8760      sqlite3IoTrace = iotracePrintf;
8761      iotrace = stdout;
8762    }else{
8763      iotrace = fopen(azArg[1], "w");
8764      if( iotrace==0 ){
8765        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8766        sqlite3IoTrace = 0;
8767        rc = 1;
8768      }else{
8769        sqlite3IoTrace = iotracePrintf;
8770      }
8771    }
8772  }else
8773#endif
8774
8775  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8776    static const struct {
8777       const char *zLimitName;   /* Name of a limit */
8778       int limitCode;            /* Integer code for that limit */
8779    } aLimit[] = {
8780      { "length",                SQLITE_LIMIT_LENGTH                    },
8781      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8782      { "column",                SQLITE_LIMIT_COLUMN                    },
8783      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8784      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8785      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8786      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8787      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8788      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8789      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8790      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8791      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8792    };
8793    int i, n2;
8794    open_db(p, 0);
8795    if( nArg==1 ){
8796      for(i=0; i<ArraySize(aLimit); i++){
8797        printf("%20s %d\n", aLimit[i].zLimitName,
8798               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8799      }
8800    }else if( nArg>3 ){
8801      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8802      rc = 1;
8803      goto meta_command_exit;
8804    }else{
8805      int iLimit = -1;
8806      n2 = strlen30(azArg[1]);
8807      for(i=0; i<ArraySize(aLimit); i++){
8808        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8809          if( iLimit<0 ){
8810            iLimit = i;
8811          }else{
8812            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8813            rc = 1;
8814            goto meta_command_exit;
8815          }
8816        }
8817      }
8818      if( iLimit<0 ){
8819        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8820                        "enter \".limits\" with no arguments for a list.\n",
8821                         azArg[1]);
8822        rc = 1;
8823        goto meta_command_exit;
8824      }
8825      if( nArg==3 ){
8826        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8827                      (int)integerValue(azArg[2]));
8828      }
8829      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8830             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8831    }
8832  }else
8833
8834  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8835    open_db(p, 0);
8836    lintDotCommand(p, azArg, nArg);
8837  }else
8838
8839#ifndef SQLITE_OMIT_LOAD_EXTENSION
8840  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8841    const char *zFile, *zProc;
8842    char *zErrMsg = 0;
8843    failIfSafeMode(p, "cannot run .load in safe mode");
8844    if( nArg<2 ){
8845      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8846      rc = 1;
8847      goto meta_command_exit;
8848    }
8849    zFile = azArg[1];
8850    zProc = nArg>=3 ? azArg[2] : 0;
8851    open_db(p, 0);
8852    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8853    if( rc!=SQLITE_OK ){
8854      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8855      sqlite3_free(zErrMsg);
8856      rc = 1;
8857    }
8858  }else
8859#endif
8860
8861  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8862    failIfSafeMode(p, "cannot run .log in safe mode");
8863    if( nArg!=2 ){
8864      raw_printf(stderr, "Usage: .log FILENAME\n");
8865      rc = 1;
8866    }else{
8867      const char *zFile = azArg[1];
8868      output_file_close(p->pLog);
8869      p->pLog = output_file_open(zFile, 0);
8870    }
8871  }else
8872
8873  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8874    const char *zMode = nArg>=2 ? azArg[1] : "";
8875    int n2 = strlen30(zMode);
8876    int c2 = zMode[0];
8877    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8878      p->mode = MODE_Line;
8879      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8880    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8881      p->mode = MODE_Column;
8882      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8883        p->showHeader = 1;
8884      }
8885      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8886    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8887      p->mode = MODE_List;
8888      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8889      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8890    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8891      p->mode = MODE_Html;
8892    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8893      p->mode = MODE_Tcl;
8894      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8895      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8896    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8897      p->mode = MODE_Csv;
8898      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8899      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8900    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8901      p->mode = MODE_List;
8902      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8903    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8904      p->mode = MODE_Insert;
8905      set_table_name(p, nArg>=3 ? azArg[2] : "table");
8906    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8907      p->mode = MODE_Quote;
8908      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8909      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8910    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8911      p->mode = MODE_Ascii;
8912      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8913      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8914    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8915      p->mode = MODE_Markdown;
8916    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8917      p->mode = MODE_Table;
8918    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8919      p->mode = MODE_Box;
8920    }else if( c2=='c' && strncmp(azArg[1],"count",n2)==0 ){
8921      p->mode = MODE_Count;
8922    }else if( c2=='o' && strncmp(azArg[1],"off",n2)==0 ){
8923      p->mode = MODE_Off;
8924    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8925      p->mode = MODE_Json;
8926    }else if( nArg==1 ){
8927      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8928    }else{
8929      raw_printf(stderr, "Error: mode should be one of: "
8930         "ascii box column csv html insert json line list markdown "
8931         "quote table tabs tcl\n");
8932      rc = 1;
8933    }
8934    p->cMode = p->mode;
8935  }else
8936
8937  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
8938    if( nArg!=2 ){
8939      raw_printf(stderr, "Usage: .nonce NONCE\n");
8940      rc = 1;
8941    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
8942      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", p->lineno, azArg[1]);
8943      exit(1);
8944    }else{
8945      p->bSafeMode = 0;
8946      return 0;  /* Return immediately to bypass the safe mode reset
8947                 ** at the end of this procedure */
8948    }
8949  }else
8950
8951  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8952    if( nArg==2 ){
8953      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8954                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8955    }else{
8956      raw_printf(stderr, "Usage: .nullvalue STRING\n");
8957      rc = 1;
8958    }
8959  }else
8960
8961#ifdef SQLITE_DEBUG
8962  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8963    int i;
8964    for(i=1; i<nArg; i++){
8965      const char *z = azArg[i];
8966      if( z[0]=='-' && z[1]=='-' ) z++;
8967      if( strcmp(z,"-repeat")==0 ){
8968        if( i==nArg-1 ){
8969          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8970          rc = 1;
8971        }else{
8972          oomRepeat = (int)integerValue(azArg[++i]);
8973        }
8974      }else if( IsDigit(z[0]) ){
8975        oomCounter = (int)integerValue(azArg[i]);
8976      }else{
8977        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8978        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8979        rc = 1;
8980      }
8981    }
8982    if( rc==0 ){
8983      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8984      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
8985    }
8986  }else
8987#endif /* SQLITE_DEBUG */
8988
8989  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8990    char *zNewFilename = 0;  /* Name of the database file to open */
8991    int iName = 1;           /* Index in azArg[] of the filename */
8992    int newFlag = 0;         /* True to delete file before opening */
8993    int openMode = SHELL_OPEN_UNSPEC;
8994
8995    /* Check for command-line arguments */
8996    for(iName=1; iName<nArg; iName++){
8997      const char *z = azArg[iName];
8998      if( optionMatch(z,"new") ){
8999        newFlag = 1;
9000#ifdef SQLITE_HAVE_ZLIB
9001      }else if( optionMatch(z, "zip") ){
9002        openMode = SHELL_OPEN_ZIPFILE;
9003#endif
9004      }else if( optionMatch(z, "append") ){
9005        openMode = SHELL_OPEN_APPENDVFS;
9006      }else if( optionMatch(z, "readonly") ){
9007        openMode = SHELL_OPEN_READONLY;
9008      }else if( optionMatch(z, "nofollow") ){
9009        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9010#ifndef SQLITE_OMIT_DESERIALIZE
9011      }else if( optionMatch(z, "deserialize") ){
9012        openMode = SHELL_OPEN_DESERIALIZE;
9013      }else if( optionMatch(z, "hexdb") ){
9014        openMode = SHELL_OPEN_HEXDB;
9015      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9016        p->szMax = integerValue(azArg[++iName]);
9017#endif /* SQLITE_OMIT_DESERIALIZE */
9018      }else if( z[0]=='-' ){
9019        utf8_printf(stderr, "unknown option: %s\n", z);
9020        rc = 1;
9021        goto meta_command_exit;
9022      }else if( zNewFilename ){
9023        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9024        rc = 1;
9025        goto meta_command_exit;
9026      }else{
9027        zNewFilename = sqlite3_mprintf("%s", z);
9028      }
9029    }
9030
9031    /* Close the existing database */
9032    session_close_all(p, -1);
9033    close_db(p->db);
9034    p->db = 0;
9035    p->pAuxDb->zDbFilename = 0;
9036    sqlite3_free(p->pAuxDb->zFreeOnClose);
9037    p->pAuxDb->zFreeOnClose = 0;
9038    p->openMode = openMode;
9039    p->openFlags = 0;
9040    p->szMax = 0;
9041
9042    /* If a filename is specified, try to open it first */
9043    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
9044      if( newFlag && !p->bSafeMode ) shellDeleteFile(zNewFilename);
9045      if( p->bSafeMode
9046       && p->openMode!=SHELL_OPEN_HEXDB
9047       && zNewFilename
9048       && strcmp(zNewFilename,":memory:")!=0
9049      ){
9050        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9051      }
9052      p->pAuxDb->zDbFilename = zNewFilename;
9053      open_db(p, OPEN_DB_KEEPALIVE);
9054      if( p->db==0 ){
9055        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9056        sqlite3_free(zNewFilename);
9057      }else{
9058        p->pAuxDb->zFreeOnClose = zNewFilename;
9059      }
9060    }
9061    if( p->db==0 ){
9062      /* As a fall-back open a TEMP database */
9063      p->pAuxDb->zDbFilename = 0;
9064      open_db(p, 0);
9065    }
9066  }else
9067
9068  if( (c=='o'
9069        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9070   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9071  ){
9072    char *zFile = 0;
9073    int bTxtMode = 0;
9074    int i;
9075    int eMode = 0;
9076    int bBOM = 0;
9077    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
9078
9079    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9080    if( c=='e' ){
9081      eMode = 'x';
9082      bOnce = 2;
9083    }else if( strncmp(azArg[0],"once",n)==0 ){
9084      bOnce = 1;
9085    }
9086    for(i=1; i<nArg; i++){
9087      char *z = azArg[i];
9088      if( z[0]=='-' ){
9089        if( z[1]=='-' ) z++;
9090        if( strcmp(z,"-bom")==0 ){
9091          bBOM = 1;
9092        }else if( c!='e' && strcmp(z,"-x")==0 ){
9093          eMode = 'x';  /* spreadsheet */
9094        }else if( c!='e' && strcmp(z,"-e")==0 ){
9095          eMode = 'e';  /* text editor */
9096        }else{
9097          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9098                      azArg[i]);
9099          showHelp(p->out, azArg[0]);
9100          rc = 1;
9101          goto meta_command_exit;
9102        }
9103      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9104        zFile = sqlite3_mprintf("%s", z);
9105        if( zFile && zFile[0]=='|' ){
9106          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9107          break;
9108        }
9109      }else{
9110        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9111                    azArg[i]);
9112        showHelp(p->out, azArg[0]);
9113        rc = 1;
9114        sqlite3_free(zFile);
9115        goto meta_command_exit;
9116      }
9117    }
9118    if( zFile==0 ){
9119      zFile = sqlite3_mprintf("stdout");
9120    }
9121    if( bOnce ){
9122      p->outCount = 2;
9123    }else{
9124      p->outCount = 0;
9125    }
9126    output_reset(p);
9127#ifndef SQLITE_NOHAVE_SYSTEM
9128    if( eMode=='e' || eMode=='x' ){
9129      p->doXdgOpen = 1;
9130      outputModePush(p);
9131      if( eMode=='x' ){
9132        /* spreadsheet mode.  Output as CSV. */
9133        newTempFile(p, "csv");
9134        ShellClearFlag(p, SHFLG_Echo);
9135        p->mode = MODE_Csv;
9136        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9137        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9138      }else{
9139        /* text editor mode */
9140        newTempFile(p, "txt");
9141        bTxtMode = 1;
9142      }
9143      sqlite3_free(zFile);
9144      zFile = sqlite3_mprintf("%s", p->zTempFile);
9145    }
9146#endif /* SQLITE_NOHAVE_SYSTEM */
9147    shell_check_oom(zFile);
9148    if( zFile[0]=='|' ){
9149#ifdef SQLITE_OMIT_POPEN
9150      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9151      rc = 1;
9152      p->out = stdout;
9153#else
9154      p->out = popen(zFile + 1, "w");
9155      if( p->out==0 ){
9156        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9157        p->out = stdout;
9158        rc = 1;
9159      }else{
9160        if( bBOM ) fprintf(p->out,"\357\273\277");
9161        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9162      }
9163#endif
9164    }else{
9165      p->out = output_file_open(zFile, bTxtMode);
9166      if( p->out==0 ){
9167        if( strcmp(zFile,"off")!=0 ){
9168          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9169        }
9170        p->out = stdout;
9171        rc = 1;
9172      } else {
9173        if( bBOM ) fprintf(p->out,"\357\273\277");
9174        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9175      }
9176    }
9177    sqlite3_free(zFile);
9178  }else
9179
9180  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9181    open_db(p,0);
9182    if( nArg<=1 ) goto parameter_syntax_error;
9183
9184    /* .parameter clear
9185    ** Clear all bind parameters by dropping the TEMP table that holds them.
9186    */
9187    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9188      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9189                   0, 0, 0);
9190    }else
9191
9192    /* .parameter list
9193    ** List all bind parameters.
9194    */
9195    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9196      sqlite3_stmt *pStmt = 0;
9197      int rx;
9198      int len = 0;
9199      rx = sqlite3_prepare_v2(p->db,
9200             "SELECT max(length(key)) "
9201             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9202      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9203        len = sqlite3_column_int(pStmt, 0);
9204        if( len>40 ) len = 40;
9205      }
9206      sqlite3_finalize(pStmt);
9207      pStmt = 0;
9208      if( len ){
9209        rx = sqlite3_prepare_v2(p->db,
9210             "SELECT key, quote(value) "
9211             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9212        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9213          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9214                      sqlite3_column_text(pStmt,1));
9215        }
9216        sqlite3_finalize(pStmt);
9217      }
9218    }else
9219
9220    /* .parameter init
9221    ** Make sure the TEMP table used to hold bind parameters exists.
9222    ** Create it if necessary.
9223    */
9224    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9225      bind_table_init(p);
9226    }else
9227
9228    /* .parameter set NAME VALUE
9229    ** Set or reset a bind parameter.  NAME should be the full parameter
9230    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9231    ** VALUE can be in either SQL literal notation, or if not it will be
9232    ** understood to be a text string.
9233    */
9234    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9235      int rx;
9236      char *zSql;
9237      sqlite3_stmt *pStmt;
9238      const char *zKey = azArg[2];
9239      const char *zValue = azArg[3];
9240      bind_table_init(p);
9241      zSql = sqlite3_mprintf(
9242                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9243                  "VALUES(%Q,%s);", zKey, zValue);
9244      shell_check_oom(zSql);
9245      pStmt = 0;
9246      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9247      sqlite3_free(zSql);
9248      if( rx!=SQLITE_OK ){
9249        sqlite3_finalize(pStmt);
9250        pStmt = 0;
9251        zSql = sqlite3_mprintf(
9252                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9253                   "VALUES(%Q,%Q);", zKey, zValue);
9254        shell_check_oom(zSql);
9255        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9256        sqlite3_free(zSql);
9257        if( rx!=SQLITE_OK ){
9258          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9259          sqlite3_finalize(pStmt);
9260          pStmt = 0;
9261          rc = 1;
9262        }
9263      }
9264      sqlite3_step(pStmt);
9265      sqlite3_finalize(pStmt);
9266    }else
9267
9268    /* .parameter unset NAME
9269    ** Remove the NAME binding from the parameter binding table, if it
9270    ** exists.
9271    */
9272    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9273      char *zSql = sqlite3_mprintf(
9274          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9275      shell_check_oom(zSql);
9276      sqlite3_exec(p->db, zSql, 0, 0, 0);
9277      sqlite3_free(zSql);
9278    }else
9279    /* If no command name matches, show a syntax error */
9280    parameter_syntax_error:
9281    showHelp(p->out, "parameter");
9282  }else
9283
9284  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9285    int i;
9286    for(i=1; i<nArg; i++){
9287      if( i>1 ) raw_printf(p->out, " ");
9288      utf8_printf(p->out, "%s", azArg[i]);
9289    }
9290    raw_printf(p->out, "\n");
9291  }else
9292
9293#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9294  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9295    int i;
9296    int nn = 0;
9297    p->flgProgress = 0;
9298    p->mxProgress = 0;
9299    p->nProgress = 0;
9300    for(i=1; i<nArg; i++){
9301      const char *z = azArg[i];
9302      if( z[0]=='-' ){
9303        z++;
9304        if( z[0]=='-' ) z++;
9305        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9306          p->flgProgress |= SHELL_PROGRESS_QUIET;
9307          continue;
9308        }
9309        if( strcmp(z,"reset")==0 ){
9310          p->flgProgress |= SHELL_PROGRESS_RESET;
9311          continue;
9312        }
9313        if( strcmp(z,"once")==0 ){
9314          p->flgProgress |= SHELL_PROGRESS_ONCE;
9315          continue;
9316        }
9317        if( strcmp(z,"limit")==0 ){
9318          if( i+1>=nArg ){
9319            utf8_printf(stderr, "Error: missing argument on --limit\n");
9320            rc = 1;
9321            goto meta_command_exit;
9322          }else{
9323            p->mxProgress = (int)integerValue(azArg[++i]);
9324          }
9325          continue;
9326        }
9327        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9328        rc = 1;
9329        goto meta_command_exit;
9330      }else{
9331        nn = (int)integerValue(z);
9332      }
9333    }
9334    open_db(p, 0);
9335    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9336  }else
9337#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9338
9339  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9340    if( nArg >= 2) {
9341      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9342    }
9343    if( nArg >= 3) {
9344      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9345    }
9346  }else
9347
9348  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9349    rc = 2;
9350  }else
9351
9352  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9353    FILE *inSaved = p->in;
9354    int savedLineno = p->lineno;
9355    failIfSafeMode(p, "cannot run .read in safe mode");
9356    if( nArg!=2 ){
9357      raw_printf(stderr, "Usage: .read FILE\n");
9358      rc = 1;
9359      goto meta_command_exit;
9360    }
9361    if( azArg[1][0]=='|' ){
9362#ifdef SQLITE_OMIT_POPEN
9363      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9364      rc = 1;
9365      p->out = stdout;
9366#else
9367      p->in = popen(azArg[1]+1, "r");
9368      if( p->in==0 ){
9369        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9370        rc = 1;
9371      }else{
9372        rc = process_input(p);
9373        pclose(p->in);
9374      }
9375#endif
9376    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9377      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9378      rc = 1;
9379    }else{
9380      rc = process_input(p);
9381      fclose(p->in);
9382    }
9383    p->in = inSaved;
9384    p->lineno = savedLineno;
9385  }else
9386
9387  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9388    const char *zSrcFile;
9389    const char *zDb;
9390    sqlite3 *pSrc;
9391    sqlite3_backup *pBackup;
9392    int nTimeout = 0;
9393
9394    failIfSafeMode(p, "cannot run .restore in safe mode");
9395    if( nArg==2 ){
9396      zSrcFile = azArg[1];
9397      zDb = "main";
9398    }else if( nArg==3 ){
9399      zSrcFile = azArg[2];
9400      zDb = azArg[1];
9401    }else{
9402      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9403      rc = 1;
9404      goto meta_command_exit;
9405    }
9406    rc = sqlite3_open(zSrcFile, &pSrc);
9407    if( rc!=SQLITE_OK ){
9408      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9409      close_db(pSrc);
9410      return 1;
9411    }
9412    open_db(p, 0);
9413    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9414    if( pBackup==0 ){
9415      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9416      close_db(pSrc);
9417      return 1;
9418    }
9419    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9420          || rc==SQLITE_BUSY  ){
9421      if( rc==SQLITE_BUSY ){
9422        if( nTimeout++ >= 3 ) break;
9423        sqlite3_sleep(100);
9424      }
9425    }
9426    sqlite3_backup_finish(pBackup);
9427    if( rc==SQLITE_DONE ){
9428      rc = 0;
9429    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9430      raw_printf(stderr, "Error: source database is busy\n");
9431      rc = 1;
9432    }else{
9433      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9434      rc = 1;
9435    }
9436    close_db(pSrc);
9437  }else
9438
9439  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9440    if( nArg==2 ){
9441      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9442#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9443      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9444#endif
9445    }else{
9446      raw_printf(stderr, "Usage: .scanstats on|off\n");
9447      rc = 1;
9448    }
9449  }else
9450
9451  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9452    ShellText sSelect;
9453    ShellState data;
9454    char *zErrMsg = 0;
9455    const char *zDiv = "(";
9456    const char *zName = 0;
9457    int iSchema = 0;
9458    int bDebug = 0;
9459    int bNoSystemTabs = 0;
9460    int ii;
9461
9462    open_db(p, 0);
9463    memcpy(&data, p, sizeof(data));
9464    data.showHeader = 0;
9465    data.cMode = data.mode = MODE_Semi;
9466    initText(&sSelect);
9467    for(ii=1; ii<nArg; ii++){
9468      if( optionMatch(azArg[ii],"indent") ){
9469        data.cMode = data.mode = MODE_Pretty;
9470      }else if( optionMatch(azArg[ii],"debug") ){
9471        bDebug = 1;
9472      }else if( optionMatch(azArg[ii],"nosys") ){
9473        bNoSystemTabs = 1;
9474      }else if( azArg[ii][0]=='-' ){
9475        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9476        rc = 1;
9477        goto meta_command_exit;
9478      }else if( zName==0 ){
9479        zName = azArg[ii];
9480      }else{
9481        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9482        rc = 1;
9483        goto meta_command_exit;
9484      }
9485    }
9486    if( zName!=0 ){
9487      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9488                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9489                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9490                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9491      if( isSchema ){
9492        char *new_argv[2], *new_colv[2];
9493        new_argv[0] = sqlite3_mprintf(
9494                      "CREATE TABLE %s (\n"
9495                      "  type text,\n"
9496                      "  name text,\n"
9497                      "  tbl_name text,\n"
9498                      "  rootpage integer,\n"
9499                      "  sql text\n"
9500                      ")", zName);
9501        shell_check_oom(new_argv[0]);
9502        new_argv[1] = 0;
9503        new_colv[0] = "sql";
9504        new_colv[1] = 0;
9505        callback(&data, 1, new_argv, new_colv);
9506        sqlite3_free(new_argv[0]);
9507      }
9508    }
9509    if( zDiv ){
9510      sqlite3_stmt *pStmt = 0;
9511      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9512                              -1, &pStmt, 0);
9513      if( rc ){
9514        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9515        sqlite3_finalize(pStmt);
9516        rc = 1;
9517        goto meta_command_exit;
9518      }
9519      appendText(&sSelect, "SELECT sql FROM", 0);
9520      iSchema = 0;
9521      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9522        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9523        char zScNum[30];
9524        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9525        appendText(&sSelect, zDiv, 0);
9526        zDiv = " UNION ALL ";
9527        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9528        if( sqlite3_stricmp(zDb, "main")!=0 ){
9529          appendText(&sSelect, zDb, '\'');
9530        }else{
9531          appendText(&sSelect, "NULL", 0);
9532        }
9533        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9534        appendText(&sSelect, zScNum, 0);
9535        appendText(&sSelect, " AS snum, ", 0);
9536        appendText(&sSelect, zDb, '\'');
9537        appendText(&sSelect, " AS sname FROM ", 0);
9538        appendText(&sSelect, zDb, quoteChar(zDb));
9539        appendText(&sSelect, ".sqlite_schema", 0);
9540      }
9541      sqlite3_finalize(pStmt);
9542#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9543      if( zName ){
9544        appendText(&sSelect,
9545           " UNION ALL SELECT shell_module_schema(name),"
9546           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9547        0);
9548      }
9549#endif
9550      appendText(&sSelect, ") WHERE ", 0);
9551      if( zName ){
9552        char *zQarg = sqlite3_mprintf("%Q", zName);
9553        shell_check_oom(zQarg);
9554        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9555                    strchr(zName, '[') != 0;
9556        if( strchr(zName, '.') ){
9557          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9558        }else{
9559          appendText(&sSelect, "lower(tbl_name)", 0);
9560        }
9561        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9562        appendText(&sSelect, zQarg, 0);
9563        if( !bGlob ){
9564          appendText(&sSelect, " ESCAPE '\\' ", 0);
9565        }
9566        appendText(&sSelect, " AND ", 0);
9567        sqlite3_free(zQarg);
9568      }
9569      if( bNoSystemTabs ){
9570        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9571      }
9572      appendText(&sSelect, "sql IS NOT NULL"
9573                           " ORDER BY snum, rowid", 0);
9574      if( bDebug ){
9575        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9576      }else{
9577        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9578      }
9579      freeText(&sSelect);
9580    }
9581    if( zErrMsg ){
9582      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9583      sqlite3_free(zErrMsg);
9584      rc = 1;
9585    }else if( rc != SQLITE_OK ){
9586      raw_printf(stderr,"Error: querying schema information\n");
9587      rc = 1;
9588    }else{
9589      rc = 0;
9590    }
9591  }else
9592
9593  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9594    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9595    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9596  }else
9597
9598#if defined(SQLITE_ENABLE_SESSION)
9599  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9600    struct AuxDb *pAuxDb = p->pAuxDb;
9601    OpenSession *pSession = &pAuxDb->aSession[0];
9602    char **azCmd = &azArg[1];
9603    int iSes = 0;
9604    int nCmd = nArg - 1;
9605    int i;
9606    if( nArg<=1 ) goto session_syntax_error;
9607    open_db(p, 0);
9608    if( nArg>=3 ){
9609      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9610        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9611      }
9612      if( iSes<pAuxDb->nSession ){
9613        pSession = &pAuxDb->aSession[iSes];
9614        azCmd++;
9615        nCmd--;
9616      }else{
9617        pSession = &pAuxDb->aSession[0];
9618        iSes = 0;
9619      }
9620    }
9621
9622    /* .session attach TABLE
9623    ** Invoke the sqlite3session_attach() interface to attach a particular
9624    ** table so that it is never filtered.
9625    */
9626    if( strcmp(azCmd[0],"attach")==0 ){
9627      if( nCmd!=2 ) goto session_syntax_error;
9628      if( pSession->p==0 ){
9629        session_not_open:
9630        raw_printf(stderr, "ERROR: No sessions are open\n");
9631      }else{
9632        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9633        if( rc ){
9634          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9635          rc = 0;
9636        }
9637      }
9638    }else
9639
9640    /* .session changeset FILE
9641    ** .session patchset FILE
9642    ** Write a changeset or patchset into a file.  The file is overwritten.
9643    */
9644    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9645      FILE *out = 0;
9646      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9647      if( nCmd!=2 ) goto session_syntax_error;
9648      if( pSession->p==0 ) goto session_not_open;
9649      out = fopen(azCmd[1], "wb");
9650      if( out==0 ){
9651        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9652                    azCmd[1]);
9653      }else{
9654        int szChng;
9655        void *pChng;
9656        if( azCmd[0][0]=='c' ){
9657          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9658        }else{
9659          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9660        }
9661        if( rc ){
9662          printf("Error: error code %d\n", rc);
9663          rc = 0;
9664        }
9665        if( pChng
9666          && fwrite(pChng, szChng, 1, out)!=1 ){
9667          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9668                  szChng);
9669        }
9670        sqlite3_free(pChng);
9671        fclose(out);
9672      }
9673    }else
9674
9675    /* .session close
9676    ** Close the identified session
9677    */
9678    if( strcmp(azCmd[0], "close")==0 ){
9679      if( nCmd!=1 ) goto session_syntax_error;
9680      if( pAuxDb->nSession ){
9681        session_close(pSession);
9682        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9683      }
9684    }else
9685
9686    /* .session enable ?BOOLEAN?
9687    ** Query or set the enable flag
9688    */
9689    if( strcmp(azCmd[0], "enable")==0 ){
9690      int ii;
9691      if( nCmd>2 ) goto session_syntax_error;
9692      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9693      if( pAuxDb->nSession ){
9694        ii = sqlite3session_enable(pSession->p, ii);
9695        utf8_printf(p->out, "session %s enable flag = %d\n",
9696                    pSession->zName, ii);
9697      }
9698    }else
9699
9700    /* .session filter GLOB ....
9701    ** Set a list of GLOB patterns of table names to be excluded.
9702    */
9703    if( strcmp(azCmd[0], "filter")==0 ){
9704      int ii, nByte;
9705      if( nCmd<2 ) goto session_syntax_error;
9706      if( pAuxDb->nSession ){
9707        for(ii=0; ii<pSession->nFilter; ii++){
9708          sqlite3_free(pSession->azFilter[ii]);
9709        }
9710        sqlite3_free(pSession->azFilter);
9711        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9712        pSession->azFilter = sqlite3_malloc( nByte );
9713        if( pSession->azFilter==0 ){
9714          raw_printf(stderr, "Error: out or memory\n");
9715          exit(1);
9716        }
9717        for(ii=1; ii<nCmd; ii++){
9718          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9719          shell_check_oom(x);
9720        }
9721        pSession->nFilter = ii-1;
9722      }
9723    }else
9724
9725    /* .session indirect ?BOOLEAN?
9726    ** Query or set the indirect flag
9727    */
9728    if( strcmp(azCmd[0], "indirect")==0 ){
9729      int ii;
9730      if( nCmd>2 ) goto session_syntax_error;
9731      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9732      if( pAuxDb->nSession ){
9733        ii = sqlite3session_indirect(pSession->p, ii);
9734        utf8_printf(p->out, "session %s indirect flag = %d\n",
9735                    pSession->zName, ii);
9736      }
9737    }else
9738
9739    /* .session isempty
9740    ** Determine if the session is empty
9741    */
9742    if( strcmp(azCmd[0], "isempty")==0 ){
9743      int ii;
9744      if( nCmd!=1 ) goto session_syntax_error;
9745      if( pAuxDb->nSession ){
9746        ii = sqlite3session_isempty(pSession->p);
9747        utf8_printf(p->out, "session %s isempty flag = %d\n",
9748                    pSession->zName, ii);
9749      }
9750    }else
9751
9752    /* .session list
9753    ** List all currently open sessions
9754    */
9755    if( strcmp(azCmd[0],"list")==0 ){
9756      for(i=0; i<pAuxDb->nSession; i++){
9757        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9758      }
9759    }else
9760
9761    /* .session open DB NAME
9762    ** Open a new session called NAME on the attached database DB.
9763    ** DB is normally "main".
9764    */
9765    if( strcmp(azCmd[0],"open")==0 ){
9766      char *zName;
9767      if( nCmd!=3 ) goto session_syntax_error;
9768      zName = azCmd[2];
9769      if( zName[0]==0 ) goto session_syntax_error;
9770      for(i=0; i<pAuxDb->nSession; i++){
9771        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9772          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9773          goto meta_command_exit;
9774        }
9775      }
9776      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9777        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9778        goto meta_command_exit;
9779      }
9780      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9781      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9782      if( rc ){
9783        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9784        rc = 0;
9785        goto meta_command_exit;
9786      }
9787      pSession->nFilter = 0;
9788      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9789      pAuxDb->nSession++;
9790      pSession->zName = sqlite3_mprintf("%s", zName);
9791      shell_check_oom(pSession->zName);
9792    }else
9793    /* If no command name matches, show a syntax error */
9794    session_syntax_error:
9795    showHelp(p->out, "session");
9796  }else
9797#endif
9798
9799#ifdef SQLITE_DEBUG
9800  /* Undocumented commands for internal testing.  Subject to change
9801  ** without notice. */
9802  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9803    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9804      int i, v;
9805      for(i=1; i<nArg; i++){
9806        v = booleanValue(azArg[i]);
9807        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9808      }
9809    }
9810    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9811      int i; sqlite3_int64 v;
9812      for(i=1; i<nArg; i++){
9813        char zBuf[200];
9814        v = integerValue(azArg[i]);
9815        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9816        utf8_printf(p->out, "%s", zBuf);
9817      }
9818    }
9819  }else
9820#endif
9821
9822  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9823    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9824    int bVerbose = 0;        /* Verbose output */
9825    int bSelftestExists;     /* True if SELFTEST already exists */
9826    int i, k;                /* Loop counters */
9827    int nTest = 0;           /* Number of tests runs */
9828    int nErr = 0;            /* Number of errors seen */
9829    ShellText str;           /* Answer for a query */
9830    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9831
9832    open_db(p,0);
9833    for(i=1; i<nArg; i++){
9834      const char *z = azArg[i];
9835      if( z[0]=='-' && z[1]=='-' ) z++;
9836      if( strcmp(z,"-init")==0 ){
9837        bIsInit = 1;
9838      }else
9839      if( strcmp(z,"-v")==0 ){
9840        bVerbose++;
9841      }else
9842      {
9843        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9844                    azArg[i], azArg[0]);
9845        raw_printf(stderr, "Should be one of: --init -v\n");
9846        rc = 1;
9847        goto meta_command_exit;
9848      }
9849    }
9850    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9851           != SQLITE_OK ){
9852      bSelftestExists = 0;
9853    }else{
9854      bSelftestExists = 1;
9855    }
9856    if( bIsInit ){
9857      createSelftestTable(p);
9858      bSelftestExists = 1;
9859    }
9860    initText(&str);
9861    appendText(&str, "x", 0);
9862    for(k=bSelftestExists; k>=0; k--){
9863      if( k==1 ){
9864        rc = sqlite3_prepare_v2(p->db,
9865            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9866            -1, &pStmt, 0);
9867      }else{
9868        rc = sqlite3_prepare_v2(p->db,
9869          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9870          "      (1,'run','PRAGMA integrity_check','ok')",
9871          -1, &pStmt, 0);
9872      }
9873      if( rc ){
9874        raw_printf(stderr, "Error querying the selftest table\n");
9875        rc = 1;
9876        sqlite3_finalize(pStmt);
9877        goto meta_command_exit;
9878      }
9879      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9880        int tno = sqlite3_column_int(pStmt, 0);
9881        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9882        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9883        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9884
9885        k = 0;
9886        if( bVerbose>0 ){
9887          printf("%d: %s %s\n", tno, zOp, zSql);
9888        }
9889        if( strcmp(zOp,"memo")==0 ){
9890          utf8_printf(p->out, "%s\n", zSql);
9891        }else
9892        if( strcmp(zOp,"run")==0 ){
9893          char *zErrMsg = 0;
9894          str.n = 0;
9895          str.z[0] = 0;
9896          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9897          nTest++;
9898          if( bVerbose ){
9899            utf8_printf(p->out, "Result: %s\n", str.z);
9900          }
9901          if( rc || zErrMsg ){
9902            nErr++;
9903            rc = 1;
9904            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9905            sqlite3_free(zErrMsg);
9906          }else if( strcmp(zAns,str.z)!=0 ){
9907            nErr++;
9908            rc = 1;
9909            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9910            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9911          }
9912        }else
9913        {
9914          utf8_printf(stderr,
9915            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9916          rc = 1;
9917          break;
9918        }
9919      } /* End loop over rows of content from SELFTEST */
9920      sqlite3_finalize(pStmt);
9921    } /* End loop over k */
9922    freeText(&str);
9923    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9924  }else
9925
9926  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9927    if( nArg<2 || nArg>3 ){
9928      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9929      rc = 1;
9930    }
9931    if( nArg>=2 ){
9932      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9933                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9934    }
9935    if( nArg>=3 ){
9936      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9937                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9938    }
9939  }else
9940
9941  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9942    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
9943    int i;                   /* Loop counter */
9944    int bSchema = 0;         /* Also hash the schema */
9945    int bSeparate = 0;       /* Hash each table separately */
9946    int iSize = 224;         /* Hash algorithm to use */
9947    int bDebug = 0;          /* Only show the query that would have run */
9948    sqlite3_stmt *pStmt;     /* For querying tables names */
9949    char *zSql;              /* SQL to be run */
9950    char *zSep;              /* Separator */
9951    ShellText sSql;          /* Complete SQL for the query to run the hash */
9952    ShellText sQuery;        /* Set of queries used to read all content */
9953    open_db(p, 0);
9954    for(i=1; i<nArg; i++){
9955      const char *z = azArg[i];
9956      if( z[0]=='-' ){
9957        z++;
9958        if( z[0]=='-' ) z++;
9959        if( strcmp(z,"schema")==0 ){
9960          bSchema = 1;
9961        }else
9962        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9963         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9964        ){
9965          iSize = atoi(&z[5]);
9966        }else
9967        if( strcmp(z,"debug")==0 ){
9968          bDebug = 1;
9969        }else
9970        {
9971          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9972                      azArg[i], azArg[0]);
9973          showHelp(p->out, azArg[0]);
9974          rc = 1;
9975          goto meta_command_exit;
9976        }
9977      }else if( zLike ){
9978        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9979        rc = 1;
9980        goto meta_command_exit;
9981      }else{
9982        zLike = z;
9983        bSeparate = 1;
9984        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9985      }
9986    }
9987    if( bSchema ){
9988      zSql = "SELECT lower(name) FROM sqlite_schema"
9989             " WHERE type='table' AND coalesce(rootpage,0)>1"
9990             " UNION ALL SELECT 'sqlite_schema'"
9991             " ORDER BY 1 collate nocase";
9992    }else{
9993      zSql = "SELECT lower(name) FROM sqlite_schema"
9994             " WHERE type='table' AND coalesce(rootpage,0)>1"
9995             " AND name NOT LIKE 'sqlite_%'"
9996             " ORDER BY 1 collate nocase";
9997    }
9998    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9999    initText(&sQuery);
10000    initText(&sSql);
10001    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10002    zSep = "VALUES(";
10003    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10004      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10005      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10006      if( strncmp(zTab, "sqlite_",7)!=0 ){
10007        appendText(&sQuery,"SELECT * FROM ", 0);
10008        appendText(&sQuery,zTab,'"');
10009        appendText(&sQuery," NOT INDEXED;", 0);
10010      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10011        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10012                           " ORDER BY name;", 0);
10013      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10014        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10015                           " ORDER BY name;", 0);
10016      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10017        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10018                           " ORDER BY tbl,idx;", 0);
10019      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10020        appendText(&sQuery, "SELECT * FROM ", 0);
10021        appendText(&sQuery, zTab, 0);
10022        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10023      }
10024      appendText(&sSql, zSep, 0);
10025      appendText(&sSql, sQuery.z, '\'');
10026      sQuery.n = 0;
10027      appendText(&sSql, ",", 0);
10028      appendText(&sSql, zTab, '\'');
10029      zSep = "),(";
10030    }
10031    sqlite3_finalize(pStmt);
10032    if( bSeparate ){
10033      zSql = sqlite3_mprintf(
10034          "%s))"
10035          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10036          "   FROM [sha3sum$query]",
10037          sSql.z, iSize);
10038    }else{
10039      zSql = sqlite3_mprintf(
10040          "%s))"
10041          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10042          "   FROM [sha3sum$query]",
10043          sSql.z, iSize);
10044    }
10045    shell_check_oom(zSql);
10046    freeText(&sQuery);
10047    freeText(&sSql);
10048    if( bDebug ){
10049      utf8_printf(p->out, "%s\n", zSql);
10050    }else{
10051      shell_exec(p, zSql, 0);
10052    }
10053    sqlite3_free(zSql);
10054  }else
10055
10056#ifndef SQLITE_NOHAVE_SYSTEM
10057  if( c=='s'
10058   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10059  ){
10060    char *zCmd;
10061    int i, x;
10062    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10063    if( nArg<2 ){
10064      raw_printf(stderr, "Usage: .system COMMAND\n");
10065      rc = 1;
10066      goto meta_command_exit;
10067    }
10068    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10069    for(i=2; i<nArg && zCmd!=0; i++){
10070      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10071                             zCmd, azArg[i]);
10072    }
10073    x = zCmd!=0 ? system(zCmd) : 1;
10074    sqlite3_free(zCmd);
10075    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10076  }else
10077#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10078
10079  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10080    static const char *azBool[] = { "off", "on", "trigger", "full"};
10081    const char *zOut;
10082    int i;
10083    if( nArg!=1 ){
10084      raw_printf(stderr, "Usage: .show\n");
10085      rc = 1;
10086      goto meta_command_exit;
10087    }
10088    utf8_printf(p->out, "%12.12s: %s\n","echo",
10089                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10090    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10091    utf8_printf(p->out, "%12.12s: %s\n","explain",
10092         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10093    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10094    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10095    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10096      output_c_string(p->out, p->nullValue);
10097      raw_printf(p->out, "\n");
10098    utf8_printf(p->out,"%12.12s: %s\n","output",
10099            strlen30(p->outfile) ? p->outfile : "stdout");
10100    utf8_printf(p->out,"%12.12s: ", "colseparator");
10101      output_c_string(p->out, p->colSeparator);
10102      raw_printf(p->out, "\n");
10103    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10104      output_c_string(p->out, p->rowSeparator);
10105      raw_printf(p->out, "\n");
10106    switch( p->statsOn ){
10107      case 0:  zOut = "off";     break;
10108      default: zOut = "on";      break;
10109      case 2:  zOut = "stmt";    break;
10110      case 3:  zOut = "vmstep";  break;
10111    }
10112    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10113    utf8_printf(p->out, "%12.12s: ", "width");
10114    for (i=0;i<p->nWidth;i++) {
10115      raw_printf(p->out, "%d ", p->colWidth[i]);
10116    }
10117    raw_printf(p->out, "\n");
10118    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10119                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10120  }else
10121
10122  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10123    if( nArg==2 ){
10124      if( strcmp(azArg[1],"stmt")==0 ){
10125        p->statsOn = 2;
10126      }else if( strcmp(azArg[1],"vmstep")==0 ){
10127        p->statsOn = 3;
10128      }else{
10129        p->statsOn = (u8)booleanValue(azArg[1]);
10130      }
10131    }else if( nArg==1 ){
10132      display_stats(p->db, p, 0);
10133    }else{
10134      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10135      rc = 1;
10136    }
10137  }else
10138
10139  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10140   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10141                 || strncmp(azArg[0], "indexes", n)==0) )
10142  ){
10143    sqlite3_stmt *pStmt;
10144    char **azResult;
10145    int nRow, nAlloc;
10146    int ii;
10147    ShellText s;
10148    initText(&s);
10149    open_db(p, 0);
10150    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10151    if( rc ){
10152      sqlite3_finalize(pStmt);
10153      return shellDatabaseError(p->db);
10154    }
10155
10156    if( nArg>2 && c=='i' ){
10157      /* It is an historical accident that the .indexes command shows an error
10158      ** when called with the wrong number of arguments whereas the .tables
10159      ** command does not. */
10160      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10161      rc = 1;
10162      sqlite3_finalize(pStmt);
10163      goto meta_command_exit;
10164    }
10165    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10166      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10167      if( zDbName==0 ) continue;
10168      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10169      if( sqlite3_stricmp(zDbName, "main")==0 ){
10170        appendText(&s, "SELECT name FROM ", 0);
10171      }else{
10172        appendText(&s, "SELECT ", 0);
10173        appendText(&s, zDbName, '\'');
10174        appendText(&s, "||'.'||name FROM ", 0);
10175      }
10176      appendText(&s, zDbName, '"');
10177      appendText(&s, ".sqlite_schema ", 0);
10178      if( c=='t' ){
10179        appendText(&s," WHERE type IN ('table','view')"
10180                      "   AND name NOT LIKE 'sqlite_%'"
10181                      "   AND name LIKE ?1", 0);
10182      }else{
10183        appendText(&s," WHERE type='index'"
10184                      "   AND tbl_name LIKE ?1", 0);
10185      }
10186    }
10187    rc = sqlite3_finalize(pStmt);
10188    if( rc==SQLITE_OK ){
10189      appendText(&s, " ORDER BY 1", 0);
10190      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10191    }
10192    freeText(&s);
10193    if( rc ) return shellDatabaseError(p->db);
10194
10195    /* Run the SQL statement prepared by the above block. Store the results
10196    ** as an array of nul-terminated strings in azResult[].  */
10197    nRow = nAlloc = 0;
10198    azResult = 0;
10199    if( nArg>1 ){
10200      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10201    }else{
10202      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10203    }
10204    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10205      if( nRow>=nAlloc ){
10206        char **azNew;
10207        int n2 = nAlloc*2 + 10;
10208        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10209        shell_check_oom(azNew);
10210        nAlloc = n2;
10211        azResult = azNew;
10212      }
10213      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10214      shell_check_oom(azResult[nRow]);
10215      nRow++;
10216    }
10217    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10218      rc = shellDatabaseError(p->db);
10219    }
10220
10221    /* Pretty-print the contents of array azResult[] to the output */
10222    if( rc==0 && nRow>0 ){
10223      int len, maxlen = 0;
10224      int i, j;
10225      int nPrintCol, nPrintRow;
10226      for(i=0; i<nRow; i++){
10227        len = strlen30(azResult[i]);
10228        if( len>maxlen ) maxlen = len;
10229      }
10230      nPrintCol = 80/(maxlen+2);
10231      if( nPrintCol<1 ) nPrintCol = 1;
10232      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10233      for(i=0; i<nPrintRow; i++){
10234        for(j=i; j<nRow; j+=nPrintRow){
10235          char *zSp = j<nPrintRow ? "" : "  ";
10236          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10237                      azResult[j] ? azResult[j]:"");
10238        }
10239        raw_printf(p->out, "\n");
10240      }
10241    }
10242
10243    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10244    sqlite3_free(azResult);
10245  }else
10246
10247  /* Begin redirecting output to the file "testcase-out.txt" */
10248  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10249    output_reset(p);
10250    p->out = output_file_open("testcase-out.txt", 0);
10251    if( p->out==0 ){
10252      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10253    }
10254    if( nArg>=2 ){
10255      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10256    }else{
10257      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10258    }
10259  }else
10260
10261#ifndef SQLITE_UNTESTABLE
10262  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10263    static const struct {
10264       const char *zCtrlName;   /* Name of a test-control option */
10265       int ctrlCode;            /* Integer code for that option */
10266       int unSafe;              /* Not valid for --safe mode */
10267       const char *zUsage;      /* Usage notes */
10268    } aCtrl[] = {
10269      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10270      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10271    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10272    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10273      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10274      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10275    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10276      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10277      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10278      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10279      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10280      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10281#ifdef YYCOVERAGE
10282      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10283#endif
10284      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10285      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10286      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10287      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10288      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10289      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10290      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10291    };
10292    int testctrl = -1;
10293    int iCtrl = -1;
10294    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10295    int isOk = 0;
10296    int i, n2;
10297    const char *zCmd = 0;
10298
10299    open_db(p, 0);
10300    zCmd = nArg>=2 ? azArg[1] : "help";
10301
10302    /* The argument can optionally begin with "-" or "--" */
10303    if( zCmd[0]=='-' && zCmd[1] ){
10304      zCmd++;
10305      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10306    }
10307
10308    /* --help lists all test-controls */
10309    if( strcmp(zCmd,"help")==0 ){
10310      utf8_printf(p->out, "Available test-controls:\n");
10311      for(i=0; i<ArraySize(aCtrl); i++){
10312        utf8_printf(p->out, "  .testctrl %s %s\n",
10313                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10314      }
10315      rc = 1;
10316      goto meta_command_exit;
10317    }
10318
10319    /* convert testctrl text option to value. allow any unique prefix
10320    ** of the option name, or a numerical value. */
10321    n2 = strlen30(zCmd);
10322    for(i=0; i<ArraySize(aCtrl); i++){
10323      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10324        if( testctrl<0 ){
10325          testctrl = aCtrl[i].ctrlCode;
10326          iCtrl = i;
10327        }else{
10328          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10329                              "Use \".testctrl --help\" for help\n", zCmd);
10330          rc = 1;
10331          goto meta_command_exit;
10332        }
10333      }
10334    }
10335    if( testctrl<0 ){
10336      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10337                         "Use \".testctrl --help\" for help\n", zCmd);
10338    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10339      utf8_printf(stderr,
10340         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10341         p->lineno, aCtrl[iCtrl].zCtrlName);
10342      exit(1);
10343    }else{
10344      switch(testctrl){
10345
10346        /* sqlite3_test_control(int, db, int) */
10347        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10348          if( nArg==3 ){
10349            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10350            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10351            isOk = 3;
10352          }
10353          break;
10354
10355        /* sqlite3_test_control(int) */
10356        case SQLITE_TESTCTRL_PRNG_SAVE:
10357        case SQLITE_TESTCTRL_PRNG_RESTORE:
10358        case SQLITE_TESTCTRL_BYTEORDER:
10359          if( nArg==2 ){
10360            rc2 = sqlite3_test_control(testctrl);
10361            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10362          }
10363          break;
10364
10365        /* sqlite3_test_control(int, uint) */
10366        case SQLITE_TESTCTRL_PENDING_BYTE:
10367          if( nArg==3 ){
10368            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10369            rc2 = sqlite3_test_control(testctrl, opt);
10370            isOk = 3;
10371          }
10372          break;
10373
10374        /* sqlite3_test_control(int, int, sqlite3*) */
10375        case SQLITE_TESTCTRL_PRNG_SEED:
10376          if( nArg==3 || nArg==4 ){
10377            int ii = (int)integerValue(azArg[2]);
10378            sqlite3 *db;
10379            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10380              sqlite3_randomness(sizeof(ii),&ii);
10381              printf("-- random seed: %d\n", ii);
10382            }
10383            if( nArg==3 ){
10384              db = 0;
10385            }else{
10386              db = p->db;
10387              /* Make sure the schema has been loaded */
10388              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10389            }
10390            rc2 = sqlite3_test_control(testctrl, ii, db);
10391            isOk = 3;
10392          }
10393          break;
10394
10395        /* sqlite3_test_control(int, int) */
10396        case SQLITE_TESTCTRL_ASSERT:
10397        case SQLITE_TESTCTRL_ALWAYS:
10398          if( nArg==3 ){
10399            int opt = booleanValue(azArg[2]);
10400            rc2 = sqlite3_test_control(testctrl, opt);
10401            isOk = 1;
10402          }
10403          break;
10404
10405        /* sqlite3_test_control(int, int) */
10406        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10407        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10408          if( nArg==3 ){
10409            int opt = booleanValue(azArg[2]);
10410            rc2 = sqlite3_test_control(testctrl, opt);
10411            isOk = 3;
10412          }
10413          break;
10414
10415        /* sqlite3_test_control(sqlite3*) */
10416        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10417          rc2 = sqlite3_test_control(testctrl, p->db);
10418          isOk = 3;
10419          break;
10420
10421        case SQLITE_TESTCTRL_IMPOSTER:
10422          if( nArg==5 ){
10423            rc2 = sqlite3_test_control(testctrl, p->db,
10424                          azArg[2],
10425                          integerValue(azArg[3]),
10426                          integerValue(azArg[4]));
10427            isOk = 3;
10428          }
10429          break;
10430
10431        case SQLITE_TESTCTRL_SEEK_COUNT: {
10432          u64 x = 0;
10433          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10434          utf8_printf(p->out, "%llu\n", x);
10435          isOk = 3;
10436          break;
10437        }
10438
10439#ifdef YYCOVERAGE
10440        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10441          if( nArg==2 ){
10442            sqlite3_test_control(testctrl, p->out);
10443            isOk = 3;
10444          }
10445          break;
10446        }
10447#endif
10448#ifdef SQLITE_DEBUG
10449        case SQLITE_TESTCTRL_TUNE: {
10450          if( nArg==4 ){
10451            int id = (int)integerValue(azArg[2]);
10452            int val = (int)integerValue(azArg[3]);
10453            sqlite3_test_control(testctrl, id, &val);
10454            isOk = 3;
10455          }else if( nArg==3 ){
10456            int id = (int)integerValue(azArg[2]);
10457            sqlite3_test_control(testctrl, -id, &rc2);
10458            isOk = 1;
10459          }else if( nArg==2 ){
10460            int id = 1;
10461            while(1){
10462              int val = 0;
10463              rc2 = sqlite3_test_control(testctrl, -id, &val);
10464              if( rc2!=SQLITE_OK ) break;
10465              if( id>1 ) utf8_printf(p->out, "  ");
10466              utf8_printf(p->out, "%d: %d", id, val);
10467              id++;
10468            }
10469            if( id>1 ) utf8_printf(p->out, "\n");
10470            isOk = 3;
10471          }
10472          break;
10473        }
10474#endif
10475        case SQLITE_TESTCTRL_SORTER_MMAP:
10476          if( nArg==3 ){
10477            int opt = (unsigned int)integerValue(azArg[2]);
10478            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10479            isOk = 3;
10480          }
10481          break;
10482      }
10483    }
10484    if( isOk==0 && iCtrl>=0 ){
10485      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10486      rc = 1;
10487    }else if( isOk==1 ){
10488      raw_printf(p->out, "%d\n", rc2);
10489    }else if( isOk==2 ){
10490      raw_printf(p->out, "0x%08x\n", rc2);
10491    }
10492  }else
10493#endif /* !defined(SQLITE_UNTESTABLE) */
10494
10495  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10496    open_db(p, 0);
10497    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10498  }else
10499
10500  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10501    if( nArg==2 ){
10502      enableTimer = booleanValue(azArg[1]);
10503      if( enableTimer && !HAS_TIMER ){
10504        raw_printf(stderr, "Error: timer not available on this system.\n");
10505        enableTimer = 0;
10506      }
10507    }else{
10508      raw_printf(stderr, "Usage: .timer on|off\n");
10509      rc = 1;
10510    }
10511  }else
10512
10513#ifndef SQLITE_OMIT_TRACE
10514  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10515    int mType = 0;
10516    int jj;
10517    open_db(p, 0);
10518    for(jj=1; jj<nArg; jj++){
10519      const char *z = azArg[jj];
10520      if( z[0]=='-' ){
10521        if( optionMatch(z, "expanded") ){
10522          p->eTraceType = SHELL_TRACE_EXPANDED;
10523        }
10524#ifdef SQLITE_ENABLE_NORMALIZE
10525        else if( optionMatch(z, "normalized") ){
10526          p->eTraceType = SHELL_TRACE_NORMALIZED;
10527        }
10528#endif
10529        else if( optionMatch(z, "plain") ){
10530          p->eTraceType = SHELL_TRACE_PLAIN;
10531        }
10532        else if( optionMatch(z, "profile") ){
10533          mType |= SQLITE_TRACE_PROFILE;
10534        }
10535        else if( optionMatch(z, "row") ){
10536          mType |= SQLITE_TRACE_ROW;
10537        }
10538        else if( optionMatch(z, "stmt") ){
10539          mType |= SQLITE_TRACE_STMT;
10540        }
10541        else if( optionMatch(z, "close") ){
10542          mType |= SQLITE_TRACE_CLOSE;
10543        }
10544        else {
10545          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10546          rc = 1;
10547          goto meta_command_exit;
10548        }
10549      }else{
10550        output_file_close(p->traceOut);
10551        p->traceOut = output_file_open(azArg[1], 0);
10552      }
10553    }
10554    if( p->traceOut==0 ){
10555      sqlite3_trace_v2(p->db, 0, 0, 0);
10556    }else{
10557      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10558      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10559    }
10560  }else
10561#endif /* !defined(SQLITE_OMIT_TRACE) */
10562
10563#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10564  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10565    int ii;
10566    int lenOpt;
10567    char *zOpt;
10568    if( nArg<2 ){
10569      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10570      rc = 1;
10571      goto meta_command_exit;
10572    }
10573    open_db(p, 0);
10574    zOpt = azArg[1];
10575    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10576    lenOpt = (int)strlen(zOpt);
10577    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10578      assert( azArg[nArg]==0 );
10579      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10580    }else{
10581      for(ii=1; ii<nArg; ii++){
10582        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10583      }
10584    }
10585  }else
10586#endif
10587
10588#if SQLITE_USER_AUTHENTICATION
10589  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10590    if( nArg<2 ){
10591      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10592      rc = 1;
10593      goto meta_command_exit;
10594    }
10595    open_db(p, 0);
10596    if( strcmp(azArg[1],"login")==0 ){
10597      if( nArg!=4 ){
10598        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10599        rc = 1;
10600        goto meta_command_exit;
10601      }
10602      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10603                                     strlen30(azArg[3]));
10604      if( rc ){
10605        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10606        rc = 1;
10607      }
10608    }else if( strcmp(azArg[1],"add")==0 ){
10609      if( nArg!=5 ){
10610        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10611        rc = 1;
10612        goto meta_command_exit;
10613      }
10614      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10615                            booleanValue(azArg[4]));
10616      if( rc ){
10617        raw_printf(stderr, "User-Add failed: %d\n", rc);
10618        rc = 1;
10619      }
10620    }else if( strcmp(azArg[1],"edit")==0 ){
10621      if( nArg!=5 ){
10622        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10623        rc = 1;
10624        goto meta_command_exit;
10625      }
10626      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10627                              booleanValue(azArg[4]));
10628      if( rc ){
10629        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10630        rc = 1;
10631      }
10632    }else if( strcmp(azArg[1],"delete")==0 ){
10633      if( nArg!=3 ){
10634        raw_printf(stderr, "Usage: .user delete USER\n");
10635        rc = 1;
10636        goto meta_command_exit;
10637      }
10638      rc = sqlite3_user_delete(p->db, azArg[2]);
10639      if( rc ){
10640        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10641        rc = 1;
10642      }
10643    }else{
10644      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10645      rc = 1;
10646      goto meta_command_exit;
10647    }
10648  }else
10649#endif /* SQLITE_USER_AUTHENTICATION */
10650
10651  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10652    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10653        sqlite3_libversion(), sqlite3_sourceid());
10654#if SQLITE_HAVE_ZLIB
10655    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10656#endif
10657#define CTIMEOPT_VAL_(opt) #opt
10658#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10659#if defined(__clang__) && defined(__clang_major__)
10660    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10661                    CTIMEOPT_VAL(__clang_minor__) "."
10662                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10663#elif defined(_MSC_VER)
10664    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10665#elif defined(__GNUC__) && defined(__VERSION__)
10666    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10667#endif
10668  }else
10669
10670  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10671    const char *zDbName = nArg==2 ? azArg[1] : "main";
10672    sqlite3_vfs *pVfs = 0;
10673    if( p->db ){
10674      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10675      if( pVfs ){
10676        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10677        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10678        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10679        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10680      }
10681    }
10682  }else
10683
10684  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10685    sqlite3_vfs *pVfs;
10686    sqlite3_vfs *pCurrent = 0;
10687    if( p->db ){
10688      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10689    }
10690    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10691      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10692           pVfs==pCurrent ? "  <--- CURRENT" : "");
10693      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10694      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10695      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10696      if( pVfs->pNext ){
10697        raw_printf(p->out, "-----------------------------------\n");
10698      }
10699    }
10700  }else
10701
10702  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10703    const char *zDbName = nArg==2 ? azArg[1] : "main";
10704    char *zVfsName = 0;
10705    if( p->db ){
10706      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10707      if( zVfsName ){
10708        utf8_printf(p->out, "%s\n", zVfsName);
10709        sqlite3_free(zVfsName);
10710      }
10711    }
10712  }else
10713
10714  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10715    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10716    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10717  }else
10718
10719  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10720    int j;
10721    assert( nArg<=ArraySize(azArg) );
10722    p->nWidth = nArg-1;
10723    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10724    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10725    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10726    for(j=1; j<nArg; j++){
10727      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10728    }
10729  }else
10730
10731  {
10732    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10733      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10734    rc = 1;
10735  }
10736
10737meta_command_exit:
10738  if( p->outCount ){
10739    p->outCount--;
10740    if( p->outCount==0 ) output_reset(p);
10741  }
10742  p->bSafeMode = p->bSafeModePersist;
10743  return rc;
10744}
10745
10746/* Line scan result and intermediate states (supporting scan resumption)
10747*/
10748#ifndef CHAR_BIT
10749# define CHAR_BIT 8
10750#endif
10751typedef enum {
10752  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10753  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10754  QSS_Start = 0
10755} QuickScanState;
10756#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10757#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10758#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10759#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10760#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10761
10762/*
10763** Scan line for classification to guide shell's handling.
10764** The scan is resumable for subsequent lines when prior
10765** return values are passed as the 2nd argument.
10766*/
10767static QuickScanState quickscan(char *zLine, QuickScanState qss){
10768  char cin;
10769  char cWait = (char)qss; /* intentional narrowing loss */
10770  if( cWait==0 ){
10771  PlainScan:
10772    assert( cWait==0 );
10773    while( (cin = *zLine++)!=0 ){
10774      if( IsSpace(cin) )
10775        continue;
10776      switch (cin){
10777      case '-':
10778        if( *zLine!='-' )
10779          break;
10780        while((cin = *++zLine)!=0 )
10781          if( cin=='\n')
10782            goto PlainScan;
10783        return qss;
10784      case ';':
10785        qss |= QSS_EndingSemi;
10786        continue;
10787      case '/':
10788        if( *zLine=='*' ){
10789          ++zLine;
10790          cWait = '*';
10791          qss = QSS_SETV(qss, cWait);
10792          goto TermScan;
10793        }
10794        break;
10795      case '[':
10796        cin = ']';
10797        /* fall thru */
10798      case '`': case '\'': case '"':
10799        cWait = cin;
10800        qss = QSS_HasDark | cWait;
10801        goto TermScan;
10802      default:
10803        break;
10804      }
10805      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10806    }
10807  }else{
10808  TermScan:
10809    while( (cin = *zLine++)!=0 ){
10810      if( cin==cWait ){
10811        switch( cWait ){
10812        case '*':
10813          if( *zLine != '/' )
10814            continue;
10815          ++zLine;
10816          cWait = 0;
10817          qss = QSS_SETV(qss, 0);
10818          goto PlainScan;
10819        case '`': case '\'': case '"':
10820          if(*zLine==cWait){
10821            ++zLine;
10822            continue;
10823          }
10824          /* fall thru */
10825        case ']':
10826          cWait = 0;
10827          qss = QSS_SETV(qss, 0);
10828          goto PlainScan;
10829        default: assert(0);
10830        }
10831      }
10832    }
10833  }
10834  return qss;
10835}
10836
10837/*
10838** Return TRUE if the line typed in is an SQL command terminator other
10839** than a semi-colon.  The SQL Server style "go" command is understood
10840** as is the Oracle "/".
10841*/
10842static int line_is_command_terminator(char *zLine){
10843  while( IsSpace(zLine[0]) ){ zLine++; };
10844  if( zLine[0]=='/' )
10845    zLine += 1; /* Oracle */
10846  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10847    zLine += 2; /* SQL Server */
10848  else
10849    return 0;
10850  return quickscan(zLine,QSS_Start)==QSS_Start;
10851}
10852
10853/*
10854** We need a default sqlite3_complete() implementation to use in case
10855** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10856** any arbitrary text is a complete SQL statement.  This is not very
10857** user-friendly, but it does seem to work.
10858*/
10859#ifdef SQLITE_OMIT_COMPLETE
10860#define sqlite3_complete(x) 1
10861#endif
10862
10863/*
10864** Return true if zSql is a complete SQL statement.  Return false if it
10865** ends in the middle of a string literal or C-style comment.
10866*/
10867static int line_is_complete(char *zSql, int nSql){
10868  int rc;
10869  if( zSql==0 ) return 1;
10870  zSql[nSql] = ';';
10871  zSql[nSql+1] = 0;
10872  rc = sqlite3_complete(zSql);
10873  zSql[nSql] = 0;
10874  return rc;
10875}
10876
10877/*
10878** Run a single line of SQL.  Return the number of errors.
10879*/
10880static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10881  int rc;
10882  char *zErrMsg = 0;
10883
10884  open_db(p, 0);
10885  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10886  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10887  BEGIN_TIMER;
10888  rc = shell_exec(p, zSql, &zErrMsg);
10889  END_TIMER;
10890  if( rc || zErrMsg ){
10891    char zPrefix[100];
10892    if( in!=0 || !stdin_is_interactive ){
10893      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10894                       "Error: near line %d:", startline);
10895    }else{
10896      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10897    }
10898    if( zErrMsg!=0 ){
10899      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10900      sqlite3_free(zErrMsg);
10901      zErrMsg = 0;
10902    }else{
10903      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10904    }
10905    return 1;
10906  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10907    char zLineBuf[2000];
10908    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
10909            "changes: %lld   total_changes: %lld",
10910            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
10911    raw_printf(p->out, "%s\n", zLineBuf);
10912  }
10913  return 0;
10914}
10915
10916
10917/*
10918** Read input from *in and process it.  If *in==0 then input
10919** is interactive - the user is typing it it.  Otherwise, input
10920** is coming from a file or device.  A prompt is issued and history
10921** is saved only if input is interactive.  An interrupt signal will
10922** cause this routine to exit immediately, unless input is interactive.
10923**
10924** Return the number of errors.
10925*/
10926static int process_input(ShellState *p){
10927  char *zLine = 0;          /* A single input line */
10928  char *zSql = 0;           /* Accumulated SQL text */
10929  int nLine;                /* Length of current line */
10930  int nSql = 0;             /* Bytes of zSql[] used */
10931  int nAlloc = 0;           /* Allocated zSql[] space */
10932  int rc;                   /* Error code */
10933  int errCnt = 0;           /* Number of errors seen */
10934  int startline = 0;        /* Line number for start of current input */
10935  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
10936
10937  p->lineno = 0;
10938  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10939    fflush(p->out);
10940    zLine = one_input_line(p->in, zLine, nSql>0);
10941    if( zLine==0 ){
10942      /* End of input */
10943      if( p->in==0 && stdin_is_interactive ) printf("\n");
10944      break;
10945    }
10946    if( seenInterrupt ){
10947      if( p->in!=0 ) break;
10948      seenInterrupt = 0;
10949    }
10950    p->lineno++;
10951    if( QSS_INPLAIN(qss)
10952        && line_is_command_terminator(zLine)
10953        && line_is_complete(zSql, nSql) ){
10954      memcpy(zLine,";",2);
10955    }
10956    qss = quickscan(zLine, qss);
10957    if( QSS_PLAINWHITE(qss) && nSql==0 ){
10958      if( ShellHasFlag(p, SHFLG_Echo) )
10959        printf("%s\n", zLine);
10960      /* Just swallow single-line whitespace */
10961      qss = QSS_Start;
10962      continue;
10963    }
10964    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10965      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10966      if( zLine[0]=='.' ){
10967        rc = do_meta_command(zLine, p);
10968        if( rc==2 ){ /* exit requested */
10969          break;
10970        }else if( rc ){
10971          errCnt++;
10972        }
10973      }
10974      qss = QSS_Start;
10975      continue;
10976    }
10977    /* No single-line dispositions remain; accumulate line(s). */
10978    nLine = strlen30(zLine);
10979    if( nSql+nLine+2>=nAlloc ){
10980      /* Grow buffer by half-again increments when big. */
10981      nAlloc = nSql+(nSql>>1)+nLine+100;
10982      zSql = realloc(zSql, nAlloc);
10983      shell_check_oom(zSql);
10984    }
10985    if( nSql==0 ){
10986      int i;
10987      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10988      assert( nAlloc>0 && zSql!=0 );
10989      memcpy(zSql, zLine+i, nLine+1-i);
10990      startline = p->lineno;
10991      nSql = nLine-i;
10992    }else{
10993      zSql[nSql++] = '\n';
10994      memcpy(zSql+nSql, zLine, nLine+1);
10995      nSql += nLine;
10996    }
10997    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
10998      errCnt += runOneSqlLine(p, zSql, p->in, startline);
10999      nSql = 0;
11000      if( p->outCount ){
11001        output_reset(p);
11002        p->outCount = 0;
11003      }else{
11004        clearTempFile(p);
11005      }
11006      p->bSafeMode = p->bSafeModePersist;
11007      qss = QSS_Start;
11008    }else if( nSql && QSS_PLAINWHITE(qss) ){
11009      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
11010      nSql = 0;
11011      qss = QSS_Start;
11012    }
11013  }
11014  if( nSql && QSS_PLAINDARK(qss) ){
11015    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11016  }
11017  free(zSql);
11018  free(zLine);
11019  return errCnt>0;
11020}
11021
11022/*
11023** Return a pathname which is the user's home directory.  A
11024** 0 return indicates an error of some kind.
11025*/
11026static char *find_home_dir(int clearFlag){
11027  static char *home_dir = NULL;
11028  if( clearFlag ){
11029    free(home_dir);
11030    home_dir = 0;
11031    return 0;
11032  }
11033  if( home_dir ) return home_dir;
11034
11035#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11036     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11037  {
11038    struct passwd *pwent;
11039    uid_t uid = getuid();
11040    if( (pwent=getpwuid(uid)) != NULL) {
11041      home_dir = pwent->pw_dir;
11042    }
11043  }
11044#endif
11045
11046#if defined(_WIN32_WCE)
11047  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11048   */
11049  home_dir = "/";
11050#else
11051
11052#if defined(_WIN32) || defined(WIN32)
11053  if (!home_dir) {
11054    home_dir = getenv("USERPROFILE");
11055  }
11056#endif
11057
11058  if (!home_dir) {
11059    home_dir = getenv("HOME");
11060  }
11061
11062#if defined(_WIN32) || defined(WIN32)
11063  if (!home_dir) {
11064    char *zDrive, *zPath;
11065    int n;
11066    zDrive = getenv("HOMEDRIVE");
11067    zPath = getenv("HOMEPATH");
11068    if( zDrive && zPath ){
11069      n = strlen30(zDrive) + strlen30(zPath) + 1;
11070      home_dir = malloc( n );
11071      if( home_dir==0 ) return 0;
11072      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11073      return home_dir;
11074    }
11075    home_dir = "c:\\";
11076  }
11077#endif
11078
11079#endif /* !_WIN32_WCE */
11080
11081  if( home_dir ){
11082    int n = strlen30(home_dir) + 1;
11083    char *z = malloc( n );
11084    if( z ) memcpy(z, home_dir, n);
11085    home_dir = z;
11086  }
11087
11088  return home_dir;
11089}
11090
11091/*
11092** Read input from the file given by sqliterc_override.  Or if that
11093** parameter is NULL, take input from ~/.sqliterc
11094**
11095** Returns the number of errors.
11096*/
11097static void process_sqliterc(
11098  ShellState *p,                  /* Configuration data */
11099  const char *sqliterc_override   /* Name of config file. NULL to use default */
11100){
11101  char *home_dir = NULL;
11102  const char *sqliterc = sqliterc_override;
11103  char *zBuf = 0;
11104  FILE *inSaved = p->in;
11105  int savedLineno = p->lineno;
11106
11107  if (sqliterc == NULL) {
11108    home_dir = find_home_dir(0);
11109    if( home_dir==0 ){
11110      raw_printf(stderr, "-- warning: cannot find home directory;"
11111                      " cannot read ~/.sqliterc\n");
11112      return;
11113    }
11114    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11115    shell_check_oom(zBuf);
11116    sqliterc = zBuf;
11117  }
11118  p->in = fopen(sqliterc,"rb");
11119  if( p->in ){
11120    if( stdin_is_interactive ){
11121      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11122    }
11123    if( process_input(p) && bail_on_error ) exit(1);
11124    fclose(p->in);
11125  }else if( sqliterc_override!=0 ){
11126    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11127    if( bail_on_error ) exit(1);
11128  }
11129  p->in = inSaved;
11130  p->lineno = savedLineno;
11131  sqlite3_free(zBuf);
11132}
11133
11134/*
11135** Show available command line options
11136*/
11137static const char zOptions[] =
11138#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11139  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11140#endif
11141  "   -append              append the database to the end of the file\n"
11142  "   -ascii               set output mode to 'ascii'\n"
11143  "   -bail                stop after hitting an error\n"
11144  "   -batch               force batch I/O\n"
11145  "   -box                 set output mode to 'box'\n"
11146  "   -column              set output mode to 'column'\n"
11147  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11148  "   -csv                 set output mode to 'csv'\n"
11149#if !defined(SQLITE_OMIT_DESERIALIZE)
11150  "   -deserialize         open the database using sqlite3_deserialize()\n"
11151#endif
11152  "   -echo                print commands before execution\n"
11153  "   -init FILENAME       read/process named file\n"
11154  "   -[no]header          turn headers on or off\n"
11155#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11156  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11157#endif
11158  "   -help                show this message\n"
11159  "   -html                set output mode to HTML\n"
11160  "   -interactive         force interactive I/O\n"
11161  "   -json                set output mode to 'json'\n"
11162  "   -line                set output mode to 'line'\n"
11163  "   -list                set output mode to 'list'\n"
11164  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11165  "   -markdown            set output mode to 'markdown'\n"
11166#if !defined(SQLITE_OMIT_DESERIALIZE)
11167  "   -maxsize N           maximum size for a --deserialize database\n"
11168#endif
11169  "   -memtrace            trace all memory allocations and deallocations\n"
11170  "   -mmap N              default mmap size set to N\n"
11171#ifdef SQLITE_ENABLE_MULTIPLEX
11172  "   -multiplex           enable the multiplexor VFS\n"
11173#endif
11174  "   -newline SEP         set output row separator. Default: '\\n'\n"
11175  "   -nofollow            refuse to open symbolic links to database files\n"
11176  "   -nonce STRING        set the safe-mode escape nonce\n"
11177  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11178  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11179  "   -quote               set output mode to 'quote'\n"
11180  "   -readonly            open the database read-only\n"
11181  "   -safe                enable safe-mode\n"
11182  "   -separator SEP       set output column separator. Default: '|'\n"
11183#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11184  "   -sorterref SIZE      sorter references threshold size\n"
11185#endif
11186  "   -stats               print memory stats before each finalize\n"
11187  "   -table               set output mode to 'table'\n"
11188  "   -tabs                set output mode to 'tabs'\n"
11189  "   -version             show SQLite version\n"
11190  "   -vfs NAME            use NAME as the default VFS\n"
11191#ifdef SQLITE_ENABLE_VFSTRACE
11192  "   -vfstrace            enable tracing of all VFS calls\n"
11193#endif
11194#ifdef SQLITE_HAVE_ZLIB
11195  "   -zip                 open the file as a ZIP Archive\n"
11196#endif
11197;
11198static void usage(int showDetail){
11199  utf8_printf(stderr,
11200      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11201      "FILENAME is the name of an SQLite database. A new database is created\n"
11202      "if the file does not previously exist.\n", Argv0);
11203  if( showDetail ){
11204    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11205  }else{
11206    raw_printf(stderr, "Use the -help option for additional information\n");
11207  }
11208  exit(1);
11209}
11210
11211/*
11212** Internal check:  Verify that the SQLite is uninitialized.  Print a
11213** error message if it is initialized.
11214*/
11215static void verify_uninitialized(void){
11216  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11217    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11218                        " initialization.\n");
11219  }
11220}
11221
11222/*
11223** Initialize the state information in data
11224*/
11225static void main_init(ShellState *data) {
11226  memset(data, 0, sizeof(*data));
11227  data->normalMode = data->cMode = data->mode = MODE_List;
11228  data->autoExplain = 1;
11229  data->pAuxDb = &data->aAuxDb[0];
11230  memcpy(data->colSeparator,SEP_Column, 2);
11231  memcpy(data->rowSeparator,SEP_Row, 2);
11232  data->showHeader = 0;
11233  data->shellFlgs = SHFLG_Lookaside;
11234  verify_uninitialized();
11235  sqlite3_config(SQLITE_CONFIG_URI, 1);
11236  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11237  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11238  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11239  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11240}
11241
11242/*
11243** Output text to the console in a font that attracts extra attention.
11244*/
11245#ifdef _WIN32
11246static void printBold(const char *zText){
11247#if !SQLITE_OS_WINRT
11248  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11249  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11250  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11251  SetConsoleTextAttribute(out,
11252         FOREGROUND_RED|FOREGROUND_INTENSITY
11253  );
11254#endif
11255  printf("%s", zText);
11256#if !SQLITE_OS_WINRT
11257  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11258#endif
11259}
11260#else
11261static void printBold(const char *zText){
11262  printf("\033[1m%s\033[0m", zText);
11263}
11264#endif
11265
11266/*
11267** Get the argument to an --option.  Throw an error and die if no argument
11268** is available.
11269*/
11270static char *cmdline_option_value(int argc, char **argv, int i){
11271  if( i==argc ){
11272    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11273            argv[0], argv[argc-1]);
11274    exit(1);
11275  }
11276  return argv[i];
11277}
11278
11279#ifndef SQLITE_SHELL_IS_UTF8
11280#  if (defined(_WIN32) || defined(WIN32)) \
11281   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11282#    define SQLITE_SHELL_IS_UTF8          (0)
11283#  else
11284#    define SQLITE_SHELL_IS_UTF8          (1)
11285#  endif
11286#endif
11287
11288#if SQLITE_SHELL_IS_UTF8
11289int SQLITE_CDECL main(int argc, char **argv){
11290#else
11291int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11292  char **argv;
11293#endif
11294  char *zErrMsg = 0;
11295  ShellState data;
11296  const char *zInitFile = 0;
11297  int i;
11298  int rc = 0;
11299  int warnInmemoryDb = 0;
11300  int readStdin = 1;
11301  int nCmd = 0;
11302  char **azCmd = 0;
11303  const char *zVfs = 0;           /* Value of -vfs command-line option */
11304#if !SQLITE_SHELL_IS_UTF8
11305  char **argvToFree = 0;
11306  int argcToFree = 0;
11307#endif
11308
11309  setBinaryMode(stdin, 0);
11310  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11311  stdin_is_interactive = isatty(0);
11312  stdout_is_console = isatty(1);
11313
11314#ifdef SQLITE_DEBUG
11315  registerOomSimulator();
11316#endif
11317
11318#if !defined(_WIN32_WCE)
11319  if( getenv("SQLITE_DEBUG_BREAK") ){
11320    if( isatty(0) && isatty(2) ){
11321      fprintf(stderr,
11322          "attach debugger to process %d and press any key to continue.\n",
11323          GETPID());
11324      fgetc(stdin);
11325    }else{
11326#if defined(_WIN32) || defined(WIN32)
11327#if SQLITE_OS_WINRT
11328      __debugbreak();
11329#else
11330      DebugBreak();
11331#endif
11332#elif defined(SIGTRAP)
11333      raise(SIGTRAP);
11334#endif
11335    }
11336  }
11337#endif
11338
11339#if USE_SYSTEM_SQLITE+0!=1
11340  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11341    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11342            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11343    exit(1);
11344  }
11345#endif
11346  main_init(&data);
11347
11348  /* On Windows, we must translate command-line arguments into UTF-8.
11349  ** The SQLite memory allocator subsystem has to be enabled in order to
11350  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11351  ** subsequent sqlite3_config() calls will work.  So copy all results into
11352  ** memory that does not come from the SQLite memory allocator.
11353  */
11354#if !SQLITE_SHELL_IS_UTF8
11355  sqlite3_initialize();
11356  argvToFree = malloc(sizeof(argv[0])*argc*2);
11357  shell_check_oom(argvToFree);
11358  argcToFree = argc;
11359  argv = argvToFree + argc;
11360  for(i=0; i<argc; i++){
11361    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11362    int n;
11363    shell_check_oom(z);
11364    n = (int)strlen(z);
11365    argv[i] = malloc( n+1 );
11366    shell_check_oom(argv[i]);
11367    memcpy(argv[i], z, n+1);
11368    argvToFree[i] = argv[i];
11369    sqlite3_free(z);
11370  }
11371  sqlite3_shutdown();
11372#endif
11373
11374  assert( argc>=1 && argv && argv[0] );
11375  Argv0 = argv[0];
11376
11377  /* Make sure we have a valid signal handler early, before anything
11378  ** else is done.
11379  */
11380#ifdef SIGINT
11381  signal(SIGINT, interrupt_handler);
11382#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11383  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11384#endif
11385
11386#ifdef SQLITE_SHELL_DBNAME_PROC
11387  {
11388    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11389    ** of a C-function that will provide the name of the database file.  Use
11390    ** this compile-time option to embed this shell program in larger
11391    ** applications. */
11392    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11393    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11394    warnInmemoryDb = 0;
11395  }
11396#endif
11397
11398  /* Do an initial pass through the command-line argument to locate
11399  ** the name of the database file, the name of the initialization file,
11400  ** the size of the alternative malloc heap,
11401  ** and the first command to execute.
11402  */
11403  verify_uninitialized();
11404  for(i=1; i<argc; i++){
11405    char *z;
11406    z = argv[i];
11407    if( z[0]!='-' ){
11408      if( data.aAuxDb->zDbFilename==0 ){
11409        data.aAuxDb->zDbFilename = z;
11410      }else{
11411        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11412        ** mean that nothing is read from stdin */
11413        readStdin = 0;
11414        nCmd++;
11415        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11416        shell_check_oom(azCmd);
11417        azCmd[nCmd-1] = z;
11418      }
11419    }
11420    if( z[1]=='-' ) z++;
11421    if( strcmp(z,"-separator")==0
11422     || strcmp(z,"-nullvalue")==0
11423     || strcmp(z,"-newline")==0
11424     || strcmp(z,"-cmd")==0
11425    ){
11426      (void)cmdline_option_value(argc, argv, ++i);
11427    }else if( strcmp(z,"-init")==0 ){
11428      zInitFile = cmdline_option_value(argc, argv, ++i);
11429    }else if( strcmp(z,"-batch")==0 ){
11430      /* Need to check for batch mode here to so we can avoid printing
11431      ** informational messages (like from process_sqliterc) before
11432      ** we do the actual processing of arguments later in a second pass.
11433      */
11434      stdin_is_interactive = 0;
11435    }else if( strcmp(z,"-heap")==0 ){
11436#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11437      const char *zSize;
11438      sqlite3_int64 szHeap;
11439
11440      zSize = cmdline_option_value(argc, argv, ++i);
11441      szHeap = integerValue(zSize);
11442      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11443      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11444#else
11445      (void)cmdline_option_value(argc, argv, ++i);
11446#endif
11447    }else if( strcmp(z,"-pagecache")==0 ){
11448      sqlite3_int64 n, sz;
11449      sz = integerValue(cmdline_option_value(argc,argv,++i));
11450      if( sz>70000 ) sz = 70000;
11451      if( sz<0 ) sz = 0;
11452      n = integerValue(cmdline_option_value(argc,argv,++i));
11453      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11454        n = 0xffffffffffffLL/sz;
11455      }
11456      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11457                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11458      data.shellFlgs |= SHFLG_Pagecache;
11459    }else if( strcmp(z,"-lookaside")==0 ){
11460      int n, sz;
11461      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11462      if( sz<0 ) sz = 0;
11463      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11464      if( n<0 ) n = 0;
11465      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11466      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11467    }else if( strcmp(z,"-threadsafe")==0 ){
11468      int n;
11469      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11470      switch( n ){
11471         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11472         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11473         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11474      }
11475#ifdef SQLITE_ENABLE_VFSTRACE
11476    }else if( strcmp(z,"-vfstrace")==0 ){
11477      extern int vfstrace_register(
11478         const char *zTraceName,
11479         const char *zOldVfsName,
11480         int (*xOut)(const char*,void*),
11481         void *pOutArg,
11482         int makeDefault
11483      );
11484      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11485#endif
11486#ifdef SQLITE_ENABLE_MULTIPLEX
11487    }else if( strcmp(z,"-multiplex")==0 ){
11488      extern int sqlite3_multiple_initialize(const char*,int);
11489      sqlite3_multiplex_initialize(0, 1);
11490#endif
11491    }else if( strcmp(z,"-mmap")==0 ){
11492      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11493      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11494#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11495    }else if( strcmp(z,"-sorterref")==0 ){
11496      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11497      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11498#endif
11499    }else if( strcmp(z,"-vfs")==0 ){
11500      zVfs = cmdline_option_value(argc, argv, ++i);
11501#ifdef SQLITE_HAVE_ZLIB
11502    }else if( strcmp(z,"-zip")==0 ){
11503      data.openMode = SHELL_OPEN_ZIPFILE;
11504#endif
11505    }else if( strcmp(z,"-append")==0 ){
11506      data.openMode = SHELL_OPEN_APPENDVFS;
11507#ifndef SQLITE_OMIT_DESERIALIZE
11508    }else if( strcmp(z,"-deserialize")==0 ){
11509      data.openMode = SHELL_OPEN_DESERIALIZE;
11510    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11511      data.szMax = integerValue(argv[++i]);
11512#endif
11513    }else if( strcmp(z,"-readonly")==0 ){
11514      data.openMode = SHELL_OPEN_READONLY;
11515    }else if( strcmp(z,"-nofollow")==0 ){
11516      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11517#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11518    }else if( strncmp(z, "-A",2)==0 ){
11519      /* All remaining command-line arguments are passed to the ".archive"
11520      ** command, so ignore them */
11521      break;
11522#endif
11523    }else if( strcmp(z, "-memtrace")==0 ){
11524      sqlite3MemTraceActivate(stderr);
11525    }else if( strcmp(z,"-bail")==0 ){
11526      bail_on_error = 1;
11527    }else if( strcmp(z,"-nonce")==0 ){
11528      free(data.zNonce);
11529      data.zNonce = strdup(argv[++i]);
11530    }else if( strcmp(z,"-safe")==0 ){
11531      /* no-op - catch this on the second pass */
11532    }
11533  }
11534  verify_uninitialized();
11535
11536
11537#ifdef SQLITE_SHELL_INIT_PROC
11538  {
11539    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11540    ** of a C-function that will perform initialization actions on SQLite that
11541    ** occur just before or after sqlite3_initialize(). Use this compile-time
11542    ** option to embed this shell program in larger applications. */
11543    extern void SQLITE_SHELL_INIT_PROC(void);
11544    SQLITE_SHELL_INIT_PROC();
11545  }
11546#else
11547  /* All the sqlite3_config() calls have now been made. So it is safe
11548  ** to call sqlite3_initialize() and process any command line -vfs option. */
11549  sqlite3_initialize();
11550#endif
11551
11552  if( zVfs ){
11553    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11554    if( pVfs ){
11555      sqlite3_vfs_register(pVfs, 1);
11556    }else{
11557      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11558      exit(1);
11559    }
11560  }
11561
11562  if( data.pAuxDb->zDbFilename==0 ){
11563#ifndef SQLITE_OMIT_MEMORYDB
11564    data.pAuxDb->zDbFilename = ":memory:";
11565    warnInmemoryDb = argc==1;
11566#else
11567    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11568    return 1;
11569#endif
11570  }
11571  data.out = stdout;
11572  sqlite3_appendvfs_init(0,0,0);
11573
11574  /* Go ahead and open the database file if it already exists.  If the
11575  ** file does not exist, delay opening it.  This prevents empty database
11576  ** files from being created if a user mistypes the database name argument
11577  ** to the sqlite command-line tool.
11578  */
11579  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11580    open_db(&data, 0);
11581  }
11582
11583  /* Process the initialization file if there is one.  If no -init option
11584  ** is given on the command line, look for a file named ~/.sqliterc and
11585  ** try to process it.
11586  */
11587  process_sqliterc(&data,zInitFile);
11588
11589  /* Make a second pass through the command-line argument and set
11590  ** options.  This second pass is delayed until after the initialization
11591  ** file is processed so that the command-line arguments will override
11592  ** settings in the initialization file.
11593  */
11594  for(i=1; i<argc; i++){
11595    char *z = argv[i];
11596    if( z[0]!='-' ) continue;
11597    if( z[1]=='-' ){ z++; }
11598    if( strcmp(z,"-init")==0 ){
11599      i++;
11600    }else if( strcmp(z,"-html")==0 ){
11601      data.mode = MODE_Html;
11602    }else if( strcmp(z,"-list")==0 ){
11603      data.mode = MODE_List;
11604    }else if( strcmp(z,"-quote")==0 ){
11605      data.mode = MODE_Quote;
11606      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11607      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11608    }else if( strcmp(z,"-line")==0 ){
11609      data.mode = MODE_Line;
11610    }else if( strcmp(z,"-column")==0 ){
11611      data.mode = MODE_Column;
11612    }else if( strcmp(z,"-json")==0 ){
11613      data.mode = MODE_Json;
11614    }else if( strcmp(z,"-markdown")==0 ){
11615      data.mode = MODE_Markdown;
11616    }else if( strcmp(z,"-table")==0 ){
11617      data.mode = MODE_Table;
11618    }else if( strcmp(z,"-box")==0 ){
11619      data.mode = MODE_Box;
11620    }else if( strcmp(z,"-csv")==0 ){
11621      data.mode = MODE_Csv;
11622      memcpy(data.colSeparator,",",2);
11623#ifdef SQLITE_HAVE_ZLIB
11624    }else if( strcmp(z,"-zip")==0 ){
11625      data.openMode = SHELL_OPEN_ZIPFILE;
11626#endif
11627    }else if( strcmp(z,"-append")==0 ){
11628      data.openMode = SHELL_OPEN_APPENDVFS;
11629#ifndef SQLITE_OMIT_DESERIALIZE
11630    }else if( strcmp(z,"-deserialize")==0 ){
11631      data.openMode = SHELL_OPEN_DESERIALIZE;
11632    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11633      data.szMax = integerValue(argv[++i]);
11634#endif
11635    }else if( strcmp(z,"-readonly")==0 ){
11636      data.openMode = SHELL_OPEN_READONLY;
11637    }else if( strcmp(z,"-nofollow")==0 ){
11638      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11639    }else if( strcmp(z,"-ascii")==0 ){
11640      data.mode = MODE_Ascii;
11641      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11642      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11643    }else if( strcmp(z,"-tabs")==0 ){
11644      data.mode = MODE_List;
11645      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11646      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11647    }else if( strcmp(z,"-separator")==0 ){
11648      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11649                       "%s",cmdline_option_value(argc,argv,++i));
11650    }else if( strcmp(z,"-newline")==0 ){
11651      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11652                       "%s",cmdline_option_value(argc,argv,++i));
11653    }else if( strcmp(z,"-nullvalue")==0 ){
11654      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11655                       "%s",cmdline_option_value(argc,argv,++i));
11656    }else if( strcmp(z,"-header")==0 ){
11657      data.showHeader = 1;
11658      ShellSetFlag(&data, SHFLG_HeaderSet);
11659     }else if( strcmp(z,"-noheader")==0 ){
11660      data.showHeader = 0;
11661      ShellSetFlag(&data, SHFLG_HeaderSet);
11662    }else if( strcmp(z,"-echo")==0 ){
11663      ShellSetFlag(&data, SHFLG_Echo);
11664    }else if( strcmp(z,"-eqp")==0 ){
11665      data.autoEQP = AUTOEQP_on;
11666    }else if( strcmp(z,"-eqpfull")==0 ){
11667      data.autoEQP = AUTOEQP_full;
11668    }else if( strcmp(z,"-stats")==0 ){
11669      data.statsOn = 1;
11670    }else if( strcmp(z,"-scanstats")==0 ){
11671      data.scanstatsOn = 1;
11672    }else if( strcmp(z,"-backslash")==0 ){
11673      /* Undocumented command-line option: -backslash
11674      ** Causes C-style backslash escapes to be evaluated in SQL statements
11675      ** prior to sending the SQL into SQLite.  Useful for injecting
11676      ** crazy bytes in the middle of SQL statements for testing and debugging.
11677      */
11678      ShellSetFlag(&data, SHFLG_Backslash);
11679    }else if( strcmp(z,"-bail")==0 ){
11680      /* No-op.  The bail_on_error flag should already be set. */
11681    }else if( strcmp(z,"-version")==0 ){
11682      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11683      return 0;
11684    }else if( strcmp(z,"-interactive")==0 ){
11685      stdin_is_interactive = 1;
11686    }else if( strcmp(z,"-batch")==0 ){
11687      stdin_is_interactive = 0;
11688    }else if( strcmp(z,"-heap")==0 ){
11689      i++;
11690    }else if( strcmp(z,"-pagecache")==0 ){
11691      i+=2;
11692    }else if( strcmp(z,"-lookaside")==0 ){
11693      i+=2;
11694    }else if( strcmp(z,"-threadsafe")==0 ){
11695      i+=2;
11696    }else if( strcmp(z,"-nonce")==0 ){
11697      i += 2;
11698    }else if( strcmp(z,"-mmap")==0 ){
11699      i++;
11700    }else if( strcmp(z,"-memtrace")==0 ){
11701      i++;
11702#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11703    }else if( strcmp(z,"-sorterref")==0 ){
11704      i++;
11705#endif
11706    }else if( strcmp(z,"-vfs")==0 ){
11707      i++;
11708#ifdef SQLITE_ENABLE_VFSTRACE
11709    }else if( strcmp(z,"-vfstrace")==0 ){
11710      i++;
11711#endif
11712#ifdef SQLITE_ENABLE_MULTIPLEX
11713    }else if( strcmp(z,"-multiplex")==0 ){
11714      i++;
11715#endif
11716    }else if( strcmp(z,"-help")==0 ){
11717      usage(1);
11718    }else if( strcmp(z,"-cmd")==0 ){
11719      /* Run commands that follow -cmd first and separately from commands
11720      ** that simply appear on the command-line.  This seems goofy.  It would
11721      ** be better if all commands ran in the order that they appear.  But
11722      ** we retain the goofy behavior for historical compatibility. */
11723      if( i==argc-1 ) break;
11724      z = cmdline_option_value(argc,argv,++i);
11725      if( z[0]=='.' ){
11726        rc = do_meta_command(z, &data);
11727        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11728      }else{
11729        open_db(&data, 0);
11730        rc = shell_exec(&data, z, &zErrMsg);
11731        if( zErrMsg!=0 ){
11732          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11733          if( bail_on_error ) return rc!=0 ? rc : 1;
11734        }else if( rc!=0 ){
11735          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11736          if( bail_on_error ) return rc;
11737        }
11738      }
11739#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11740    }else if( strncmp(z, "-A", 2)==0 ){
11741      if( nCmd>0 ){
11742        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11743                            " with \"%s\"\n", z);
11744        return 1;
11745      }
11746      open_db(&data, OPEN_DB_ZIPFILE);
11747      if( z[2] ){
11748        argv[i] = &z[2];
11749        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11750      }else{
11751        arDotCommand(&data, 1, argv+i, argc-i);
11752      }
11753      readStdin = 0;
11754      break;
11755#endif
11756    }else if( strcmp(z,"-safe")==0 ){
11757      data.bSafeMode = data.bSafeModePersist = 1;
11758    }else{
11759      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11760      raw_printf(stderr,"Use -help for a list of options.\n");
11761      return 1;
11762    }
11763    data.cMode = data.mode;
11764  }
11765
11766  if( !readStdin ){
11767    /* Run all arguments that do not begin with '-' as if they were separate
11768    ** command-line inputs, except for the argToSkip argument which contains
11769    ** the database filename.
11770    */
11771    for(i=0; i<nCmd; i++){
11772      if( azCmd[i][0]=='.' ){
11773        rc = do_meta_command(azCmd[i], &data);
11774        if( rc ){
11775          free(azCmd);
11776          return rc==2 ? 0 : rc;
11777        }
11778      }else{
11779        open_db(&data, 0);
11780        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11781        if( zErrMsg || rc ){
11782          if( zErrMsg!=0 ){
11783            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11784          }else{
11785            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11786          }
11787          sqlite3_free(zErrMsg);
11788          free(azCmd);
11789          return rc!=0 ? rc : 1;
11790        }
11791      }
11792    }
11793  }else{
11794    /* Run commands received from standard input
11795    */
11796    if( stdin_is_interactive ){
11797      char *zHome;
11798      char *zHistory;
11799      int nHistory;
11800      printf(
11801        "SQLite version %s %.19s\n" /*extra-version-info*/
11802        "Enter \".help\" for usage hints.\n",
11803        sqlite3_libversion(), sqlite3_sourceid()
11804      );
11805      if( warnInmemoryDb ){
11806        printf("Connected to a ");
11807        printBold("transient in-memory database");
11808        printf(".\nUse \".open FILENAME\" to reopen on a "
11809               "persistent database.\n");
11810      }
11811      zHistory = getenv("SQLITE_HISTORY");
11812      if( zHistory ){
11813        zHistory = strdup(zHistory);
11814      }else if( (zHome = find_home_dir(0))!=0 ){
11815        nHistory = strlen30(zHome) + 20;
11816        if( (zHistory = malloc(nHistory))!=0 ){
11817          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11818        }
11819      }
11820      if( zHistory ){ shell_read_history(zHistory); }
11821#if HAVE_READLINE || HAVE_EDITLINE
11822      rl_attempted_completion_function = readline_completion;
11823#elif HAVE_LINENOISE
11824      linenoiseSetCompletionCallback(linenoise_completion);
11825#endif
11826      data.in = 0;
11827      rc = process_input(&data);
11828      if( zHistory ){
11829        shell_stifle_history(2000);
11830        shell_write_history(zHistory);
11831        free(zHistory);
11832      }
11833    }else{
11834      data.in = stdin;
11835      rc = process_input(&data);
11836    }
11837  }
11838  free(azCmd);
11839  set_table_name(&data, 0);
11840  if( data.db ){
11841    session_close_all(&data, -1);
11842    close_db(data.db);
11843  }
11844  for(i=0; i<ArraySize(data.aAuxDb); i++){
11845    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
11846    if( data.aAuxDb[i].db ){
11847      session_close_all(&data, i);
11848      close_db(data.aAuxDb[i].db);
11849    }
11850  }
11851  find_home_dir(1);
11852  output_reset(&data);
11853  data.doXdgOpen = 0;
11854  clearTempFile(&data);
11855#if !SQLITE_SHELL_IS_UTF8
11856  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11857  free(argvToFree);
11858#endif
11859  free(data.colWidth);
11860  free(data.zNonce);
11861  /* Clear the global data structure so that valgrind will detect memory
11862  ** leaks */
11863  memset(&data, 0, sizeof(data));
11864  return rc;
11865}
11866