xref: /sqlite-3.40.0/src/shell.c.in (revision 697c50b9)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26#ifdef SQLITE_CUSTOM_INCLUDE
27# define INC_STRINGIFY_(f) #f
28# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
29# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** Warning pragmas copied from msvc.h in the core.
42*/
43#if defined(_MSC_VER)
44#pragma warning(disable : 4054)
45#pragma warning(disable : 4055)
46#pragma warning(disable : 4100)
47#pragma warning(disable : 4127)
48#pragma warning(disable : 4130)
49#pragma warning(disable : 4152)
50#pragma warning(disable : 4189)
51#pragma warning(disable : 4206)
52#pragma warning(disable : 4210)
53#pragma warning(disable : 4232)
54#pragma warning(disable : 4244)
55#pragma warning(disable : 4305)
56#pragma warning(disable : 4306)
57#pragma warning(disable : 4702)
58#pragma warning(disable : 4706)
59#endif /* defined(_MSC_VER) */
60
61/*
62** No support for loadable extensions in VxWorks.
63*/
64#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
65# define SQLITE_OMIT_LOAD_EXTENSION 1
66#endif
67
68/*
69** Enable large-file support for fopen() and friends on unix.
70*/
71#ifndef SQLITE_DISABLE_LFS
72# define _LARGE_FILE       1
73# ifndef _FILE_OFFSET_BITS
74#   define _FILE_OFFSET_BITS 64
75# endif
76# define _LARGEFILE_SOURCE 1
77#endif
78
79#include <stdlib.h>
80#include <string.h>
81#include <stdio.h>
82#include <assert.h>
83#include "sqlite3.h"
84typedef sqlite3_int64 i64;
85typedef sqlite3_uint64 u64;
86typedef unsigned char u8;
87#if SQLITE_USER_AUTHENTICATION
88# include "sqlite3userauth.h"
89#endif
90#include <ctype.h>
91#include <stdarg.h>
92
93#if !defined(_WIN32) && !defined(WIN32)
94# include <signal.h>
95# if !defined(__RTP__) && !defined(_WRS_KERNEL)
96#  include <pwd.h>
97# endif
98#endif
99#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100# include <unistd.h>
101# include <dirent.h>
102# define GETPID getpid
103# if defined(__MINGW32__)
104#  define DIRENT dirent
105#  ifndef S_ISLNK
106#   define S_ISLNK(mode) (0)
107#  endif
108# endif
109#else
110# define GETPID (int)GetCurrentProcessId
111#endif
112#include <sys/types.h>
113#include <sys/stat.h>
114
115#if HAVE_READLINE
116# include <readline/readline.h>
117# include <readline/history.h>
118#endif
119
120#if HAVE_EDITLINE
121# include <editline/readline.h>
122#endif
123
124#if HAVE_EDITLINE || HAVE_READLINE
125
126# define shell_add_history(X) add_history(X)
127# define shell_read_history(X) read_history(X)
128# define shell_write_history(X) write_history(X)
129# define shell_stifle_history(X) stifle_history(X)
130# define shell_readline(X) readline(X)
131
132#elif HAVE_LINENOISE
133
134# include "linenoise.h"
135# define shell_add_history(X) linenoiseHistoryAdd(X)
136# define shell_read_history(X) linenoiseHistoryLoad(X)
137# define shell_write_history(X) linenoiseHistorySave(X)
138# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
139# define shell_readline(X) linenoise(X)
140
141#else
142
143# define shell_read_history(X)
144# define shell_write_history(X)
145# define shell_stifle_history(X)
146
147# define SHELL_USE_LOCAL_GETLINE 1
148#endif
149
150
151#if defined(_WIN32) || defined(WIN32)
152# if SQLITE_OS_WINRT
153#  define SQLITE_OMIT_POPEN 1
154# else
155#  include <io.h>
156#  include <fcntl.h>
157#  define isatty(h) _isatty(h)
158#  ifndef access
159#   define access(f,m) _access((f),(m))
160#  endif
161#  ifndef unlink
162#   define unlink _unlink
163#  endif
164#  ifndef strdup
165#   define strdup _strdup
166#  endif
167#  undef popen
168#  define popen _popen
169#  undef pclose
170#  define pclose _pclose
171# endif
172#else
173 /* Make sure isatty() has a prototype. */
174 extern int isatty(int);
175
176# if !defined(__RTP__) && !defined(_WRS_KERNEL)
177  /* popen and pclose are not C89 functions and so are
178  ** sometimes omitted from the <stdio.h> header */
179   extern FILE *popen(const char*,const char*);
180   extern int pclose(FILE*);
181# else
182#  define SQLITE_OMIT_POPEN 1
183# endif
184#endif
185
186#if defined(_WIN32_WCE)
187/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
188 * thus we always assume that we have a console. That can be
189 * overridden with the -batch command line option.
190 */
191#define isatty(x) 1
192#endif
193
194/* ctype macros that work with signed characters */
195#define IsSpace(X)  isspace((unsigned char)X)
196#define IsDigit(X)  isdigit((unsigned char)X)
197#define ToLower(X)  (char)tolower((unsigned char)X)
198
199#if defined(_WIN32) || defined(WIN32)
200#if SQLITE_OS_WINRT
201#include <intrin.h>
202#endif
203#include <windows.h>
204
205/* string conversion routines only needed on Win32 */
206extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
207extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
208extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
209extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
210#endif
211
212/* On Windows, we normally run with output mode of TEXT so that \n characters
213** are automatically translated into \r\n.  However, this behavior needs
214** to be disabled in some cases (ex: when generating CSV output and when
215** rendering quoted strings that contain \n characters).  The following
216** routines take care of that.
217*/
218#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
219static void setBinaryMode(FILE *file, int isOutput){
220  if( isOutput ) fflush(file);
221  _setmode(_fileno(file), _O_BINARY);
222}
223static void setTextMode(FILE *file, int isOutput){
224  if( isOutput ) fflush(file);
225  _setmode(_fileno(file), _O_TEXT);
226}
227#else
228# define setBinaryMode(X,Y)
229# define setTextMode(X,Y)
230#endif
231
232
233/* True if the timer is enabled */
234static int enableTimer = 0;
235
236/* Return the current wall-clock time */
237static sqlite3_int64 timeOfDay(void){
238  static sqlite3_vfs *clockVfs = 0;
239  sqlite3_int64 t;
240  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
241  if( clockVfs==0 ) return 0;  /* Never actually happens */
242  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
243    clockVfs->xCurrentTimeInt64(clockVfs, &t);
244  }else{
245    double r;
246    clockVfs->xCurrentTime(clockVfs, &r);
247    t = (sqlite3_int64)(r*86400000.0);
248  }
249  return t;
250}
251
252#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
253#include <sys/time.h>
254#include <sys/resource.h>
255
256/* VxWorks does not support getrusage() as far as we can determine */
257#if defined(_WRS_KERNEL) || defined(__RTP__)
258struct rusage {
259  struct timeval ru_utime; /* user CPU time used */
260  struct timeval ru_stime; /* system CPU time used */
261};
262#define getrusage(A,B) memset(B,0,sizeof(*B))
263#endif
264
265/* Saved resource information for the beginning of an operation */
266static struct rusage sBegin;  /* CPU time at start */
267static sqlite3_int64 iBegin;  /* Wall-clock time at start */
268
269/*
270** Begin timing an operation
271*/
272static void beginTimer(void){
273  if( enableTimer ){
274    getrusage(RUSAGE_SELF, &sBegin);
275    iBegin = timeOfDay();
276  }
277}
278
279/* Return the difference of two time_structs in seconds */
280static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
281  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
282         (double)(pEnd->tv_sec - pStart->tv_sec);
283}
284
285/*
286** Print the timing results.
287*/
288static void endTimer(void){
289  if( enableTimer ){
290    sqlite3_int64 iEnd = timeOfDay();
291    struct rusage sEnd;
292    getrusage(RUSAGE_SELF, &sEnd);
293    printf("Run Time: real %.3f user %f sys %f\n",
294       (iEnd - iBegin)*0.001,
295       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
296       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
297  }
298}
299
300#define BEGIN_TIMER beginTimer()
301#define END_TIMER endTimer()
302#define HAS_TIMER 1
303
304#elif (defined(_WIN32) || defined(WIN32))
305
306/* Saved resource information for the beginning of an operation */
307static HANDLE hProcess;
308static FILETIME ftKernelBegin;
309static FILETIME ftUserBegin;
310static sqlite3_int64 ftWallBegin;
311typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
312                                    LPFILETIME, LPFILETIME);
313static GETPROCTIMES getProcessTimesAddr = NULL;
314
315/*
316** Check to see if we have timer support.  Return 1 if necessary
317** support found (or found previously).
318*/
319static int hasTimer(void){
320  if( getProcessTimesAddr ){
321    return 1;
322  } else {
323#if !SQLITE_OS_WINRT
324    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
325    ** versions. See if the version we are running on has it, and if it
326    ** does, save off a pointer to it and the current process handle.
327    */
328    hProcess = GetCurrentProcess();
329    if( hProcess ){
330      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
331      if( NULL != hinstLib ){
332        getProcessTimesAddr =
333            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
334        if( NULL != getProcessTimesAddr ){
335          return 1;
336        }
337        FreeLibrary(hinstLib);
338      }
339    }
340#endif
341  }
342  return 0;
343}
344
345/*
346** Begin timing an operation
347*/
348static void beginTimer(void){
349  if( enableTimer && getProcessTimesAddr ){
350    FILETIME ftCreation, ftExit;
351    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
352                        &ftKernelBegin,&ftUserBegin);
353    ftWallBegin = timeOfDay();
354  }
355}
356
357/* Return the difference of two FILETIME structs in seconds */
358static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
359  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
360  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
361  return (double) ((i64End - i64Start) / 10000000.0);
362}
363
364/*
365** Print the timing results.
366*/
367static void endTimer(void){
368  if( enableTimer && getProcessTimesAddr){
369    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
370    sqlite3_int64 ftWallEnd = timeOfDay();
371    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
372    printf("Run Time: real %.3f user %f sys %f\n",
373       (ftWallEnd - ftWallBegin)*0.001,
374       timeDiff(&ftUserBegin, &ftUserEnd),
375       timeDiff(&ftKernelBegin, &ftKernelEnd));
376  }
377}
378
379#define BEGIN_TIMER beginTimer()
380#define END_TIMER endTimer()
381#define HAS_TIMER hasTimer()
382
383#else
384#define BEGIN_TIMER
385#define END_TIMER
386#define HAS_TIMER 0
387#endif
388
389/*
390** Used to prevent warnings about unused parameters
391*/
392#define UNUSED_PARAMETER(x) (void)(x)
393
394/*
395** Number of elements in an array
396*/
397#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
398
399/*
400** If the following flag is set, then command execution stops
401** at an error if we are not interactive.
402*/
403static int bail_on_error = 0;
404
405/*
406** Threat stdin as an interactive input if the following variable
407** is true.  Otherwise, assume stdin is connected to a file or pipe.
408*/
409static int stdin_is_interactive = 1;
410
411/*
412** On Windows systems we have to know if standard output is a console
413** in order to translate UTF-8 into MBCS.  The following variable is
414** true if translation is required.
415*/
416static int stdout_is_console = 1;
417
418/*
419** The following is the open SQLite database.  We make a pointer
420** to this database a static variable so that it can be accessed
421** by the SIGINT handler to interrupt database processing.
422*/
423static sqlite3 *globalDb = 0;
424
425/*
426** True if an interrupt (Control-C) has been received.
427*/
428static volatile int seenInterrupt = 0;
429
430/*
431** This is the name of our program. It is set in main(), used
432** in a number of other places, mostly for error messages.
433*/
434static char *Argv0;
435
436/*
437** Prompt strings. Initialized in main. Settable with
438**   .prompt main continue
439*/
440static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
441static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
442
443/*
444** Render output like fprintf().  Except, if the output is going to the
445** console and if this is running on a Windows machine, translate the
446** output from UTF-8 into MBCS.
447*/
448#if defined(_WIN32) || defined(WIN32)
449void utf8_printf(FILE *out, const char *zFormat, ...){
450  va_list ap;
451  va_start(ap, zFormat);
452  if( stdout_is_console && (out==stdout || out==stderr) ){
453    char *z1 = sqlite3_vmprintf(zFormat, ap);
454    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
455    sqlite3_free(z1);
456    fputs(z2, out);
457    sqlite3_free(z2);
458  }else{
459    vfprintf(out, zFormat, ap);
460  }
461  va_end(ap);
462}
463#elif !defined(utf8_printf)
464# define utf8_printf fprintf
465#endif
466
467/*
468** Render output like fprintf().  This should not be used on anything that
469** includes string formatting (e.g. "%s").
470*/
471#if !defined(raw_printf)
472# define raw_printf fprintf
473#endif
474
475/* Indicate out-of-memory and exit. */
476static void shell_out_of_memory(void){
477  raw_printf(stderr,"Error: out of memory\n");
478  exit(1);
479}
480
481/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
482** out-of-memory error.
483*/
484static void shell_check_oom(void *p){
485  if( p==0 ) shell_out_of_memory();
486}
487
488/*
489** Write I/O traces to the following stream.
490*/
491#ifdef SQLITE_ENABLE_IOTRACE
492static FILE *iotrace = 0;
493#endif
494
495/*
496** This routine works like printf in that its first argument is a
497** format string and subsequent arguments are values to be substituted
498** in place of % fields.  The result of formatting this string
499** is written to iotrace.
500*/
501#ifdef SQLITE_ENABLE_IOTRACE
502static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
503  va_list ap;
504  char *z;
505  if( iotrace==0 ) return;
506  va_start(ap, zFormat);
507  z = sqlite3_vmprintf(zFormat, ap);
508  va_end(ap);
509  utf8_printf(iotrace, "%s", z);
510  sqlite3_free(z);
511}
512#endif
513
514/*
515** Output string zUtf to stream pOut as w characters.  If w is negative,
516** then right-justify the text.  W is the width in UTF-8 characters, not
517** in bytes.  This is different from the %*.*s specification in printf
518** since with %*.*s the width is measured in bytes, not characters.
519*/
520static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
521  int i;
522  int n;
523  int aw = w<0 ? -w : w;
524  for(i=n=0; zUtf[i]; i++){
525    if( (zUtf[i]&0xc0)!=0x80 ){
526      n++;
527      if( n==aw ){
528        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
529        break;
530      }
531    }
532  }
533  if( n>=aw ){
534    utf8_printf(pOut, "%.*s", i, zUtf);
535  }else if( w<0 ){
536    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
537  }else{
538    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
539  }
540}
541
542
543/*
544** Determines if a string is a number of not.
545*/
546static int isNumber(const char *z, int *realnum){
547  if( *z=='-' || *z=='+' ) z++;
548  if( !IsDigit(*z) ){
549    return 0;
550  }
551  z++;
552  if( realnum ) *realnum = 0;
553  while( IsDigit(*z) ){ z++; }
554  if( *z=='.' ){
555    z++;
556    if( !IsDigit(*z) ) return 0;
557    while( IsDigit(*z) ){ z++; }
558    if( realnum ) *realnum = 1;
559  }
560  if( *z=='e' || *z=='E' ){
561    z++;
562    if( *z=='+' || *z=='-' ) z++;
563    if( !IsDigit(*z) ) return 0;
564    while( IsDigit(*z) ){ z++; }
565    if( realnum ) *realnum = 1;
566  }
567  return *z==0;
568}
569
570/*
571** Compute a string length that is limited to what can be stored in
572** lower 30 bits of a 32-bit signed integer.
573*/
574static int strlen30(const char *z){
575  const char *z2 = z;
576  while( *z2 ){ z2++; }
577  return 0x3fffffff & (int)(z2 - z);
578}
579
580/*
581** Return the length of a string in characters.  Multibyte UTF8 characters
582** count as a single character.
583*/
584static int strlenChar(const char *z){
585  int n = 0;
586  while( *z ){
587    if( (0xc0&*(z++))!=0x80 ) n++;
588  }
589  return n;
590}
591
592/*
593** Return open FILE * if zFile exists, can be opened for read
594** and is an ordinary file or a character stream source.
595** Otherwise return 0.
596*/
597static FILE * openChrSource(const char *zFile){
598#ifdef _WIN32
599  struct _stat x = {0};
600# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
601  /* On Windows, open first, then check the stream nature. This order
602  ** is necessary because _stat() and sibs, when checking a named pipe,
603  ** effectively break the pipe as its supplier sees it. */
604  FILE *rv = fopen(zFile, "rb");
605  if( rv==0 ) return 0;
606  if( _fstat(_fileno(rv), &x) != 0
607      || !STAT_CHR_SRC(x.st_mode)){
608    fclose(rv);
609    rv = 0;
610  }
611  return rv;
612#else
613  struct stat x = {0};
614  int rc = stat(zFile, &x);
615# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
616  if( rc!=0 ) return 0;
617  if( STAT_CHR_SRC(x.st_mode) ){
618    return fopen(zFile, "rb");
619  }else{
620    return 0;
621  }
622#endif
623#undef STAT_CHR_SRC
624}
625
626/*
627** This routine reads a line of text from FILE in, stores
628** the text in memory obtained from malloc() and returns a pointer
629** to the text.  NULL is returned at end of file, or if malloc()
630** fails.
631**
632** If zLine is not NULL then it is a malloced buffer returned from
633** a previous call to this routine that may be reused.
634*/
635static char *local_getline(char *zLine, FILE *in){
636  int nLine = zLine==0 ? 0 : 100;
637  int n = 0;
638
639  while( 1 ){
640    if( n+100>nLine ){
641      nLine = nLine*2 + 100;
642      zLine = realloc(zLine, nLine);
643      shell_check_oom(zLine);
644    }
645    if( fgets(&zLine[n], nLine - n, in)==0 ){
646      if( n==0 ){
647        free(zLine);
648        return 0;
649      }
650      zLine[n] = 0;
651      break;
652    }
653    while( zLine[n] ) n++;
654    if( n>0 && zLine[n-1]=='\n' ){
655      n--;
656      if( n>0 && zLine[n-1]=='\r' ) n--;
657      zLine[n] = 0;
658      break;
659    }
660  }
661#if defined(_WIN32) || defined(WIN32)
662  /* For interactive input on Windows systems, translate the
663  ** multi-byte characterset characters into UTF-8. */
664  if( stdin_is_interactive && in==stdin ){
665    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
666    if( zTrans ){
667      int nTrans = strlen30(zTrans)+1;
668      if( nTrans>nLine ){
669        zLine = realloc(zLine, nTrans);
670        shell_check_oom(zLine);
671      }
672      memcpy(zLine, zTrans, nTrans);
673      sqlite3_free(zTrans);
674    }
675  }
676#endif /* defined(_WIN32) || defined(WIN32) */
677  return zLine;
678}
679
680/*
681** Retrieve a single line of input text.
682**
683** If in==0 then read from standard input and prompt before each line.
684** If isContinuation is true, then a continuation prompt is appropriate.
685** If isContinuation is zero, then the main prompt should be used.
686**
687** If zPrior is not NULL then it is a buffer from a prior call to this
688** routine that can be reused.
689**
690** The result is stored in space obtained from malloc() and must either
691** be freed by the caller or else passed back into this routine via the
692** zPrior argument for reuse.
693*/
694static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
695  char *zPrompt;
696  char *zResult;
697  if( in!=0 ){
698    zResult = local_getline(zPrior, in);
699  }else{
700    zPrompt = isContinuation ? continuePrompt : mainPrompt;
701#if SHELL_USE_LOCAL_GETLINE
702    printf("%s", zPrompt);
703    fflush(stdout);
704    zResult = local_getline(zPrior, stdin);
705#else
706    free(zPrior);
707    zResult = shell_readline(zPrompt);
708    if( zResult && *zResult ) shell_add_history(zResult);
709#endif
710  }
711  return zResult;
712}
713
714
715/*
716** Return the value of a hexadecimal digit.  Return -1 if the input
717** is not a hex digit.
718*/
719static int hexDigitValue(char c){
720  if( c>='0' && c<='9' ) return c - '0';
721  if( c>='a' && c<='f' ) return c - 'a' + 10;
722  if( c>='A' && c<='F' ) return c - 'A' + 10;
723  return -1;
724}
725
726/*
727** Interpret zArg as an integer value, possibly with suffixes.
728*/
729static sqlite3_int64 integerValue(const char *zArg){
730  sqlite3_int64 v = 0;
731  static const struct { char *zSuffix; int iMult; } aMult[] = {
732    { "KiB", 1024 },
733    { "MiB", 1024*1024 },
734    { "GiB", 1024*1024*1024 },
735    { "KB",  1000 },
736    { "MB",  1000000 },
737    { "GB",  1000000000 },
738    { "K",   1000 },
739    { "M",   1000000 },
740    { "G",   1000000000 },
741  };
742  int i;
743  int isNeg = 0;
744  if( zArg[0]=='-' ){
745    isNeg = 1;
746    zArg++;
747  }else if( zArg[0]=='+' ){
748    zArg++;
749  }
750  if( zArg[0]=='0' && zArg[1]=='x' ){
751    int x;
752    zArg += 2;
753    while( (x = hexDigitValue(zArg[0]))>=0 ){
754      v = (v<<4) + x;
755      zArg++;
756    }
757  }else{
758    while( IsDigit(zArg[0]) ){
759      v = v*10 + zArg[0] - '0';
760      zArg++;
761    }
762  }
763  for(i=0; i<ArraySize(aMult); i++){
764    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
765      v *= aMult[i].iMult;
766      break;
767    }
768  }
769  return isNeg? -v : v;
770}
771
772/*
773** A variable length string to which one can append text.
774*/
775typedef struct ShellText ShellText;
776struct ShellText {
777  char *z;
778  int n;
779  int nAlloc;
780};
781
782/*
783** Initialize and destroy a ShellText object
784*/
785static void initText(ShellText *p){
786  memset(p, 0, sizeof(*p));
787}
788static void freeText(ShellText *p){
789  free(p->z);
790  initText(p);
791}
792
793/* zIn is either a pointer to a NULL-terminated string in memory obtained
794** from malloc(), or a NULL pointer. The string pointed to by zAppend is
795** added to zIn, and the result returned in memory obtained from malloc().
796** zIn, if it was not NULL, is freed.
797**
798** If the third argument, quote, is not '\0', then it is used as a
799** quote character for zAppend.
800*/
801static void appendText(ShellText *p, char const *zAppend, char quote){
802  int len;
803  int i;
804  int nAppend = strlen30(zAppend);
805
806  len = nAppend+p->n+1;
807  if( quote ){
808    len += 2;
809    for(i=0; i<nAppend; i++){
810      if( zAppend[i]==quote ) len++;
811    }
812  }
813
814  if( p->z==0 || p->n+len>=p->nAlloc ){
815    p->nAlloc = p->nAlloc*2 + len + 20;
816    p->z = realloc(p->z, p->nAlloc);
817    shell_check_oom(p->z);
818  }
819
820  if( quote ){
821    char *zCsr = p->z+p->n;
822    *zCsr++ = quote;
823    for(i=0; i<nAppend; i++){
824      *zCsr++ = zAppend[i];
825      if( zAppend[i]==quote ) *zCsr++ = quote;
826    }
827    *zCsr++ = quote;
828    p->n = (int)(zCsr - p->z);
829    *zCsr = '\0';
830  }else{
831    memcpy(p->z+p->n, zAppend, nAppend);
832    p->n += nAppend;
833    p->z[p->n] = '\0';
834  }
835}
836
837/*
838** Attempt to determine if identifier zName needs to be quoted, either
839** because it contains non-alphanumeric characters, or because it is an
840** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
841** that quoting is required.
842**
843** Return '"' if quoting is required.  Return 0 if no quoting is required.
844*/
845static char quoteChar(const char *zName){
846  int i;
847  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
848  for(i=0; zName[i]; i++){
849    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
850  }
851  return sqlite3_keyword_check(zName, i) ? '"' : 0;
852}
853
854/*
855** Construct a fake object name and column list to describe the structure
856** of the view, virtual table, or table valued function zSchema.zName.
857*/
858static char *shellFakeSchema(
859  sqlite3 *db,            /* The database connection containing the vtab */
860  const char *zSchema,    /* Schema of the database holding the vtab */
861  const char *zName       /* The name of the virtual table */
862){
863  sqlite3_stmt *pStmt = 0;
864  char *zSql;
865  ShellText s;
866  char cQuote;
867  char *zDiv = "(";
868  int nRow = 0;
869
870  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
871                         zSchema ? zSchema : "main", zName);
872  shell_check_oom(zSql);
873  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
874  sqlite3_free(zSql);
875  initText(&s);
876  if( zSchema ){
877    cQuote = quoteChar(zSchema);
878    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
879    appendText(&s, zSchema, cQuote);
880    appendText(&s, ".", 0);
881  }
882  cQuote = quoteChar(zName);
883  appendText(&s, zName, cQuote);
884  while( sqlite3_step(pStmt)==SQLITE_ROW ){
885    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
886    nRow++;
887    appendText(&s, zDiv, 0);
888    zDiv = ",";
889    if( zCol==0 ) zCol = "";
890    cQuote = quoteChar(zCol);
891    appendText(&s, zCol, cQuote);
892  }
893  appendText(&s, ")", 0);
894  sqlite3_finalize(pStmt);
895  if( nRow==0 ){
896    freeText(&s);
897    s.z = 0;
898  }
899  return s.z;
900}
901
902/*
903** SQL function:  shell_module_schema(X)
904**
905** Return a fake schema for the table-valued function or eponymous virtual
906** table X.
907*/
908static void shellModuleSchema(
909  sqlite3_context *pCtx,
910  int nVal,
911  sqlite3_value **apVal
912){
913  const char *zName;
914  char *zFake;
915  UNUSED_PARAMETER(nVal);
916  zName = (const char*)sqlite3_value_text(apVal[0]);
917  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
918  if( zFake ){
919    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
920                        -1, sqlite3_free);
921    free(zFake);
922  }
923}
924
925/*
926** SQL function:  shell_add_schema(S,X)
927**
928** Add the schema name X to the CREATE statement in S and return the result.
929** Examples:
930**
931**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
932**
933** Also works on
934**
935**    CREATE INDEX
936**    CREATE UNIQUE INDEX
937**    CREATE VIEW
938**    CREATE TRIGGER
939**    CREATE VIRTUAL TABLE
940**
941** This UDF is used by the .schema command to insert the schema name of
942** attached databases into the middle of the sqlite_schema.sql field.
943*/
944static void shellAddSchemaName(
945  sqlite3_context *pCtx,
946  int nVal,
947  sqlite3_value **apVal
948){
949  static const char *aPrefix[] = {
950     "TABLE",
951     "INDEX",
952     "UNIQUE INDEX",
953     "VIEW",
954     "TRIGGER",
955     "VIRTUAL TABLE"
956  };
957  int i = 0;
958  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
959  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
960  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
961  sqlite3 *db = sqlite3_context_db_handle(pCtx);
962  UNUSED_PARAMETER(nVal);
963  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
964    for(i=0; i<ArraySize(aPrefix); i++){
965      int n = strlen30(aPrefix[i]);
966      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
967        char *z = 0;
968        char *zFake = 0;
969        if( zSchema ){
970          char cQuote = quoteChar(zSchema);
971          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
972            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
973          }else{
974            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
975          }
976        }
977        if( zName
978         && aPrefix[i][0]=='V'
979         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
980        ){
981          if( z==0 ){
982            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
983          }else{
984            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
985          }
986          free(zFake);
987        }
988        if( z ){
989          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
990          return;
991        }
992      }
993    }
994  }
995  sqlite3_result_value(pCtx, apVal[0]);
996}
997
998/*
999** The source code for several run-time loadable extensions is inserted
1000** below by the ../tool/mkshellc.tcl script.  Before processing that included
1001** code, we need to override some macros to make the included program code
1002** work here in the middle of this regular program.
1003*/
1004#define SQLITE_EXTENSION_INIT1
1005#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1006
1007#if defined(_WIN32) && defined(_MSC_VER)
1008INCLUDE test_windirent.h
1009INCLUDE test_windirent.c
1010#define dirent DIRENT
1011#endif
1012INCLUDE ../ext/misc/shathree.c
1013INCLUDE ../ext/misc/fileio.c
1014INCLUDE ../ext/misc/completion.c
1015INCLUDE ../ext/misc/appendvfs.c
1016INCLUDE ../ext/misc/memtrace.c
1017INCLUDE ../ext/misc/uint.c
1018INCLUDE ../ext/misc/decimal.c
1019INCLUDE ../ext/misc/ieee754.c
1020INCLUDE ../ext/misc/series.c
1021INCLUDE ../ext/misc/regexp.c
1022#ifdef SQLITE_HAVE_ZLIB
1023INCLUDE ../ext/misc/zipfile.c
1024INCLUDE ../ext/misc/sqlar.c
1025#endif
1026INCLUDE ../ext/expert/sqlite3expert.h
1027INCLUDE ../ext/expert/sqlite3expert.c
1028
1029#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1030INCLUDE ../ext/misc/dbdata.c
1031#endif
1032
1033#if defined(SQLITE_ENABLE_SESSION)
1034/*
1035** State information for a single open session
1036*/
1037typedef struct OpenSession OpenSession;
1038struct OpenSession {
1039  char *zName;             /* Symbolic name for this session */
1040  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1041  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1042  sqlite3_session *p;      /* The open session */
1043};
1044#endif
1045
1046typedef struct ExpertInfo ExpertInfo;
1047struct ExpertInfo {
1048  sqlite3expert *pExpert;
1049  int bVerbose;
1050};
1051
1052/* A single line in the EQP output */
1053typedef struct EQPGraphRow EQPGraphRow;
1054struct EQPGraphRow {
1055  int iEqpId;           /* ID for this row */
1056  int iParentId;        /* ID of the parent row */
1057  EQPGraphRow *pNext;   /* Next row in sequence */
1058  char zText[1];        /* Text to display for this row */
1059};
1060
1061/* All EQP output is collected into an instance of the following */
1062typedef struct EQPGraph EQPGraph;
1063struct EQPGraph {
1064  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1065  EQPGraphRow *pLast;   /* Last element of the pRow list */
1066  char zPrefix[100];    /* Graph prefix */
1067};
1068
1069/* Parameters affecting columnar mode result display (defaulting together) */
1070typedef struct ColModeOpts {
1071  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1072  u8 bQuote;            /* Quote results for .mode box and table */
1073  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1074} ColModeOpts;
1075#define ColModeOpts_default { 60, 0, 0 }
1076#define ColModeOpts_default_qbox { 60, 1, 0 }
1077
1078/*
1079** State information about the database connection is contained in an
1080** instance of the following structure.
1081*/
1082typedef struct ShellState ShellState;
1083struct ShellState {
1084  sqlite3 *db;           /* The database */
1085  u8 autoExplain;        /* Automatically turn on .explain mode */
1086  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1087  u8 autoEQPtest;        /* autoEQP is in test mode */
1088  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1089  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1090  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1091  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1092  u8 nEqpLevel;          /* Depth of the EQP output graph */
1093  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1094  u8 bSafeMode;          /* True to prohibit unsafe operations */
1095  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1096  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1097  unsigned statsOn;      /* True to display memory stats before each finalize */
1098  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1099  int inputNesting;      /* Track nesting level of .read and other redirects */
1100  int outCount;          /* Revert to stdout when reaching zero */
1101  int cnt;               /* Number of records displayed so far */
1102  int lineno;            /* Line number of last line read from in */
1103  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1104  FILE *in;              /* Read commands from this stream */
1105  FILE *out;             /* Write results here */
1106  FILE *traceOut;        /* Output for sqlite3_trace() */
1107  int nErr;              /* Number of errors seen */
1108  int mode;              /* An output mode setting */
1109  int modePrior;         /* Saved mode */
1110  int cMode;             /* temporary output mode for the current query */
1111  int normalMode;        /* Output mode before ".explain on" */
1112  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1113  int showHeader;        /* True to show column names in List or Column mode */
1114  int nCheck;            /* Number of ".check" commands run */
1115  unsigned nProgress;    /* Number of progress callbacks encountered */
1116  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1117  unsigned flgProgress;  /* Flags for the progress callback */
1118  unsigned shellFlgs;    /* Various flags */
1119  unsigned priorShFlgs;  /* Saved copy of flags */
1120  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1121  char *zDestTable;      /* Name of destination table when MODE_Insert */
1122  char *zTempFile;       /* Temporary file that might need deleting */
1123  char zTestcase[30];    /* Name of current test case */
1124  char colSeparator[20]; /* Column separator character for several modes */
1125  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1126  char colSepPrior[20];  /* Saved column separator */
1127  char rowSepPrior[20];  /* Saved row separator */
1128  int *colWidth;         /* Requested width of each column in columnar modes */
1129  int *actualWidth;      /* Actual width of each column */
1130  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1131  char nullValue[20];    /* The text to print when a NULL comes back from
1132                         ** the database */
1133  char outfile[FILENAME_MAX]; /* Filename for *out */
1134  sqlite3_stmt *pStmt;   /* Current statement if any. */
1135  FILE *pLog;            /* Write log output here */
1136  struct AuxDb {         /* Storage space for auxiliary database connections */
1137    sqlite3 *db;               /* Connection pointer */
1138    const char *zDbFilename;   /* Filename used to open the connection */
1139    char *zFreeOnClose;        /* Free this memory allocation on close */
1140#if defined(SQLITE_ENABLE_SESSION)
1141    int nSession;              /* Number of active sessions */
1142    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1143#endif
1144  } aAuxDb[5],           /* Array of all database connections */
1145    *pAuxDb;             /* Currently active database connection */
1146  int *aiIndent;         /* Array of indents used in MODE_Explain */
1147  int nIndent;           /* Size of array aiIndent[] */
1148  int iIndent;           /* Index of current op in aiIndent[] */
1149  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1150  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1151  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1152};
1153
1154
1155/* Allowed values for ShellState.autoEQP
1156*/
1157#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1158#define AUTOEQP_on       1           /* Automatic EQP is on */
1159#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1160#define AUTOEQP_full     3           /* Show full EXPLAIN */
1161
1162/* Allowed values for ShellState.openMode
1163*/
1164#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1165#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1166#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1167#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1168#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1169#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1170#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1171
1172/* Allowed values for ShellState.eTraceType
1173*/
1174#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1175#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1176#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1177
1178/* Bits in the ShellState.flgProgress variable */
1179#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1180#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1181                                   ** callback limit is reached, and for each
1182                                   ** top-level SQL statement */
1183#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1184
1185/*
1186** These are the allowed shellFlgs values
1187*/
1188#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1189#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1190#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1191#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1192#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1193#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1194#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1195#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1196#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1197#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1198
1199/*
1200** Macros for testing and setting shellFlgs
1201*/
1202#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1203#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1204#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1205
1206/*
1207** These are the allowed modes.
1208*/
1209#define MODE_Line     0  /* One column per line.  Blank line between records */
1210#define MODE_Column   1  /* One record per line in neat columns */
1211#define MODE_List     2  /* One record per line with a separator */
1212#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1213#define MODE_Html     4  /* Generate an XHTML table */
1214#define MODE_Insert   5  /* Generate SQL "insert" statements */
1215#define MODE_Quote    6  /* Quote values as for SQL */
1216#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1217#define MODE_Csv      8  /* Quote strings, numbers are plain */
1218#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1219#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1220#define MODE_Pretty  11  /* Pretty-print schemas */
1221#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1222#define MODE_Json    13  /* Output JSON */
1223#define MODE_Markdown 14 /* Markdown formatting */
1224#define MODE_Table   15  /* MySQL-style table formatting */
1225#define MODE_Box     16  /* Unicode box-drawing characters */
1226#define MODE_Count   17  /* Output only a count of the rows of output */
1227#define MODE_Off     18  /* No query output shown */
1228
1229static const char *modeDescr[] = {
1230  "line",
1231  "column",
1232  "list",
1233  "semi",
1234  "html",
1235  "insert",
1236  "quote",
1237  "tcl",
1238  "csv",
1239  "explain",
1240  "ascii",
1241  "prettyprint",
1242  "eqp",
1243  "json",
1244  "markdown",
1245  "table",
1246  "box",
1247  "count",
1248  "off"
1249};
1250
1251/*
1252** These are the column/row/line separators used by the various
1253** import/export modes.
1254*/
1255#define SEP_Column    "|"
1256#define SEP_Row       "\n"
1257#define SEP_Tab       "\t"
1258#define SEP_Space     " "
1259#define SEP_Comma     ","
1260#define SEP_CrLf      "\r\n"
1261#define SEP_Unit      "\x1F"
1262#define SEP_Record    "\x1E"
1263
1264/*
1265** Limit input nesting via .read or any other input redirect.
1266** It's not too expensive, so a generous allowance can be made.
1267*/
1268#define MAX_INPUT_NESTING 25
1269
1270/*
1271** A callback for the sqlite3_log() interface.
1272*/
1273static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1274  ShellState *p = (ShellState*)pArg;
1275  if( p->pLog==0 ) return;
1276  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1277  fflush(p->pLog);
1278}
1279
1280/*
1281** SQL function:  shell_putsnl(X)
1282**
1283** Write the text X to the screen (or whatever output is being directed)
1284** adding a newline at the end, and then return X.
1285*/
1286static void shellPutsFunc(
1287  sqlite3_context *pCtx,
1288  int nVal,
1289  sqlite3_value **apVal
1290){
1291  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1292  (void)nVal;
1293  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1294  sqlite3_result_value(pCtx, apVal[0]);
1295}
1296
1297/*
1298** If in safe mode, print an error message described by the arguments
1299** and exit immediately.
1300*/
1301static void failIfSafeMode(
1302  ShellState *p,
1303  const char *zErrMsg,
1304  ...
1305){
1306  if( p->bSafeMode ){
1307    va_list ap;
1308    char *zMsg;
1309    va_start(ap, zErrMsg);
1310    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1311    va_end(ap);
1312    raw_printf(stderr, "line %d: ", p->lineno);
1313    utf8_printf(stderr, "%s\n", zMsg);
1314    exit(1);
1315  }
1316}
1317
1318/*
1319** SQL function:   edit(VALUE)
1320**                 edit(VALUE,EDITOR)
1321**
1322** These steps:
1323**
1324**     (1) Write VALUE into a temporary file.
1325**     (2) Run program EDITOR on that temporary file.
1326**     (3) Read the temporary file back and return its content as the result.
1327**     (4) Delete the temporary file
1328**
1329** If the EDITOR argument is omitted, use the value in the VISUAL
1330** environment variable.  If still there is no EDITOR, through an error.
1331**
1332** Also throw an error if the EDITOR program returns a non-zero exit code.
1333*/
1334#ifndef SQLITE_NOHAVE_SYSTEM
1335static void editFunc(
1336  sqlite3_context *context,
1337  int argc,
1338  sqlite3_value **argv
1339){
1340  const char *zEditor;
1341  char *zTempFile = 0;
1342  sqlite3 *db;
1343  char *zCmd = 0;
1344  int bBin;
1345  int rc;
1346  int hasCRNL = 0;
1347  FILE *f = 0;
1348  sqlite3_int64 sz;
1349  sqlite3_int64 x;
1350  unsigned char *p = 0;
1351
1352  if( argc==2 ){
1353    zEditor = (const char*)sqlite3_value_text(argv[1]);
1354  }else{
1355    zEditor = getenv("VISUAL");
1356  }
1357  if( zEditor==0 ){
1358    sqlite3_result_error(context, "no editor for edit()", -1);
1359    return;
1360  }
1361  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1362    sqlite3_result_error(context, "NULL input to edit()", -1);
1363    return;
1364  }
1365  db = sqlite3_context_db_handle(context);
1366  zTempFile = 0;
1367  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1368  if( zTempFile==0 ){
1369    sqlite3_uint64 r = 0;
1370    sqlite3_randomness(sizeof(r), &r);
1371    zTempFile = sqlite3_mprintf("temp%llx", r);
1372    if( zTempFile==0 ){
1373      sqlite3_result_error_nomem(context);
1374      return;
1375    }
1376  }
1377  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1378  /* When writing the file to be edited, do \n to \r\n conversions on systems
1379  ** that want \r\n line endings */
1380  f = fopen(zTempFile, bBin ? "wb" : "w");
1381  if( f==0 ){
1382    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1383    goto edit_func_end;
1384  }
1385  sz = sqlite3_value_bytes(argv[0]);
1386  if( bBin ){
1387    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1388  }else{
1389    const char *z = (const char*)sqlite3_value_text(argv[0]);
1390    /* Remember whether or not the value originally contained \r\n */
1391    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1392    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1393  }
1394  fclose(f);
1395  f = 0;
1396  if( x!=sz ){
1397    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1398    goto edit_func_end;
1399  }
1400  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1401  if( zCmd==0 ){
1402    sqlite3_result_error_nomem(context);
1403    goto edit_func_end;
1404  }
1405  rc = system(zCmd);
1406  sqlite3_free(zCmd);
1407  if( rc ){
1408    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1409    goto edit_func_end;
1410  }
1411  f = fopen(zTempFile, "rb");
1412  if( f==0 ){
1413    sqlite3_result_error(context,
1414      "edit() cannot reopen temp file after edit", -1);
1415    goto edit_func_end;
1416  }
1417  fseek(f, 0, SEEK_END);
1418  sz = ftell(f);
1419  rewind(f);
1420  p = sqlite3_malloc64( sz+1 );
1421  if( p==0 ){
1422    sqlite3_result_error_nomem(context);
1423    goto edit_func_end;
1424  }
1425  x = fread(p, 1, (size_t)sz, f);
1426  fclose(f);
1427  f = 0;
1428  if( x!=sz ){
1429    sqlite3_result_error(context, "could not read back the whole file", -1);
1430    goto edit_func_end;
1431  }
1432  if( bBin ){
1433    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1434  }else{
1435    sqlite3_int64 i, j;
1436    if( hasCRNL ){
1437      /* If the original contains \r\n then do no conversions back to \n */
1438    }else{
1439      /* If the file did not originally contain \r\n then convert any new
1440      ** \r\n back into \n */
1441      for(i=j=0; i<sz; i++){
1442        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1443        p[j++] = p[i];
1444      }
1445      sz = j;
1446      p[sz] = 0;
1447    }
1448    sqlite3_result_text64(context, (const char*)p, sz,
1449                          sqlite3_free, SQLITE_UTF8);
1450  }
1451  p = 0;
1452
1453edit_func_end:
1454  if( f ) fclose(f);
1455  unlink(zTempFile);
1456  sqlite3_free(zTempFile);
1457  sqlite3_free(p);
1458}
1459#endif /* SQLITE_NOHAVE_SYSTEM */
1460
1461/*
1462** Save or restore the current output mode
1463*/
1464static void outputModePush(ShellState *p){
1465  p->modePrior = p->mode;
1466  p->priorShFlgs = p->shellFlgs;
1467  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1468  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1469}
1470static void outputModePop(ShellState *p){
1471  p->mode = p->modePrior;
1472  p->shellFlgs = p->priorShFlgs;
1473  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1474  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1475}
1476
1477/*
1478** Output the given string as a hex-encoded blob (eg. X'1234' )
1479*/
1480static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1481  int i;
1482  char *zBlob = (char *)pBlob;
1483  raw_printf(out,"X'");
1484  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1485  raw_printf(out,"'");
1486}
1487
1488/*
1489** Find a string that is not found anywhere in z[].  Return a pointer
1490** to that string.
1491**
1492** Try to use zA and zB first.  If both of those are already found in z[]
1493** then make up some string and store it in the buffer zBuf.
1494*/
1495static const char *unused_string(
1496  const char *z,                    /* Result must not appear anywhere in z */
1497  const char *zA, const char *zB,   /* Try these first */
1498  char *zBuf                        /* Space to store a generated string */
1499){
1500  unsigned i = 0;
1501  if( strstr(z, zA)==0 ) return zA;
1502  if( strstr(z, zB)==0 ) return zB;
1503  do{
1504    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1505  }while( strstr(z,zBuf)!=0 );
1506  return zBuf;
1507}
1508
1509/*
1510** Output the given string as a quoted string using SQL quoting conventions.
1511**
1512** See also: output_quoted_escaped_string()
1513*/
1514static void output_quoted_string(FILE *out, const char *z){
1515  int i;
1516  char c;
1517  setBinaryMode(out, 1);
1518  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1519  if( c==0 ){
1520    utf8_printf(out,"'%s'",z);
1521  }else{
1522    raw_printf(out, "'");
1523    while( *z ){
1524      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1525      if( c=='\'' ) i++;
1526      if( i ){
1527        utf8_printf(out, "%.*s", i, z);
1528        z += i;
1529      }
1530      if( c=='\'' ){
1531        raw_printf(out, "'");
1532        continue;
1533      }
1534      if( c==0 ){
1535        break;
1536      }
1537      z++;
1538    }
1539    raw_printf(out, "'");
1540  }
1541  setTextMode(out, 1);
1542}
1543
1544/*
1545** Output the given string as a quoted string using SQL quoting conventions.
1546** Additionallly , escape the "\n" and "\r" characters so that they do not
1547** get corrupted by end-of-line translation facilities in some operating
1548** systems.
1549**
1550** This is like output_quoted_string() but with the addition of the \r\n
1551** escape mechanism.
1552*/
1553static void output_quoted_escaped_string(FILE *out, const char *z){
1554  int i;
1555  char c;
1556  setBinaryMode(out, 1);
1557  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1558  if( c==0 ){
1559    utf8_printf(out,"'%s'",z);
1560  }else{
1561    const char *zNL = 0;
1562    const char *zCR = 0;
1563    int nNL = 0;
1564    int nCR = 0;
1565    char zBuf1[20], zBuf2[20];
1566    for(i=0; z[i]; i++){
1567      if( z[i]=='\n' ) nNL++;
1568      if( z[i]=='\r' ) nCR++;
1569    }
1570    if( nNL ){
1571      raw_printf(out, "replace(");
1572      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1573    }
1574    if( nCR ){
1575      raw_printf(out, "replace(");
1576      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1577    }
1578    raw_printf(out, "'");
1579    while( *z ){
1580      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1581      if( c=='\'' ) i++;
1582      if( i ){
1583        utf8_printf(out, "%.*s", i, z);
1584        z += i;
1585      }
1586      if( c=='\'' ){
1587        raw_printf(out, "'");
1588        continue;
1589      }
1590      if( c==0 ){
1591        break;
1592      }
1593      z++;
1594      if( c=='\n' ){
1595        raw_printf(out, "%s", zNL);
1596        continue;
1597      }
1598      raw_printf(out, "%s", zCR);
1599    }
1600    raw_printf(out, "'");
1601    if( nCR ){
1602      raw_printf(out, ",'%s',char(13))", zCR);
1603    }
1604    if( nNL ){
1605      raw_printf(out, ",'%s',char(10))", zNL);
1606    }
1607  }
1608  setTextMode(out, 1);
1609}
1610
1611/*
1612** Output the given string as a quoted according to C or TCL quoting rules.
1613*/
1614static void output_c_string(FILE *out, const char *z){
1615  unsigned int c;
1616  fputc('"', out);
1617  while( (c = *(z++))!=0 ){
1618    if( c=='\\' ){
1619      fputc(c, out);
1620      fputc(c, out);
1621    }else if( c=='"' ){
1622      fputc('\\', out);
1623      fputc('"', out);
1624    }else if( c=='\t' ){
1625      fputc('\\', out);
1626      fputc('t', out);
1627    }else if( c=='\n' ){
1628      fputc('\\', out);
1629      fputc('n', out);
1630    }else if( c=='\r' ){
1631      fputc('\\', out);
1632      fputc('r', out);
1633    }else if( !isprint(c&0xff) ){
1634      raw_printf(out, "\\%03o", c&0xff);
1635    }else{
1636      fputc(c, out);
1637    }
1638  }
1639  fputc('"', out);
1640}
1641
1642/*
1643** Output the given string as a quoted according to JSON quoting rules.
1644*/
1645static void output_json_string(FILE *out, const char *z, int n){
1646  unsigned int c;
1647  if( n<0 ) n = (int)strlen(z);
1648  fputc('"', out);
1649  while( n-- ){
1650    c = *(z++);
1651    if( c=='\\' || c=='"' ){
1652      fputc('\\', out);
1653      fputc(c, out);
1654    }else if( c<=0x1f ){
1655      fputc('\\', out);
1656      if( c=='\b' ){
1657        fputc('b', out);
1658      }else if( c=='\f' ){
1659        fputc('f', out);
1660      }else if( c=='\n' ){
1661        fputc('n', out);
1662      }else if( c=='\r' ){
1663        fputc('r', out);
1664      }else if( c=='\t' ){
1665        fputc('t', out);
1666      }else{
1667         raw_printf(out, "u%04x",c);
1668      }
1669    }else{
1670      fputc(c, out);
1671    }
1672  }
1673  fputc('"', out);
1674}
1675
1676/*
1677** Output the given string with characters that are special to
1678** HTML escaped.
1679*/
1680static void output_html_string(FILE *out, const char *z){
1681  int i;
1682  if( z==0 ) z = "";
1683  while( *z ){
1684    for(i=0;   z[i]
1685            && z[i]!='<'
1686            && z[i]!='&'
1687            && z[i]!='>'
1688            && z[i]!='\"'
1689            && z[i]!='\'';
1690        i++){}
1691    if( i>0 ){
1692      utf8_printf(out,"%.*s",i,z);
1693    }
1694    if( z[i]=='<' ){
1695      raw_printf(out,"&lt;");
1696    }else if( z[i]=='&' ){
1697      raw_printf(out,"&amp;");
1698    }else if( z[i]=='>' ){
1699      raw_printf(out,"&gt;");
1700    }else if( z[i]=='\"' ){
1701      raw_printf(out,"&quot;");
1702    }else if( z[i]=='\'' ){
1703      raw_printf(out,"&#39;");
1704    }else{
1705      break;
1706    }
1707    z += i + 1;
1708  }
1709}
1710
1711/*
1712** If a field contains any character identified by a 1 in the following
1713** array, then the string must be quoted for CSV.
1714*/
1715static const char needCsvQuote[] = {
1716  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1717  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1718  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1719  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1720  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1721  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1722  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1723  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1724  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1725  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1726  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1727  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1728  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1729  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1730  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1731  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1732};
1733
1734/*
1735** Output a single term of CSV.  Actually, p->colSeparator is used for
1736** the separator, which may or may not be a comma.  p->nullValue is
1737** the null value.  Strings are quoted if necessary.  The separator
1738** is only issued if bSep is true.
1739*/
1740static void output_csv(ShellState *p, const char *z, int bSep){
1741  FILE *out = p->out;
1742  if( z==0 ){
1743    utf8_printf(out,"%s",p->nullValue);
1744  }else{
1745    unsigned i;
1746    for(i=0; z[i]; i++){
1747      if( needCsvQuote[((unsigned char*)z)[i]] ){
1748        i = 0;
1749        break;
1750      }
1751    }
1752    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1753      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1754      shell_check_oom(zQuoted);
1755      utf8_printf(out, "%s", zQuoted);
1756      sqlite3_free(zQuoted);
1757    }else{
1758      utf8_printf(out, "%s", z);
1759    }
1760  }
1761  if( bSep ){
1762    utf8_printf(p->out, "%s", p->colSeparator);
1763  }
1764}
1765
1766/*
1767** This routine runs when the user presses Ctrl-C
1768*/
1769static void interrupt_handler(int NotUsed){
1770  UNUSED_PARAMETER(NotUsed);
1771  seenInterrupt++;
1772  if( seenInterrupt>2 ) exit(1);
1773  if( globalDb ) sqlite3_interrupt(globalDb);
1774}
1775
1776#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1777/*
1778** This routine runs for console events (e.g. Ctrl-C) on Win32
1779*/
1780static BOOL WINAPI ConsoleCtrlHandler(
1781  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1782){
1783  if( dwCtrlType==CTRL_C_EVENT ){
1784    interrupt_handler(0);
1785    return TRUE;
1786  }
1787  return FALSE;
1788}
1789#endif
1790
1791#ifndef SQLITE_OMIT_AUTHORIZATION
1792/*
1793** This authorizer runs in safe mode.
1794*/
1795static int safeModeAuth(
1796  void *pClientData,
1797  int op,
1798  const char *zA1,
1799  const char *zA2,
1800  const char *zA3,
1801  const char *zA4
1802){
1803  ShellState *p = (ShellState*)pClientData;
1804  static const char *azProhibitedFunctions[] = {
1805    "edit",
1806    "fts3_tokenizer",
1807    "load_extension",
1808    "readfile",
1809    "writefile",
1810    "zipfile",
1811    "zipfile_cds",
1812  };
1813  UNUSED_PARAMETER(zA2);
1814  UNUSED_PARAMETER(zA3);
1815  UNUSED_PARAMETER(zA4);
1816  switch( op ){
1817    case SQLITE_ATTACH: {
1818      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1819      break;
1820    }
1821    case SQLITE_FUNCTION: {
1822      int i;
1823      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1824        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1825          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1826                         azProhibitedFunctions[i]);
1827        }
1828      }
1829      break;
1830    }
1831  }
1832  return SQLITE_OK;
1833}
1834
1835/*
1836** When the ".auth ON" is set, the following authorizer callback is
1837** invoked.  It always returns SQLITE_OK.
1838*/
1839static int shellAuth(
1840  void *pClientData,
1841  int op,
1842  const char *zA1,
1843  const char *zA2,
1844  const char *zA3,
1845  const char *zA4
1846){
1847  ShellState *p = (ShellState*)pClientData;
1848  static const char *azAction[] = { 0,
1849     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1850     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1851     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1852     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1853     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1854     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1855     "PRAGMA",               "READ",                 "SELECT",
1856     "TRANSACTION",          "UPDATE",               "ATTACH",
1857     "DETACH",               "ALTER_TABLE",          "REINDEX",
1858     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1859     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1860  };
1861  int i;
1862  const char *az[4];
1863  az[0] = zA1;
1864  az[1] = zA2;
1865  az[2] = zA3;
1866  az[3] = zA4;
1867  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1868  for(i=0; i<4; i++){
1869    raw_printf(p->out, " ");
1870    if( az[i] ){
1871      output_c_string(p->out, az[i]);
1872    }else{
1873      raw_printf(p->out, "NULL");
1874    }
1875  }
1876  raw_printf(p->out, "\n");
1877  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1878  return SQLITE_OK;
1879}
1880#endif
1881
1882/*
1883** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1884**
1885** This routine converts some CREATE TABLE statements for shadow tables
1886** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1887*/
1888static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1889  if( z==0 ) return;
1890  if( zTail==0 ) return;
1891  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1892    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1893  }else{
1894    utf8_printf(out, "%s%s", z, zTail);
1895  }
1896}
1897static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1898  char c = z[n];
1899  z[n] = 0;
1900  printSchemaLine(out, z, zTail);
1901  z[n] = c;
1902}
1903
1904/*
1905** Return true if string z[] has nothing but whitespace and comments to the
1906** end of the first line.
1907*/
1908static int wsToEol(const char *z){
1909  int i;
1910  for(i=0; z[i]; i++){
1911    if( z[i]=='\n' ) return 1;
1912    if( IsSpace(z[i]) ) continue;
1913    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1914    return 0;
1915  }
1916  return 1;
1917}
1918
1919/*
1920** Add a new entry to the EXPLAIN QUERY PLAN data
1921*/
1922static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1923  EQPGraphRow *pNew;
1924  int nText = strlen30(zText);
1925  if( p->autoEQPtest ){
1926    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1927  }
1928  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1929  shell_check_oom(pNew);
1930  pNew->iEqpId = iEqpId;
1931  pNew->iParentId = p2;
1932  memcpy(pNew->zText, zText, nText+1);
1933  pNew->pNext = 0;
1934  if( p->sGraph.pLast ){
1935    p->sGraph.pLast->pNext = pNew;
1936  }else{
1937    p->sGraph.pRow = pNew;
1938  }
1939  p->sGraph.pLast = pNew;
1940}
1941
1942/*
1943** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1944** in p->sGraph.
1945*/
1946static void eqp_reset(ShellState *p){
1947  EQPGraphRow *pRow, *pNext;
1948  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1949    pNext = pRow->pNext;
1950    sqlite3_free(pRow);
1951  }
1952  memset(&p->sGraph, 0, sizeof(p->sGraph));
1953}
1954
1955/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1956** pOld, or return the first such line if pOld is NULL
1957*/
1958static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1959  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1960  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1961  return pRow;
1962}
1963
1964/* Render a single level of the graph that has iEqpId as its parent.  Called
1965** recursively to render sublevels.
1966*/
1967static void eqp_render_level(ShellState *p, int iEqpId){
1968  EQPGraphRow *pRow, *pNext;
1969  int n = strlen30(p->sGraph.zPrefix);
1970  char *z;
1971  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1972    pNext = eqp_next_row(p, iEqpId, pRow);
1973    z = pRow->zText;
1974    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1975                pNext ? "|--" : "`--", z);
1976    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1977      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1978      eqp_render_level(p, pRow->iEqpId);
1979      p->sGraph.zPrefix[n] = 0;
1980    }
1981  }
1982}
1983
1984/*
1985** Display and reset the EXPLAIN QUERY PLAN data
1986*/
1987static void eqp_render(ShellState *p){
1988  EQPGraphRow *pRow = p->sGraph.pRow;
1989  if( pRow ){
1990    if( pRow->zText[0]=='-' ){
1991      if( pRow->pNext==0 ){
1992        eqp_reset(p);
1993        return;
1994      }
1995      utf8_printf(p->out, "%s\n", pRow->zText+3);
1996      p->sGraph.pRow = pRow->pNext;
1997      sqlite3_free(pRow);
1998    }else{
1999      utf8_printf(p->out, "QUERY PLAN\n");
2000    }
2001    p->sGraph.zPrefix[0] = 0;
2002    eqp_render_level(p, 0);
2003    eqp_reset(p);
2004  }
2005}
2006
2007#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2008/*
2009** Progress handler callback.
2010*/
2011static int progress_handler(void *pClientData) {
2012  ShellState *p = (ShellState*)pClientData;
2013  p->nProgress++;
2014  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2015    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2016    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2017    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2018    return 1;
2019  }
2020  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2021    raw_printf(p->out, "Progress %u\n", p->nProgress);
2022  }
2023  return 0;
2024}
2025#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2026
2027/*
2028** Print N dashes
2029*/
2030static void print_dashes(FILE *out, int N){
2031  const char zDash[] = "--------------------------------------------------";
2032  const int nDash = sizeof(zDash) - 1;
2033  while( N>nDash ){
2034    fputs(zDash, out);
2035    N -= nDash;
2036  }
2037  raw_printf(out, "%.*s", N, zDash);
2038}
2039
2040/*
2041** Print a markdown or table-style row separator using ascii-art
2042*/
2043static void print_row_separator(
2044  ShellState *p,
2045  int nArg,
2046  const char *zSep
2047){
2048  int i;
2049  if( nArg>0 ){
2050    fputs(zSep, p->out);
2051    print_dashes(p->out, p->actualWidth[0]+2);
2052    for(i=1; i<nArg; i++){
2053      fputs(zSep, p->out);
2054      print_dashes(p->out, p->actualWidth[i]+2);
2055    }
2056    fputs(zSep, p->out);
2057  }
2058  fputs("\n", p->out);
2059}
2060
2061/*
2062** This is the callback routine that the shell
2063** invokes for each row of a query result.
2064*/
2065static int shell_callback(
2066  void *pArg,
2067  int nArg,        /* Number of result columns */
2068  char **azArg,    /* Text of each result column */
2069  char **azCol,    /* Column names */
2070  int *aiType      /* Column types.  Might be NULL */
2071){
2072  int i;
2073  ShellState *p = (ShellState*)pArg;
2074
2075  if( azArg==0 ) return 0;
2076  switch( p->cMode ){
2077    case MODE_Count:
2078    case MODE_Off: {
2079      break;
2080    }
2081    case MODE_Line: {
2082      int w = 5;
2083      if( azArg==0 ) break;
2084      for(i=0; i<nArg; i++){
2085        int len = strlen30(azCol[i] ? azCol[i] : "");
2086        if( len>w ) w = len;
2087      }
2088      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2089      for(i=0; i<nArg; i++){
2090        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2091                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2092      }
2093      break;
2094    }
2095    case MODE_Explain: {
2096      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2097      if( nArg>ArraySize(aExplainWidth) ){
2098        nArg = ArraySize(aExplainWidth);
2099      }
2100      if( p->cnt++==0 ){
2101        for(i=0; i<nArg; i++){
2102          int w = aExplainWidth[i];
2103          utf8_width_print(p->out, w, azCol[i]);
2104          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2105        }
2106        for(i=0; i<nArg; i++){
2107          int w = aExplainWidth[i];
2108          print_dashes(p->out, w);
2109          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2110        }
2111      }
2112      if( azArg==0 ) break;
2113      for(i=0; i<nArg; i++){
2114        int w = aExplainWidth[i];
2115        if( i==nArg-1 ) w = 0;
2116        if( azArg[i] && strlenChar(azArg[i])>w ){
2117          w = strlenChar(azArg[i]);
2118        }
2119        if( i==1 && p->aiIndent && p->pStmt ){
2120          if( p->iIndent<p->nIndent ){
2121            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2122          }
2123          p->iIndent++;
2124        }
2125        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2126        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2127      }
2128      break;
2129    }
2130    case MODE_Semi: {   /* .schema and .fullschema output */
2131      printSchemaLine(p->out, azArg[0], ";\n");
2132      break;
2133    }
2134    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2135      char *z;
2136      int j;
2137      int nParen = 0;
2138      char cEnd = 0;
2139      char c;
2140      int nLine = 0;
2141      assert( nArg==1 );
2142      if( azArg[0]==0 ) break;
2143      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2144       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2145      ){
2146        utf8_printf(p->out, "%s;\n", azArg[0]);
2147        break;
2148      }
2149      z = sqlite3_mprintf("%s", azArg[0]);
2150      shell_check_oom(z);
2151      j = 0;
2152      for(i=0; IsSpace(z[i]); i++){}
2153      for(; (c = z[i])!=0; i++){
2154        if( IsSpace(c) ){
2155          if( z[j-1]=='\r' ) z[j-1] = '\n';
2156          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2157        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2158          j--;
2159        }
2160        z[j++] = c;
2161      }
2162      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2163      z[j] = 0;
2164      if( strlen30(z)>=79 ){
2165        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2166          if( c==cEnd ){
2167            cEnd = 0;
2168          }else if( c=='"' || c=='\'' || c=='`' ){
2169            cEnd = c;
2170          }else if( c=='[' ){
2171            cEnd = ']';
2172          }else if( c=='-' && z[i+1]=='-' ){
2173            cEnd = '\n';
2174          }else if( c=='(' ){
2175            nParen++;
2176          }else if( c==')' ){
2177            nParen--;
2178            if( nLine>0 && nParen==0 && j>0 ){
2179              printSchemaLineN(p->out, z, j, "\n");
2180              j = 0;
2181            }
2182          }
2183          z[j++] = c;
2184          if( nParen==1 && cEnd==0
2185           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2186          ){
2187            if( c=='\n' ) j--;
2188            printSchemaLineN(p->out, z, j, "\n  ");
2189            j = 0;
2190            nLine++;
2191            while( IsSpace(z[i+1]) ){ i++; }
2192          }
2193        }
2194        z[j] = 0;
2195      }
2196      printSchemaLine(p->out, z, ";\n");
2197      sqlite3_free(z);
2198      break;
2199    }
2200    case MODE_List: {
2201      if( p->cnt++==0 && p->showHeader ){
2202        for(i=0; i<nArg; i++){
2203          utf8_printf(p->out,"%s%s",azCol[i],
2204                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2205        }
2206      }
2207      if( azArg==0 ) break;
2208      for(i=0; i<nArg; i++){
2209        char *z = azArg[i];
2210        if( z==0 ) z = p->nullValue;
2211        utf8_printf(p->out, "%s", z);
2212        if( i<nArg-1 ){
2213          utf8_printf(p->out, "%s", p->colSeparator);
2214        }else{
2215          utf8_printf(p->out, "%s", p->rowSeparator);
2216        }
2217      }
2218      break;
2219    }
2220    case MODE_Html: {
2221      if( p->cnt++==0 && p->showHeader ){
2222        raw_printf(p->out,"<TR>");
2223        for(i=0; i<nArg; i++){
2224          raw_printf(p->out,"<TH>");
2225          output_html_string(p->out, azCol[i]);
2226          raw_printf(p->out,"</TH>\n");
2227        }
2228        raw_printf(p->out,"</TR>\n");
2229      }
2230      if( azArg==0 ) break;
2231      raw_printf(p->out,"<TR>");
2232      for(i=0; i<nArg; i++){
2233        raw_printf(p->out,"<TD>");
2234        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2235        raw_printf(p->out,"</TD>\n");
2236      }
2237      raw_printf(p->out,"</TR>\n");
2238      break;
2239    }
2240    case MODE_Tcl: {
2241      if( p->cnt++==0 && p->showHeader ){
2242        for(i=0; i<nArg; i++){
2243          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2244          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2245        }
2246        utf8_printf(p->out, "%s", p->rowSeparator);
2247      }
2248      if( azArg==0 ) break;
2249      for(i=0; i<nArg; i++){
2250        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2251        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2252      }
2253      utf8_printf(p->out, "%s", p->rowSeparator);
2254      break;
2255    }
2256    case MODE_Csv: {
2257      setBinaryMode(p->out, 1);
2258      if( p->cnt++==0 && p->showHeader ){
2259        for(i=0; i<nArg; i++){
2260          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2261        }
2262        utf8_printf(p->out, "%s", p->rowSeparator);
2263      }
2264      if( nArg>0 ){
2265        for(i=0; i<nArg; i++){
2266          output_csv(p, azArg[i], i<nArg-1);
2267        }
2268        utf8_printf(p->out, "%s", p->rowSeparator);
2269      }
2270      setTextMode(p->out, 1);
2271      break;
2272    }
2273    case MODE_Insert: {
2274      if( azArg==0 ) break;
2275      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2276      if( p->showHeader ){
2277        raw_printf(p->out,"(");
2278        for(i=0; i<nArg; i++){
2279          if( i>0 ) raw_printf(p->out, ",");
2280          if( quoteChar(azCol[i]) ){
2281            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2282            shell_check_oom(z);
2283            utf8_printf(p->out, "%s", z);
2284            sqlite3_free(z);
2285          }else{
2286            raw_printf(p->out, "%s", azCol[i]);
2287          }
2288        }
2289        raw_printf(p->out,")");
2290      }
2291      p->cnt++;
2292      for(i=0; i<nArg; i++){
2293        raw_printf(p->out, i>0 ? "," : " VALUES(");
2294        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2295          utf8_printf(p->out,"NULL");
2296        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2297          if( ShellHasFlag(p, SHFLG_Newlines) ){
2298            output_quoted_string(p->out, azArg[i]);
2299          }else{
2300            output_quoted_escaped_string(p->out, azArg[i]);
2301          }
2302        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2303          utf8_printf(p->out,"%s", azArg[i]);
2304        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2305          char z[50];
2306          double r = sqlite3_column_double(p->pStmt, i);
2307          sqlite3_uint64 ur;
2308          memcpy(&ur,&r,sizeof(r));
2309          if( ur==0x7ff0000000000000LL ){
2310            raw_printf(p->out, "1e999");
2311          }else if( ur==0xfff0000000000000LL ){
2312            raw_printf(p->out, "-1e999");
2313          }else{
2314            sqlite3_snprintf(50,z,"%!.20g", r);
2315            raw_printf(p->out, "%s", z);
2316          }
2317        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2318          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2319          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2320          output_hex_blob(p->out, pBlob, nBlob);
2321        }else if( isNumber(azArg[i], 0) ){
2322          utf8_printf(p->out,"%s", azArg[i]);
2323        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2324          output_quoted_string(p->out, azArg[i]);
2325        }else{
2326          output_quoted_escaped_string(p->out, azArg[i]);
2327        }
2328      }
2329      raw_printf(p->out,");\n");
2330      break;
2331    }
2332    case MODE_Json: {
2333      if( azArg==0 ) break;
2334      if( p->cnt==0 ){
2335        fputs("[{", p->out);
2336      }else{
2337        fputs(",\n{", p->out);
2338      }
2339      p->cnt++;
2340      for(i=0; i<nArg; i++){
2341        output_json_string(p->out, azCol[i], -1);
2342        putc(':', p->out);
2343        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2344          fputs("null",p->out);
2345        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2346          char z[50];
2347          double r = sqlite3_column_double(p->pStmt, i);
2348          sqlite3_uint64 ur;
2349          memcpy(&ur,&r,sizeof(r));
2350          if( ur==0x7ff0000000000000LL ){
2351            raw_printf(p->out, "1e999");
2352          }else if( ur==0xfff0000000000000LL ){
2353            raw_printf(p->out, "-1e999");
2354          }else{
2355            sqlite3_snprintf(50,z,"%!.20g", r);
2356            raw_printf(p->out, "%s", z);
2357          }
2358        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2359          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2360          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2361          output_json_string(p->out, pBlob, nBlob);
2362        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2363          output_json_string(p->out, azArg[i], -1);
2364        }else{
2365          utf8_printf(p->out,"%s", azArg[i]);
2366        }
2367        if( i<nArg-1 ){
2368          putc(',', p->out);
2369        }
2370      }
2371      putc('}', p->out);
2372      break;
2373    }
2374    case MODE_Quote: {
2375      if( azArg==0 ) break;
2376      if( p->cnt==0 && p->showHeader ){
2377        for(i=0; i<nArg; i++){
2378          if( i>0 ) fputs(p->colSeparator, p->out);
2379          output_quoted_string(p->out, azCol[i]);
2380        }
2381        fputs(p->rowSeparator, p->out);
2382      }
2383      p->cnt++;
2384      for(i=0; i<nArg; i++){
2385        if( i>0 ) fputs(p->colSeparator, p->out);
2386        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2387          utf8_printf(p->out,"NULL");
2388        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2389          output_quoted_string(p->out, azArg[i]);
2390        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2391          utf8_printf(p->out,"%s", azArg[i]);
2392        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2393          char z[50];
2394          double r = sqlite3_column_double(p->pStmt, i);
2395          sqlite3_snprintf(50,z,"%!.20g", r);
2396          raw_printf(p->out, "%s", z);
2397        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2398          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2399          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2400          output_hex_blob(p->out, pBlob, nBlob);
2401        }else if( isNumber(azArg[i], 0) ){
2402          utf8_printf(p->out,"%s", azArg[i]);
2403        }else{
2404          output_quoted_string(p->out, azArg[i]);
2405        }
2406      }
2407      fputs(p->rowSeparator, p->out);
2408      break;
2409    }
2410    case MODE_Ascii: {
2411      if( p->cnt++==0 && p->showHeader ){
2412        for(i=0; i<nArg; i++){
2413          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2414          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2415        }
2416        utf8_printf(p->out, "%s", p->rowSeparator);
2417      }
2418      if( azArg==0 ) break;
2419      for(i=0; i<nArg; i++){
2420        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2421        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2422      }
2423      utf8_printf(p->out, "%s", p->rowSeparator);
2424      break;
2425    }
2426    case MODE_EQP: {
2427      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2428      break;
2429    }
2430  }
2431  return 0;
2432}
2433
2434/*
2435** This is the callback routine that the SQLite library
2436** invokes for each row of a query result.
2437*/
2438static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2439  /* since we don't have type info, call the shell_callback with a NULL value */
2440  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2441}
2442
2443/*
2444** This is the callback routine from sqlite3_exec() that appends all
2445** output onto the end of a ShellText object.
2446*/
2447static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2448  ShellText *p = (ShellText*)pArg;
2449  int i;
2450  UNUSED_PARAMETER(az);
2451  if( azArg==0 ) return 0;
2452  if( p->n ) appendText(p, "|", 0);
2453  for(i=0; i<nArg; i++){
2454    if( i ) appendText(p, ",", 0);
2455    if( azArg[i] ) appendText(p, azArg[i], 0);
2456  }
2457  return 0;
2458}
2459
2460/*
2461** Generate an appropriate SELFTEST table in the main database.
2462*/
2463static void createSelftestTable(ShellState *p){
2464  char *zErrMsg = 0;
2465  sqlite3_exec(p->db,
2466    "SAVEPOINT selftest_init;\n"
2467    "CREATE TABLE IF NOT EXISTS selftest(\n"
2468    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2469    "  op TEXT,\n"                   /* Operator:  memo run */
2470    "  cmd TEXT,\n"                  /* Command text */
2471    "  ans TEXT\n"                   /* Desired answer */
2472    ");"
2473    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2474    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2475    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2476    "         'memo','Tests generated by --init');\n"
2477    "INSERT INTO [_shell$self]\n"
2478    "  SELECT 'run',\n"
2479    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2480                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2481    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2482                          "FROM sqlite_schema ORDER BY 2',224));\n"
2483    "INSERT INTO [_shell$self]\n"
2484    "  SELECT 'run',"
2485    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2486    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2487    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2488    "  FROM (\n"
2489    "    SELECT name FROM sqlite_schema\n"
2490    "     WHERE type='table'\n"
2491    "       AND name<>'selftest'\n"
2492    "       AND coalesce(rootpage,0)>0\n"
2493    "  )\n"
2494    " ORDER BY name;\n"
2495    "INSERT INTO [_shell$self]\n"
2496    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2497    "INSERT INTO selftest(tno,op,cmd,ans)"
2498    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2499    "DROP TABLE [_shell$self];"
2500    ,0,0,&zErrMsg);
2501  if( zErrMsg ){
2502    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2503    sqlite3_free(zErrMsg);
2504  }
2505  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2506}
2507
2508
2509/*
2510** Set the destination table field of the ShellState structure to
2511** the name of the table given.  Escape any quote characters in the
2512** table name.
2513*/
2514static void set_table_name(ShellState *p, const char *zName){
2515  int i, n;
2516  char cQuote;
2517  char *z;
2518
2519  if( p->zDestTable ){
2520    free(p->zDestTable);
2521    p->zDestTable = 0;
2522  }
2523  if( zName==0 ) return;
2524  cQuote = quoteChar(zName);
2525  n = strlen30(zName);
2526  if( cQuote ) n += n+2;
2527  z = p->zDestTable = malloc( n+1 );
2528  shell_check_oom(z);
2529  n = 0;
2530  if( cQuote ) z[n++] = cQuote;
2531  for(i=0; zName[i]; i++){
2532    z[n++] = zName[i];
2533    if( zName[i]==cQuote ) z[n++] = cQuote;
2534  }
2535  if( cQuote ) z[n++] = cQuote;
2536  z[n] = 0;
2537}
2538
2539/*
2540** Maybe construct two lines of text that point out the position of a
2541** syntax error.  Return a pointer to the text, in memory obtained from
2542** sqlite3_malloc().  Or, if the most recent error does not involve a
2543** specific token that we can point to, return an empty string.
2544**
2545** In all cases, the memory returned is obtained from sqlite3_malloc64()
2546** and should be released by the caller invoking sqlite3_free().
2547*/
2548static char *shell_error_context(const char *zSql, sqlite3 *db){
2549  int iOffset;
2550  size_t len;
2551  char *zCode;
2552  char *zMsg;
2553  int i;
2554  if( db==0
2555   || zSql==0
2556   || (iOffset = sqlite3_error_offset(db))<0
2557  ){
2558    return sqlite3_mprintf("");
2559  }
2560  while( iOffset>50 ){
2561    iOffset--;
2562    zSql++;
2563    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2564  }
2565  len = strlen(zSql);
2566  if( len>78 ){
2567    len = 78;
2568    while( (zSql[len]&0xc0)==0x80 ) len--;
2569  }
2570  zCode = sqlite3_mprintf("%.*s", len, zSql);
2571  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2572  if( iOffset<25 ){
2573    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2574  }else{
2575    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2576  }
2577  return zMsg;
2578}
2579
2580
2581/*
2582** Execute a query statement that will generate SQL output.  Print
2583** the result columns, comma-separated, on a line and then add a
2584** semicolon terminator to the end of that line.
2585**
2586** If the number of columns is 1 and that column contains text "--"
2587** then write the semicolon on a separate line.  That way, if a
2588** "--" comment occurs at the end of the statement, the comment
2589** won't consume the semicolon terminator.
2590*/
2591static int run_table_dump_query(
2592  ShellState *p,           /* Query context */
2593  const char *zSelect      /* SELECT statement to extract content */
2594){
2595  sqlite3_stmt *pSelect;
2596  int rc;
2597  int nResult;
2598  int i;
2599  const char *z;
2600  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2601  if( rc!=SQLITE_OK || !pSelect ){
2602    char *zContext = shell_error_context(zSelect, p->db);
2603    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2604                sqlite3_errmsg(p->db), zContext);
2605    sqlite3_free(zContext);
2606    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2607    return rc;
2608  }
2609  rc = sqlite3_step(pSelect);
2610  nResult = sqlite3_column_count(pSelect);
2611  while( rc==SQLITE_ROW ){
2612    z = (const char*)sqlite3_column_text(pSelect, 0);
2613    utf8_printf(p->out, "%s", z);
2614    for(i=1; i<nResult; i++){
2615      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2616    }
2617    if( z==0 ) z = "";
2618    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2619    if( z[0] ){
2620      raw_printf(p->out, "\n;\n");
2621    }else{
2622      raw_printf(p->out, ";\n");
2623    }
2624    rc = sqlite3_step(pSelect);
2625  }
2626  rc = sqlite3_finalize(pSelect);
2627  if( rc!=SQLITE_OK ){
2628    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2629                sqlite3_errmsg(p->db));
2630    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2631  }
2632  return rc;
2633}
2634
2635/*
2636** Allocate space and save off string indicating current error.
2637*/
2638static char *save_err_msg(
2639  sqlite3 *db,           /* Database to query */
2640  const char *zWhen,     /* Qualifier (format) wrapper */
2641  int rc,                /* Error code returned from API */
2642  const char *zSql       /* SQL string, or NULL */
2643){
2644  char *zErr;
2645  char *zContext;
2646  if( zWhen==0 ) zWhen = "%s (%d)%s";
2647  zContext = shell_error_context(zSql, db);
2648  zErr = sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc, zContext);
2649  shell_check_oom(zErr);
2650  sqlite3_free(zContext);
2651  return zErr;
2652}
2653
2654#ifdef __linux__
2655/*
2656** Attempt to display I/O stats on Linux using /proc/PID/io
2657*/
2658static void displayLinuxIoStats(FILE *out){
2659  FILE *in;
2660  char z[200];
2661  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2662  in = fopen(z, "rb");
2663  if( in==0 ) return;
2664  while( fgets(z, sizeof(z), in)!=0 ){
2665    static const struct {
2666      const char *zPattern;
2667      const char *zDesc;
2668    } aTrans[] = {
2669      { "rchar: ",                  "Bytes received by read():" },
2670      { "wchar: ",                  "Bytes sent to write():"    },
2671      { "syscr: ",                  "Read() system calls:"      },
2672      { "syscw: ",                  "Write() system calls:"     },
2673      { "read_bytes: ",             "Bytes read from storage:"  },
2674      { "write_bytes: ",            "Bytes written to storage:" },
2675      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2676    };
2677    int i;
2678    for(i=0; i<ArraySize(aTrans); i++){
2679      int n = strlen30(aTrans[i].zPattern);
2680      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2681        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2682        break;
2683      }
2684    }
2685  }
2686  fclose(in);
2687}
2688#endif
2689
2690/*
2691** Display a single line of status using 64-bit values.
2692*/
2693static void displayStatLine(
2694  ShellState *p,            /* The shell context */
2695  char *zLabel,             /* Label for this one line */
2696  char *zFormat,            /* Format for the result */
2697  int iStatusCtrl,          /* Which status to display */
2698  int bReset                /* True to reset the stats */
2699){
2700  sqlite3_int64 iCur = -1;
2701  sqlite3_int64 iHiwtr = -1;
2702  int i, nPercent;
2703  char zLine[200];
2704  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2705  for(i=0, nPercent=0; zFormat[i]; i++){
2706    if( zFormat[i]=='%' ) nPercent++;
2707  }
2708  if( nPercent>1 ){
2709    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2710  }else{
2711    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2712  }
2713  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2714}
2715
2716/*
2717** Display memory stats.
2718*/
2719static int display_stats(
2720  sqlite3 *db,                /* Database to query */
2721  ShellState *pArg,           /* Pointer to ShellState */
2722  int bReset                  /* True to reset the stats */
2723){
2724  int iCur;
2725  int iHiwtr;
2726  FILE *out;
2727  if( pArg==0 || pArg->out==0 ) return 0;
2728  out = pArg->out;
2729
2730  if( pArg->pStmt && pArg->statsOn==2 ){
2731    int nCol, i, x;
2732    sqlite3_stmt *pStmt = pArg->pStmt;
2733    char z[100];
2734    nCol = sqlite3_column_count(pStmt);
2735    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2736    for(i=0; i<nCol; i++){
2737      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2738      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2739#ifndef SQLITE_OMIT_DECLTYPE
2740      sqlite3_snprintf(30, z+x, "declared type:");
2741      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2742#endif
2743#ifdef SQLITE_ENABLE_COLUMN_METADATA
2744      sqlite3_snprintf(30, z+x, "database name:");
2745      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2746      sqlite3_snprintf(30, z+x, "table name:");
2747      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2748      sqlite3_snprintf(30, z+x, "origin name:");
2749      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2750#endif
2751    }
2752  }
2753
2754  if( pArg->statsOn==3 ){
2755    if( pArg->pStmt ){
2756      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2757      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2758    }
2759    return 0;
2760  }
2761
2762  displayStatLine(pArg, "Memory Used:",
2763     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2764  displayStatLine(pArg, "Number of Outstanding Allocations:",
2765     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2766  if( pArg->shellFlgs & SHFLG_Pagecache ){
2767    displayStatLine(pArg, "Number of Pcache Pages Used:",
2768       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2769  }
2770  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2771     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2772  displayStatLine(pArg, "Largest Allocation:",
2773     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2774  displayStatLine(pArg, "Largest Pcache Allocation:",
2775     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2776#ifdef YYTRACKMAXSTACKDEPTH
2777  displayStatLine(pArg, "Deepest Parser Stack:",
2778     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2779#endif
2780
2781  if( db ){
2782    if( pArg->shellFlgs & SHFLG_Lookaside ){
2783      iHiwtr = iCur = -1;
2784      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2785                        &iCur, &iHiwtr, bReset);
2786      raw_printf(pArg->out,
2787              "Lookaside Slots Used:                %d (max %d)\n",
2788              iCur, iHiwtr);
2789      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2790                        &iCur, &iHiwtr, bReset);
2791      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2792              iHiwtr);
2793      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2794                        &iCur, &iHiwtr, bReset);
2795      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2796              iHiwtr);
2797      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2798                        &iCur, &iHiwtr, bReset);
2799      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2800              iHiwtr);
2801    }
2802    iHiwtr = iCur = -1;
2803    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2804    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2805            iCur);
2806    iHiwtr = iCur = -1;
2807    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2808    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2809    iHiwtr = iCur = -1;
2810    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2811    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2812    iHiwtr = iCur = -1;
2813    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2814    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2815    iHiwtr = iCur = -1;
2816    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2817    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2818    iHiwtr = iCur = -1;
2819    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2820    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2821            iCur);
2822    iHiwtr = iCur = -1;
2823    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2824    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2825            iCur);
2826  }
2827
2828  if( pArg->pStmt ){
2829    int iHit, iMiss;
2830    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2831                               bReset);
2832    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2833    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2834    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2835    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2836    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2837    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2838    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2839    if( iHit || iMiss ){
2840      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2841            iHit, iHit+iMiss);
2842    }
2843    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2844    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2845    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2846    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2847    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2848    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2849    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2850    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2851  }
2852
2853#ifdef __linux__
2854  displayLinuxIoStats(pArg->out);
2855#endif
2856
2857  /* Do not remove this machine readable comment: extra-stats-output-here */
2858
2859  return 0;
2860}
2861
2862/*
2863** Display scan stats.
2864*/
2865static void display_scanstats(
2866  sqlite3 *db,                    /* Database to query */
2867  ShellState *pArg                /* Pointer to ShellState */
2868){
2869#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2870  UNUSED_PARAMETER(db);
2871  UNUSED_PARAMETER(pArg);
2872#else
2873  int i, k, n, mx;
2874  raw_printf(pArg->out, "-------- scanstats --------\n");
2875  mx = 0;
2876  for(k=0; k<=mx; k++){
2877    double rEstLoop = 1.0;
2878    for(i=n=0; 1; i++){
2879      sqlite3_stmt *p = pArg->pStmt;
2880      sqlite3_int64 nLoop, nVisit;
2881      double rEst;
2882      int iSid;
2883      const char *zExplain;
2884      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2885        break;
2886      }
2887      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2888      if( iSid>mx ) mx = iSid;
2889      if( iSid!=k ) continue;
2890      if( n==0 ){
2891        rEstLoop = (double)nLoop;
2892        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2893      }
2894      n++;
2895      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2896      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2897      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2898      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2899      rEstLoop *= rEst;
2900      raw_printf(pArg->out,
2901          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2902          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2903      );
2904    }
2905  }
2906  raw_printf(pArg->out, "---------------------------\n");
2907#endif
2908}
2909
2910/*
2911** Parameter azArray points to a zero-terminated array of strings. zStr
2912** points to a single nul-terminated string. Return non-zero if zStr
2913** is equal, according to strcmp(), to any of the strings in the array.
2914** Otherwise, return zero.
2915*/
2916static int str_in_array(const char *zStr, const char **azArray){
2917  int i;
2918  for(i=0; azArray[i]; i++){
2919    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2920  }
2921  return 0;
2922}
2923
2924/*
2925** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2926** and populate the ShellState.aiIndent[] array with the number of
2927** spaces each opcode should be indented before it is output.
2928**
2929** The indenting rules are:
2930**
2931**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2932**       all opcodes that occur between the p2 jump destination and the opcode
2933**       itself by 2 spaces.
2934**
2935**     * For each "Goto", if the jump destination is earlier in the program
2936**       and ends on one of:
2937**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2938**       or if the P1 parameter is one instead of zero,
2939**       then indent all opcodes between the earlier instruction
2940**       and "Goto" by 2 spaces.
2941*/
2942static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2943  const char *zSql;               /* The text of the SQL statement */
2944  const char *z;                  /* Used to check if this is an EXPLAIN */
2945  int *abYield = 0;               /* True if op is an OP_Yield */
2946  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2947  int iOp;                        /* Index of operation in p->aiIndent[] */
2948
2949  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2950  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2951                            "Rewind", 0 };
2952  const char *azGoto[] = { "Goto", 0 };
2953
2954  /* Try to figure out if this is really an EXPLAIN statement. If this
2955  ** cannot be verified, return early.  */
2956  if( sqlite3_column_count(pSql)!=8 ){
2957    p->cMode = p->mode;
2958    return;
2959  }
2960  zSql = sqlite3_sql(pSql);
2961  if( zSql==0 ) return;
2962  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2963  if( sqlite3_strnicmp(z, "explain", 7) ){
2964    p->cMode = p->mode;
2965    return;
2966  }
2967
2968  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2969    int i;
2970    int iAddr = sqlite3_column_int(pSql, 0);
2971    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2972
2973    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2974    ** p2 is an instruction address, set variable p2op to the index of that
2975    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2976    ** the current instruction is part of a sub-program generated by an
2977    ** SQL trigger or foreign key.  */
2978    int p2 = sqlite3_column_int(pSql, 3);
2979    int p2op = (p2 + (iOp-iAddr));
2980
2981    /* Grow the p->aiIndent array as required */
2982    if( iOp>=nAlloc ){
2983      if( iOp==0 ){
2984        /* Do further verfication that this is explain output.  Abort if
2985        ** it is not */
2986        static const char *explainCols[] = {
2987           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2988        int jj;
2989        for(jj=0; jj<ArraySize(explainCols); jj++){
2990          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2991            p->cMode = p->mode;
2992            sqlite3_reset(pSql);
2993            return;
2994          }
2995        }
2996      }
2997      nAlloc += 100;
2998      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2999      shell_check_oom(p->aiIndent);
3000      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3001      shell_check_oom(abYield);
3002    }
3003    abYield[iOp] = str_in_array(zOp, azYield);
3004    p->aiIndent[iOp] = 0;
3005    p->nIndent = iOp+1;
3006
3007    if( str_in_array(zOp, azNext) ){
3008      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3009    }
3010    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3011     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3012    ){
3013      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3014    }
3015  }
3016
3017  p->iIndent = 0;
3018  sqlite3_free(abYield);
3019  sqlite3_reset(pSql);
3020}
3021
3022/*
3023** Free the array allocated by explain_data_prepare().
3024*/
3025static void explain_data_delete(ShellState *p){
3026  sqlite3_free(p->aiIndent);
3027  p->aiIndent = 0;
3028  p->nIndent = 0;
3029  p->iIndent = 0;
3030}
3031
3032/*
3033** Disable and restore .wheretrace and .selecttrace settings.
3034*/
3035static unsigned int savedSelectTrace;
3036static unsigned int savedWhereTrace;
3037static void disable_debug_trace_modes(void){
3038  unsigned int zero = 0;
3039  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3040  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3041  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3042  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3043}
3044static void restore_debug_trace_modes(void){
3045  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3046  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3047}
3048
3049/* Create the TEMP table used to store parameter bindings */
3050static void bind_table_init(ShellState *p){
3051  int wrSchema = 0;
3052  int defensiveMode = 0;
3053  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3054  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3055  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3056  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3057  sqlite3_exec(p->db,
3058    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3059    "  key TEXT PRIMARY KEY,\n"
3060    "  value\n"
3061    ") WITHOUT ROWID;",
3062    0, 0, 0);
3063  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3064  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3065}
3066
3067/*
3068** Bind parameters on a prepared statement.
3069**
3070** Parameter bindings are taken from a TEMP table of the form:
3071**
3072**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3073**    WITHOUT ROWID;
3074**
3075** No bindings occur if this table does not exist.  The name of the table
3076** begins with "sqlite_" so that it will not collide with ordinary application
3077** tables.  The table must be in the TEMP schema.
3078*/
3079static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3080  int nVar;
3081  int i;
3082  int rc;
3083  sqlite3_stmt *pQ = 0;
3084
3085  nVar = sqlite3_bind_parameter_count(pStmt);
3086  if( nVar==0 ) return;  /* Nothing to do */
3087  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3088                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3089    return; /* Parameter table does not exist */
3090  }
3091  rc = sqlite3_prepare_v2(pArg->db,
3092          "SELECT value FROM temp.sqlite_parameters"
3093          " WHERE key=?1", -1, &pQ, 0);
3094  if( rc || pQ==0 ) return;
3095  for(i=1; i<=nVar; i++){
3096    char zNum[30];
3097    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3098    if( zVar==0 ){
3099      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3100      zVar = zNum;
3101    }
3102    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3103    if( sqlite3_step(pQ)==SQLITE_ROW ){
3104      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3105    }else{
3106      sqlite3_bind_null(pStmt, i);
3107    }
3108    sqlite3_reset(pQ);
3109  }
3110  sqlite3_finalize(pQ);
3111}
3112
3113/*
3114** UTF8 box-drawing characters.  Imagine box lines like this:
3115**
3116**           1
3117**           |
3118**       4 --+-- 2
3119**           |
3120**           3
3121**
3122** Each box characters has between 2 and 4 of the lines leading from
3123** the center.  The characters are here identified by the numbers of
3124** their corresponding lines.
3125*/
3126#define BOX_24   "\342\224\200"  /* U+2500 --- */
3127#define BOX_13   "\342\224\202"  /* U+2502  |  */
3128#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3129#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3130#define BOX_12   "\342\224\224"  /* U+2514  '- */
3131#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3132#define BOX_123  "\342\224\234"  /* U+251c  |- */
3133#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3134#define BOX_234  "\342\224\254"  /* U+252c -,- */
3135#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3136#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3137
3138/* Draw horizontal line N characters long using unicode box
3139** characters
3140*/
3141static void print_box_line(FILE *out, int N){
3142  const char zDash[] =
3143      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3144      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3145  const int nDash = sizeof(zDash) - 1;
3146  N *= 3;
3147  while( N>nDash ){
3148    utf8_printf(out, zDash);
3149    N -= nDash;
3150  }
3151  utf8_printf(out, "%.*s", N, zDash);
3152}
3153
3154/*
3155** Draw a horizontal separator for a MODE_Box table.
3156*/
3157static void print_box_row_separator(
3158  ShellState *p,
3159  int nArg,
3160  const char *zSep1,
3161  const char *zSep2,
3162  const char *zSep3
3163){
3164  int i;
3165  if( nArg>0 ){
3166    utf8_printf(p->out, "%s", zSep1);
3167    print_box_line(p->out, p->actualWidth[0]+2);
3168    for(i=1; i<nArg; i++){
3169      utf8_printf(p->out, "%s", zSep2);
3170      print_box_line(p->out, p->actualWidth[i]+2);
3171    }
3172    utf8_printf(p->out, "%s", zSep3);
3173  }
3174  fputs("\n", p->out);
3175}
3176
3177/*
3178** z[] is a line of text that is to be displayed the .mode box or table or
3179** similar tabular formats.  z[] might contain control characters such
3180** as \n, \t, \f, or \r.
3181**
3182** Compute characters to display on the first line of z[].  Stop at the
3183** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3184** from malloc()) of that first line, which caller should free sometime.
3185** Write anything to display on the next line into *pzTail.  If this is
3186** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3187*/
3188static char *translateForDisplayAndDup(
3189  const unsigned char *z,            /* Input text to be transformed */
3190  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3191  int mxWidth,                       /* Max width.  0 means no limit */
3192  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3193){
3194  int i;                 /* Input bytes consumed */
3195  int j;                 /* Output bytes generated */
3196  int k;                 /* Input bytes to be displayed */
3197  int n;                 /* Output column number */
3198  unsigned char *zOut;   /* Output text */
3199
3200  if( z==0 ){
3201    *pzTail = 0;
3202    return 0;
3203  }
3204  if( mxWidth<0 ) mxWidth = -mxWidth;
3205  if( mxWidth==0 ) mxWidth = 1000000;
3206  i = j = n = 0;
3207  while( n<mxWidth ){
3208    if( z[i]>=' ' ){
3209      n++;
3210      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3211      continue;
3212    }
3213    if( z[i]=='\t' ){
3214      do{
3215        n++;
3216        j++;
3217      }while( (n&7)!=0 && n<mxWidth );
3218      i++;
3219      continue;
3220    }
3221    break;
3222  }
3223  if( n>=mxWidth && bWordWrap  ){
3224    /* Perhaps try to back up to a better place to break the line */
3225    for(k=i; k>i/2; k--){
3226      if( isspace(z[k-1]) ) break;
3227    }
3228    if( k<=i/2 ){
3229      for(k=i; k>i/2; k--){
3230        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3231      }
3232    }
3233    if( k<=i/2 ){
3234      k = i;
3235    }else{
3236      i = k;
3237      while( z[i]==' ' ) i++;
3238    }
3239  }else{
3240    k = i;
3241  }
3242  if( n>=mxWidth && z[i]>=' ' ){
3243   *pzTail = &z[i];
3244  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3245    *pzTail = z[i+2] ? &z[i+2] : 0;
3246  }else if( z[i]==0 || z[i+1]==0 ){
3247    *pzTail = 0;
3248  }else{
3249    *pzTail = &z[i+1];
3250  }
3251  zOut = malloc( j+1 );
3252  shell_check_oom(zOut);
3253  i = j = n = 0;
3254  while( i<k ){
3255    if( z[i]>=' ' ){
3256      n++;
3257      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3258      continue;
3259    }
3260    if( z[i]=='\t' ){
3261      do{
3262        n++;
3263        zOut[j++] = ' ';
3264      }while( (n&7)!=0 && n<mxWidth );
3265      i++;
3266      continue;
3267    }
3268    break;
3269  }
3270  zOut[j] = 0;
3271  return (char*)zOut;
3272}
3273
3274/* Extract the value of the i-th current column for pStmt as an SQL literal
3275** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3276** the caller.
3277*/
3278static char *quoted_column(sqlite3_stmt *pStmt, int i){
3279  switch( sqlite3_column_type(pStmt, i) ){
3280    case SQLITE_NULL: {
3281      return sqlite3_mprintf("NULL");
3282    }
3283    case SQLITE_INTEGER:
3284    case SQLITE_FLOAT: {
3285      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3286    }
3287    case SQLITE_TEXT: {
3288      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3289    }
3290    case SQLITE_BLOB: {
3291      int j;
3292      sqlite3_str *pStr = sqlite3_str_new(0);
3293      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3294      int n = sqlite3_column_bytes(pStmt,i);
3295      sqlite3_str_append(pStr, "x'", 2);
3296      for(j=0; j<n; j++){
3297        sqlite3_str_appendf(pStr, "%02x", a[j]);
3298      }
3299      sqlite3_str_append(pStr, "'", 1);
3300      return sqlite3_str_finish(pStr);
3301    }
3302  }
3303  return 0; /* Not reached */
3304}
3305
3306/*
3307** Run a prepared statement and output the result in one of the
3308** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3309** or MODE_Box.
3310**
3311** This is different from ordinary exec_prepared_stmt() in that
3312** it has to run the entire query and gather the results into memory
3313** first, in order to determine column widths, before providing
3314** any output.
3315*/
3316static void exec_prepared_stmt_columnar(
3317  ShellState *p,                        /* Pointer to ShellState */
3318  sqlite3_stmt *pStmt                   /* Statment to run */
3319){
3320  sqlite3_int64 nRow = 0;
3321  int nColumn = 0;
3322  char **azData = 0;
3323  sqlite3_int64 nAlloc = 0;
3324  char *abRowDiv = 0;
3325  const unsigned char *uz;
3326  const char *z;
3327  char **azQuoted = 0;
3328  int rc;
3329  sqlite3_int64 i, nData;
3330  int j, nTotal, w, n;
3331  const char *colSep = 0;
3332  const char *rowSep = 0;
3333  const unsigned char **azNextLine = 0;
3334  int bNextLine = 0;
3335  int bMultiLineRowExists = 0;
3336  int bw = p->cmOpts.bWordWrap;
3337
3338  rc = sqlite3_step(pStmt);
3339  if( rc!=SQLITE_ROW ) return;
3340  nColumn = sqlite3_column_count(pStmt);
3341  nAlloc = nColumn*4;
3342  if( nAlloc<=0 ) nAlloc = 1;
3343  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3344  shell_check_oom(azData);
3345  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3346  shell_check_oom((void*)azNextLine);
3347  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3348  if( p->cmOpts.bQuote ){
3349    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3350    shell_check_oom(azQuoted);
3351    memset(azQuoted, 0, nColumn*sizeof(char*) );
3352  }
3353  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3354  shell_check_oom(abRowDiv);
3355  if( nColumn>p->nWidth ){
3356    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3357    shell_check_oom(p->colWidth);
3358    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3359    p->nWidth = nColumn;
3360    p->actualWidth = &p->colWidth[nColumn];
3361  }
3362  memset(p->actualWidth, 0, nColumn*sizeof(int));
3363  for(i=0; i<nColumn; i++){
3364    w = p->colWidth[i];
3365    if( w<0 ) w = -w;
3366    p->actualWidth[i] = w;
3367  }
3368  for(i=0; i<nColumn; i++){
3369    const unsigned char *zNotUsed;
3370    int wx = p->colWidth[i];
3371    if( wx==0 ){
3372      wx = p->cmOpts.iWrap;
3373    }
3374    if( wx<0 ) wx = -wx;
3375    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3376    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3377  }
3378  do{
3379    int useNextLine = bNextLine;
3380    bNextLine = 0;
3381    if( (nRow+2)*nColumn >= nAlloc ){
3382      nAlloc *= 2;
3383      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3384      shell_check_oom(azData);
3385      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3386      shell_check_oom(abRowDiv);
3387    }
3388    abRowDiv[nRow] = 1;
3389    nRow++;
3390    for(i=0; i<nColumn; i++){
3391      int wx = p->colWidth[i];
3392      if( wx==0 ){
3393        wx = p->cmOpts.iWrap;
3394      }
3395      if( wx<0 ) wx = -wx;
3396      if( useNextLine ){
3397        uz = azNextLine[i];
3398      }else if( p->cmOpts.bQuote ){
3399        sqlite3_free(azQuoted[i]);
3400        azQuoted[i] = quoted_column(pStmt,i);
3401        uz = (const unsigned char*)azQuoted[i];
3402      }else{
3403        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3404      }
3405      azData[nRow*nColumn + i]
3406        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3407      if( azNextLine[i] ){
3408        bNextLine = 1;
3409        abRowDiv[nRow-1] = 0;
3410        bMultiLineRowExists = 1;
3411      }
3412    }
3413  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3414  nTotal = nColumn*(nRow+1);
3415  for(i=0; i<nTotal; i++){
3416    z = azData[i];
3417    if( z==0 ) z = p->nullValue;
3418    n = strlenChar(z);
3419    j = i%nColumn;
3420    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3421  }
3422  if( seenInterrupt ) goto columnar_end;
3423  if( nColumn==0 ) goto columnar_end;
3424  switch( p->cMode ){
3425    case MODE_Column: {
3426      colSep = "  ";
3427      rowSep = "\n";
3428      if( p->showHeader ){
3429        for(i=0; i<nColumn; i++){
3430          w = p->actualWidth[i];
3431          if( p->colWidth[i]<0 ) w = -w;
3432          utf8_width_print(p->out, w, azData[i]);
3433          fputs(i==nColumn-1?"\n":"  ", p->out);
3434        }
3435        for(i=0; i<nColumn; i++){
3436          print_dashes(p->out, p->actualWidth[i]);
3437          fputs(i==nColumn-1?"\n":"  ", p->out);
3438        }
3439      }
3440      break;
3441    }
3442    case MODE_Table: {
3443      colSep = " | ";
3444      rowSep = " |\n";
3445      print_row_separator(p, nColumn, "+");
3446      fputs("| ", p->out);
3447      for(i=0; i<nColumn; i++){
3448        w = p->actualWidth[i];
3449        n = strlenChar(azData[i]);
3450        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3451        fputs(i==nColumn-1?" |\n":" | ", p->out);
3452      }
3453      print_row_separator(p, nColumn, "+");
3454      break;
3455    }
3456    case MODE_Markdown: {
3457      colSep = " | ";
3458      rowSep = " |\n";
3459      fputs("| ", p->out);
3460      for(i=0; i<nColumn; i++){
3461        w = p->actualWidth[i];
3462        n = strlenChar(azData[i]);
3463        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3464        fputs(i==nColumn-1?" |\n":" | ", p->out);
3465      }
3466      print_row_separator(p, nColumn, "|");
3467      break;
3468    }
3469    case MODE_Box: {
3470      colSep = " " BOX_13 " ";
3471      rowSep = " " BOX_13 "\n";
3472      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3473      utf8_printf(p->out, BOX_13 " ");
3474      for(i=0; i<nColumn; i++){
3475        w = p->actualWidth[i];
3476        n = strlenChar(azData[i]);
3477        utf8_printf(p->out, "%*s%s%*s%s",
3478            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3479            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3480      }
3481      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3482      break;
3483    }
3484  }
3485  for(i=nColumn, j=0; i<nTotal; i++, j++){
3486    if( j==0 && p->cMode!=MODE_Column ){
3487      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3488    }
3489    z = azData[i];
3490    if( z==0 ) z = p->nullValue;
3491    w = p->actualWidth[j];
3492    if( p->colWidth[j]<0 ) w = -w;
3493    utf8_width_print(p->out, w, z);
3494    if( j==nColumn-1 ){
3495      utf8_printf(p->out, "%s", rowSep);
3496      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3497        if( p->cMode==MODE_Table ){
3498          print_row_separator(p, nColumn, "+");
3499        }else if( p->cMode==MODE_Box ){
3500          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3501        }else if( p->cMode==MODE_Column ){
3502          raw_printf(p->out, "\n");
3503        }
3504      }
3505      j = -1;
3506      if( seenInterrupt ) goto columnar_end;
3507    }else{
3508      utf8_printf(p->out, "%s", colSep);
3509    }
3510  }
3511  if( p->cMode==MODE_Table ){
3512    print_row_separator(p, nColumn, "+");
3513  }else if( p->cMode==MODE_Box ){
3514    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3515  }
3516columnar_end:
3517  if( seenInterrupt ){
3518    utf8_printf(p->out, "Interrupt\n");
3519  }
3520  nData = (nRow+1)*nColumn;
3521  for(i=0; i<nData; i++) free(azData[i]);
3522  sqlite3_free(azData);
3523  sqlite3_free((void*)azNextLine);
3524  sqlite3_free(abRowDiv);
3525  if( azQuoted ){
3526    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3527    sqlite3_free(azQuoted);
3528  }
3529}
3530
3531/*
3532** Run a prepared statement
3533*/
3534static void exec_prepared_stmt(
3535  ShellState *pArg,                                /* Pointer to ShellState */
3536  sqlite3_stmt *pStmt                              /* Statment to run */
3537){
3538  int rc;
3539  sqlite3_uint64 nRow = 0;
3540
3541  if( pArg->cMode==MODE_Column
3542   || pArg->cMode==MODE_Table
3543   || pArg->cMode==MODE_Box
3544   || pArg->cMode==MODE_Markdown
3545  ){
3546    exec_prepared_stmt_columnar(pArg, pStmt);
3547    return;
3548  }
3549
3550  /* perform the first step.  this will tell us if we
3551  ** have a result set or not and how wide it is.
3552  */
3553  rc = sqlite3_step(pStmt);
3554  /* if we have a result set... */
3555  if( SQLITE_ROW == rc ){
3556    /* allocate space for col name ptr, value ptr, and type */
3557    int nCol = sqlite3_column_count(pStmt);
3558    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3559    if( !pData ){
3560      shell_out_of_memory();
3561    }else{
3562      char **azCols = (char **)pData;      /* Names of result columns */
3563      char **azVals = &azCols[nCol];       /* Results */
3564      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3565      int i, x;
3566      assert(sizeof(int) <= sizeof(char *));
3567      /* save off ptrs to column names */
3568      for(i=0; i<nCol; i++){
3569        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3570      }
3571      do{
3572        nRow++;
3573        /* extract the data and data types */
3574        for(i=0; i<nCol; i++){
3575          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3576          if( x==SQLITE_BLOB
3577           && pArg
3578           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3579          ){
3580            azVals[i] = "";
3581          }else{
3582            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3583          }
3584          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3585            rc = SQLITE_NOMEM;
3586            break; /* from for */
3587          }
3588        } /* end for */
3589
3590        /* if data and types extracted successfully... */
3591        if( SQLITE_ROW == rc ){
3592          /* call the supplied callback with the result row data */
3593          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3594            rc = SQLITE_ABORT;
3595          }else{
3596            rc = sqlite3_step(pStmt);
3597          }
3598        }
3599      } while( SQLITE_ROW == rc );
3600      sqlite3_free(pData);
3601      if( pArg->cMode==MODE_Json ){
3602        fputs("]\n", pArg->out);
3603      }else if( pArg->cMode==MODE_Count ){
3604        char zBuf[200];
3605        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3606                         nRow, nRow!=1 ? "s" : "");
3607        printf("%s", zBuf);
3608      }
3609    }
3610  }
3611}
3612
3613#ifndef SQLITE_OMIT_VIRTUALTABLE
3614/*
3615** This function is called to process SQL if the previous shell command
3616** was ".expert". It passes the SQL in the second argument directly to
3617** the sqlite3expert object.
3618**
3619** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3620** code. In this case, (*pzErr) may be set to point to a buffer containing
3621** an English language error message. It is the responsibility of the
3622** caller to eventually free this buffer using sqlite3_free().
3623*/
3624static int expertHandleSQL(
3625  ShellState *pState,
3626  const char *zSql,
3627  char **pzErr
3628){
3629  assert( pState->expert.pExpert );
3630  assert( pzErr==0 || *pzErr==0 );
3631  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3632}
3633
3634/*
3635** This function is called either to silently clean up the object
3636** created by the ".expert" command (if bCancel==1), or to generate a
3637** report from it and then clean it up (if bCancel==0).
3638**
3639** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3640** code. In this case, (*pzErr) may be set to point to a buffer containing
3641** an English language error message. It is the responsibility of the
3642** caller to eventually free this buffer using sqlite3_free().
3643*/
3644static int expertFinish(
3645  ShellState *pState,
3646  int bCancel,
3647  char **pzErr
3648){
3649  int rc = SQLITE_OK;
3650  sqlite3expert *p = pState->expert.pExpert;
3651  assert( p );
3652  assert( bCancel || pzErr==0 || *pzErr==0 );
3653  if( bCancel==0 ){
3654    FILE *out = pState->out;
3655    int bVerbose = pState->expert.bVerbose;
3656
3657    rc = sqlite3_expert_analyze(p, pzErr);
3658    if( rc==SQLITE_OK ){
3659      int nQuery = sqlite3_expert_count(p);
3660      int i;
3661
3662      if( bVerbose ){
3663        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3664        raw_printf(out, "-- Candidates -----------------------------\n");
3665        raw_printf(out, "%s\n", zCand);
3666      }
3667      for(i=0; i<nQuery; i++){
3668        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3669        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3670        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3671        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3672        if( bVerbose ){
3673          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3674          raw_printf(out, "%s\n\n", zSql);
3675        }
3676        raw_printf(out, "%s\n", zIdx);
3677        raw_printf(out, "%s\n", zEQP);
3678      }
3679    }
3680  }
3681  sqlite3_expert_destroy(p);
3682  pState->expert.pExpert = 0;
3683  return rc;
3684}
3685
3686/*
3687** Implementation of ".expert" dot command.
3688*/
3689static int expertDotCommand(
3690  ShellState *pState,             /* Current shell tool state */
3691  char **azArg,                   /* Array of arguments passed to dot command */
3692  int nArg                        /* Number of entries in azArg[] */
3693){
3694  int rc = SQLITE_OK;
3695  char *zErr = 0;
3696  int i;
3697  int iSample = 0;
3698
3699  assert( pState->expert.pExpert==0 );
3700  memset(&pState->expert, 0, sizeof(ExpertInfo));
3701
3702  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3703    char *z = azArg[i];
3704    int n;
3705    if( z[0]=='-' && z[1]=='-' ) z++;
3706    n = strlen30(z);
3707    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3708      pState->expert.bVerbose = 1;
3709    }
3710    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3711      if( i==(nArg-1) ){
3712        raw_printf(stderr, "option requires an argument: %s\n", z);
3713        rc = SQLITE_ERROR;
3714      }else{
3715        iSample = (int)integerValue(azArg[++i]);
3716        if( iSample<0 || iSample>100 ){
3717          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3718          rc = SQLITE_ERROR;
3719        }
3720      }
3721    }
3722    else{
3723      raw_printf(stderr, "unknown option: %s\n", z);
3724      rc = SQLITE_ERROR;
3725    }
3726  }
3727
3728  if( rc==SQLITE_OK ){
3729    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3730    if( pState->expert.pExpert==0 ){
3731      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3732      rc = SQLITE_ERROR;
3733    }else{
3734      sqlite3_expert_config(
3735          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3736      );
3737    }
3738  }
3739  sqlite3_free(zErr);
3740
3741  return rc;
3742}
3743#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3744
3745/*
3746** Execute a statement or set of statements.  Print
3747** any result rows/columns depending on the current mode
3748** set via the supplied callback.
3749**
3750** This is very similar to SQLite's built-in sqlite3_exec()
3751** function except it takes a slightly different callback
3752** and callback data argument.
3753*/
3754static int shell_exec(
3755  ShellState *pArg,                         /* Pointer to ShellState */
3756  const char *zSql,                         /* SQL to be evaluated */
3757  char **pzErrMsg                           /* Error msg written here */
3758){
3759  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3760  int rc = SQLITE_OK;             /* Return Code */
3761  int rc2;
3762  const char *zLeftover;          /* Tail of unprocessed SQL */
3763  sqlite3 *db = pArg->db;
3764
3765  if( pzErrMsg ){
3766    *pzErrMsg = NULL;
3767  }
3768
3769#ifndef SQLITE_OMIT_VIRTUALTABLE
3770  if( pArg->expert.pExpert ){
3771    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3772    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3773  }
3774#endif
3775
3776  while( zSql[0] && (SQLITE_OK == rc) ){
3777    static const char *zStmtSql;
3778    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3779    if( SQLITE_OK != rc ){
3780      if( pzErrMsg ){
3781        *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)%s", rc, zSql);
3782      }
3783    }else{
3784      if( !pStmt ){
3785        /* this happens for a comment or white-space */
3786        zSql = zLeftover;
3787        while( IsSpace(zSql[0]) ) zSql++;
3788        continue;
3789      }
3790      zStmtSql = sqlite3_sql(pStmt);
3791      if( zStmtSql==0 ) zStmtSql = "";
3792      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3793
3794      /* save off the prepared statment handle and reset row count */
3795      if( pArg ){
3796        pArg->pStmt = pStmt;
3797        pArg->cnt = 0;
3798      }
3799
3800      /* echo the sql statement if echo on */
3801      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3802        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3803      }
3804
3805      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3806      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3807        sqlite3_stmt *pExplain;
3808        char *zEQP;
3809        int triggerEQP = 0;
3810        disable_debug_trace_modes();
3811        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3812        if( pArg->autoEQP>=AUTOEQP_trigger ){
3813          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3814        }
3815        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3816        shell_check_oom(zEQP);
3817        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3818        if( rc==SQLITE_OK ){
3819          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3820            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3821            int iEqpId = sqlite3_column_int(pExplain, 0);
3822            int iParentId = sqlite3_column_int(pExplain, 1);
3823            if( zEQPLine==0 ) zEQPLine = "";
3824            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3825            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3826          }
3827          eqp_render(pArg);
3828        }
3829        sqlite3_finalize(pExplain);
3830        sqlite3_free(zEQP);
3831        if( pArg->autoEQP>=AUTOEQP_full ){
3832          /* Also do an EXPLAIN for ".eqp full" mode */
3833          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3834          shell_check_oom(zEQP);
3835          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3836          if( rc==SQLITE_OK ){
3837            pArg->cMode = MODE_Explain;
3838            explain_data_prepare(pArg, pExplain);
3839            exec_prepared_stmt(pArg, pExplain);
3840            explain_data_delete(pArg);
3841          }
3842          sqlite3_finalize(pExplain);
3843          sqlite3_free(zEQP);
3844        }
3845        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3846          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3847          /* Reprepare pStmt before reactiving trace modes */
3848          sqlite3_finalize(pStmt);
3849          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3850          if( pArg ) pArg->pStmt = pStmt;
3851        }
3852        restore_debug_trace_modes();
3853      }
3854
3855      if( pArg ){
3856        pArg->cMode = pArg->mode;
3857        if( pArg->autoExplain ){
3858          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3859            pArg->cMode = MODE_Explain;
3860          }
3861          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3862            pArg->cMode = MODE_EQP;
3863          }
3864        }
3865
3866        /* If the shell is currently in ".explain" mode, gather the extra
3867        ** data required to add indents to the output.*/
3868        if( pArg->cMode==MODE_Explain ){
3869          explain_data_prepare(pArg, pStmt);
3870        }
3871      }
3872
3873      bind_prepared_stmt(pArg, pStmt);
3874      exec_prepared_stmt(pArg, pStmt);
3875      explain_data_delete(pArg);
3876      eqp_render(pArg);
3877
3878      /* print usage stats if stats on */
3879      if( pArg && pArg->statsOn ){
3880        display_stats(db, pArg, 0);
3881      }
3882
3883      /* print loop-counters if required */
3884      if( pArg && pArg->scanstatsOn ){
3885        display_scanstats(db, pArg);
3886      }
3887
3888      /* Finalize the statement just executed. If this fails, save a
3889      ** copy of the error message. Otherwise, set zSql to point to the
3890      ** next statement to execute. */
3891      rc2 = sqlite3_finalize(pStmt);
3892      if( rc!=SQLITE_NOMEM ) rc = rc2;
3893      if( rc==SQLITE_OK ){
3894        zSql = zLeftover;
3895        while( IsSpace(zSql[0]) ) zSql++;
3896      }else if( pzErrMsg ){
3897        *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc, 0);
3898      }
3899
3900      /* clear saved stmt handle */
3901      if( pArg ){
3902        pArg->pStmt = NULL;
3903      }
3904    }
3905  } /* end while */
3906
3907  return rc;
3908}
3909
3910/*
3911** Release memory previously allocated by tableColumnList().
3912*/
3913static void freeColumnList(char **azCol){
3914  int i;
3915  for(i=1; azCol[i]; i++){
3916    sqlite3_free(azCol[i]);
3917  }
3918  /* azCol[0] is a static string */
3919  sqlite3_free(azCol);
3920}
3921
3922/*
3923** Return a list of pointers to strings which are the names of all
3924** columns in table zTab.   The memory to hold the names is dynamically
3925** allocated and must be released by the caller using a subsequent call
3926** to freeColumnList().
3927**
3928** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3929** value that needs to be preserved, then azCol[0] is filled in with the
3930** name of the rowid column.
3931**
3932** The first regular column in the table is azCol[1].  The list is terminated
3933** by an entry with azCol[i]==0.
3934*/
3935static char **tableColumnList(ShellState *p, const char *zTab){
3936  char **azCol = 0;
3937  sqlite3_stmt *pStmt;
3938  char *zSql;
3939  int nCol = 0;
3940  int nAlloc = 0;
3941  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3942  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3943  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3944  int rc;
3945
3946  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3947  shell_check_oom(zSql);
3948  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3949  sqlite3_free(zSql);
3950  if( rc ) return 0;
3951  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3952    if( nCol>=nAlloc-2 ){
3953      nAlloc = nAlloc*2 + nCol + 10;
3954      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3955      shell_check_oom(azCol);
3956    }
3957    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3958    shell_check_oom(azCol[nCol]);
3959    if( sqlite3_column_int(pStmt, 5) ){
3960      nPK++;
3961      if( nPK==1
3962       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3963                          "INTEGER")==0
3964      ){
3965        isIPK = 1;
3966      }else{
3967        isIPK = 0;
3968      }
3969    }
3970  }
3971  sqlite3_finalize(pStmt);
3972  if( azCol==0 ) return 0;
3973  azCol[0] = 0;
3974  azCol[nCol+1] = 0;
3975
3976  /* The decision of whether or not a rowid really needs to be preserved
3977  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3978  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3979  ** rowids on tables where the rowid is inaccessible because there are other
3980  ** columns in the table named "rowid", "_rowid_", and "oid".
3981  */
3982  if( preserveRowid && isIPK ){
3983    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3984    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3985    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3986    ** ROWID aliases.  To distinguish these cases, check to see if
3987    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3988    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3989    */
3990    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3991                           " WHERE origin='pk'", zTab);
3992    shell_check_oom(zSql);
3993    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3994    sqlite3_free(zSql);
3995    if( rc ){
3996      freeColumnList(azCol);
3997      return 0;
3998    }
3999    rc = sqlite3_step(pStmt);
4000    sqlite3_finalize(pStmt);
4001    preserveRowid = rc==SQLITE_ROW;
4002  }
4003  if( preserveRowid ){
4004    /* Only preserve the rowid if we can find a name to use for the
4005    ** rowid */
4006    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4007    int i, j;
4008    for(j=0; j<3; j++){
4009      for(i=1; i<=nCol; i++){
4010        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4011      }
4012      if( i>nCol ){
4013        /* At this point, we know that azRowid[j] is not the name of any
4014        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4015        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4016        ** tables will fail this last check */
4017        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4018        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4019        break;
4020      }
4021    }
4022  }
4023  return azCol;
4024}
4025
4026/*
4027** Toggle the reverse_unordered_selects setting.
4028*/
4029static void toggleSelectOrder(sqlite3 *db){
4030  sqlite3_stmt *pStmt = 0;
4031  int iSetting = 0;
4032  char zStmt[100];
4033  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4034  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4035    iSetting = sqlite3_column_int(pStmt, 0);
4036  }
4037  sqlite3_finalize(pStmt);
4038  sqlite3_snprintf(sizeof(zStmt), zStmt,
4039       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4040  sqlite3_exec(db, zStmt, 0, 0, 0);
4041}
4042
4043/*
4044** This is a different callback routine used for dumping the database.
4045** Each row received by this callback consists of a table name,
4046** the table type ("index" or "table") and SQL to create the table.
4047** This routine should print text sufficient to recreate the table.
4048*/
4049static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4050  int rc;
4051  const char *zTable;
4052  const char *zType;
4053  const char *zSql;
4054  ShellState *p = (ShellState *)pArg;
4055  int dataOnly;
4056  int noSys;
4057
4058  UNUSED_PARAMETER(azNotUsed);
4059  if( nArg!=3 || azArg==0 ) return 0;
4060  zTable = azArg[0];
4061  zType = azArg[1];
4062  zSql = azArg[2];
4063  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4064  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4065
4066  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4067    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4068  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4069    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4070  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4071    return 0;
4072  }else if( dataOnly ){
4073    /* no-op */
4074  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4075    char *zIns;
4076    if( !p->writableSchema ){
4077      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4078      p->writableSchema = 1;
4079    }
4080    zIns = sqlite3_mprintf(
4081       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4082       "VALUES('table','%q','%q',0,'%q');",
4083       zTable, zTable, zSql);
4084    shell_check_oom(zIns);
4085    utf8_printf(p->out, "%s\n", zIns);
4086    sqlite3_free(zIns);
4087    return 0;
4088  }else{
4089    printSchemaLine(p->out, zSql, ";\n");
4090  }
4091
4092  if( strcmp(zType, "table")==0 ){
4093    ShellText sSelect;
4094    ShellText sTable;
4095    char **azCol;
4096    int i;
4097    char *savedDestTable;
4098    int savedMode;
4099
4100    azCol = tableColumnList(p, zTable);
4101    if( azCol==0 ){
4102      p->nErr++;
4103      return 0;
4104    }
4105
4106    /* Always quote the table name, even if it appears to be pure ascii,
4107    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4108    initText(&sTable);
4109    appendText(&sTable, zTable, quoteChar(zTable));
4110    /* If preserving the rowid, add a column list after the table name.
4111    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4112    ** instead of the usual "INSERT INTO tab VALUES(...)".
4113    */
4114    if( azCol[0] ){
4115      appendText(&sTable, "(", 0);
4116      appendText(&sTable, azCol[0], 0);
4117      for(i=1; azCol[i]; i++){
4118        appendText(&sTable, ",", 0);
4119        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4120      }
4121      appendText(&sTable, ")", 0);
4122    }
4123
4124    /* Build an appropriate SELECT statement */
4125    initText(&sSelect);
4126    appendText(&sSelect, "SELECT ", 0);
4127    if( azCol[0] ){
4128      appendText(&sSelect, azCol[0], 0);
4129      appendText(&sSelect, ",", 0);
4130    }
4131    for(i=1; azCol[i]; i++){
4132      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4133      if( azCol[i+1] ){
4134        appendText(&sSelect, ",", 0);
4135      }
4136    }
4137    freeColumnList(azCol);
4138    appendText(&sSelect, " FROM ", 0);
4139    appendText(&sSelect, zTable, quoteChar(zTable));
4140
4141    savedDestTable = p->zDestTable;
4142    savedMode = p->mode;
4143    p->zDestTable = sTable.z;
4144    p->mode = p->cMode = MODE_Insert;
4145    rc = shell_exec(p, sSelect.z, 0);
4146    if( (rc&0xff)==SQLITE_CORRUPT ){
4147      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4148      toggleSelectOrder(p->db);
4149      shell_exec(p, sSelect.z, 0);
4150      toggleSelectOrder(p->db);
4151    }
4152    p->zDestTable = savedDestTable;
4153    p->mode = savedMode;
4154    freeText(&sTable);
4155    freeText(&sSelect);
4156    if( rc ) p->nErr++;
4157  }
4158  return 0;
4159}
4160
4161/*
4162** Run zQuery.  Use dump_callback() as the callback routine so that
4163** the contents of the query are output as SQL statements.
4164**
4165** If we get a SQLITE_CORRUPT error, rerun the query after appending
4166** "ORDER BY rowid DESC" to the end.
4167*/
4168static int run_schema_dump_query(
4169  ShellState *p,
4170  const char *zQuery
4171){
4172  int rc;
4173  char *zErr = 0;
4174  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4175  if( rc==SQLITE_CORRUPT ){
4176    char *zQ2;
4177    int len = strlen30(zQuery);
4178    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4179    if( zErr ){
4180      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4181      sqlite3_free(zErr);
4182      zErr = 0;
4183    }
4184    zQ2 = malloc( len+100 );
4185    if( zQ2==0 ) return rc;
4186    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4187    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4188    if( rc ){
4189      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4190    }else{
4191      rc = SQLITE_CORRUPT;
4192    }
4193    sqlite3_free(zErr);
4194    free(zQ2);
4195  }
4196  return rc;
4197}
4198
4199/*
4200** Text of help messages.
4201**
4202** The help text for each individual command begins with a line that starts
4203** with ".".  Subsequent lines are supplimental information.
4204**
4205** There must be two or more spaces between the end of the command and the
4206** start of the description of what that command does.
4207*/
4208static const char *(azHelp[]) = {
4209#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
4210  ".archive ...             Manage SQL archives",
4211  "   Each command must have exactly one of the following options:",
4212  "     -c, --create               Create a new archive",
4213  "     -u, --update               Add or update files with changed mtime",
4214  "     -i, --insert               Like -u but always add even if unchanged",
4215  "     -r, --remove               Remove files from archive",
4216  "     -t, --list                 List contents of archive",
4217  "     -x, --extract              Extract files from archive",
4218  "   Optional arguments:",
4219  "     -v, --verbose              Print each filename as it is processed",
4220  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4221  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4222  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4223  "     -g, --glob                 Use glob matching for names in archive",
4224  "     -n, --dryrun               Show the SQL that would have occurred",
4225  "   Examples:",
4226  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4227  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4228  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4229  "   See also:",
4230  "      http://sqlite.org/cli.html#sqlite_archive_support",
4231#endif
4232#ifndef SQLITE_OMIT_AUTHORIZATION
4233  ".auth ON|OFF             Show authorizer callbacks",
4234#endif
4235  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4236  "       --append            Use the appendvfs",
4237  "       --async             Write to FILE without journal and fsync()",
4238  ".bail on|off             Stop after hitting an error.  Default OFF",
4239  ".binary on|off           Turn binary output on or off.  Default OFF",
4240  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4241  ".changes on|off          Show number of rows changed by SQL",
4242  ".check GLOB              Fail if output since .testcase does not match",
4243  ".clone NEWDB             Clone data into NEWDB from the existing database",
4244  ".connection [close] [#]  Open or close an auxiliary database connection",
4245  ".databases               List names and files of attached databases",
4246  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4247  ".dbinfo ?DB?             Show status information about the database",
4248  ".dump ?OBJECTS?          Render database content as SQL",
4249  "   Options:",
4250  "     --data-only            Output only INSERT statements",
4251  "     --newlines             Allow unescaped newline characters in output",
4252  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4253  "     --preserve-rowids      Include ROWID values in the output",
4254  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4255  "   Additional LIKE patterns can be given in subsequent arguments",
4256  ".echo on|off             Turn command echo on or off",
4257  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4258  "   Other Modes:",
4259#ifdef SQLITE_DEBUG
4260  "      test                  Show raw EXPLAIN QUERY PLAN output",
4261  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4262#endif
4263  "      trigger               Like \"full\" but also show trigger bytecode",
4264  ".excel                   Display the output of next command in spreadsheet",
4265  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4266  ".exit ?CODE?             Exit this program with return-code CODE",
4267  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4268  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4269  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4270  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4271  "   --help                  Show CMD details",
4272  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4273  ".headers on|off          Turn display of headers on or off",
4274  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4275  ".import FILE TABLE       Import data from FILE into TABLE",
4276  "   Options:",
4277  "     --ascii               Use \\037 and \\036 as column and row separators",
4278  "     --csv                 Use , and \\n as column and row separators",
4279  "     --skip N              Skip the first N rows of input",
4280  "     --schema S            Target table to be S.TABLE",
4281  "     -v                    \"Verbose\" - increase auxiliary output",
4282  "   Notes:",
4283  "     *  If TABLE does not exist, it is created.  The first row of input",
4284  "        determines the column names.",
4285  "     *  If neither --csv or --ascii are used, the input mode is derived",
4286  "        from the \".mode\" output mode",
4287  "     *  If FILE begins with \"|\" then it is a command that generates the",
4288  "        input text.",
4289#ifndef SQLITE_OMIT_TEST_CONTROL
4290  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4291#endif
4292  ".indexes ?TABLE?         Show names of indexes",
4293  "                           If TABLE is specified, only show indexes for",
4294  "                           tables matching TABLE using the LIKE operator.",
4295#ifdef SQLITE_ENABLE_IOTRACE
4296  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4297#endif
4298  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4299  ".lint OPTIONS            Report potential schema issues.",
4300  "     Options:",
4301  "        fkey-indexes     Find missing foreign key indexes",
4302#ifndef SQLITE_OMIT_LOAD_EXTENSION
4303  ".load FILE ?ENTRY?       Load an extension library",
4304#endif
4305  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4306  ".mode MODE ?OPTIONS?     Set output mode",
4307  "   MODE is one of:",
4308  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4309  "     box         Tables using unicode box-drawing characters",
4310  "     csv         Comma-separated values",
4311  "     column      Output in columns.  (See .width)",
4312  "     html        HTML <table> code",
4313  "     insert      SQL insert statements for TABLE",
4314  "     json        Results in a JSON array",
4315  "     line        One value per line",
4316  "     list        Values delimited by \"|\"",
4317  "     markdown    Markdown table format",
4318  "     qbox        Shorthand for \"box --width 60 --quote\"",
4319  "     quote       Escape answers as for SQL",
4320  "     table       ASCII-art table",
4321  "     tabs        Tab-separated values",
4322  "     tcl         TCL list elements",
4323  "   OPTIONS: (for columnar modes or insert mode):",
4324  "     --wrap N       Wrap output lines to no longer than N characters",
4325  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4326  "     --ww           Shorthand for \"--wordwrap 1\"",
4327  "     --quote        Quote output text as SQL literals",
4328  "     --noquote      Do not quote output text",
4329  "     TABLE          The name of SQL table used for \"insert\" mode",
4330  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4331  ".nullvalue STRING        Use STRING in place of NULL values",
4332  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4333  "     If FILE begins with '|' then open as a pipe",
4334  "       --bom  Put a UTF8 byte-order mark at the beginning",
4335  "       -e     Send output to the system text editor",
4336  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4337  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4338  "     Options:",
4339  "        --append        Use appendvfs to append database to the end of FILE",
4340#ifndef SQLITE_OMIT_DESERIALIZE
4341  "        --deserialize   Load into memory using sqlite3_deserialize()",
4342  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4343  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4344#endif
4345  "        --new           Initialize FILE to an empty database",
4346  "        --nofollow      Do not follow symbolic links",
4347  "        --readonly      Open FILE readonly",
4348  "        --zip           FILE is a ZIP archive",
4349  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4350  "   If FILE begins with '|' then open it as a pipe.",
4351  "   Options:",
4352  "     --bom                 Prefix output with a UTF8 byte-order mark",
4353  "     -e                    Send output to the system text editor",
4354  "     -x                    Send output as CSV to a spreadsheet",
4355  ".parameter CMD ...       Manage SQL parameter bindings",
4356  "   clear                   Erase all bindings",
4357  "   init                    Initialize the TEMP table that holds bindings",
4358  "   list                    List the current parameter bindings",
4359  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4360  "                           PARAMETER should start with one of: $ : @ ?",
4361  "   unset PARAMETER         Remove PARAMETER from the binding table",
4362  ".print STRING...         Print literal STRING",
4363#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4364  ".progress N              Invoke progress handler after every N opcodes",
4365  "   --limit N                 Interrupt after N progress callbacks",
4366  "   --once                    Do no more than one progress interrupt",
4367  "   --quiet|-q                No output except at interrupts",
4368  "   --reset                   Reset the count for each input and interrupt",
4369#endif
4370  ".prompt MAIN CONTINUE    Replace the standard prompts",
4371  ".quit                    Exit this program",
4372  ".read FILE               Read input from FILE or command output",
4373  "    If FILE begins with \"|\", it is a command that generates the input.",
4374#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4375  ".recover                 Recover as much data as possible from corrupt db.",
4376  "   --freelist-corrupt       Assume the freelist is corrupt",
4377  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4378  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4379  "   --no-rowids              Do not attempt to recover rowid values",
4380  "                            that are not also INTEGER PRIMARY KEYs",
4381#endif
4382  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4383  ".save FILE               Write in-memory database into FILE",
4384  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4385  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4386  "   Options:",
4387  "      --indent             Try to pretty-print the schema",
4388  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4389  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4390  "    Options:",
4391  "       --init               Create a new SELFTEST table",
4392  "       -v                   Verbose output",
4393  ".separator COL ?ROW?     Change the column and row separators",
4394#if defined(SQLITE_ENABLE_SESSION)
4395  ".session ?NAME? CMD ...  Create or control sessions",
4396  "   Subcommands:",
4397  "     attach TABLE             Attach TABLE",
4398  "     changeset FILE           Write a changeset into FILE",
4399  "     close                    Close one session",
4400  "     enable ?BOOLEAN?         Set or query the enable bit",
4401  "     filter GLOB...           Reject tables matching GLOBs",
4402  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4403  "     isempty                  Query whether the session is empty",
4404  "     list                     List currently open session names",
4405  "     open DB NAME             Open a new session on DB",
4406  "     patchset FILE            Write a patchset into FILE",
4407  "   If ?NAME? is omitted, the first defined session is used.",
4408#endif
4409  ".sha3sum ...             Compute a SHA3 hash of database content",
4410  "    Options:",
4411  "      --schema              Also hash the sqlite_schema table",
4412  "      --sha3-224            Use the sha3-224 algorithm",
4413  "      --sha3-256            Use the sha3-256 algorithm (default)",
4414  "      --sha3-384            Use the sha3-384 algorithm",
4415  "      --sha3-512            Use the sha3-512 algorithm",
4416  "    Any other argument is a LIKE pattern for tables to hash",
4417#ifndef SQLITE_NOHAVE_SYSTEM
4418  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4419#endif
4420  ".show                    Show the current values for various settings",
4421  ".stats ?ARG?             Show stats or turn stats on or off",
4422  "   off                      Turn off automatic stat display",
4423  "   on                       Turn on automatic stat display",
4424  "   stmt                     Show statement stats",
4425  "   vmstep                   Show the virtual machine step count only",
4426#ifndef SQLITE_NOHAVE_SYSTEM
4427  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4428#endif
4429  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4430  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4431  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4432  "                           Run \".testctrl\" with no arguments for details",
4433  ".timeout MS              Try opening locked tables for MS milliseconds",
4434  ".timer on|off            Turn SQL timer on or off",
4435#ifndef SQLITE_OMIT_TRACE
4436  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4437  "    FILE                    Send output to FILE",
4438  "    stdout                  Send output to stdout",
4439  "    stderr                  Send output to stderr",
4440  "    off                     Disable tracing",
4441  "    --expanded              Expand query parameters",
4442#ifdef SQLITE_ENABLE_NORMALIZE
4443  "    --normalized            Normal the SQL statements",
4444#endif
4445  "    --plain                 Show SQL as it is input",
4446  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4447  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4448  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4449  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4450#endif /* SQLITE_OMIT_TRACE */
4451#ifdef SQLITE_DEBUG
4452  ".unmodule NAME ...       Unregister virtual table modules",
4453  "    --allexcept             Unregister everything except those named",
4454#endif
4455  ".vfsinfo ?AUX?           Information about the top-level VFS",
4456  ".vfslist                 List all available VFSes",
4457  ".vfsname ?AUX?           Print the name of the VFS stack",
4458  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4459  "     Negative values right-justify",
4460};
4461
4462/*
4463** Output help text.
4464**
4465** zPattern describes the set of commands for which help text is provided.
4466** If zPattern is NULL, then show all commands, but only give a one-line
4467** description of each.
4468**
4469** Return the number of matches.
4470*/
4471static int showHelp(FILE *out, const char *zPattern){
4472  int i = 0;
4473  int j = 0;
4474  int n = 0;
4475  char *zPat;
4476  if( zPattern==0
4477   || zPattern[0]=='0'
4478   || strcmp(zPattern,"-a")==0
4479   || strcmp(zPattern,"-all")==0
4480   || strcmp(zPattern,"--all")==0
4481  ){
4482    /* Show all commands, but only one line per command */
4483    if( zPattern==0 ) zPattern = "";
4484    for(i=0; i<ArraySize(azHelp); i++){
4485      if( azHelp[i][0]=='.' || zPattern[0] ){
4486        utf8_printf(out, "%s\n", azHelp[i]);
4487        n++;
4488      }
4489    }
4490  }else{
4491    /* Look for commands that for which zPattern is an exact prefix */
4492    zPat = sqlite3_mprintf(".%s*", zPattern);
4493    shell_check_oom(zPat);
4494    for(i=0; i<ArraySize(azHelp); i++){
4495      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4496        utf8_printf(out, "%s\n", azHelp[i]);
4497        j = i+1;
4498        n++;
4499      }
4500    }
4501    sqlite3_free(zPat);
4502    if( n ){
4503      if( n==1 ){
4504        /* when zPattern is a prefix of exactly one command, then include the
4505        ** details of that command, which should begin at offset j */
4506        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4507          utf8_printf(out, "%s\n", azHelp[j]);
4508          j++;
4509        }
4510      }
4511      return n;
4512    }
4513    /* Look for commands that contain zPattern anywhere.  Show the complete
4514    ** text of all commands that match. */
4515    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4516    shell_check_oom(zPat);
4517    for(i=0; i<ArraySize(azHelp); i++){
4518      if( azHelp[i][0]=='.' ) j = i;
4519      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4520        utf8_printf(out, "%s\n", azHelp[j]);
4521        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4522          j++;
4523          utf8_printf(out, "%s\n", azHelp[j]);
4524        }
4525        i = j;
4526        n++;
4527      }
4528    }
4529    sqlite3_free(zPat);
4530  }
4531  return n;
4532}
4533
4534/* Forward reference */
4535static int process_input(ShellState *p);
4536
4537/*
4538** Read the content of file zName into memory obtained from sqlite3_malloc64()
4539** and return a pointer to the buffer. The caller is responsible for freeing
4540** the memory.
4541**
4542** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4543** read.
4544**
4545** For convenience, a nul-terminator byte is always appended to the data read
4546** from the file before the buffer is returned. This byte is not included in
4547** the final value of (*pnByte), if applicable.
4548**
4549** NULL is returned if any error is encountered. The final value of *pnByte
4550** is undefined in this case.
4551*/
4552static char *readFile(const char *zName, int *pnByte){
4553  FILE *in = fopen(zName, "rb");
4554  long nIn;
4555  size_t nRead;
4556  char *pBuf;
4557  if( in==0 ) return 0;
4558  fseek(in, 0, SEEK_END);
4559  nIn = ftell(in);
4560  rewind(in);
4561  pBuf = sqlite3_malloc64( nIn+1 );
4562  if( pBuf==0 ){ fclose(in); return 0; }
4563  nRead = fread(pBuf, nIn, 1, in);
4564  fclose(in);
4565  if( nRead!=1 ){
4566    sqlite3_free(pBuf);
4567    return 0;
4568  }
4569  pBuf[nIn] = 0;
4570  if( pnByte ) *pnByte = nIn;
4571  return pBuf;
4572}
4573
4574#if defined(SQLITE_ENABLE_SESSION)
4575/*
4576** Close a single OpenSession object and release all of its associated
4577** resources.
4578*/
4579static void session_close(OpenSession *pSession){
4580  int i;
4581  sqlite3session_delete(pSession->p);
4582  sqlite3_free(pSession->zName);
4583  for(i=0; i<pSession->nFilter; i++){
4584    sqlite3_free(pSession->azFilter[i]);
4585  }
4586  sqlite3_free(pSession->azFilter);
4587  memset(pSession, 0, sizeof(OpenSession));
4588}
4589#endif
4590
4591/*
4592** Close all OpenSession objects and release all associated resources.
4593*/
4594#if defined(SQLITE_ENABLE_SESSION)
4595static void session_close_all(ShellState *p, int i){
4596  int j;
4597  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4598  for(j=0; j<pAuxDb->nSession; j++){
4599    session_close(&pAuxDb->aSession[j]);
4600  }
4601  pAuxDb->nSession = 0;
4602}
4603#else
4604# define session_close_all(X,Y)
4605#endif
4606
4607/*
4608** Implementation of the xFilter function for an open session.  Omit
4609** any tables named by ".session filter" but let all other table through.
4610*/
4611#if defined(SQLITE_ENABLE_SESSION)
4612static int session_filter(void *pCtx, const char *zTab){
4613  OpenSession *pSession = (OpenSession*)pCtx;
4614  int i;
4615  for(i=0; i<pSession->nFilter; i++){
4616    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4617  }
4618  return 1;
4619}
4620#endif
4621
4622/*
4623** Try to deduce the type of file for zName based on its content.  Return
4624** one of the SHELL_OPEN_* constants.
4625**
4626** If the file does not exist or is empty but its name looks like a ZIP
4627** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4628** Otherwise, assume an ordinary database regardless of the filename if
4629** the type cannot be determined from content.
4630*/
4631int deduceDatabaseType(const char *zName, int dfltZip){
4632  FILE *f = fopen(zName, "rb");
4633  size_t n;
4634  int rc = SHELL_OPEN_UNSPEC;
4635  char zBuf[100];
4636  if( f==0 ){
4637    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4638       return SHELL_OPEN_ZIPFILE;
4639    }else{
4640       return SHELL_OPEN_NORMAL;
4641    }
4642  }
4643  n = fread(zBuf, 16, 1, f);
4644  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4645    fclose(f);
4646    return SHELL_OPEN_NORMAL;
4647  }
4648  fseek(f, -25, SEEK_END);
4649  n = fread(zBuf, 25, 1, f);
4650  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4651    rc = SHELL_OPEN_APPENDVFS;
4652  }else{
4653    fseek(f, -22, SEEK_END);
4654    n = fread(zBuf, 22, 1, f);
4655    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4656       && zBuf[3]==0x06 ){
4657      rc = SHELL_OPEN_ZIPFILE;
4658    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4659      rc = SHELL_OPEN_ZIPFILE;
4660    }
4661  }
4662  fclose(f);
4663  return rc;
4664}
4665
4666#ifndef SQLITE_OMIT_DESERIALIZE
4667/*
4668** Reconstruct an in-memory database using the output from the "dbtotxt"
4669** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4670** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4671*/
4672static unsigned char *readHexDb(ShellState *p, int *pnData){
4673  unsigned char *a = 0;
4674  int nLine;
4675  int n = 0;
4676  int pgsz = 0;
4677  int iOffset = 0;
4678  int j, k;
4679  int rc;
4680  FILE *in;
4681  const char *zDbFilename = p->pAuxDb->zDbFilename;
4682  unsigned int x[16];
4683  char zLine[1000];
4684  if( zDbFilename ){
4685    in = fopen(zDbFilename, "r");
4686    if( in==0 ){
4687      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4688      return 0;
4689    }
4690    nLine = 0;
4691  }else{
4692    in = p->in;
4693    nLine = p->lineno;
4694    if( in==0 ) in = stdin;
4695  }
4696  *pnData = 0;
4697  nLine++;
4698  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4699  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4700  if( rc!=2 ) goto readHexDb_error;
4701  if( n<0 ) goto readHexDb_error;
4702  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4703  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4704  a = sqlite3_malloc( n ? n : 1 );
4705  shell_check_oom(a);
4706  memset(a, 0, n);
4707  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4708    utf8_printf(stderr, "invalid pagesize\n");
4709    goto readHexDb_error;
4710  }
4711  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4712    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4713    if( rc==2 ){
4714      iOffset = k;
4715      continue;
4716    }
4717    if( strncmp(zLine, "| end ", 6)==0 ){
4718      break;
4719    }
4720    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4721                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4722                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4723    if( rc==17 ){
4724      k = iOffset+j;
4725      if( k+16<=n && k>=0 ){
4726        int ii;
4727        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4728      }
4729    }
4730  }
4731  *pnData = n;
4732  if( in!=p->in ){
4733    fclose(in);
4734  }else{
4735    p->lineno = nLine;
4736  }
4737  return a;
4738
4739readHexDb_error:
4740  if( in!=p->in ){
4741    fclose(in);
4742  }else{
4743    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4744      nLine++;
4745      if(strncmp(zLine, "| end ", 6)==0 ) break;
4746    }
4747    p->lineno = nLine;
4748  }
4749  sqlite3_free(a);
4750  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4751  return 0;
4752}
4753#endif /* SQLITE_OMIT_DESERIALIZE */
4754
4755/*
4756** Scalar function "shell_int32". The first argument to this function
4757** must be a blob. The second a non-negative integer. This function
4758** reads and returns a 32-bit big-endian integer from byte
4759** offset (4*<arg2>) of the blob.
4760*/
4761static void shellInt32(
4762  sqlite3_context *context,
4763  int argc,
4764  sqlite3_value **argv
4765){
4766  const unsigned char *pBlob;
4767  int nBlob;
4768  int iInt;
4769
4770  UNUSED_PARAMETER(argc);
4771  nBlob = sqlite3_value_bytes(argv[0]);
4772  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4773  iInt = sqlite3_value_int(argv[1]);
4774
4775  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4776    const unsigned char *a = &pBlob[iInt*4];
4777    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4778                       + ((sqlite3_int64)a[1]<<16)
4779                       + ((sqlite3_int64)a[2]<< 8)
4780                       + ((sqlite3_int64)a[3]<< 0);
4781    sqlite3_result_int64(context, iVal);
4782  }
4783}
4784
4785/*
4786** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4787** using "..." with internal double-quote characters doubled.
4788*/
4789static void shellIdQuote(
4790  sqlite3_context *context,
4791  int argc,
4792  sqlite3_value **argv
4793){
4794  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4795  UNUSED_PARAMETER(argc);
4796  if( zName ){
4797    char *z = sqlite3_mprintf("\"%w\"", zName);
4798    sqlite3_result_text(context, z, -1, sqlite3_free);
4799  }
4800}
4801
4802/*
4803** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4804*/
4805static void shellUSleepFunc(
4806  sqlite3_context *context,
4807  int argcUnused,
4808  sqlite3_value **argv
4809){
4810  int sleep = sqlite3_value_int(argv[0]);
4811  (void)argcUnused;
4812  sqlite3_sleep(sleep/1000);
4813  sqlite3_result_int(context, sleep);
4814}
4815
4816/*
4817** Scalar function "shell_escape_crnl" used by the .recover command.
4818** The argument passed to this function is the output of built-in
4819** function quote(). If the first character of the input is "'",
4820** indicating that the value passed to quote() was a text value,
4821** then this function searches the input for "\n" and "\r" characters
4822** and adds a wrapper similar to the following:
4823**
4824**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4825**
4826** Or, if the first character of the input is not "'", then a copy
4827** of the input is returned.
4828*/
4829static void shellEscapeCrnl(
4830  sqlite3_context *context,
4831  int argc,
4832  sqlite3_value **argv
4833){
4834  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4835  UNUSED_PARAMETER(argc);
4836  if( zText && zText[0]=='\'' ){
4837    int nText = sqlite3_value_bytes(argv[0]);
4838    int i;
4839    char zBuf1[20];
4840    char zBuf2[20];
4841    const char *zNL = 0;
4842    const char *zCR = 0;
4843    int nCR = 0;
4844    int nNL = 0;
4845
4846    for(i=0; zText[i]; i++){
4847      if( zNL==0 && zText[i]=='\n' ){
4848        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4849        nNL = (int)strlen(zNL);
4850      }
4851      if( zCR==0 && zText[i]=='\r' ){
4852        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4853        nCR = (int)strlen(zCR);
4854      }
4855    }
4856
4857    if( zNL || zCR ){
4858      int iOut = 0;
4859      i64 nMax = (nNL > nCR) ? nNL : nCR;
4860      i64 nAlloc = nMax * nText + (nMax+64)*2;
4861      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4862      if( zOut==0 ){
4863        sqlite3_result_error_nomem(context);
4864        return;
4865      }
4866
4867      if( zNL && zCR ){
4868        memcpy(&zOut[iOut], "replace(replace(", 16);
4869        iOut += 16;
4870      }else{
4871        memcpy(&zOut[iOut], "replace(", 8);
4872        iOut += 8;
4873      }
4874      for(i=0; zText[i]; i++){
4875        if( zText[i]=='\n' ){
4876          memcpy(&zOut[iOut], zNL, nNL);
4877          iOut += nNL;
4878        }else if( zText[i]=='\r' ){
4879          memcpy(&zOut[iOut], zCR, nCR);
4880          iOut += nCR;
4881        }else{
4882          zOut[iOut] = zText[i];
4883          iOut++;
4884        }
4885      }
4886
4887      if( zNL ){
4888        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4889        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4890        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4891      }
4892      if( zCR ){
4893        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4894        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4895        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4896      }
4897
4898      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4899      sqlite3_free(zOut);
4900      return;
4901    }
4902  }
4903
4904  sqlite3_result_value(context, argv[0]);
4905}
4906
4907/* Flags for open_db().
4908**
4909** The default behavior of open_db() is to exit(1) if the database fails to
4910** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4911** but still returns without calling exit.
4912**
4913** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4914** ZIP archive if the file does not exist or is empty and its name matches
4915** the *.zip pattern.
4916*/
4917#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4918#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4919
4920/*
4921** Make sure the database is open.  If it is not, then open it.  If
4922** the database fails to open, print an error message and exit.
4923*/
4924static void open_db(ShellState *p, int openFlags){
4925  if( p->db==0 ){
4926    const char *zDbFilename = p->pAuxDb->zDbFilename;
4927    if( p->openMode==SHELL_OPEN_UNSPEC ){
4928      if( zDbFilename==0 || zDbFilename[0]==0 ){
4929        p->openMode = SHELL_OPEN_NORMAL;
4930      }else{
4931        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4932                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4933      }
4934    }
4935    switch( p->openMode ){
4936      case SHELL_OPEN_APPENDVFS: {
4937        sqlite3_open_v2(zDbFilename, &p->db,
4938           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4939        break;
4940      }
4941      case SHELL_OPEN_HEXDB:
4942      case SHELL_OPEN_DESERIALIZE: {
4943        sqlite3_open(0, &p->db);
4944        break;
4945      }
4946      case SHELL_OPEN_ZIPFILE: {
4947        sqlite3_open(":memory:", &p->db);
4948        break;
4949      }
4950      case SHELL_OPEN_READONLY: {
4951        sqlite3_open_v2(zDbFilename, &p->db,
4952            SQLITE_OPEN_READONLY|p->openFlags, 0);
4953        break;
4954      }
4955      case SHELL_OPEN_UNSPEC:
4956      case SHELL_OPEN_NORMAL: {
4957        sqlite3_open_v2(zDbFilename, &p->db,
4958           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4959        break;
4960      }
4961    }
4962    globalDb = p->db;
4963    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4964      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4965          zDbFilename, sqlite3_errmsg(p->db));
4966      if( openFlags & OPEN_DB_KEEPALIVE ){
4967        sqlite3_open(":memory:", &p->db);
4968        return;
4969      }
4970      exit(1);
4971    }
4972#ifndef SQLITE_OMIT_LOAD_EXTENSION
4973    sqlite3_enable_load_extension(p->db, 1);
4974#endif
4975    sqlite3_fileio_init(p->db, 0, 0);
4976    sqlite3_shathree_init(p->db, 0, 0);
4977    sqlite3_completion_init(p->db, 0, 0);
4978    sqlite3_uint_init(p->db, 0, 0);
4979    sqlite3_decimal_init(p->db, 0, 0);
4980    sqlite3_regexp_init(p->db, 0, 0);
4981    sqlite3_ieee_init(p->db, 0, 0);
4982    sqlite3_series_init(p->db, 0, 0);
4983#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4984    sqlite3_dbdata_init(p->db, 0, 0);
4985#endif
4986#ifdef SQLITE_HAVE_ZLIB
4987    sqlite3_zipfile_init(p->db, 0, 0);
4988    sqlite3_sqlar_init(p->db, 0, 0);
4989#endif
4990    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4991                            shellAddSchemaName, 0, 0);
4992    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4993                            shellModuleSchema, 0, 0);
4994    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4995                            shellPutsFunc, 0, 0);
4996    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4997                            shellEscapeCrnl, 0, 0);
4998    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4999                            shellInt32, 0, 0);
5000    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5001                            shellIdQuote, 0, 0);
5002    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5003                            shellUSleepFunc, 0, 0);
5004#ifndef SQLITE_NOHAVE_SYSTEM
5005    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5006                            editFunc, 0, 0);
5007    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5008                            editFunc, 0, 0);
5009#endif
5010    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5011      char *zSql = sqlite3_mprintf(
5012         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5013      shell_check_oom(zSql);
5014      sqlite3_exec(p->db, zSql, 0, 0, 0);
5015      sqlite3_free(zSql);
5016    }
5017#ifndef SQLITE_OMIT_DESERIALIZE
5018    else
5019    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5020      int rc;
5021      int nData = 0;
5022      unsigned char *aData;
5023      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5024        aData = (unsigned char*)readFile(zDbFilename, &nData);
5025      }else{
5026        aData = readHexDb(p, &nData);
5027        if( aData==0 ){
5028          return;
5029        }
5030      }
5031      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5032                   SQLITE_DESERIALIZE_RESIZEABLE |
5033                   SQLITE_DESERIALIZE_FREEONCLOSE);
5034      if( rc ){
5035        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5036      }
5037      if( p->szMax>0 ){
5038        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5039      }
5040    }
5041#endif
5042  }
5043  if( p->bSafeModePersist && p->db!=0 ){
5044    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5045  }
5046}
5047
5048/*
5049** Attempt to close the databaes connection.  Report errors.
5050*/
5051void close_db(sqlite3 *db){
5052  int rc = sqlite3_close(db);
5053  if( rc ){
5054    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5055        rc, sqlite3_errmsg(db));
5056  }
5057}
5058
5059#if HAVE_READLINE || HAVE_EDITLINE
5060/*
5061** Readline completion callbacks
5062*/
5063static char *readline_completion_generator(const char *text, int state){
5064  static sqlite3_stmt *pStmt = 0;
5065  char *zRet;
5066  if( state==0 ){
5067    char *zSql;
5068    sqlite3_finalize(pStmt);
5069    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5070                           "  FROM completion(%Q) ORDER BY 1", text);
5071    shell_check_oom(zSql);
5072    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5073    sqlite3_free(zSql);
5074  }
5075  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5076    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5077    zRet = z ? strdup(z) : 0;
5078  }else{
5079    sqlite3_finalize(pStmt);
5080    pStmt = 0;
5081    zRet = 0;
5082  }
5083  return zRet;
5084}
5085static char **readline_completion(const char *zText, int iStart, int iEnd){
5086  rl_attempted_completion_over = 1;
5087  return rl_completion_matches(zText, readline_completion_generator);
5088}
5089
5090#elif HAVE_LINENOISE
5091/*
5092** Linenoise completion callback
5093*/
5094static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5095  int nLine = strlen30(zLine);
5096  int i, iStart;
5097  sqlite3_stmt *pStmt = 0;
5098  char *zSql;
5099  char zBuf[1000];
5100
5101  if( nLine>sizeof(zBuf)-30 ) return;
5102  if( zLine[0]=='.' || zLine[0]=='#') return;
5103  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5104  if( i==nLine-1 ) return;
5105  iStart = i+1;
5106  memcpy(zBuf, zLine, iStart);
5107  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5108                         "  FROM completion(%Q,%Q) ORDER BY 1",
5109                         &zLine[iStart], zLine);
5110  shell_check_oom(zSql);
5111  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5112  sqlite3_free(zSql);
5113  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5114  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5115    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5116    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5117    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5118      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5119      linenoiseAddCompletion(lc, zBuf);
5120    }
5121  }
5122  sqlite3_finalize(pStmt);
5123}
5124#endif
5125
5126/*
5127** Do C-language style dequoting.
5128**
5129**    \a    -> alarm
5130**    \b    -> backspace
5131**    \t    -> tab
5132**    \n    -> newline
5133**    \v    -> vertical tab
5134**    \f    -> form feed
5135**    \r    -> carriage return
5136**    \s    -> space
5137**    \"    -> "
5138**    \'    -> '
5139**    \\    -> backslash
5140**    \NNN  -> ascii character NNN in octal
5141*/
5142static void resolve_backslashes(char *z){
5143  int i, j;
5144  char c;
5145  while( *z && *z!='\\' ) z++;
5146  for(i=j=0; (c = z[i])!=0; i++, j++){
5147    if( c=='\\' && z[i+1]!=0 ){
5148      c = z[++i];
5149      if( c=='a' ){
5150        c = '\a';
5151      }else if( c=='b' ){
5152        c = '\b';
5153      }else if( c=='t' ){
5154        c = '\t';
5155      }else if( c=='n' ){
5156        c = '\n';
5157      }else if( c=='v' ){
5158        c = '\v';
5159      }else if( c=='f' ){
5160        c = '\f';
5161      }else if( c=='r' ){
5162        c = '\r';
5163      }else if( c=='"' ){
5164        c = '"';
5165      }else if( c=='\'' ){
5166        c = '\'';
5167      }else if( c=='\\' ){
5168        c = '\\';
5169      }else if( c>='0' && c<='7' ){
5170        c -= '0';
5171        if( z[i+1]>='0' && z[i+1]<='7' ){
5172          i++;
5173          c = (c<<3) + z[i] - '0';
5174          if( z[i+1]>='0' && z[i+1]<='7' ){
5175            i++;
5176            c = (c<<3) + z[i] - '0';
5177          }
5178        }
5179      }
5180    }
5181    z[j] = c;
5182  }
5183  if( j<i ) z[j] = 0;
5184}
5185
5186/*
5187** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5188** for TRUE and FALSE.  Return the integer value if appropriate.
5189*/
5190static int booleanValue(const char *zArg){
5191  int i;
5192  if( zArg[0]=='0' && zArg[1]=='x' ){
5193    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5194  }else{
5195    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5196  }
5197  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5198  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5199    return 1;
5200  }
5201  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5202    return 0;
5203  }
5204  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5205          zArg);
5206  return 0;
5207}
5208
5209/*
5210** Set or clear a shell flag according to a boolean value.
5211*/
5212static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5213  if( booleanValue(zArg) ){
5214    ShellSetFlag(p, mFlag);
5215  }else{
5216    ShellClearFlag(p, mFlag);
5217  }
5218}
5219
5220/*
5221** Close an output file, assuming it is not stderr or stdout
5222*/
5223static void output_file_close(FILE *f){
5224  if( f && f!=stdout && f!=stderr ) fclose(f);
5225}
5226
5227/*
5228** Try to open an output file.   The names "stdout" and "stderr" are
5229** recognized and do the right thing.  NULL is returned if the output
5230** filename is "off".
5231*/
5232static FILE *output_file_open(const char *zFile, int bTextMode){
5233  FILE *f;
5234  if( strcmp(zFile,"stdout")==0 ){
5235    f = stdout;
5236  }else if( strcmp(zFile, "stderr")==0 ){
5237    f = stderr;
5238  }else if( strcmp(zFile, "off")==0 ){
5239    f = 0;
5240  }else{
5241    f = fopen(zFile, bTextMode ? "w" : "wb");
5242    if( f==0 ){
5243      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5244    }
5245  }
5246  return f;
5247}
5248
5249#ifndef SQLITE_OMIT_TRACE
5250/*
5251** A routine for handling output from sqlite3_trace().
5252*/
5253static int sql_trace_callback(
5254  unsigned mType,         /* The trace type */
5255  void *pArg,             /* The ShellState pointer */
5256  void *pP,               /* Usually a pointer to sqlite_stmt */
5257  void *pX                /* Auxiliary output */
5258){
5259  ShellState *p = (ShellState*)pArg;
5260  sqlite3_stmt *pStmt;
5261  const char *zSql;
5262  int nSql;
5263  if( p->traceOut==0 ) return 0;
5264  if( mType==SQLITE_TRACE_CLOSE ){
5265    utf8_printf(p->traceOut, "-- closing database connection\n");
5266    return 0;
5267  }
5268  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5269    zSql = (const char*)pX;
5270  }else{
5271    pStmt = (sqlite3_stmt*)pP;
5272    switch( p->eTraceType ){
5273      case SHELL_TRACE_EXPANDED: {
5274        zSql = sqlite3_expanded_sql(pStmt);
5275        break;
5276      }
5277#ifdef SQLITE_ENABLE_NORMALIZE
5278      case SHELL_TRACE_NORMALIZED: {
5279        zSql = sqlite3_normalized_sql(pStmt);
5280        break;
5281      }
5282#endif
5283      default: {
5284        zSql = sqlite3_sql(pStmt);
5285        break;
5286      }
5287    }
5288  }
5289  if( zSql==0 ) return 0;
5290  nSql = strlen30(zSql);
5291  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5292  switch( mType ){
5293    case SQLITE_TRACE_ROW:
5294    case SQLITE_TRACE_STMT: {
5295      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5296      break;
5297    }
5298    case SQLITE_TRACE_PROFILE: {
5299      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5300      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5301      break;
5302    }
5303  }
5304  return 0;
5305}
5306#endif
5307
5308/*
5309** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5310** a useful spot to set a debugger breakpoint.
5311*/
5312static void test_breakpoint(void){
5313  static int nCall = 0;
5314  nCall++;
5315}
5316
5317/*
5318** An object used to read a CSV and other files for import.
5319*/
5320typedef struct ImportCtx ImportCtx;
5321struct ImportCtx {
5322  const char *zFile;  /* Name of the input file */
5323  FILE *in;           /* Read the CSV text from this input stream */
5324  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5325  char *z;            /* Accumulated text for a field */
5326  int n;              /* Number of bytes in z */
5327  int nAlloc;         /* Space allocated for z[] */
5328  int nLine;          /* Current line number */
5329  int nRow;           /* Number of rows imported */
5330  int nErr;           /* Number of errors encountered */
5331  int bNotFirst;      /* True if one or more bytes already read */
5332  int cTerm;          /* Character that terminated the most recent field */
5333  int cColSep;        /* The column separator character.  (Usually ",") */
5334  int cRowSep;        /* The row separator character.  (Usually "\n") */
5335};
5336
5337/* Clean up resourced used by an ImportCtx */
5338static void import_cleanup(ImportCtx *p){
5339  if( p->in!=0 && p->xCloser!=0 ){
5340    p->xCloser(p->in);
5341    p->in = 0;
5342  }
5343  sqlite3_free(p->z);
5344  p->z = 0;
5345}
5346
5347/* Append a single byte to z[] */
5348static void import_append_char(ImportCtx *p, int c){
5349  if( p->n+1>=p->nAlloc ){
5350    p->nAlloc += p->nAlloc + 100;
5351    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5352    shell_check_oom(p->z);
5353  }
5354  p->z[p->n++] = (char)c;
5355}
5356
5357/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5358** with the option of having a separator other than ",".
5359**
5360**   +  Input comes from p->in.
5361**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5362**      from sqlite3_malloc64().
5363**   +  Use p->cSep as the column separator.  The default is ",".
5364**   +  Use p->rSep as the row separator.  The default is "\n".
5365**   +  Keep track of the line number in p->nLine.
5366**   +  Store the character that terminates the field in p->cTerm.  Store
5367**      EOF on end-of-file.
5368**   +  Report syntax errors on stderr
5369*/
5370static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5371  int c;
5372  int cSep = p->cColSep;
5373  int rSep = p->cRowSep;
5374  p->n = 0;
5375  c = fgetc(p->in);
5376  if( c==EOF || seenInterrupt ){
5377    p->cTerm = EOF;
5378    return 0;
5379  }
5380  if( c=='"' ){
5381    int pc, ppc;
5382    int startLine = p->nLine;
5383    int cQuote = c;
5384    pc = ppc = 0;
5385    while( 1 ){
5386      c = fgetc(p->in);
5387      if( c==rSep ) p->nLine++;
5388      if( c==cQuote ){
5389        if( pc==cQuote ){
5390          pc = 0;
5391          continue;
5392        }
5393      }
5394      if( (c==cSep && pc==cQuote)
5395       || (c==rSep && pc==cQuote)
5396       || (c==rSep && pc=='\r' && ppc==cQuote)
5397       || (c==EOF && pc==cQuote)
5398      ){
5399        do{ p->n--; }while( p->z[p->n]!=cQuote );
5400        p->cTerm = c;
5401        break;
5402      }
5403      if( pc==cQuote && c!='\r' ){
5404        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5405                p->zFile, p->nLine, cQuote);
5406      }
5407      if( c==EOF ){
5408        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5409                p->zFile, startLine, cQuote);
5410        p->cTerm = c;
5411        break;
5412      }
5413      import_append_char(p, c);
5414      ppc = pc;
5415      pc = c;
5416    }
5417  }else{
5418    /* If this is the first field being parsed and it begins with the
5419    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5420    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5421      import_append_char(p, c);
5422      c = fgetc(p->in);
5423      if( (c&0xff)==0xbb ){
5424        import_append_char(p, c);
5425        c = fgetc(p->in);
5426        if( (c&0xff)==0xbf ){
5427          p->bNotFirst = 1;
5428          p->n = 0;
5429          return csv_read_one_field(p);
5430        }
5431      }
5432    }
5433    while( c!=EOF && c!=cSep && c!=rSep ){
5434      import_append_char(p, c);
5435      c = fgetc(p->in);
5436    }
5437    if( c==rSep ){
5438      p->nLine++;
5439      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5440    }
5441    p->cTerm = c;
5442  }
5443  if( p->z ) p->z[p->n] = 0;
5444  p->bNotFirst = 1;
5445  return p->z;
5446}
5447
5448/* Read a single field of ASCII delimited text.
5449**
5450**   +  Input comes from p->in.
5451**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5452**      from sqlite3_malloc64().
5453**   +  Use p->cSep as the column separator.  The default is "\x1F".
5454**   +  Use p->rSep as the row separator.  The default is "\x1E".
5455**   +  Keep track of the row number in p->nLine.
5456**   +  Store the character that terminates the field in p->cTerm.  Store
5457**      EOF on end-of-file.
5458**   +  Report syntax errors on stderr
5459*/
5460static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5461  int c;
5462  int cSep = p->cColSep;
5463  int rSep = p->cRowSep;
5464  p->n = 0;
5465  c = fgetc(p->in);
5466  if( c==EOF || seenInterrupt ){
5467    p->cTerm = EOF;
5468    return 0;
5469  }
5470  while( c!=EOF && c!=cSep && c!=rSep ){
5471    import_append_char(p, c);
5472    c = fgetc(p->in);
5473  }
5474  if( c==rSep ){
5475    p->nLine++;
5476  }
5477  p->cTerm = c;
5478  if( p->z ) p->z[p->n] = 0;
5479  return p->z;
5480}
5481
5482/*
5483** Try to transfer data for table zTable.  If an error is seen while
5484** moving forward, try to go backwards.  The backwards movement won't
5485** work for WITHOUT ROWID tables.
5486*/
5487static void tryToCloneData(
5488  ShellState *p,
5489  sqlite3 *newDb,
5490  const char *zTable
5491){
5492  sqlite3_stmt *pQuery = 0;
5493  sqlite3_stmt *pInsert = 0;
5494  char *zQuery = 0;
5495  char *zInsert = 0;
5496  int rc;
5497  int i, j, n;
5498  int nTable = strlen30(zTable);
5499  int k = 0;
5500  int cnt = 0;
5501  const int spinRate = 10000;
5502
5503  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5504  shell_check_oom(zQuery);
5505  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5506  if( rc ){
5507    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5508            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5509            zQuery);
5510    goto end_data_xfer;
5511  }
5512  n = sqlite3_column_count(pQuery);
5513  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5514  shell_check_oom(zInsert);
5515  sqlite3_snprintf(200+nTable,zInsert,
5516                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5517  i = strlen30(zInsert);
5518  for(j=1; j<n; j++){
5519    memcpy(zInsert+i, ",?", 2);
5520    i += 2;
5521  }
5522  memcpy(zInsert+i, ");", 3);
5523  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5524  if( rc ){
5525    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5526            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5527            zQuery);
5528    goto end_data_xfer;
5529  }
5530  for(k=0; k<2; k++){
5531    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5532      for(i=0; i<n; i++){
5533        switch( sqlite3_column_type(pQuery, i) ){
5534          case SQLITE_NULL: {
5535            sqlite3_bind_null(pInsert, i+1);
5536            break;
5537          }
5538          case SQLITE_INTEGER: {
5539            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5540            break;
5541          }
5542          case SQLITE_FLOAT: {
5543            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5544            break;
5545          }
5546          case SQLITE_TEXT: {
5547            sqlite3_bind_text(pInsert, i+1,
5548                             (const char*)sqlite3_column_text(pQuery,i),
5549                             -1, SQLITE_STATIC);
5550            break;
5551          }
5552          case SQLITE_BLOB: {
5553            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5554                                            sqlite3_column_bytes(pQuery,i),
5555                                            SQLITE_STATIC);
5556            break;
5557          }
5558        }
5559      } /* End for */
5560      rc = sqlite3_step(pInsert);
5561      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5562        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5563                        sqlite3_errmsg(newDb));
5564      }
5565      sqlite3_reset(pInsert);
5566      cnt++;
5567      if( (cnt%spinRate)==0 ){
5568        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5569        fflush(stdout);
5570      }
5571    } /* End while */
5572    if( rc==SQLITE_DONE ) break;
5573    sqlite3_finalize(pQuery);
5574    sqlite3_free(zQuery);
5575    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5576                             zTable);
5577    shell_check_oom(zQuery);
5578    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5579    if( rc ){
5580      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5581      break;
5582    }
5583  } /* End for(k=0...) */
5584
5585end_data_xfer:
5586  sqlite3_finalize(pQuery);
5587  sqlite3_finalize(pInsert);
5588  sqlite3_free(zQuery);
5589  sqlite3_free(zInsert);
5590}
5591
5592
5593/*
5594** Try to transfer all rows of the schema that match zWhere.  For
5595** each row, invoke xForEach() on the object defined by that row.
5596** If an error is encountered while moving forward through the
5597** sqlite_schema table, try again moving backwards.
5598*/
5599static void tryToCloneSchema(
5600  ShellState *p,
5601  sqlite3 *newDb,
5602  const char *zWhere,
5603  void (*xForEach)(ShellState*,sqlite3*,const char*)
5604){
5605  sqlite3_stmt *pQuery = 0;
5606  char *zQuery = 0;
5607  int rc;
5608  const unsigned char *zName;
5609  const unsigned char *zSql;
5610  char *zErrMsg = 0;
5611
5612  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5613                           " WHERE %s", zWhere);
5614  shell_check_oom(zQuery);
5615  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5616  if( rc ){
5617    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5618                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5619                    zQuery);
5620    goto end_schema_xfer;
5621  }
5622  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5623    zName = sqlite3_column_text(pQuery, 0);
5624    zSql = sqlite3_column_text(pQuery, 1);
5625    if( zName==0 || zSql==0 ) continue;
5626    printf("%s... ", zName); fflush(stdout);
5627    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5628    if( zErrMsg ){
5629      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5630      sqlite3_free(zErrMsg);
5631      zErrMsg = 0;
5632    }
5633    if( xForEach ){
5634      xForEach(p, newDb, (const char*)zName);
5635    }
5636    printf("done\n");
5637  }
5638  if( rc!=SQLITE_DONE ){
5639    sqlite3_finalize(pQuery);
5640    sqlite3_free(zQuery);
5641    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5642                             " WHERE %s ORDER BY rowid DESC", zWhere);
5643    shell_check_oom(zQuery);
5644    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5645    if( rc ){
5646      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5647                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5648                      zQuery);
5649      goto end_schema_xfer;
5650    }
5651    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5652      zName = sqlite3_column_text(pQuery, 0);
5653      zSql = sqlite3_column_text(pQuery, 1);
5654      if( zName==0 || zSql==0 ) continue;
5655      printf("%s... ", zName); fflush(stdout);
5656      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5657      if( zErrMsg ){
5658        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5659        sqlite3_free(zErrMsg);
5660        zErrMsg = 0;
5661      }
5662      if( xForEach ){
5663        xForEach(p, newDb, (const char*)zName);
5664      }
5665      printf("done\n");
5666    }
5667  }
5668end_schema_xfer:
5669  sqlite3_finalize(pQuery);
5670  sqlite3_free(zQuery);
5671}
5672
5673/*
5674** Open a new database file named "zNewDb".  Try to recover as much information
5675** as possible out of the main database (which might be corrupt) and write it
5676** into zNewDb.
5677*/
5678static void tryToClone(ShellState *p, const char *zNewDb){
5679  int rc;
5680  sqlite3 *newDb = 0;
5681  if( access(zNewDb,0)==0 ){
5682    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5683    return;
5684  }
5685  rc = sqlite3_open(zNewDb, &newDb);
5686  if( rc ){
5687    utf8_printf(stderr, "Cannot create output database: %s\n",
5688            sqlite3_errmsg(newDb));
5689  }else{
5690    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5691    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5692    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5693    tryToCloneSchema(p, newDb, "type!='table'", 0);
5694    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5695    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5696  }
5697  close_db(newDb);
5698}
5699
5700/*
5701** Change the output file back to stdout.
5702**
5703** If the p->doXdgOpen flag is set, that means the output was being
5704** redirected to a temporary file named by p->zTempFile.  In that case,
5705** launch start/open/xdg-open on that temporary file.
5706*/
5707static void output_reset(ShellState *p){
5708  if( p->outfile[0]=='|' ){
5709#ifndef SQLITE_OMIT_POPEN
5710    pclose(p->out);
5711#endif
5712  }else{
5713    output_file_close(p->out);
5714#ifndef SQLITE_NOHAVE_SYSTEM
5715    if( p->doXdgOpen ){
5716      const char *zXdgOpenCmd =
5717#if defined(_WIN32)
5718      "start";
5719#elif defined(__APPLE__)
5720      "open";
5721#else
5722      "xdg-open";
5723#endif
5724      char *zCmd;
5725      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5726      if( system(zCmd) ){
5727        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5728      }else{
5729        /* Give the start/open/xdg-open command some time to get
5730        ** going before we continue, and potential delete the
5731        ** p->zTempFile data file out from under it */
5732        sqlite3_sleep(2000);
5733      }
5734      sqlite3_free(zCmd);
5735      outputModePop(p);
5736      p->doXdgOpen = 0;
5737    }
5738#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5739  }
5740  p->outfile[0] = 0;
5741  p->out = stdout;
5742}
5743
5744/*
5745** Run an SQL command and return the single integer result.
5746*/
5747static int db_int(ShellState *p, const char *zSql){
5748  sqlite3_stmt *pStmt;
5749  int res = 0;
5750  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5751  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5752    res = sqlite3_column_int(pStmt,0);
5753  }
5754  sqlite3_finalize(pStmt);
5755  return res;
5756}
5757
5758/*
5759** Convert a 2-byte or 4-byte big-endian integer into a native integer
5760*/
5761static unsigned int get2byteInt(unsigned char *a){
5762  return (a[0]<<8) + a[1];
5763}
5764static unsigned int get4byteInt(unsigned char *a){
5765  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5766}
5767
5768/*
5769** Implementation of the ".dbinfo" command.
5770**
5771** Return 1 on error, 2 to exit, and 0 otherwise.
5772*/
5773static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5774  static const struct { const char *zName; int ofst; } aField[] = {
5775     { "file change counter:",  24  },
5776     { "database page count:",  28  },
5777     { "freelist page count:",  36  },
5778     { "schema cookie:",        40  },
5779     { "schema format:",        44  },
5780     { "default cache size:",   48  },
5781     { "autovacuum top root:",  52  },
5782     { "incremental vacuum:",   64  },
5783     { "text encoding:",        56  },
5784     { "user version:",         60  },
5785     { "application id:",       68  },
5786     { "software version:",     96  },
5787  };
5788  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5789     { "number of tables:",
5790       "SELECT count(*) FROM %s WHERE type='table'" },
5791     { "number of indexes:",
5792       "SELECT count(*) FROM %s WHERE type='index'" },
5793     { "number of triggers:",
5794       "SELECT count(*) FROM %s WHERE type='trigger'" },
5795     { "number of views:",
5796       "SELECT count(*) FROM %s WHERE type='view'" },
5797     { "schema size:",
5798       "SELECT total(length(sql)) FROM %s" },
5799  };
5800  int i, rc;
5801  unsigned iDataVersion;
5802  char *zSchemaTab;
5803  char *zDb = nArg>=2 ? azArg[1] : "main";
5804  sqlite3_stmt *pStmt = 0;
5805  unsigned char aHdr[100];
5806  open_db(p, 0);
5807  if( p->db==0 ) return 1;
5808  rc = sqlite3_prepare_v2(p->db,
5809             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5810             -1, &pStmt, 0);
5811  if( rc ){
5812    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5813    sqlite3_finalize(pStmt);
5814    return 1;
5815  }
5816  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5817  if( sqlite3_step(pStmt)==SQLITE_ROW
5818   && sqlite3_column_bytes(pStmt,0)>100
5819  ){
5820    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5821    sqlite3_finalize(pStmt);
5822  }else{
5823    raw_printf(stderr, "unable to read database header\n");
5824    sqlite3_finalize(pStmt);
5825    return 1;
5826  }
5827  i = get2byteInt(aHdr+16);
5828  if( i==1 ) i = 65536;
5829  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5830  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5831  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5832  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5833  for(i=0; i<ArraySize(aField); i++){
5834    int ofst = aField[i].ofst;
5835    unsigned int val = get4byteInt(aHdr + ofst);
5836    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5837    switch( ofst ){
5838      case 56: {
5839        if( val==1 ) raw_printf(p->out, " (utf8)");
5840        if( val==2 ) raw_printf(p->out, " (utf16le)");
5841        if( val==3 ) raw_printf(p->out, " (utf16be)");
5842      }
5843    }
5844    raw_printf(p->out, "\n");
5845  }
5846  if( zDb==0 ){
5847    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5848  }else if( strcmp(zDb,"temp")==0 ){
5849    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5850  }else{
5851    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5852  }
5853  for(i=0; i<ArraySize(aQuery); i++){
5854    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5855    int val = db_int(p, zSql);
5856    sqlite3_free(zSql);
5857    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5858  }
5859  sqlite3_free(zSchemaTab);
5860  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5861  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5862  return 0;
5863}
5864
5865/*
5866** Print the current sqlite3_errmsg() value to stderr and return 1.
5867*/
5868static int shellDatabaseError(sqlite3 *db){
5869  const char *zErr = sqlite3_errmsg(db);
5870  utf8_printf(stderr, "Error: %s\n", zErr);
5871  return 1;
5872}
5873
5874/*
5875** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5876** if they match and FALSE (0) if they do not match.
5877**
5878** Globbing rules:
5879**
5880**      '*'       Matches any sequence of zero or more characters.
5881**
5882**      '?'       Matches exactly one character.
5883**
5884**     [...]      Matches one character from the enclosed list of
5885**                characters.
5886**
5887**     [^...]     Matches one character not in the enclosed list.
5888**
5889**      '#'       Matches any sequence of one or more digits with an
5890**                optional + or - sign in front
5891**
5892**      ' '       Any span of whitespace matches any other span of
5893**                whitespace.
5894**
5895** Extra whitespace at the end of z[] is ignored.
5896*/
5897static int testcase_glob(const char *zGlob, const char *z){
5898  int c, c2;
5899  int invert;
5900  int seen;
5901
5902  while( (c = (*(zGlob++)))!=0 ){
5903    if( IsSpace(c) ){
5904      if( !IsSpace(*z) ) return 0;
5905      while( IsSpace(*zGlob) ) zGlob++;
5906      while( IsSpace(*z) ) z++;
5907    }else if( c=='*' ){
5908      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5909        if( c=='?' && (*(z++))==0 ) return 0;
5910      }
5911      if( c==0 ){
5912        return 1;
5913      }else if( c=='[' ){
5914        while( *z && testcase_glob(zGlob-1,z)==0 ){
5915          z++;
5916        }
5917        return (*z)!=0;
5918      }
5919      while( (c2 = (*(z++)))!=0 ){
5920        while( c2!=c ){
5921          c2 = *(z++);
5922          if( c2==0 ) return 0;
5923        }
5924        if( testcase_glob(zGlob,z) ) return 1;
5925      }
5926      return 0;
5927    }else if( c=='?' ){
5928      if( (*(z++))==0 ) return 0;
5929    }else if( c=='[' ){
5930      int prior_c = 0;
5931      seen = 0;
5932      invert = 0;
5933      c = *(z++);
5934      if( c==0 ) return 0;
5935      c2 = *(zGlob++);
5936      if( c2=='^' ){
5937        invert = 1;
5938        c2 = *(zGlob++);
5939      }
5940      if( c2==']' ){
5941        if( c==']' ) seen = 1;
5942        c2 = *(zGlob++);
5943      }
5944      while( c2 && c2!=']' ){
5945        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5946          c2 = *(zGlob++);
5947          if( c>=prior_c && c<=c2 ) seen = 1;
5948          prior_c = 0;
5949        }else{
5950          if( c==c2 ){
5951            seen = 1;
5952          }
5953          prior_c = c2;
5954        }
5955        c2 = *(zGlob++);
5956      }
5957      if( c2==0 || (seen ^ invert)==0 ) return 0;
5958    }else if( c=='#' ){
5959      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5960      if( !IsDigit(z[0]) ) return 0;
5961      z++;
5962      while( IsDigit(z[0]) ){ z++; }
5963    }else{
5964      if( c!=(*(z++)) ) return 0;
5965    }
5966  }
5967  while( IsSpace(*z) ){ z++; }
5968  return *z==0;
5969}
5970
5971
5972/*
5973** Compare the string as a command-line option with either one or two
5974** initial "-" characters.
5975*/
5976static int optionMatch(const char *zStr, const char *zOpt){
5977  if( zStr[0]!='-' ) return 0;
5978  zStr++;
5979  if( zStr[0]=='-' ) zStr++;
5980  return strcmp(zStr, zOpt)==0;
5981}
5982
5983/*
5984** Delete a file.
5985*/
5986int shellDeleteFile(const char *zFilename){
5987  int rc;
5988#ifdef _WIN32
5989  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5990  rc = _wunlink(z);
5991  sqlite3_free(z);
5992#else
5993  rc = unlink(zFilename);
5994#endif
5995  return rc;
5996}
5997
5998/*
5999** Try to delete the temporary file (if there is one) and free the
6000** memory used to hold the name of the temp file.
6001*/
6002static void clearTempFile(ShellState *p){
6003  if( p->zTempFile==0 ) return;
6004  if( p->doXdgOpen ) return;
6005  if( shellDeleteFile(p->zTempFile) ) return;
6006  sqlite3_free(p->zTempFile);
6007  p->zTempFile = 0;
6008}
6009
6010/*
6011** Create a new temp file name with the given suffix.
6012*/
6013static void newTempFile(ShellState *p, const char *zSuffix){
6014  clearTempFile(p);
6015  sqlite3_free(p->zTempFile);
6016  p->zTempFile = 0;
6017  if( p->db ){
6018    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6019  }
6020  if( p->zTempFile==0 ){
6021    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6022    ** will not work and we will need to fallback to guessing */
6023    char *zTemp;
6024    sqlite3_uint64 r;
6025    sqlite3_randomness(sizeof(r), &r);
6026    zTemp = getenv("TEMP");
6027    if( zTemp==0 ) zTemp = getenv("TMP");
6028    if( zTemp==0 ){
6029#ifdef _WIN32
6030      zTemp = "\\tmp";
6031#else
6032      zTemp = "/tmp";
6033#endif
6034    }
6035    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6036  }else{
6037    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6038  }
6039  shell_check_oom(p->zTempFile);
6040}
6041
6042
6043/*
6044** The implementation of SQL scalar function fkey_collate_clause(), used
6045** by the ".lint fkey-indexes" command. This scalar function is always
6046** called with four arguments - the parent table name, the parent column name,
6047** the child table name and the child column name.
6048**
6049**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6050**
6051** If either of the named tables or columns do not exist, this function
6052** returns an empty string. An empty string is also returned if both tables
6053** and columns exist but have the same default collation sequence. Or,
6054** if both exist but the default collation sequences are different, this
6055** function returns the string " COLLATE <parent-collation>", where
6056** <parent-collation> is the default collation sequence of the parent column.
6057*/
6058static void shellFkeyCollateClause(
6059  sqlite3_context *pCtx,
6060  int nVal,
6061  sqlite3_value **apVal
6062){
6063  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6064  const char *zParent;
6065  const char *zParentCol;
6066  const char *zParentSeq;
6067  const char *zChild;
6068  const char *zChildCol;
6069  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6070  int rc;
6071
6072  assert( nVal==4 );
6073  zParent = (const char*)sqlite3_value_text(apVal[0]);
6074  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6075  zChild = (const char*)sqlite3_value_text(apVal[2]);
6076  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6077
6078  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6079  rc = sqlite3_table_column_metadata(
6080      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6081  );
6082  if( rc==SQLITE_OK ){
6083    rc = sqlite3_table_column_metadata(
6084        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6085    );
6086  }
6087
6088  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6089    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6090    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6091    sqlite3_free(z);
6092  }
6093}
6094
6095
6096/*
6097** The implementation of dot-command ".lint fkey-indexes".
6098*/
6099static int lintFkeyIndexes(
6100  ShellState *pState,             /* Current shell tool state */
6101  char **azArg,                   /* Array of arguments passed to dot command */
6102  int nArg                        /* Number of entries in azArg[] */
6103){
6104  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6105  FILE *out = pState->out;        /* Stream to write non-error output to */
6106  int bVerbose = 0;               /* If -verbose is present */
6107  int bGroupByParent = 0;         /* If -groupbyparent is present */
6108  int i;                          /* To iterate through azArg[] */
6109  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6110  int rc;                         /* Return code */
6111  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6112
6113  /*
6114  ** This SELECT statement returns one row for each foreign key constraint
6115  ** in the schema of the main database. The column values are:
6116  **
6117  ** 0. The text of an SQL statement similar to:
6118  **
6119  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6120  **
6121  **    This SELECT is similar to the one that the foreign keys implementation
6122  **    needs to run internally on child tables. If there is an index that can
6123  **    be used to optimize this query, then it can also be used by the FK
6124  **    implementation to optimize DELETE or UPDATE statements on the parent
6125  **    table.
6126  **
6127  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6128  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6129  **    contains an index that can be used to optimize the query.
6130  **
6131  ** 2. Human readable text that describes the child table and columns. e.g.
6132  **
6133  **       "child_table(child_key1, child_key2)"
6134  **
6135  ** 3. Human readable text that describes the parent table and columns. e.g.
6136  **
6137  **       "parent_table(parent_key1, parent_key2)"
6138  **
6139  ** 4. A full CREATE INDEX statement for an index that could be used to
6140  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6141  **
6142  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6143  **
6144  ** 5. The name of the parent table.
6145  **
6146  ** These six values are used by the C logic below to generate the report.
6147  */
6148  const char *zSql =
6149  "SELECT "
6150    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6151    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6152    "  || fkey_collate_clause("
6153    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6154    ", "
6155    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6156    "  || group_concat('*=?', ' AND ') || ')'"
6157    ", "
6158    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6159    ", "
6160    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6161    ", "
6162    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6163    "  || ' ON ' || quote(s.name) || '('"
6164    "  || group_concat(quote(f.[from]) ||"
6165    "        fkey_collate_clause("
6166    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6167    "  || ');'"
6168    ", "
6169    "     f.[table] "
6170    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6171    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6172    "GROUP BY s.name, f.id "
6173    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6174  ;
6175  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6176
6177  for(i=2; i<nArg; i++){
6178    int n = strlen30(azArg[i]);
6179    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6180      bVerbose = 1;
6181    }
6182    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6183      bGroupByParent = 1;
6184      zIndent = "    ";
6185    }
6186    else{
6187      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6188          azArg[0], azArg[1]
6189      );
6190      return SQLITE_ERROR;
6191    }
6192  }
6193
6194  /* Register the fkey_collate_clause() SQL function */
6195  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6196      0, shellFkeyCollateClause, 0, 0
6197  );
6198
6199
6200  if( rc==SQLITE_OK ){
6201    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6202  }
6203  if( rc==SQLITE_OK ){
6204    sqlite3_bind_int(pSql, 1, bGroupByParent);
6205  }
6206
6207  if( rc==SQLITE_OK ){
6208    int rc2;
6209    char *zPrev = 0;
6210    while( SQLITE_ROW==sqlite3_step(pSql) ){
6211      int res = -1;
6212      sqlite3_stmt *pExplain = 0;
6213      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6214      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6215      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6216      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6217      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6218      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6219
6220      if( zEQP==0 ) continue;
6221      if( zGlob==0 ) continue;
6222      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6223      if( rc!=SQLITE_OK ) break;
6224      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6225        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6226        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6227                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6228      }
6229      rc = sqlite3_finalize(pExplain);
6230      if( rc!=SQLITE_OK ) break;
6231
6232      if( res<0 ){
6233        raw_printf(stderr, "Error: internal error");
6234        break;
6235      }else{
6236        if( bGroupByParent
6237        && (bVerbose || res==0)
6238        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6239        ){
6240          raw_printf(out, "-- Parent table %s\n", zParent);
6241          sqlite3_free(zPrev);
6242          zPrev = sqlite3_mprintf("%s", zParent);
6243        }
6244
6245        if( res==0 ){
6246          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6247        }else if( bVerbose ){
6248          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6249              zIndent, zFrom, zTarget
6250          );
6251        }
6252      }
6253    }
6254    sqlite3_free(zPrev);
6255
6256    if( rc!=SQLITE_OK ){
6257      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6258    }
6259
6260    rc2 = sqlite3_finalize(pSql);
6261    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6262      rc = rc2;
6263      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6264    }
6265  }else{
6266    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6267  }
6268
6269  return rc;
6270}
6271
6272/*
6273** Implementation of ".lint" dot command.
6274*/
6275static int lintDotCommand(
6276  ShellState *pState,             /* Current shell tool state */
6277  char **azArg,                   /* Array of arguments passed to dot command */
6278  int nArg                        /* Number of entries in azArg[] */
6279){
6280  int n;
6281  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6282  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6283  return lintFkeyIndexes(pState, azArg, nArg);
6284
6285 usage:
6286  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6287  raw_printf(stderr, "Where sub-commands are:\n");
6288  raw_printf(stderr, "    fkey-indexes\n");
6289  return SQLITE_ERROR;
6290}
6291
6292#if !defined SQLITE_OMIT_VIRTUALTABLE
6293static void shellPrepare(
6294  sqlite3 *db,
6295  int *pRc,
6296  const char *zSql,
6297  sqlite3_stmt **ppStmt
6298){
6299  *ppStmt = 0;
6300  if( *pRc==SQLITE_OK ){
6301    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6302    if( rc!=SQLITE_OK ){
6303      raw_printf(stderr, "sql error: %s (%d)\n",
6304          sqlite3_errmsg(db), sqlite3_errcode(db)
6305      );
6306      *pRc = rc;
6307    }
6308  }
6309}
6310
6311/*
6312** Create a prepared statement using printf-style arguments for the SQL.
6313**
6314** This routine is could be marked "static".  But it is not always used,
6315** depending on compile-time options.  By omitting the "static", we avoid
6316** nuisance compiler warnings about "defined but not used".
6317*/
6318void shellPreparePrintf(
6319  sqlite3 *db,
6320  int *pRc,
6321  sqlite3_stmt **ppStmt,
6322  const char *zFmt,
6323  ...
6324){
6325  *ppStmt = 0;
6326  if( *pRc==SQLITE_OK ){
6327    va_list ap;
6328    char *z;
6329    va_start(ap, zFmt);
6330    z = sqlite3_vmprintf(zFmt, ap);
6331    va_end(ap);
6332    if( z==0 ){
6333      *pRc = SQLITE_NOMEM;
6334    }else{
6335      shellPrepare(db, pRc, z, ppStmt);
6336      sqlite3_free(z);
6337    }
6338  }
6339}
6340
6341/* Finalize the prepared statement created using shellPreparePrintf().
6342**
6343** This routine is could be marked "static".  But it is not always used,
6344** depending on compile-time options.  By omitting the "static", we avoid
6345** nuisance compiler warnings about "defined but not used".
6346*/
6347void shellFinalize(
6348  int *pRc,
6349  sqlite3_stmt *pStmt
6350){
6351  if( pStmt ){
6352    sqlite3 *db = sqlite3_db_handle(pStmt);
6353    int rc = sqlite3_finalize(pStmt);
6354    if( *pRc==SQLITE_OK ){
6355      if( rc!=SQLITE_OK ){
6356        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6357      }
6358      *pRc = rc;
6359    }
6360  }
6361}
6362
6363/* Reset the prepared statement created using shellPreparePrintf().
6364**
6365** This routine is could be marked "static".  But it is not always used,
6366** depending on compile-time options.  By omitting the "static", we avoid
6367** nuisance compiler warnings about "defined but not used".
6368*/
6369void shellReset(
6370  int *pRc,
6371  sqlite3_stmt *pStmt
6372){
6373  int rc = sqlite3_reset(pStmt);
6374  if( *pRc==SQLITE_OK ){
6375    if( rc!=SQLITE_OK ){
6376      sqlite3 *db = sqlite3_db_handle(pStmt);
6377      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6378    }
6379    *pRc = rc;
6380  }
6381}
6382#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6383
6384#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6385/******************************************************************************
6386** The ".archive" or ".ar" command.
6387*/
6388/*
6389** Structure representing a single ".ar" command.
6390*/
6391typedef struct ArCommand ArCommand;
6392struct ArCommand {
6393  u8 eCmd;                        /* An AR_CMD_* value */
6394  u8 bVerbose;                    /* True if --verbose */
6395  u8 bZip;                        /* True if the archive is a ZIP */
6396  u8 bDryRun;                     /* True if --dry-run */
6397  u8 bAppend;                     /* True if --append */
6398  u8 bGlob;                       /* True if --glob */
6399  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6400  int nArg;                       /* Number of command arguments */
6401  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6402  const char *zFile;              /* --file argument, or NULL */
6403  const char *zDir;               /* --directory argument, or NULL */
6404  char **azArg;                   /* Array of command arguments */
6405  ShellState *p;                  /* Shell state */
6406  sqlite3 *db;                    /* Database containing the archive */
6407};
6408
6409/*
6410** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6411*/
6412static int arUsage(FILE *f){
6413  showHelp(f,"archive");
6414  return SQLITE_ERROR;
6415}
6416
6417/*
6418** Print an error message for the .ar command to stderr and return
6419** SQLITE_ERROR.
6420*/
6421static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6422  va_list ap;
6423  char *z;
6424  va_start(ap, zFmt);
6425  z = sqlite3_vmprintf(zFmt, ap);
6426  va_end(ap);
6427  utf8_printf(stderr, "Error: %s\n", z);
6428  if( pAr->fromCmdLine ){
6429    utf8_printf(stderr, "Use \"-A\" for more help\n");
6430  }else{
6431    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6432  }
6433  sqlite3_free(z);
6434  return SQLITE_ERROR;
6435}
6436
6437/*
6438** Values for ArCommand.eCmd.
6439*/
6440#define AR_CMD_CREATE       1
6441#define AR_CMD_UPDATE       2
6442#define AR_CMD_INSERT       3
6443#define AR_CMD_EXTRACT      4
6444#define AR_CMD_LIST         5
6445#define AR_CMD_HELP         6
6446#define AR_CMD_REMOVE       7
6447
6448/*
6449** Other (non-command) switches.
6450*/
6451#define AR_SWITCH_VERBOSE     8
6452#define AR_SWITCH_FILE        9
6453#define AR_SWITCH_DIRECTORY  10
6454#define AR_SWITCH_APPEND     11
6455#define AR_SWITCH_DRYRUN     12
6456#define AR_SWITCH_GLOB       13
6457
6458static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6459  switch( eSwitch ){
6460    case AR_CMD_CREATE:
6461    case AR_CMD_EXTRACT:
6462    case AR_CMD_LIST:
6463    case AR_CMD_REMOVE:
6464    case AR_CMD_UPDATE:
6465    case AR_CMD_INSERT:
6466    case AR_CMD_HELP:
6467      if( pAr->eCmd ){
6468        return arErrorMsg(pAr, "multiple command options");
6469      }
6470      pAr->eCmd = eSwitch;
6471      break;
6472
6473    case AR_SWITCH_DRYRUN:
6474      pAr->bDryRun = 1;
6475      break;
6476    case AR_SWITCH_GLOB:
6477      pAr->bGlob = 1;
6478      break;
6479    case AR_SWITCH_VERBOSE:
6480      pAr->bVerbose = 1;
6481      break;
6482    case AR_SWITCH_APPEND:
6483      pAr->bAppend = 1;
6484      /* Fall thru into --file */
6485    case AR_SWITCH_FILE:
6486      pAr->zFile = zArg;
6487      break;
6488    case AR_SWITCH_DIRECTORY:
6489      pAr->zDir = zArg;
6490      break;
6491  }
6492
6493  return SQLITE_OK;
6494}
6495
6496/*
6497** Parse the command line for an ".ar" command. The results are written into
6498** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6499** successfully, otherwise an error message is written to stderr and
6500** SQLITE_ERROR returned.
6501*/
6502static int arParseCommand(
6503  char **azArg,                   /* Array of arguments passed to dot command */
6504  int nArg,                       /* Number of entries in azArg[] */
6505  ArCommand *pAr                  /* Populate this object */
6506){
6507  struct ArSwitch {
6508    const char *zLong;
6509    char cShort;
6510    u8 eSwitch;
6511    u8 bArg;
6512  } aSwitch[] = {
6513    { "create",    'c', AR_CMD_CREATE,       0 },
6514    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6515    { "insert",    'i', AR_CMD_INSERT,       0 },
6516    { "list",      't', AR_CMD_LIST,         0 },
6517    { "remove",    'r', AR_CMD_REMOVE,       0 },
6518    { "update",    'u', AR_CMD_UPDATE,       0 },
6519    { "help",      'h', AR_CMD_HELP,         0 },
6520    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6521    { "file",      'f', AR_SWITCH_FILE,      1 },
6522    { "append",    'a', AR_SWITCH_APPEND,    1 },
6523    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6524    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6525    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6526  };
6527  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6528  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6529
6530  if( nArg<=1 ){
6531    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6532    return arUsage(stderr);
6533  }else{
6534    char *z = azArg[1];
6535    if( z[0]!='-' ){
6536      /* Traditional style [tar] invocation */
6537      int i;
6538      int iArg = 2;
6539      for(i=0; z[i]; i++){
6540        const char *zArg = 0;
6541        struct ArSwitch *pOpt;
6542        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6543          if( z[i]==pOpt->cShort ) break;
6544        }
6545        if( pOpt==pEnd ){
6546          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6547        }
6548        if( pOpt->bArg ){
6549          if( iArg>=nArg ){
6550            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6551          }
6552          zArg = azArg[iArg++];
6553        }
6554        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6555      }
6556      pAr->nArg = nArg-iArg;
6557      if( pAr->nArg>0 ){
6558        pAr->azArg = &azArg[iArg];
6559      }
6560    }else{
6561      /* Non-traditional invocation */
6562      int iArg;
6563      for(iArg=1; iArg<nArg; iArg++){
6564        int n;
6565        z = azArg[iArg];
6566        if( z[0]!='-' ){
6567          /* All remaining command line words are command arguments. */
6568          pAr->azArg = &azArg[iArg];
6569          pAr->nArg = nArg-iArg;
6570          break;
6571        }
6572        n = strlen30(z);
6573
6574        if( z[1]!='-' ){
6575          int i;
6576          /* One or more short options */
6577          for(i=1; i<n; i++){
6578            const char *zArg = 0;
6579            struct ArSwitch *pOpt;
6580            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6581              if( z[i]==pOpt->cShort ) break;
6582            }
6583            if( pOpt==pEnd ){
6584              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6585            }
6586            if( pOpt->bArg ){
6587              if( i<(n-1) ){
6588                zArg = &z[i+1];
6589                i = n;
6590              }else{
6591                if( iArg>=(nArg-1) ){
6592                  return arErrorMsg(pAr, "option requires an argument: %c",
6593                                    z[i]);
6594                }
6595                zArg = azArg[++iArg];
6596              }
6597            }
6598            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6599          }
6600        }else if( z[2]=='\0' ){
6601          /* A -- option, indicating that all remaining command line words
6602          ** are command arguments.  */
6603          pAr->azArg = &azArg[iArg+1];
6604          pAr->nArg = nArg-iArg-1;
6605          break;
6606        }else{
6607          /* A long option */
6608          const char *zArg = 0;             /* Argument for option, if any */
6609          struct ArSwitch *pMatch = 0;      /* Matching option */
6610          struct ArSwitch *pOpt;            /* Iterator */
6611          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6612            const char *zLong = pOpt->zLong;
6613            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6614              if( pMatch ){
6615                return arErrorMsg(pAr, "ambiguous option: %s",z);
6616              }else{
6617                pMatch = pOpt;
6618              }
6619            }
6620          }
6621
6622          if( pMatch==0 ){
6623            return arErrorMsg(pAr, "unrecognized option: %s", z);
6624          }
6625          if( pMatch->bArg ){
6626            if( iArg>=(nArg-1) ){
6627              return arErrorMsg(pAr, "option requires an argument: %s", z);
6628            }
6629            zArg = azArg[++iArg];
6630          }
6631          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6632        }
6633      }
6634    }
6635  }
6636
6637  return SQLITE_OK;
6638}
6639
6640/*
6641** This function assumes that all arguments within the ArCommand.azArg[]
6642** array refer to archive members, as for the --extract, --list or --remove
6643** commands. It checks that each of them are "present". If any specified
6644** file is not present in the archive, an error is printed to stderr and an
6645** error code returned. Otherwise, if all specified arguments are present
6646** in the archive, SQLITE_OK is returned. Here, "present" means either an
6647** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6648** when pAr->bGlob is true.
6649**
6650** This function strips any trailing '/' characters from each argument.
6651** This is consistent with the way the [tar] command seems to work on
6652** Linux.
6653*/
6654static int arCheckEntries(ArCommand *pAr){
6655  int rc = SQLITE_OK;
6656  if( pAr->nArg ){
6657    int i, j;
6658    sqlite3_stmt *pTest = 0;
6659    const char *zSel = (pAr->bGlob)
6660      ? "SELECT name FROM %s WHERE glob($name,name)"
6661      : "SELECT name FROM %s WHERE name=$name";
6662
6663    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6664    j = sqlite3_bind_parameter_index(pTest, "$name");
6665    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6666      char *z = pAr->azArg[i];
6667      int n = strlen30(z);
6668      int bOk = 0;
6669      while( n>0 && z[n-1]=='/' ) n--;
6670      z[n] = '\0';
6671      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6672      if( SQLITE_ROW==sqlite3_step(pTest) ){
6673        bOk = 1;
6674      }
6675      shellReset(&rc, pTest);
6676      if( rc==SQLITE_OK && bOk==0 ){
6677        utf8_printf(stderr, "not found in archive: %s\n", z);
6678        rc = SQLITE_ERROR;
6679      }
6680    }
6681    shellFinalize(&rc, pTest);
6682  }
6683  return rc;
6684}
6685
6686/*
6687** Format a WHERE clause that can be used against the "sqlar" table to
6688** identify all archive members that match the command arguments held
6689** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6690** The caller is responsible for eventually calling sqlite3_free() on
6691** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6692** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6693*/
6694static void arWhereClause(
6695  int *pRc,
6696  ArCommand *pAr,
6697  char **pzWhere                  /* OUT: New WHERE clause */
6698){
6699  char *zWhere = 0;
6700  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6701  if( *pRc==SQLITE_OK ){
6702    if( pAr->nArg==0 ){
6703      zWhere = sqlite3_mprintf("1");
6704    }else{
6705      int i;
6706      const char *zSep = "";
6707      for(i=0; i<pAr->nArg; i++){
6708        const char *z = pAr->azArg[i];
6709        zWhere = sqlite3_mprintf(
6710          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6711          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6712        );
6713        if( zWhere==0 ){
6714          *pRc = SQLITE_NOMEM;
6715          break;
6716        }
6717        zSep = " OR ";
6718      }
6719    }
6720  }
6721  *pzWhere = zWhere;
6722}
6723
6724/*
6725** Implementation of .ar "lisT" command.
6726*/
6727static int arListCommand(ArCommand *pAr){
6728  const char *zSql = "SELECT %s FROM %s WHERE %s";
6729  const char *azCols[] = {
6730    "name",
6731    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6732  };
6733
6734  char *zWhere = 0;
6735  sqlite3_stmt *pSql = 0;
6736  int rc;
6737
6738  rc = arCheckEntries(pAr);
6739  arWhereClause(&rc, pAr, &zWhere);
6740
6741  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6742                     pAr->zSrcTable, zWhere);
6743  if( pAr->bDryRun ){
6744    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6745  }else{
6746    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6747      if( pAr->bVerbose ){
6748        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6749            sqlite3_column_text(pSql, 0),
6750            sqlite3_column_int(pSql, 1),
6751            sqlite3_column_text(pSql, 2),
6752            sqlite3_column_text(pSql, 3)
6753        );
6754      }else{
6755        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6756      }
6757    }
6758  }
6759  shellFinalize(&rc, pSql);
6760  sqlite3_free(zWhere);
6761  return rc;
6762}
6763
6764
6765/*
6766** Implementation of .ar "Remove" command.
6767*/
6768static int arRemoveCommand(ArCommand *pAr){
6769  int rc = 0;
6770  char *zSql = 0;
6771  char *zWhere = 0;
6772
6773  if( pAr->nArg ){
6774    /* Verify that args actually exist within the archive before proceeding.
6775    ** And formulate a WHERE clause to match them.  */
6776    rc = arCheckEntries(pAr);
6777    arWhereClause(&rc, pAr, &zWhere);
6778  }
6779  if( rc==SQLITE_OK ){
6780    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6781                           pAr->zSrcTable, zWhere);
6782    if( pAr->bDryRun ){
6783      utf8_printf(pAr->p->out, "%s\n", zSql);
6784    }else{
6785      char *zErr = 0;
6786      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6787      if( rc==SQLITE_OK ){
6788        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6789        if( rc!=SQLITE_OK ){
6790          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6791        }else{
6792          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6793        }
6794      }
6795      if( zErr ){
6796        utf8_printf(stdout, "ERROR: %s\n", zErr);
6797        sqlite3_free(zErr);
6798      }
6799    }
6800  }
6801  sqlite3_free(zWhere);
6802  sqlite3_free(zSql);
6803  return rc;
6804}
6805
6806/*
6807** Implementation of .ar "eXtract" command.
6808*/
6809static int arExtractCommand(ArCommand *pAr){
6810  const char *zSql1 =
6811    "SELECT "
6812    " ($dir || name),"
6813    " writefile(($dir || name), %s, mode, mtime) "
6814    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6815    " AND name NOT GLOB '*..[/\\]*'";
6816
6817  const char *azExtraArg[] = {
6818    "sqlar_uncompress(data, sz)",
6819    "data"
6820  };
6821
6822  sqlite3_stmt *pSql = 0;
6823  int rc = SQLITE_OK;
6824  char *zDir = 0;
6825  char *zWhere = 0;
6826  int i, j;
6827
6828  /* If arguments are specified, check that they actually exist within
6829  ** the archive before proceeding. And formulate a WHERE clause to
6830  ** match them.  */
6831  rc = arCheckEntries(pAr);
6832  arWhereClause(&rc, pAr, &zWhere);
6833
6834  if( rc==SQLITE_OK ){
6835    if( pAr->zDir ){
6836      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6837    }else{
6838      zDir = sqlite3_mprintf("");
6839    }
6840    if( zDir==0 ) rc = SQLITE_NOMEM;
6841  }
6842
6843  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6844      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6845  );
6846
6847  if( rc==SQLITE_OK ){
6848    j = sqlite3_bind_parameter_index(pSql, "$dir");
6849    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6850
6851    /* Run the SELECT statement twice. The first time, writefile() is called
6852    ** for all archive members that should be extracted. The second time,
6853    ** only for the directories. This is because the timestamps for
6854    ** extracted directories must be reset after they are populated (as
6855    ** populating them changes the timestamp).  */
6856    for(i=0; i<2; i++){
6857      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6858      sqlite3_bind_int(pSql, j, i);
6859      if( pAr->bDryRun ){
6860        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6861      }else{
6862        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6863          if( i==0 && pAr->bVerbose ){
6864            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6865          }
6866        }
6867      }
6868      shellReset(&rc, pSql);
6869    }
6870    shellFinalize(&rc, pSql);
6871  }
6872
6873  sqlite3_free(zDir);
6874  sqlite3_free(zWhere);
6875  return rc;
6876}
6877
6878/*
6879** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6880*/
6881static int arExecSql(ArCommand *pAr, const char *zSql){
6882  int rc;
6883  if( pAr->bDryRun ){
6884    utf8_printf(pAr->p->out, "%s\n", zSql);
6885    rc = SQLITE_OK;
6886  }else{
6887    char *zErr = 0;
6888    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6889    if( zErr ){
6890      utf8_printf(stdout, "ERROR: %s\n", zErr);
6891      sqlite3_free(zErr);
6892    }
6893  }
6894  return rc;
6895}
6896
6897
6898/*
6899** Implementation of .ar "create", "insert", and "update" commands.
6900**
6901**     create    ->     Create a new SQL archive
6902**     insert    ->     Insert or reinsert all files listed
6903**     update    ->     Insert files that have changed or that were not
6904**                      previously in the archive
6905**
6906** Create the "sqlar" table in the database if it does not already exist.
6907** Then add each file in the azFile[] array to the archive. Directories
6908** are added recursively. If argument bVerbose is non-zero, a message is
6909** printed on stdout for each file archived.
6910**
6911** The create command is the same as update, except that it drops
6912** any existing "sqlar" table before beginning.  The "insert" command
6913** always overwrites every file named on the command-line, where as
6914** "update" only overwrites if the size or mtime or mode has changed.
6915*/
6916static int arCreateOrUpdateCommand(
6917  ArCommand *pAr,                 /* Command arguments and options */
6918  int bUpdate,                    /* true for a --create. */
6919  int bOnlyIfChanged              /* Only update if file has changed */
6920){
6921  const char *zCreate =
6922      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6923      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6924      "  mode INT,               -- access permissions\n"
6925      "  mtime INT,              -- last modification time\n"
6926      "  sz INT,                 -- original file size\n"
6927      "  data BLOB               -- compressed content\n"
6928      ")";
6929  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6930  const char *zInsertFmt[2] = {
6931     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6932     "  SELECT\n"
6933     "    %s,\n"
6934     "    mode,\n"
6935     "    mtime,\n"
6936     "    CASE substr(lsmode(mode),1,1)\n"
6937     "      WHEN '-' THEN length(data)\n"
6938     "      WHEN 'd' THEN 0\n"
6939     "      ELSE -1 END,\n"
6940     "    sqlar_compress(data)\n"
6941     "  FROM fsdir(%Q,%Q) AS disk\n"
6942     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6943     ,
6944     "REPLACE INTO %s(name,mode,mtime,data)\n"
6945     "  SELECT\n"
6946     "    %s,\n"
6947     "    mode,\n"
6948     "    mtime,\n"
6949     "    data\n"
6950     "  FROM fsdir(%Q,%Q) AS disk\n"
6951     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6952  };
6953  int i;                          /* For iterating through azFile[] */
6954  int rc;                         /* Return code */
6955  const char *zTab = 0;           /* SQL table into which to insert */
6956  char *zSql;
6957  char zTemp[50];
6958  char *zExists = 0;
6959
6960  arExecSql(pAr, "PRAGMA page_size=512");
6961  rc = arExecSql(pAr, "SAVEPOINT ar;");
6962  if( rc!=SQLITE_OK ) return rc;
6963  zTemp[0] = 0;
6964  if( pAr->bZip ){
6965    /* Initialize the zipfile virtual table, if necessary */
6966    if( pAr->zFile ){
6967      sqlite3_uint64 r;
6968      sqlite3_randomness(sizeof(r),&r);
6969      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6970      zTab = zTemp;
6971      zSql = sqlite3_mprintf(
6972         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6973         zTab, pAr->zFile
6974      );
6975      rc = arExecSql(pAr, zSql);
6976      sqlite3_free(zSql);
6977    }else{
6978      zTab = "zip";
6979    }
6980  }else{
6981    /* Initialize the table for an SQLAR */
6982    zTab = "sqlar";
6983    if( bUpdate==0 ){
6984      rc = arExecSql(pAr, zDrop);
6985      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6986    }
6987    rc = arExecSql(pAr, zCreate);
6988  }
6989  if( bOnlyIfChanged ){
6990    zExists = sqlite3_mprintf(
6991      " AND NOT EXISTS("
6992          "SELECT 1 FROM %s AS mem"
6993          " WHERE mem.name=disk.name"
6994          " AND mem.mtime=disk.mtime"
6995          " AND mem.mode=disk.mode)", zTab);
6996  }else{
6997    zExists = sqlite3_mprintf("");
6998  }
6999  if( zExists==0 ) rc = SQLITE_NOMEM;
7000  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7001    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7002        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7003        pAr->azArg[i], pAr->zDir, zExists);
7004    rc = arExecSql(pAr, zSql2);
7005    sqlite3_free(zSql2);
7006  }
7007end_ar_transaction:
7008  if( rc!=SQLITE_OK ){
7009    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7010  }else{
7011    rc = arExecSql(pAr, "RELEASE ar;");
7012    if( pAr->bZip && pAr->zFile ){
7013      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7014      arExecSql(pAr, zSql);
7015      sqlite3_free(zSql);
7016    }
7017  }
7018  sqlite3_free(zExists);
7019  return rc;
7020}
7021
7022/*
7023** Implementation of ".ar" dot command.
7024*/
7025static int arDotCommand(
7026  ShellState *pState,          /* Current shell tool state */
7027  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7028  char **azArg,                /* Array of arguments passed to dot command */
7029  int nArg                     /* Number of entries in azArg[] */
7030){
7031  ArCommand cmd;
7032  int rc;
7033  memset(&cmd, 0, sizeof(cmd));
7034  cmd.fromCmdLine = fromCmdLine;
7035  rc = arParseCommand(azArg, nArg, &cmd);
7036  if( rc==SQLITE_OK ){
7037    int eDbType = SHELL_OPEN_UNSPEC;
7038    cmd.p = pState;
7039    cmd.db = pState->db;
7040    if( cmd.zFile ){
7041      eDbType = deduceDatabaseType(cmd.zFile, 1);
7042    }else{
7043      eDbType = pState->openMode;
7044    }
7045    if( eDbType==SHELL_OPEN_ZIPFILE ){
7046      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7047        if( cmd.zFile==0 ){
7048          cmd.zSrcTable = sqlite3_mprintf("zip");
7049        }else{
7050          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7051        }
7052      }
7053      cmd.bZip = 1;
7054    }else if( cmd.zFile ){
7055      int flags;
7056      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7057      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7058           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7059        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7060      }else{
7061        flags = SQLITE_OPEN_READONLY;
7062      }
7063      cmd.db = 0;
7064      if( cmd.bDryRun ){
7065        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7066             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7067      }
7068      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7069             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7070      if( rc!=SQLITE_OK ){
7071        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7072            cmd.zFile, sqlite3_errmsg(cmd.db)
7073        );
7074        goto end_ar_command;
7075      }
7076      sqlite3_fileio_init(cmd.db, 0, 0);
7077      sqlite3_sqlar_init(cmd.db, 0, 0);
7078      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7079                              shellPutsFunc, 0, 0);
7080
7081    }
7082    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7083      if( cmd.eCmd!=AR_CMD_CREATE
7084       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7085      ){
7086        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7087        rc = SQLITE_ERROR;
7088        goto end_ar_command;
7089      }
7090      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7091    }
7092
7093    switch( cmd.eCmd ){
7094      case AR_CMD_CREATE:
7095        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7096        break;
7097
7098      case AR_CMD_EXTRACT:
7099        rc = arExtractCommand(&cmd);
7100        break;
7101
7102      case AR_CMD_LIST:
7103        rc = arListCommand(&cmd);
7104        break;
7105
7106      case AR_CMD_HELP:
7107        arUsage(pState->out);
7108        break;
7109
7110      case AR_CMD_INSERT:
7111        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7112        break;
7113
7114      case AR_CMD_REMOVE:
7115        rc = arRemoveCommand(&cmd);
7116        break;
7117
7118      default:
7119        assert( cmd.eCmd==AR_CMD_UPDATE );
7120        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7121        break;
7122    }
7123  }
7124end_ar_command:
7125  if( cmd.db!=pState->db ){
7126    close_db(cmd.db);
7127  }
7128  sqlite3_free(cmd.zSrcTable);
7129
7130  return rc;
7131}
7132/* End of the ".archive" or ".ar" command logic
7133*******************************************************************************/
7134#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7135
7136#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7137/*
7138** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7139** Otherwise, the SQL statement or statements in zSql are executed using
7140** database connection db and the error code written to *pRc before
7141** this function returns.
7142*/
7143static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7144  int rc = *pRc;
7145  if( rc==SQLITE_OK ){
7146    char *zErr = 0;
7147    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7148    if( rc!=SQLITE_OK ){
7149      raw_printf(stderr, "SQL error: %s\n", zErr);
7150    }
7151    sqlite3_free(zErr);
7152    *pRc = rc;
7153  }
7154}
7155
7156/*
7157** Like shellExec(), except that zFmt is a printf() style format string.
7158*/
7159static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7160  char *z = 0;
7161  if( *pRc==SQLITE_OK ){
7162    va_list ap;
7163    va_start(ap, zFmt);
7164    z = sqlite3_vmprintf(zFmt, ap);
7165    va_end(ap);
7166    if( z==0 ){
7167      *pRc = SQLITE_NOMEM;
7168    }else{
7169      shellExec(db, pRc, z);
7170    }
7171    sqlite3_free(z);
7172  }
7173}
7174
7175/*
7176** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7177** Otherwise, an attempt is made to allocate, zero and return a pointer
7178** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7179** to SQLITE_NOMEM and NULL returned.
7180*/
7181static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7182  void *pRet = 0;
7183  if( *pRc==SQLITE_OK ){
7184    pRet = sqlite3_malloc64(nByte);
7185    if( pRet==0 ){
7186      *pRc = SQLITE_NOMEM;
7187    }else{
7188      memset(pRet, 0, nByte);
7189    }
7190  }
7191  return pRet;
7192}
7193
7194/*
7195** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7196** Otherwise, zFmt is treated as a printf() style string. The result of
7197** formatting it along with any trailing arguments is written into a
7198** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7199** It is the responsibility of the caller to eventually free this buffer
7200** using a call to sqlite3_free().
7201**
7202** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7203** pointer returned.
7204*/
7205static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7206  char *z = 0;
7207  if( *pRc==SQLITE_OK ){
7208    va_list ap;
7209    va_start(ap, zFmt);
7210    z = sqlite3_vmprintf(zFmt, ap);
7211    va_end(ap);
7212    if( z==0 ){
7213      *pRc = SQLITE_NOMEM;
7214    }
7215  }
7216  return z;
7217}
7218
7219/*
7220** When running the ".recover" command, each output table, and the special
7221** orphaned row table if it is required, is represented by an instance
7222** of the following struct.
7223*/
7224typedef struct RecoverTable RecoverTable;
7225struct RecoverTable {
7226  char *zQuoted;                  /* Quoted version of table name */
7227  int nCol;                       /* Number of columns in table */
7228  char **azlCol;                  /* Array of column lists */
7229  int iPk;                        /* Index of IPK column */
7230};
7231
7232/*
7233** Free a RecoverTable object allocated by recoverFindTable() or
7234** recoverOrphanTable().
7235*/
7236static void recoverFreeTable(RecoverTable *pTab){
7237  if( pTab ){
7238    sqlite3_free(pTab->zQuoted);
7239    if( pTab->azlCol ){
7240      int i;
7241      for(i=0; i<=pTab->nCol; i++){
7242        sqlite3_free(pTab->azlCol[i]);
7243      }
7244      sqlite3_free(pTab->azlCol);
7245    }
7246    sqlite3_free(pTab);
7247  }
7248}
7249
7250/*
7251** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7252** Otherwise, it allocates and returns a RecoverTable object based on the
7253** final four arguments passed to this function. It is the responsibility
7254** of the caller to eventually free the returned object using
7255** recoverFreeTable().
7256*/
7257static RecoverTable *recoverNewTable(
7258  int *pRc,                       /* IN/OUT: Error code */
7259  const char *zName,              /* Name of table */
7260  const char *zSql,               /* CREATE TABLE statement */
7261  int bIntkey,
7262  int nCol
7263){
7264  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7265  int rc = *pRc;
7266  RecoverTable *pTab = 0;
7267
7268  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7269  if( rc==SQLITE_OK ){
7270    int nSqlCol = 0;
7271    int bSqlIntkey = 0;
7272    sqlite3_stmt *pStmt = 0;
7273
7274    rc = sqlite3_open("", &dbtmp);
7275    if( rc==SQLITE_OK ){
7276      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7277                              shellIdQuote, 0, 0);
7278    }
7279    if( rc==SQLITE_OK ){
7280      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7281    }
7282    if( rc==SQLITE_OK ){
7283      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7284      if( rc==SQLITE_ERROR ){
7285        rc = SQLITE_OK;
7286        goto finished;
7287      }
7288    }
7289    shellPreparePrintf(dbtmp, &rc, &pStmt,
7290        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7291    );
7292    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7293      nSqlCol = sqlite3_column_int(pStmt, 0);
7294    }
7295    shellFinalize(&rc, pStmt);
7296
7297    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7298      goto finished;
7299    }
7300
7301    shellPreparePrintf(dbtmp, &rc, &pStmt,
7302      "SELECT ("
7303      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7304      ") FROM sqlite_schema WHERE name = %Q", zName
7305    );
7306    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7307      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7308    }
7309    shellFinalize(&rc, pStmt);
7310
7311    if( bIntkey==bSqlIntkey ){
7312      int i;
7313      const char *zPk = "_rowid_";
7314      sqlite3_stmt *pPkFinder = 0;
7315
7316      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7317      ** set zPk to the name of the PK column, and pTab->iPk to the index
7318      ** of the column, where columns are 0-numbered from left to right.
7319      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7320      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7321      pTab->iPk = -2;
7322      if( bIntkey ){
7323        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7324          "SELECT cid, name FROM pragma_table_info(%Q) "
7325          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7326          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7327          , zName, zName
7328        );
7329        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7330          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7331          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7332          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7333        }
7334      }
7335
7336      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7337      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7338      pTab->nCol = nSqlCol;
7339
7340      if( bIntkey ){
7341        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7342      }else{
7343        pTab->azlCol[0] = shellMPrintf(&rc, "");
7344      }
7345      i = 1;
7346      shellPreparePrintf(dbtmp, &rc, &pStmt,
7347          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7348          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7349          "FROM pragma_table_info(%Q)",
7350          bIntkey ? ", " : "", pTab->iPk,
7351          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7352          zName
7353      );
7354      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7355        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7356        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7357        i++;
7358      }
7359      shellFinalize(&rc, pStmt);
7360
7361      shellFinalize(&rc, pPkFinder);
7362    }
7363  }
7364
7365 finished:
7366  sqlite3_close(dbtmp);
7367  *pRc = rc;
7368  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7369    recoverFreeTable(pTab);
7370    pTab = 0;
7371  }
7372  return pTab;
7373}
7374
7375/*
7376** This function is called to search the schema recovered from the
7377** sqlite_schema table of the (possibly) corrupt database as part
7378** of a ".recover" command. Specifically, for a table with root page
7379** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7380** table must be a WITHOUT ROWID table, or if non-zero, not one of
7381** those.
7382**
7383** If a table is found, a (RecoverTable*) object is returned. Or, if
7384** no such table is found, but bIntkey is false and iRoot is the
7385** root page of an index in the recovered schema, then (*pbNoop) is
7386** set to true and NULL returned. Or, if there is no such table or
7387** index, NULL is returned and (*pbNoop) set to 0, indicating that
7388** the caller should write data to the orphans table.
7389*/
7390static RecoverTable *recoverFindTable(
7391  ShellState *pState,             /* Shell state object */
7392  int *pRc,                       /* IN/OUT: Error code */
7393  int iRoot,                      /* Root page of table */
7394  int bIntkey,                    /* True for an intkey table */
7395  int nCol,                       /* Number of columns in table */
7396  int *pbNoop                     /* OUT: True if iRoot is root of index */
7397){
7398  sqlite3_stmt *pStmt = 0;
7399  RecoverTable *pRet = 0;
7400  int bNoop = 0;
7401  const char *zSql = 0;
7402  const char *zName = 0;
7403
7404  /* Search the recovered schema for an object with root page iRoot. */
7405  shellPreparePrintf(pState->db, pRc, &pStmt,
7406      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7407  );
7408  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7409    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7410    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7411      bNoop = 1;
7412      break;
7413    }
7414    if( sqlite3_stricmp(zType, "table")==0 ){
7415      zName = (const char*)sqlite3_column_text(pStmt, 1);
7416      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7417      if( zName!=0 && zSql!=0 ){
7418        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7419        break;
7420      }
7421    }
7422  }
7423
7424  shellFinalize(pRc, pStmt);
7425  *pbNoop = bNoop;
7426  return pRet;
7427}
7428
7429/*
7430** Return a RecoverTable object representing the orphans table.
7431*/
7432static RecoverTable *recoverOrphanTable(
7433  ShellState *pState,             /* Shell state object */
7434  int *pRc,                       /* IN/OUT: Error code */
7435  const char *zLostAndFound,      /* Base name for orphans table */
7436  int nCol                        /* Number of user data columns */
7437){
7438  RecoverTable *pTab = 0;
7439  if( nCol>=0 && *pRc==SQLITE_OK ){
7440    int i;
7441
7442    /* This block determines the name of the orphan table. The prefered
7443    ** name is zLostAndFound. But if that clashes with another name
7444    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7445    ** and so on until a non-clashing name is found.  */
7446    int iTab = 0;
7447    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7448    sqlite3_stmt *pTest = 0;
7449    shellPrepare(pState->db, pRc,
7450        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7451    );
7452    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7453    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7454      shellReset(pRc, pTest);
7455      sqlite3_free(zTab);
7456      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7457      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7458    }
7459    shellFinalize(pRc, pTest);
7460
7461    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7462    if( pTab ){
7463      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7464      pTab->nCol = nCol;
7465      pTab->iPk = -2;
7466      if( nCol>0 ){
7467        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7468        if( pTab->azlCol ){
7469          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7470          for(i=nCol-1; i>=0; i--){
7471            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7472          }
7473        }
7474      }
7475
7476      if( *pRc!=SQLITE_OK ){
7477        recoverFreeTable(pTab);
7478        pTab = 0;
7479      }else{
7480        raw_printf(pState->out,
7481            "CREATE TABLE %s(rootpgno INTEGER, "
7482            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7483        );
7484        for(i=0; i<nCol; i++){
7485          raw_printf(pState->out, ", c%d", i);
7486        }
7487        raw_printf(pState->out, ");\n");
7488      }
7489    }
7490    sqlite3_free(zTab);
7491  }
7492  return pTab;
7493}
7494
7495/*
7496** This function is called to recover data from the database. A script
7497** to construct a new database containing all recovered data is output
7498** on stream pState->out.
7499*/
7500static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7501  int rc = SQLITE_OK;
7502  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7503  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7504  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7505  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7506  const char *zLostAndFound = "lost_and_found";
7507  int i;
7508  int nOrphan = -1;
7509  RecoverTable *pOrphan = 0;
7510
7511  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7512  int bRowids = 1;                /* 0 if --no-rowids */
7513  for(i=1; i<nArg; i++){
7514    char *z = azArg[i];
7515    int n;
7516    if( z[0]=='-' && z[1]=='-' ) z++;
7517    n = strlen30(z);
7518    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7519      bFreelist = 0;
7520    }else
7521    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7522      i++;
7523      zRecoveryDb = azArg[i];
7524    }else
7525    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7526      i++;
7527      zLostAndFound = azArg[i];
7528    }else
7529    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7530      bRowids = 0;
7531    }
7532    else{
7533      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7534      showHelp(pState->out, azArg[0]);
7535      return 1;
7536    }
7537  }
7538
7539  shellExecPrintf(pState->db, &rc,
7540    /* Attach an in-memory database named 'recovery'. Create an indexed
7541    ** cache of the sqlite_dbptr virtual table. */
7542    "PRAGMA writable_schema = on;"
7543    "ATTACH %Q AS recovery;"
7544    "DROP TABLE IF EXISTS recovery.dbptr;"
7545    "DROP TABLE IF EXISTS recovery.freelist;"
7546    "DROP TABLE IF EXISTS recovery.map;"
7547    "DROP TABLE IF EXISTS recovery.schema;"
7548    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7549  );
7550
7551  if( bFreelist ){
7552    shellExec(pState->db, &rc,
7553      "WITH trunk(pgno) AS ("
7554      "  SELECT shell_int32("
7555      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7556      "      WHERE x>0"
7557      "    UNION"
7558      "  SELECT shell_int32("
7559      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7560      "      FROM trunk WHERE x>0"
7561      "),"
7562      "freelist(data, n, freepgno) AS ("
7563      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7564      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7565      "    UNION ALL"
7566      "  SELECT data, n-1, shell_int32(data, 2+n) "
7567      "      FROM freelist WHERE n>=0"
7568      ")"
7569      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7570    );
7571  }
7572
7573  /* If this is an auto-vacuum database, add all pointer-map pages to
7574  ** the freelist table. Do this regardless of whether or not
7575  ** --freelist-corrupt was specified.  */
7576  shellExec(pState->db, &rc,
7577    "WITH ptrmap(pgno) AS ("
7578    "  SELECT 2 WHERE shell_int32("
7579    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7580    "  )"
7581    "    UNION ALL "
7582    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7583    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7584    ")"
7585    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7586  );
7587
7588  shellExec(pState->db, &rc,
7589    "CREATE TABLE recovery.dbptr("
7590    "      pgno, child, PRIMARY KEY(child, pgno)"
7591    ") WITHOUT ROWID;"
7592    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7593    "    SELECT * FROM sqlite_dbptr"
7594    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7595
7596    /* Delete any pointer to page 1. This ensures that page 1 is considered
7597    ** a root page, regardless of how corrupt the db is. */
7598    "DELETE FROM recovery.dbptr WHERE child = 1;"
7599
7600    /* Delete all pointers to any pages that have more than one pointer
7601    ** to them. Such pages will be treated as root pages when recovering
7602    ** data.  */
7603    "DELETE FROM recovery.dbptr WHERE child IN ("
7604    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7605    ");"
7606
7607    /* Create the "map" table that will (eventually) contain instructions
7608    ** for dealing with each page in the db that contains one or more
7609    ** records. */
7610    "CREATE TABLE recovery.map("
7611      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7612    ");"
7613
7614    /* Populate table [map]. If there are circular loops of pages in the
7615    ** database, the following adds all pages in such a loop to the map
7616    ** as individual root pages. This could be handled better.  */
7617    "WITH pages(i, maxlen) AS ("
7618    "  SELECT page_count, ("
7619    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7620    "  ) FROM pragma_page_count WHERE page_count>0"
7621    "    UNION ALL"
7622    "  SELECT i-1, ("
7623    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7624    "  ) FROM pages WHERE i>=2"
7625    ")"
7626    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7627    "  SELECT i, maxlen, NULL, ("
7628    "    WITH p(orig, pgno, parent) AS ("
7629    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7630    "        UNION "
7631    "      SELECT i, p.parent, "
7632    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7633    "    )"
7634    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7635    ") "
7636    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7637    "UPDATE recovery.map AS o SET intkey = ("
7638    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7639    ");"
7640
7641    /* Extract data from page 1 and any linked pages into table
7642    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7643    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7644    "INSERT INTO recovery.schema SELECT "
7645    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7646    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7647    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7648    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7649    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7650    "FROM sqlite_dbdata WHERE pgno IN ("
7651    "  SELECT pgno FROM recovery.map WHERE root=1"
7652    ")"
7653    "GROUP BY pgno, cell;"
7654    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7655  );
7656
7657  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7658  ** CREATE TABLE statements that extracted from the existing schema.  */
7659  if( rc==SQLITE_OK ){
7660    sqlite3_stmt *pStmt = 0;
7661    /* ".recover" might output content in an order which causes immediate
7662    ** foreign key constraints to be violated. So disable foreign-key
7663    ** constraint enforcement to prevent problems when running the output
7664    ** script. */
7665    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7666    raw_printf(pState->out, "BEGIN;\n");
7667    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7668    shellPrepare(pState->db, &rc,
7669        "SELECT sql FROM recovery.schema "
7670        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7671    );
7672    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7673      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7674      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7675          &zCreateTable[12]
7676      );
7677    }
7678    shellFinalize(&rc, pStmt);
7679  }
7680
7681  /* Figure out if an orphan table will be required. And if so, how many
7682  ** user columns it should contain */
7683  shellPrepare(pState->db, &rc,
7684      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7685      , &pLoop
7686  );
7687  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7688    nOrphan = sqlite3_column_int(pLoop, 0);
7689  }
7690  shellFinalize(&rc, pLoop);
7691  pLoop = 0;
7692
7693  shellPrepare(pState->db, &rc,
7694      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7695  );
7696
7697  shellPrepare(pState->db, &rc,
7698      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7699      "(case when (? AND field<0) then NULL else value end)"
7700      "), ', ')"
7701      ", min(field) "
7702      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7703      "GROUP BY cell", &pCells
7704  );
7705
7706  /* Loop through each root page. */
7707  shellPrepare(pState->db, &rc,
7708      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7709      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7710      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7711      ")", &pLoop
7712  );
7713  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7714    int iRoot = sqlite3_column_int(pLoop, 0);
7715    int bIntkey = sqlite3_column_int(pLoop, 1);
7716    int nCol = sqlite3_column_int(pLoop, 2);
7717    int bNoop = 0;
7718    RecoverTable *pTab;
7719
7720    assert( bIntkey==0 || bIntkey==1 );
7721    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7722    if( bNoop || rc ) continue;
7723    if( pTab==0 ){
7724      if( pOrphan==0 ){
7725        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7726      }
7727      pTab = pOrphan;
7728      if( pTab==0 ) break;
7729    }
7730
7731    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7732      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7733    }
7734    sqlite3_bind_int(pPages, 1, iRoot);
7735    if( bRowids==0 && pTab->iPk<0 ){
7736      sqlite3_bind_int(pCells, 1, 1);
7737    }else{
7738      sqlite3_bind_int(pCells, 1, 0);
7739    }
7740    sqlite3_bind_int(pCells, 3, pTab->iPk);
7741
7742    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7743      int iPgno = sqlite3_column_int(pPages, 0);
7744      sqlite3_bind_int(pCells, 2, iPgno);
7745      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7746        int nField = sqlite3_column_int(pCells, 0);
7747        int iMin = sqlite3_column_int(pCells, 2);
7748        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7749
7750        RecoverTable *pTab2 = pTab;
7751        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7752          if( pOrphan==0 ){
7753            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7754          }
7755          pTab2 = pOrphan;
7756          if( pTab2==0 ) break;
7757        }
7758
7759        nField = nField+1;
7760        if( pTab2==pOrphan ){
7761          raw_printf(pState->out,
7762              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7763              pTab2->zQuoted, iRoot, iPgno, nField,
7764              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7765          );
7766        }else{
7767          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7768              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7769          );
7770        }
7771      }
7772      shellReset(&rc, pCells);
7773    }
7774    shellReset(&rc, pPages);
7775    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7776  }
7777  shellFinalize(&rc, pLoop);
7778  shellFinalize(&rc, pPages);
7779  shellFinalize(&rc, pCells);
7780  recoverFreeTable(pOrphan);
7781
7782  /* The rest of the schema */
7783  if( rc==SQLITE_OK ){
7784    sqlite3_stmt *pStmt = 0;
7785    shellPrepare(pState->db, &rc,
7786        "SELECT sql, name FROM recovery.schema "
7787        "WHERE sql NOT LIKE 'create table%'", &pStmt
7788    );
7789    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7790      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7791      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7792        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7793        char *zPrint = shellMPrintf(&rc,
7794          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7795          zName, zName, zSql
7796        );
7797        raw_printf(pState->out, "%s;\n", zPrint);
7798        sqlite3_free(zPrint);
7799      }else{
7800        raw_printf(pState->out, "%s;\n", zSql);
7801      }
7802    }
7803    shellFinalize(&rc, pStmt);
7804  }
7805
7806  if( rc==SQLITE_OK ){
7807    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7808    raw_printf(pState->out, "COMMIT;\n");
7809  }
7810  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7811  return rc;
7812}
7813#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7814
7815/*
7816** If an input line begins with "." then invoke this routine to
7817** process that line.
7818**
7819** Return 1 on error, 2 to exit, and 0 otherwise.
7820*/
7821static int do_meta_command(char *zLine, ShellState *p){
7822  int h = 1;
7823  int nArg = 0;
7824  int n, c;
7825  int rc = 0;
7826  char *azArg[52];
7827
7828#ifndef SQLITE_OMIT_VIRTUALTABLE
7829  if( p->expert.pExpert ){
7830    expertFinish(p, 1, 0);
7831  }
7832#endif
7833
7834  /* Parse the input line into tokens.
7835  */
7836  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7837    while( IsSpace(zLine[h]) ){ h++; }
7838    if( zLine[h]==0 ) break;
7839    if( zLine[h]=='\'' || zLine[h]=='"' ){
7840      int delim = zLine[h++];
7841      azArg[nArg++] = &zLine[h];
7842      while( zLine[h] && zLine[h]!=delim ){
7843        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7844        h++;
7845      }
7846      if( zLine[h]==delim ){
7847        zLine[h++] = 0;
7848      }
7849      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7850    }else{
7851      azArg[nArg++] = &zLine[h];
7852      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7853      if( zLine[h] ) zLine[h++] = 0;
7854      resolve_backslashes(azArg[nArg-1]);
7855    }
7856  }
7857  azArg[nArg] = 0;
7858
7859  /* Process the input line.
7860  */
7861  if( nArg==0 ) return 0; /* no tokens, no error */
7862  n = strlen30(azArg[0]);
7863  c = azArg[0][0];
7864  clearTempFile(p);
7865
7866#ifndef SQLITE_OMIT_AUTHORIZATION
7867  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7868    if( nArg!=2 ){
7869      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7870      rc = 1;
7871      goto meta_command_exit;
7872    }
7873    open_db(p, 0);
7874    if( booleanValue(azArg[1]) ){
7875      sqlite3_set_authorizer(p->db, shellAuth, p);
7876    }else if( p->bSafeModePersist ){
7877      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7878    }else{
7879      sqlite3_set_authorizer(p->db, 0, 0);
7880    }
7881  }else
7882#endif
7883
7884#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7885  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7886    open_db(p, 0);
7887    failIfSafeMode(p, "cannot run .archive in safe mode");
7888    rc = arDotCommand(p, 0, azArg, nArg);
7889  }else
7890#endif
7891
7892  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7893   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7894  ){
7895    const char *zDestFile = 0;
7896    const char *zDb = 0;
7897    sqlite3 *pDest;
7898    sqlite3_backup *pBackup;
7899    int j;
7900    int bAsync = 0;
7901    const char *zVfs = 0;
7902    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7903    for(j=1; j<nArg; j++){
7904      const char *z = azArg[j];
7905      if( z[0]=='-' ){
7906        if( z[1]=='-' ) z++;
7907        if( strcmp(z, "-append")==0 ){
7908          zVfs = "apndvfs";
7909        }else
7910        if( strcmp(z, "-async")==0 ){
7911          bAsync = 1;
7912        }else
7913        {
7914          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7915          return 1;
7916        }
7917      }else if( zDestFile==0 ){
7918        zDestFile = azArg[j];
7919      }else if( zDb==0 ){
7920        zDb = zDestFile;
7921        zDestFile = azArg[j];
7922      }else{
7923        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7924        return 1;
7925      }
7926    }
7927    if( zDestFile==0 ){
7928      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7929      return 1;
7930    }
7931    if( zDb==0 ) zDb = "main";
7932    rc = sqlite3_open_v2(zDestFile, &pDest,
7933                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7934    if( rc!=SQLITE_OK ){
7935      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7936      close_db(pDest);
7937      return 1;
7938    }
7939    if( bAsync ){
7940      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7941                   0, 0, 0);
7942    }
7943    open_db(p, 0);
7944    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7945    if( pBackup==0 ){
7946      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7947      close_db(pDest);
7948      return 1;
7949    }
7950    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7951    sqlite3_backup_finish(pBackup);
7952    if( rc==SQLITE_DONE ){
7953      rc = 0;
7954    }else{
7955      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7956      rc = 1;
7957    }
7958    close_db(pDest);
7959  }else
7960
7961  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7962    if( nArg==2 ){
7963      bail_on_error = booleanValue(azArg[1]);
7964    }else{
7965      raw_printf(stderr, "Usage: .bail on|off\n");
7966      rc = 1;
7967    }
7968  }else
7969
7970  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7971    if( nArg==2 ){
7972      if( booleanValue(azArg[1]) ){
7973        setBinaryMode(p->out, 1);
7974      }else{
7975        setTextMode(p->out, 1);
7976      }
7977    }else{
7978      raw_printf(stderr, "Usage: .binary on|off\n");
7979      rc = 1;
7980    }
7981  }else
7982
7983  /* The undocumented ".breakpoint" command causes a call to the no-op
7984  ** routine named test_breakpoint().
7985  */
7986  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7987    test_breakpoint();
7988  }else
7989
7990  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7991    failIfSafeMode(p, "cannot run .cd in safe mode");
7992    if( nArg==2 ){
7993#if defined(_WIN32) || defined(WIN32)
7994      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7995      rc = !SetCurrentDirectoryW(z);
7996      sqlite3_free(z);
7997#else
7998      rc = chdir(azArg[1]);
7999#endif
8000      if( rc ){
8001        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8002        rc = 1;
8003      }
8004    }else{
8005      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8006      rc = 1;
8007    }
8008  }else
8009
8010  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8011    if( nArg==2 ){
8012      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8013    }else{
8014      raw_printf(stderr, "Usage: .changes on|off\n");
8015      rc = 1;
8016    }
8017  }else
8018
8019  /* Cancel output redirection, if it is currently set (by .testcase)
8020  ** Then read the content of the testcase-out.txt file and compare against
8021  ** azArg[1].  If there are differences, report an error and exit.
8022  */
8023  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8024    char *zRes = 0;
8025    output_reset(p);
8026    if( nArg!=2 ){
8027      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8028      rc = 2;
8029    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8030      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8031      rc = 2;
8032    }else if( testcase_glob(azArg[1],zRes)==0 ){
8033      utf8_printf(stderr,
8034                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8035                 p->zTestcase, azArg[1], zRes);
8036      rc = 1;
8037    }else{
8038      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8039      p->nCheck++;
8040    }
8041    sqlite3_free(zRes);
8042  }else
8043
8044  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8045    failIfSafeMode(p, "cannot run .clone in safe mode");
8046    if( nArg==2 ){
8047      tryToClone(p, azArg[1]);
8048    }else{
8049      raw_printf(stderr, "Usage: .clone FILENAME\n");
8050      rc = 1;
8051    }
8052  }else
8053
8054  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8055    if( nArg==1 ){
8056      /* List available connections */
8057      int i;
8058      for(i=0; i<ArraySize(p->aAuxDb); i++){
8059        const char *zFile = p->aAuxDb[i].zDbFilename;
8060        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8061          zFile = "(not open)";
8062        }else if( zFile==0 ){
8063          zFile = "(memory)";
8064        }else if( zFile[0]==0 ){
8065          zFile = "(temporary-file)";
8066        }
8067        if( p->pAuxDb == &p->aAuxDb[i] ){
8068          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8069        }else if( p->aAuxDb[i].db!=0 ){
8070          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8071        }
8072      }
8073    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8074      int i = azArg[1][0] - '0';
8075      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8076        p->pAuxDb->db = p->db;
8077        p->pAuxDb = &p->aAuxDb[i];
8078        globalDb = p->db = p->pAuxDb->db;
8079        p->pAuxDb->db = 0;
8080      }
8081    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8082           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8083      int i = azArg[2][0] - '0';
8084      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8085        /* No-op */
8086      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8087        raw_printf(stderr, "cannot close the active database connection\n");
8088        rc = 1;
8089      }else if( p->aAuxDb[i].db ){
8090        session_close_all(p, i);
8091        close_db(p->aAuxDb[i].db);
8092        p->aAuxDb[i].db = 0;
8093      }
8094    }else{
8095      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8096      rc = 1;
8097    }
8098  }else
8099
8100  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8101    char **azName = 0;
8102    int nName = 0;
8103    sqlite3_stmt *pStmt;
8104    int i;
8105    open_db(p, 0);
8106    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8107    if( rc ){
8108      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8109      rc = 1;
8110    }else{
8111      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8112        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8113        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8114        if( zSchema==0 || zFile==0 ) continue;
8115        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8116        shell_check_oom(azName);
8117        azName[nName*2] = strdup(zSchema);
8118        azName[nName*2+1] = strdup(zFile);
8119        nName++;
8120      }
8121    }
8122    sqlite3_finalize(pStmt);
8123    for(i=0; i<nName; i++){
8124      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8125      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8126      const char *z = azName[i*2+1];
8127      utf8_printf(p->out, "%s: %s %s%s\n",
8128         azName[i*2],
8129         z && z[0] ? z : "\"\"",
8130         bRdonly ? "r/o" : "r/w",
8131         eTxn==SQLITE_TXN_NONE ? "" :
8132            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8133      free(azName[i*2]);
8134      free(azName[i*2+1]);
8135    }
8136    sqlite3_free(azName);
8137  }else
8138
8139  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8140    static const struct DbConfigChoices {
8141      const char *zName;
8142      int op;
8143    } aDbConfig[] = {
8144        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8145        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8146        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8147        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8148        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8149        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8150        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8151        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8152        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8153        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8154        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8155        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8156        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8157        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8158        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8159        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8160    };
8161    int ii, v;
8162    open_db(p, 0);
8163    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8164      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8165      if( nArg>=3 ){
8166        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8167      }
8168      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8169      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8170      if( nArg>1 ) break;
8171    }
8172    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8173      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8174      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8175    }
8176  }else
8177
8178  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8179    rc = shell_dbinfo_command(p, nArg, azArg);
8180  }else
8181
8182#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8183  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8184    open_db(p, 0);
8185    rc = recoverDatabaseCmd(p, nArg, azArg);
8186  }else
8187#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8188
8189  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8190    char *zLike = 0;
8191    char *zSql;
8192    int i;
8193    int savedShowHeader = p->showHeader;
8194    int savedShellFlags = p->shellFlgs;
8195    ShellClearFlag(p,
8196       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8197       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8198    for(i=1; i<nArg; i++){
8199      if( azArg[i][0]=='-' ){
8200        const char *z = azArg[i]+1;
8201        if( z[0]=='-' ) z++;
8202        if( strcmp(z,"preserve-rowids")==0 ){
8203#ifdef SQLITE_OMIT_VIRTUALTABLE
8204          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8205                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8206          rc = 1;
8207          sqlite3_free(zLike);
8208          goto meta_command_exit;
8209#else
8210          ShellSetFlag(p, SHFLG_PreserveRowid);
8211#endif
8212        }else
8213        if( strcmp(z,"newlines")==0 ){
8214          ShellSetFlag(p, SHFLG_Newlines);
8215        }else
8216        if( strcmp(z,"data-only")==0 ){
8217          ShellSetFlag(p, SHFLG_DumpDataOnly);
8218        }else
8219        if( strcmp(z,"nosys")==0 ){
8220          ShellSetFlag(p, SHFLG_DumpNoSys);
8221        }else
8222        {
8223          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8224          rc = 1;
8225          sqlite3_free(zLike);
8226          goto meta_command_exit;
8227        }
8228      }else{
8229        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8230        ** only dump data for tables for which either the table name matches
8231        ** the LIKE pattern, or the table appears to be a shadow table of
8232        ** a virtual table for which the name matches the LIKE pattern.
8233        */
8234        char *zExpr = sqlite3_mprintf(
8235            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8236            "  SELECT 1 FROM sqlite_schema WHERE "
8237            "    name LIKE %Q ESCAPE '\\' AND"
8238            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8239            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8240            ")", azArg[i], azArg[i]
8241        );
8242
8243        if( zLike ){
8244          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8245        }else{
8246          zLike = zExpr;
8247        }
8248      }
8249    }
8250
8251    open_db(p, 0);
8252
8253    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8254      /* When playing back a "dump", the content might appear in an order
8255      ** which causes immediate foreign key constraints to be violated.
8256      ** So disable foreign-key constraint enforcement to prevent problems. */
8257      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8258      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8259    }
8260    p->writableSchema = 0;
8261    p->showHeader = 0;
8262    /* Set writable_schema=ON since doing so forces SQLite to initialize
8263    ** as much of the schema as it can even if the sqlite_schema table is
8264    ** corrupt. */
8265    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8266    p->nErr = 0;
8267    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8268    zSql = sqlite3_mprintf(
8269      "SELECT name, type, sql FROM sqlite_schema AS o "
8270      "WHERE (%s) AND type=='table'"
8271      "  AND sql NOT NULL"
8272      " ORDER BY tbl_name='sqlite_sequence', rowid",
8273      zLike
8274    );
8275    run_schema_dump_query(p,zSql);
8276    sqlite3_free(zSql);
8277    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8278      zSql = sqlite3_mprintf(
8279        "SELECT sql FROM sqlite_schema AS o "
8280        "WHERE (%s) AND sql NOT NULL"
8281        "  AND type IN ('index','trigger','view')",
8282        zLike
8283      );
8284      run_table_dump_query(p, zSql);
8285      sqlite3_free(zSql);
8286    }
8287    sqlite3_free(zLike);
8288    if( p->writableSchema ){
8289      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8290      p->writableSchema = 0;
8291    }
8292    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8293    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8294    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8295      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8296    }
8297    p->showHeader = savedShowHeader;
8298    p->shellFlgs = savedShellFlags;
8299  }else
8300
8301  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8302    if( nArg==2 ){
8303      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8304    }else{
8305      raw_printf(stderr, "Usage: .echo on|off\n");
8306      rc = 1;
8307    }
8308  }else
8309
8310  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8311    if( nArg==2 ){
8312      p->autoEQPtest = 0;
8313      if( p->autoEQPtrace ){
8314        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8315        p->autoEQPtrace = 0;
8316      }
8317      if( strcmp(azArg[1],"full")==0 ){
8318        p->autoEQP = AUTOEQP_full;
8319      }else if( strcmp(azArg[1],"trigger")==0 ){
8320        p->autoEQP = AUTOEQP_trigger;
8321#ifdef SQLITE_DEBUG
8322      }else if( strcmp(azArg[1],"test")==0 ){
8323        p->autoEQP = AUTOEQP_on;
8324        p->autoEQPtest = 1;
8325      }else if( strcmp(azArg[1],"trace")==0 ){
8326        p->autoEQP = AUTOEQP_full;
8327        p->autoEQPtrace = 1;
8328        open_db(p, 0);
8329        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8330        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8331#endif
8332      }else{
8333        p->autoEQP = (u8)booleanValue(azArg[1]);
8334      }
8335    }else{
8336      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8337      rc = 1;
8338    }
8339  }else
8340
8341  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8342    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8343    rc = 2;
8344  }else
8345
8346  /* The ".explain" command is automatic now.  It is largely pointless.  It
8347  ** retained purely for backwards compatibility */
8348  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8349    int val = 1;
8350    if( nArg>=2 ){
8351      if( strcmp(azArg[1],"auto")==0 ){
8352        val = 99;
8353      }else{
8354        val =  booleanValue(azArg[1]);
8355      }
8356    }
8357    if( val==1 && p->mode!=MODE_Explain ){
8358      p->normalMode = p->mode;
8359      p->mode = MODE_Explain;
8360      p->autoExplain = 0;
8361    }else if( val==0 ){
8362      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8363      p->autoExplain = 0;
8364    }else if( val==99 ){
8365      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8366      p->autoExplain = 1;
8367    }
8368  }else
8369
8370#ifndef SQLITE_OMIT_VIRTUALTABLE
8371  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8372    if( p->bSafeMode ){
8373      raw_printf(stderr,
8374        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8375        azArg[0]);
8376      rc = 1;
8377    }else{
8378      open_db(p, 0);
8379      expertDotCommand(p, azArg, nArg);
8380    }
8381  }else
8382#endif
8383
8384  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8385    static const struct {
8386       const char *zCtrlName;   /* Name of a test-control option */
8387       int ctrlCode;            /* Integer code for that option */
8388       const char *zUsage;      /* Usage notes */
8389    } aCtrl[] = {
8390      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8391      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8392      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8393      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8394      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8395   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8396      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8397      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8398      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8399      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8400   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8401    };
8402    int filectrl = -1;
8403    int iCtrl = -1;
8404    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8405    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8406    int n2, i;
8407    const char *zCmd = 0;
8408    const char *zSchema = 0;
8409
8410    open_db(p, 0);
8411    zCmd = nArg>=2 ? azArg[1] : "help";
8412
8413    if( zCmd[0]=='-'
8414     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8415     && nArg>=4
8416    ){
8417      zSchema = azArg[2];
8418      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8419      nArg -= 2;
8420      zCmd = azArg[1];
8421    }
8422
8423    /* The argument can optionally begin with "-" or "--" */
8424    if( zCmd[0]=='-' && zCmd[1] ){
8425      zCmd++;
8426      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8427    }
8428
8429    /* --help lists all file-controls */
8430    if( strcmp(zCmd,"help")==0 ){
8431      utf8_printf(p->out, "Available file-controls:\n");
8432      for(i=0; i<ArraySize(aCtrl); i++){
8433        utf8_printf(p->out, "  .filectrl %s %s\n",
8434                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8435      }
8436      rc = 1;
8437      goto meta_command_exit;
8438    }
8439
8440    /* convert filectrl text option to value. allow any unique prefix
8441    ** of the option name, or a numerical value. */
8442    n2 = strlen30(zCmd);
8443    for(i=0; i<ArraySize(aCtrl); i++){
8444      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8445        if( filectrl<0 ){
8446          filectrl = aCtrl[i].ctrlCode;
8447          iCtrl = i;
8448        }else{
8449          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8450                              "Use \".filectrl --help\" for help\n", zCmd);
8451          rc = 1;
8452          goto meta_command_exit;
8453        }
8454      }
8455    }
8456    if( filectrl<0 ){
8457      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8458                         "Use \".filectrl --help\" for help\n", zCmd);
8459    }else{
8460      switch(filectrl){
8461        case SQLITE_FCNTL_SIZE_LIMIT: {
8462          if( nArg!=2 && nArg!=3 ) break;
8463          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8464          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8465          isOk = 1;
8466          break;
8467        }
8468        case SQLITE_FCNTL_LOCK_TIMEOUT:
8469        case SQLITE_FCNTL_CHUNK_SIZE: {
8470          int x;
8471          if( nArg!=3 ) break;
8472          x = (int)integerValue(azArg[2]);
8473          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8474          isOk = 2;
8475          break;
8476        }
8477        case SQLITE_FCNTL_PERSIST_WAL:
8478        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8479          int x;
8480          if( nArg!=2 && nArg!=3 ) break;
8481          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8482          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8483          iRes = x;
8484          isOk = 1;
8485          break;
8486        }
8487        case SQLITE_FCNTL_DATA_VERSION:
8488        case SQLITE_FCNTL_HAS_MOVED: {
8489          int x;
8490          if( nArg!=2 ) break;
8491          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8492          iRes = x;
8493          isOk = 1;
8494          break;
8495        }
8496        case SQLITE_FCNTL_TEMPFILENAME: {
8497          char *z = 0;
8498          if( nArg!=2 ) break;
8499          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8500          if( z ){
8501            utf8_printf(p->out, "%s\n", z);
8502            sqlite3_free(z);
8503          }
8504          isOk = 2;
8505          break;
8506        }
8507        case SQLITE_FCNTL_RESERVE_BYTES: {
8508          int x;
8509          if( nArg>=3 ){
8510            x = atoi(azArg[2]);
8511            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8512          }
8513          x = -1;
8514          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8515          utf8_printf(p->out,"%d\n", x);
8516          isOk = 2;
8517          break;
8518        }
8519      }
8520    }
8521    if( isOk==0 && iCtrl>=0 ){
8522      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8523      rc = 1;
8524    }else if( isOk==1 ){
8525      char zBuf[100];
8526      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8527      raw_printf(p->out, "%s\n", zBuf);
8528    }
8529  }else
8530
8531  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8532    ShellState data;
8533    int doStats = 0;
8534    memcpy(&data, p, sizeof(data));
8535    data.showHeader = 0;
8536    data.cMode = data.mode = MODE_Semi;
8537    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8538      data.cMode = data.mode = MODE_Pretty;
8539      nArg = 1;
8540    }
8541    if( nArg!=1 ){
8542      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8543      rc = 1;
8544      goto meta_command_exit;
8545    }
8546    open_db(p, 0);
8547    rc = sqlite3_exec(p->db,
8548       "SELECT sql FROM"
8549       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8550       "     FROM sqlite_schema UNION ALL"
8551       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8552       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8553       "ORDER BY x",
8554       callback, &data, 0
8555    );
8556    if( rc==SQLITE_OK ){
8557      sqlite3_stmt *pStmt;
8558      rc = sqlite3_prepare_v2(p->db,
8559               "SELECT rowid FROM sqlite_schema"
8560               " WHERE name GLOB 'sqlite_stat[134]'",
8561               -1, &pStmt, 0);
8562      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8563      sqlite3_finalize(pStmt);
8564    }
8565    if( doStats==0 ){
8566      raw_printf(p->out, "/* No STAT tables available */\n");
8567    }else{
8568      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8569      data.cMode = data.mode = MODE_Insert;
8570      data.zDestTable = "sqlite_stat1";
8571      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8572      data.zDestTable = "sqlite_stat4";
8573      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8574      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8575    }
8576  }else
8577
8578  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8579    if( nArg==2 ){
8580      p->showHeader = booleanValue(azArg[1]);
8581      p->shellFlgs |= SHFLG_HeaderSet;
8582    }else{
8583      raw_printf(stderr, "Usage: .headers on|off\n");
8584      rc = 1;
8585    }
8586  }else
8587
8588  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8589    if( nArg>=2 ){
8590      n = showHelp(p->out, azArg[1]);
8591      if( n==0 ){
8592        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8593      }
8594    }else{
8595      showHelp(p->out, 0);
8596    }
8597  }else
8598
8599  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8600    char *zTable = 0;           /* Insert data into this table */
8601    char *zSchema = "main";     /* within this schema */
8602    char *zFile = 0;            /* Name of file to extra content from */
8603    sqlite3_stmt *pStmt = NULL; /* A statement */
8604    int nCol;                   /* Number of columns in the table */
8605    int nByte;                  /* Number of bytes in an SQL string */
8606    int i, j;                   /* Loop counters */
8607    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8608    int nSep;                   /* Number of bytes in p->colSeparator[] */
8609    char *zSql;                 /* An SQL statement */
8610    ImportCtx sCtx;             /* Reader context */
8611    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8612    int eVerbose = 0;           /* Larger for more console output */
8613    int nSkip = 0;              /* Initial lines to skip */
8614    int useOutputMode = 1;      /* Use output mode to determine separators */
8615
8616    failIfSafeMode(p, "cannot run .import in safe mode");
8617    memset(&sCtx, 0, sizeof(sCtx));
8618    sCtx.z = sqlite3_malloc64(120);
8619    if( sCtx.z==0 ){
8620      import_cleanup(&sCtx);
8621      shell_out_of_memory();
8622    }
8623    if( p->mode==MODE_Ascii ){
8624      xRead = ascii_read_one_field;
8625    }else{
8626      xRead = csv_read_one_field;
8627    }
8628    for(i=1; i<nArg; i++){
8629      char *z = azArg[i];
8630      if( z[0]=='-' && z[1]=='-' ) z++;
8631      if( z[0]!='-' ){
8632        if( zFile==0 ){
8633          zFile = z;
8634        }else if( zTable==0 ){
8635          zTable = z;
8636        }else{
8637          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8638          showHelp(p->out, "import");
8639          rc = 1;
8640          goto meta_command_exit;
8641        }
8642      }else if( strcmp(z,"-v")==0 ){
8643        eVerbose++;
8644      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8645        zSchema = azArg[++i];
8646      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8647        nSkip = integerValue(azArg[++i]);
8648      }else if( strcmp(z,"-ascii")==0 ){
8649        sCtx.cColSep = SEP_Unit[0];
8650        sCtx.cRowSep = SEP_Record[0];
8651        xRead = ascii_read_one_field;
8652        useOutputMode = 0;
8653      }else if( strcmp(z,"-csv")==0 ){
8654        sCtx.cColSep = ',';
8655        sCtx.cRowSep = '\n';
8656        xRead = csv_read_one_field;
8657        useOutputMode = 0;
8658      }else{
8659        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8660        showHelp(p->out, "import");
8661        rc = 1;
8662        goto meta_command_exit;
8663      }
8664    }
8665    if( zTable==0 ){
8666      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8667                  zFile==0 ? "FILE" : "TABLE");
8668      showHelp(p->out, "import");
8669      rc = 1;
8670      goto meta_command_exit;
8671    }
8672    seenInterrupt = 0;
8673    open_db(p, 0);
8674    if( useOutputMode ){
8675      /* If neither the --csv or --ascii options are specified, then set
8676      ** the column and row separator characters from the output mode. */
8677      nSep = strlen30(p->colSeparator);
8678      if( nSep==0 ){
8679        raw_printf(stderr,
8680                   "Error: non-null column separator required for import\n");
8681        rc = 1;
8682        goto meta_command_exit;
8683      }
8684      if( nSep>1 ){
8685        raw_printf(stderr,
8686              "Error: multi-character column separators not allowed"
8687              " for import\n");
8688        rc = 1;
8689        goto meta_command_exit;
8690      }
8691      nSep = strlen30(p->rowSeparator);
8692      if( nSep==0 ){
8693        raw_printf(stderr,
8694            "Error: non-null row separator required for import\n");
8695        rc = 1;
8696        goto meta_command_exit;
8697      }
8698      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8699        /* When importing CSV (only), if the row separator is set to the
8700        ** default output row separator, change it to the default input
8701        ** row separator.  This avoids having to maintain different input
8702        ** and output row separators. */
8703        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8704        nSep = strlen30(p->rowSeparator);
8705      }
8706      if( nSep>1 ){
8707        raw_printf(stderr, "Error: multi-character row separators not allowed"
8708                           " for import\n");
8709        rc = 1;
8710        goto meta_command_exit;
8711      }
8712      sCtx.cColSep = p->colSeparator[0];
8713      sCtx.cRowSep = p->rowSeparator[0];
8714    }
8715    sCtx.zFile = zFile;
8716    sCtx.nLine = 1;
8717    if( sCtx.zFile[0]=='|' ){
8718#ifdef SQLITE_OMIT_POPEN
8719      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8720      rc = 1;
8721      goto meta_command_exit;
8722#else
8723      sCtx.in = popen(sCtx.zFile+1, "r");
8724      sCtx.zFile = "<pipe>";
8725      sCtx.xCloser = pclose;
8726#endif
8727    }else{
8728      sCtx.in = fopen(sCtx.zFile, "rb");
8729      sCtx.xCloser = fclose;
8730    }
8731    if( sCtx.in==0 ){
8732      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8733      rc = 1;
8734      import_cleanup(&sCtx);
8735      goto meta_command_exit;
8736    }
8737    /* Below, resources must be freed before exit. */
8738    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8739      char zSep[2];
8740      zSep[1] = 0;
8741      zSep[0] = sCtx.cColSep;
8742      utf8_printf(p->out, "Column separator ");
8743      output_c_string(p->out, zSep);
8744      utf8_printf(p->out, ", row separator ");
8745      zSep[0] = sCtx.cRowSep;
8746      output_c_string(p->out, zSep);
8747      utf8_printf(p->out, "\n");
8748    }
8749    while( (nSkip--)>0 ){
8750      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8751    }
8752    zSql = sqlite3_mprintf("SELECT * FROM \"%w\".\"%w\"", zSchema, zTable);
8753    if( zSql==0 ){
8754      import_cleanup(&sCtx);
8755      shell_out_of_memory();
8756    }
8757    nByte = strlen30(zSql);
8758    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8759    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8760    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8761      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"",
8762                                      zSchema, zTable);
8763      char cSep = '(';
8764      while( xRead(&sCtx) ){
8765        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
8766        cSep = ',';
8767        if( sCtx.cTerm!=sCtx.cColSep ) break;
8768      }
8769      if( cSep=='(' ){
8770        sqlite3_free(zCreate);
8771        import_cleanup(&sCtx);
8772        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8773        rc = 1;
8774        goto meta_command_exit;
8775      }
8776      zCreate = sqlite3_mprintf("%z\n)", zCreate);
8777      if( eVerbose>=1 ){
8778        utf8_printf(p->out, "%s\n", zCreate);
8779      }
8780      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8781      if( rc ){
8782        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8783        sqlite3_free(zCreate);
8784        import_cleanup(&sCtx);
8785        rc = 1;
8786        goto meta_command_exit;
8787      }
8788      sqlite3_free(zCreate);
8789      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8790    }
8791    sqlite3_free(zSql);
8792    if( rc ){
8793      if (pStmt) sqlite3_finalize(pStmt);
8794      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8795      import_cleanup(&sCtx);
8796      rc = 1;
8797      goto meta_command_exit;
8798    }
8799    nCol = sqlite3_column_count(pStmt);
8800    sqlite3_finalize(pStmt);
8801    pStmt = 0;
8802    if( nCol==0 ) return 0; /* no columns, no error */
8803    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8804    if( zSql==0 ){
8805      import_cleanup(&sCtx);
8806      shell_out_of_memory();
8807    }
8808    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?",
8809                     zSchema, zTable);
8810    j = strlen30(zSql);
8811    for(i=1; i<nCol; i++){
8812      zSql[j++] = ',';
8813      zSql[j++] = '?';
8814    }
8815    zSql[j++] = ')';
8816    zSql[j] = 0;
8817    if( eVerbose>=2 ){
8818      utf8_printf(p->out, "Insert using: %s\n", zSql);
8819    }
8820    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8821    sqlite3_free(zSql);
8822    if( rc ){
8823      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8824      if (pStmt) sqlite3_finalize(pStmt);
8825      import_cleanup(&sCtx);
8826      rc = 1;
8827      goto meta_command_exit;
8828    }
8829    needCommit = sqlite3_get_autocommit(p->db);
8830    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8831    do{
8832      int startLine = sCtx.nLine;
8833      for(i=0; i<nCol; i++){
8834        char *z = xRead(&sCtx);
8835        /*
8836        ** Did we reach end-of-file before finding any columns?
8837        ** If so, stop instead of NULL filling the remaining columns.
8838        */
8839        if( z==0 && i==0 ) break;
8840        /*
8841        ** Did we reach end-of-file OR end-of-line before finding any
8842        ** columns in ASCII mode?  If so, stop instead of NULL filling
8843        ** the remaining columns.
8844        */
8845        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8846        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8847        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8848          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8849                          "filling the rest with NULL\n",
8850                          sCtx.zFile, startLine, nCol, i+1);
8851          i += 2;
8852          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8853        }
8854      }
8855      if( sCtx.cTerm==sCtx.cColSep ){
8856        do{
8857          xRead(&sCtx);
8858          i++;
8859        }while( sCtx.cTerm==sCtx.cColSep );
8860        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8861                        "extras ignored\n",
8862                        sCtx.zFile, startLine, nCol, i);
8863      }
8864      if( i>=nCol ){
8865        sqlite3_step(pStmt);
8866        rc = sqlite3_reset(pStmt);
8867        if( rc!=SQLITE_OK ){
8868          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8869                      startLine, sqlite3_errmsg(p->db));
8870          sCtx.nErr++;
8871        }else{
8872          sCtx.nRow++;
8873        }
8874      }
8875    }while( sCtx.cTerm!=EOF );
8876
8877    import_cleanup(&sCtx);
8878    sqlite3_finalize(pStmt);
8879    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8880    if( eVerbose>0 ){
8881      utf8_printf(p->out,
8882          "Added %d rows with %d errors using %d lines of input\n",
8883          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8884    }
8885  }else
8886
8887#ifndef SQLITE_UNTESTABLE
8888  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8889    char *zSql;
8890    char *zCollist = 0;
8891    sqlite3_stmt *pStmt;
8892    int tnum = 0;
8893    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8894    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8895    int i;
8896    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8897      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8898                          "       .imposter off\n");
8899      /* Also allowed, but not documented:
8900      **
8901      **    .imposter TABLE IMPOSTER
8902      **
8903      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8904      ** imposter is another WITHOUT ROWID table with the columns in
8905      ** storage order. */
8906      rc = 1;
8907      goto meta_command_exit;
8908    }
8909    open_db(p, 0);
8910    if( nArg==2 ){
8911      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8912      goto meta_command_exit;
8913    }
8914    zSql = sqlite3_mprintf(
8915      "SELECT rootpage, 0 FROM sqlite_schema"
8916      " WHERE name='%q' AND type='index'"
8917      "UNION ALL "
8918      "SELECT rootpage, 1 FROM sqlite_schema"
8919      " WHERE name='%q' AND type='table'"
8920      "   AND sql LIKE '%%without%%rowid%%'",
8921      azArg[1], azArg[1]
8922    );
8923    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8924    sqlite3_free(zSql);
8925    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8926      tnum = sqlite3_column_int(pStmt, 0);
8927      isWO = sqlite3_column_int(pStmt, 1);
8928    }
8929    sqlite3_finalize(pStmt);
8930    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8931    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8932    sqlite3_free(zSql);
8933    i = 0;
8934    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8935      char zLabel[20];
8936      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8937      i++;
8938      if( zCol==0 ){
8939        if( sqlite3_column_int(pStmt,1)==-1 ){
8940          zCol = "_ROWID_";
8941        }else{
8942          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8943          zCol = zLabel;
8944        }
8945      }
8946      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8947        lenPK = (int)strlen(zCollist);
8948      }
8949      if( zCollist==0 ){
8950        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8951      }else{
8952        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8953      }
8954    }
8955    sqlite3_finalize(pStmt);
8956    if( i==0 || tnum==0 ){
8957      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8958      rc = 1;
8959      sqlite3_free(zCollist);
8960      goto meta_command_exit;
8961    }
8962    if( lenPK==0 ) lenPK = 100000;
8963    zSql = sqlite3_mprintf(
8964          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8965          azArg[2], zCollist, lenPK, zCollist);
8966    sqlite3_free(zCollist);
8967    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8968    if( rc==SQLITE_OK ){
8969      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8970      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8971      if( rc ){
8972        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8973      }else{
8974        utf8_printf(stdout, "%s;\n", zSql);
8975        raw_printf(stdout,
8976          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8977          azArg[1], isWO ? "table" : "index"
8978        );
8979      }
8980    }else{
8981      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8982      rc = 1;
8983    }
8984    sqlite3_free(zSql);
8985  }else
8986#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8987
8988#ifdef SQLITE_ENABLE_IOTRACE
8989  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8990    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8991    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8992    iotrace = 0;
8993    if( nArg<2 ){
8994      sqlite3IoTrace = 0;
8995    }else if( strcmp(azArg[1], "-")==0 ){
8996      sqlite3IoTrace = iotracePrintf;
8997      iotrace = stdout;
8998    }else{
8999      iotrace = fopen(azArg[1], "w");
9000      if( iotrace==0 ){
9001        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9002        sqlite3IoTrace = 0;
9003        rc = 1;
9004      }else{
9005        sqlite3IoTrace = iotracePrintf;
9006      }
9007    }
9008  }else
9009#endif
9010
9011  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9012    static const struct {
9013       const char *zLimitName;   /* Name of a limit */
9014       int limitCode;            /* Integer code for that limit */
9015    } aLimit[] = {
9016      { "length",                SQLITE_LIMIT_LENGTH                    },
9017      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9018      { "column",                SQLITE_LIMIT_COLUMN                    },
9019      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9020      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9021      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9022      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9023      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9024      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9025      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9026      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9027      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9028    };
9029    int i, n2;
9030    open_db(p, 0);
9031    if( nArg==1 ){
9032      for(i=0; i<ArraySize(aLimit); i++){
9033        printf("%20s %d\n", aLimit[i].zLimitName,
9034               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9035      }
9036    }else if( nArg>3 ){
9037      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9038      rc = 1;
9039      goto meta_command_exit;
9040    }else{
9041      int iLimit = -1;
9042      n2 = strlen30(azArg[1]);
9043      for(i=0; i<ArraySize(aLimit); i++){
9044        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9045          if( iLimit<0 ){
9046            iLimit = i;
9047          }else{
9048            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9049            rc = 1;
9050            goto meta_command_exit;
9051          }
9052        }
9053      }
9054      if( iLimit<0 ){
9055        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9056                        "enter \".limits\" with no arguments for a list.\n",
9057                         azArg[1]);
9058        rc = 1;
9059        goto meta_command_exit;
9060      }
9061      if( nArg==3 ){
9062        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9063                      (int)integerValue(azArg[2]));
9064      }
9065      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9066             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9067    }
9068  }else
9069
9070  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9071    open_db(p, 0);
9072    lintDotCommand(p, azArg, nArg);
9073  }else
9074
9075#ifndef SQLITE_OMIT_LOAD_EXTENSION
9076  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9077    const char *zFile, *zProc;
9078    char *zErrMsg = 0;
9079    failIfSafeMode(p, "cannot run .load in safe mode");
9080    if( nArg<2 ){
9081      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9082      rc = 1;
9083      goto meta_command_exit;
9084    }
9085    zFile = azArg[1];
9086    zProc = nArg>=3 ? azArg[2] : 0;
9087    open_db(p, 0);
9088    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9089    if( rc!=SQLITE_OK ){
9090      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9091      sqlite3_free(zErrMsg);
9092      rc = 1;
9093    }
9094  }else
9095#endif
9096
9097  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9098    failIfSafeMode(p, "cannot run .log in safe mode");
9099    if( nArg!=2 ){
9100      raw_printf(stderr, "Usage: .log FILENAME\n");
9101      rc = 1;
9102    }else{
9103      const char *zFile = azArg[1];
9104      output_file_close(p->pLog);
9105      p->pLog = output_file_open(zFile, 0);
9106    }
9107  }else
9108
9109  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9110    const char *zMode = 0;
9111    const char *zTabname = 0;
9112    int i, n2;
9113    ColModeOpts cmOpts = ColModeOpts_default;
9114    for(i=1; i<nArg; i++){
9115      const char *z = azArg[i];
9116      if( optionMatch(z,"wrap") && i+1<nArg ){
9117        cmOpts.iWrap = integerValue(azArg[++i]);
9118      }else if( optionMatch(z,"ww") ){
9119        cmOpts.bWordWrap = 1;
9120      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9121        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9122      }else if( optionMatch(z,"quote") ){
9123        cmOpts.bQuote = 1;
9124      }else if( optionMatch(z,"noquote") ){
9125        cmOpts.bQuote = 0;
9126      }else if( zMode==0 ){
9127        zMode = z;
9128        /* Apply defaults for qbox pseudo-mods. If that
9129         * overwrites already-set values, user was informed of this.
9130         */
9131        if( strcmp(z, "qbox")==0 ){
9132          ColModeOpts cmo = ColModeOpts_default_qbox;
9133          zMode = "box";
9134          cmOpts = cmo;
9135        }
9136      }else if( zTabname==0 ){
9137        zTabname = z;
9138      }else if( z[0]=='-' ){
9139        utf8_printf(stderr, "unknown option: %s\n", z);
9140        utf8_printf(stderr, "options:\n"
9141                            "  --noquote\n"
9142                            "  --quote\n"
9143                            "  --wordwrap on/off\n"
9144                            "  --wrap N\n"
9145                            "  --ww\n");
9146        rc = 1;
9147        goto meta_command_exit;
9148      }else{
9149        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9150        rc = 1;
9151        goto meta_command_exit;
9152      }
9153    }
9154    if( zMode==0 ){
9155      if( p->mode==MODE_Column
9156       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9157      ){
9158        raw_printf
9159          (p->out,
9160           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9161           modeDescr[p->mode], p->cmOpts.iWrap,
9162           p->cmOpts.bWordWrap ? "on" : "off",
9163           p->cmOpts.bQuote ? "" : "no");
9164      }else{
9165        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9166      }
9167      zMode = modeDescr[p->mode];
9168    }
9169    n2 = strlen30(zMode);
9170    if( strncmp(zMode,"lines",n2)==0 ){
9171      p->mode = MODE_Line;
9172      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9173    }else if( strncmp(zMode,"columns",n2)==0 ){
9174      p->mode = MODE_Column;
9175      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9176        p->showHeader = 1;
9177      }
9178      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9179      p->cmOpts = cmOpts;
9180    }else if( strncmp(zMode,"list",n2)==0 ){
9181      p->mode = MODE_List;
9182      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9183      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9184    }else if( strncmp(zMode,"html",n2)==0 ){
9185      p->mode = MODE_Html;
9186    }else if( strncmp(zMode,"tcl",n2)==0 ){
9187      p->mode = MODE_Tcl;
9188      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9189      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9190    }else if( strncmp(zMode,"csv",n2)==0 ){
9191      p->mode = MODE_Csv;
9192      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9193      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9194    }else if( strncmp(zMode,"tabs",n2)==0 ){
9195      p->mode = MODE_List;
9196      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9197    }else if( strncmp(zMode,"insert",n2)==0 ){
9198      p->mode = MODE_Insert;
9199      set_table_name(p, zTabname ? zTabname : "table");
9200    }else if( strncmp(zMode,"quote",n2)==0 ){
9201      p->mode = MODE_Quote;
9202      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9203      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9204    }else if( strncmp(zMode,"ascii",n2)==0 ){
9205      p->mode = MODE_Ascii;
9206      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9207      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9208    }else if( strncmp(zMode,"markdown",n2)==0 ){
9209      p->mode = MODE_Markdown;
9210      p->cmOpts = cmOpts;
9211    }else if( strncmp(zMode,"table",n2)==0 ){
9212      p->mode = MODE_Table;
9213      p->cmOpts = cmOpts;
9214    }else if( strncmp(zMode,"box",n2)==0 ){
9215      p->mode = MODE_Box;
9216      p->cmOpts = cmOpts;
9217    }else if( strncmp(zMode,"count",n2)==0 ){
9218      p->mode = MODE_Count;
9219    }else if( strncmp(zMode,"off",n2)==0 ){
9220      p->mode = MODE_Off;
9221    }else if( strncmp(zMode,"json",n2)==0 ){
9222      p->mode = MODE_Json;
9223    }else{
9224      raw_printf(stderr, "Error: mode should be one of: "
9225         "ascii box column csv html insert json line list markdown "
9226         "qbox quote table tabs tcl\n");
9227      rc = 1;
9228    }
9229    p->cMode = p->mode;
9230  }else
9231
9232  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9233    if( nArg!=2 ){
9234      raw_printf(stderr, "Usage: .nonce NONCE\n");
9235      rc = 1;
9236    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9237      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9238                 p->lineno, azArg[1]);
9239      exit(1);
9240    }else{
9241      p->bSafeMode = 0;
9242      return 0;  /* Return immediately to bypass the safe mode reset
9243                 ** at the end of this procedure */
9244    }
9245  }else
9246
9247  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9248    if( nArg==2 ){
9249      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9250                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9251    }else{
9252      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9253      rc = 1;
9254    }
9255  }else
9256
9257  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9258    const char *zFN = 0;     /* Pointer to constant filename */
9259    char *zNewFilename = 0;  /* Name of the database file to open */
9260    int iName = 1;           /* Index in azArg[] of the filename */
9261    int newFlag = 0;         /* True to delete file before opening */
9262    int openMode = SHELL_OPEN_UNSPEC;
9263
9264    /* Check for command-line arguments */
9265    for(iName=1; iName<nArg; iName++){
9266      const char *z = azArg[iName];
9267      if( optionMatch(z,"new") ){
9268        newFlag = 1;
9269#ifdef SQLITE_HAVE_ZLIB
9270      }else if( optionMatch(z, "zip") ){
9271        openMode = SHELL_OPEN_ZIPFILE;
9272#endif
9273      }else if( optionMatch(z, "append") ){
9274        openMode = SHELL_OPEN_APPENDVFS;
9275      }else if( optionMatch(z, "readonly") ){
9276        openMode = SHELL_OPEN_READONLY;
9277      }else if( optionMatch(z, "nofollow") ){
9278        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9279#ifndef SQLITE_OMIT_DESERIALIZE
9280      }else if( optionMatch(z, "deserialize") ){
9281        openMode = SHELL_OPEN_DESERIALIZE;
9282      }else if( optionMatch(z, "hexdb") ){
9283        openMode = SHELL_OPEN_HEXDB;
9284      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9285        p->szMax = integerValue(azArg[++iName]);
9286#endif /* SQLITE_OMIT_DESERIALIZE */
9287      }else if( z[0]=='-' ){
9288        utf8_printf(stderr, "unknown option: %s\n", z);
9289        rc = 1;
9290        goto meta_command_exit;
9291      }else if( zFN ){
9292        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9293        rc = 1;
9294        goto meta_command_exit;
9295      }else{
9296        zFN = z;
9297      }
9298    }
9299
9300    /* Close the existing database */
9301    session_close_all(p, -1);
9302    close_db(p->db);
9303    p->db = 0;
9304    p->pAuxDb->zDbFilename = 0;
9305    sqlite3_free(p->pAuxDb->zFreeOnClose);
9306    p->pAuxDb->zFreeOnClose = 0;
9307    p->openMode = openMode;
9308    p->openFlags = 0;
9309    p->szMax = 0;
9310
9311    /* If a filename is specified, try to open it first */
9312    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9313      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9314      if( p->bSafeMode
9315       && p->openMode!=SHELL_OPEN_HEXDB
9316       && zFN
9317       && strcmp(zFN,":memory:")!=0
9318      ){
9319        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9320      }
9321      if( zFN ){
9322        zNewFilename = sqlite3_mprintf("%s", zFN);
9323        shell_check_oom(zNewFilename);
9324      }else{
9325        zNewFilename = 0;
9326      }
9327      p->pAuxDb->zDbFilename = zNewFilename;
9328      open_db(p, OPEN_DB_KEEPALIVE);
9329      if( p->db==0 ){
9330        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9331        sqlite3_free(zNewFilename);
9332      }else{
9333        p->pAuxDb->zFreeOnClose = zNewFilename;
9334      }
9335    }
9336    if( p->db==0 ){
9337      /* As a fall-back open a TEMP database */
9338      p->pAuxDb->zDbFilename = 0;
9339      open_db(p, 0);
9340    }
9341  }else
9342
9343  if( (c=='o'
9344        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9345   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9346  ){
9347    char *zFile = 0;
9348    int bTxtMode = 0;
9349    int i;
9350    int eMode = 0;
9351    int bBOM = 0;
9352    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
9353
9354    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9355    if( c=='e' ){
9356      eMode = 'x';
9357      bOnce = 2;
9358    }else if( strncmp(azArg[0],"once",n)==0 ){
9359      bOnce = 1;
9360    }
9361    for(i=1; i<nArg; i++){
9362      char *z = azArg[i];
9363      if( z[0]=='-' ){
9364        if( z[1]=='-' ) z++;
9365        if( strcmp(z,"-bom")==0 ){
9366          bBOM = 1;
9367        }else if( c!='e' && strcmp(z,"-x")==0 ){
9368          eMode = 'x';  /* spreadsheet */
9369        }else if( c!='e' && strcmp(z,"-e")==0 ){
9370          eMode = 'e';  /* text editor */
9371        }else{
9372          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9373                      azArg[i]);
9374          showHelp(p->out, azArg[0]);
9375          rc = 1;
9376          goto meta_command_exit;
9377        }
9378      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9379        zFile = sqlite3_mprintf("%s", z);
9380        if( zFile && zFile[0]=='|' ){
9381          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9382          break;
9383        }
9384      }else{
9385        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9386                    azArg[i]);
9387        showHelp(p->out, azArg[0]);
9388        rc = 1;
9389        sqlite3_free(zFile);
9390        goto meta_command_exit;
9391      }
9392    }
9393    if( zFile==0 ){
9394      zFile = sqlite3_mprintf("stdout");
9395    }
9396    if( bOnce ){
9397      p->outCount = 2;
9398    }else{
9399      p->outCount = 0;
9400    }
9401    output_reset(p);
9402#ifndef SQLITE_NOHAVE_SYSTEM
9403    if( eMode=='e' || eMode=='x' ){
9404      p->doXdgOpen = 1;
9405      outputModePush(p);
9406      if( eMode=='x' ){
9407        /* spreadsheet mode.  Output as CSV. */
9408        newTempFile(p, "csv");
9409        ShellClearFlag(p, SHFLG_Echo);
9410        p->mode = MODE_Csv;
9411        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9412        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9413      }else{
9414        /* text editor mode */
9415        newTempFile(p, "txt");
9416        bTxtMode = 1;
9417      }
9418      sqlite3_free(zFile);
9419      zFile = sqlite3_mprintf("%s", p->zTempFile);
9420    }
9421#endif /* SQLITE_NOHAVE_SYSTEM */
9422    shell_check_oom(zFile);
9423    if( zFile[0]=='|' ){
9424#ifdef SQLITE_OMIT_POPEN
9425      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9426      rc = 1;
9427      p->out = stdout;
9428#else
9429      p->out = popen(zFile + 1, "w");
9430      if( p->out==0 ){
9431        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9432        p->out = stdout;
9433        rc = 1;
9434      }else{
9435        if( bBOM ) fprintf(p->out,"\357\273\277");
9436        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9437      }
9438#endif
9439    }else{
9440      p->out = output_file_open(zFile, bTxtMode);
9441      if( p->out==0 ){
9442        if( strcmp(zFile,"off")!=0 ){
9443          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9444        }
9445        p->out = stdout;
9446        rc = 1;
9447      } else {
9448        if( bBOM ) fprintf(p->out,"\357\273\277");
9449        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9450      }
9451    }
9452    sqlite3_free(zFile);
9453  }else
9454
9455  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9456    open_db(p,0);
9457    if( nArg<=1 ) goto parameter_syntax_error;
9458
9459    /* .parameter clear
9460    ** Clear all bind parameters by dropping the TEMP table that holds them.
9461    */
9462    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9463      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9464                   0, 0, 0);
9465    }else
9466
9467    /* .parameter list
9468    ** List all bind parameters.
9469    */
9470    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9471      sqlite3_stmt *pStmt = 0;
9472      int rx;
9473      int len = 0;
9474      rx = sqlite3_prepare_v2(p->db,
9475             "SELECT max(length(key)) "
9476             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9477      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9478        len = sqlite3_column_int(pStmt, 0);
9479        if( len>40 ) len = 40;
9480      }
9481      sqlite3_finalize(pStmt);
9482      pStmt = 0;
9483      if( len ){
9484        rx = sqlite3_prepare_v2(p->db,
9485             "SELECT key, quote(value) "
9486             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9487        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9488          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9489                      sqlite3_column_text(pStmt,1));
9490        }
9491        sqlite3_finalize(pStmt);
9492      }
9493    }else
9494
9495    /* .parameter init
9496    ** Make sure the TEMP table used to hold bind parameters exists.
9497    ** Create it if necessary.
9498    */
9499    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9500      bind_table_init(p);
9501    }else
9502
9503    /* .parameter set NAME VALUE
9504    ** Set or reset a bind parameter.  NAME should be the full parameter
9505    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9506    ** VALUE can be in either SQL literal notation, or if not it will be
9507    ** understood to be a text string.
9508    */
9509    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9510      int rx;
9511      char *zSql;
9512      sqlite3_stmt *pStmt;
9513      const char *zKey = azArg[2];
9514      const char *zValue = azArg[3];
9515      bind_table_init(p);
9516      zSql = sqlite3_mprintf(
9517                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9518                  "VALUES(%Q,%s);", zKey, zValue);
9519      shell_check_oom(zSql);
9520      pStmt = 0;
9521      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9522      sqlite3_free(zSql);
9523      if( rx!=SQLITE_OK ){
9524        sqlite3_finalize(pStmt);
9525        pStmt = 0;
9526        zSql = sqlite3_mprintf(
9527                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9528                   "VALUES(%Q,%Q);", zKey, zValue);
9529        shell_check_oom(zSql);
9530        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9531        sqlite3_free(zSql);
9532        if( rx!=SQLITE_OK ){
9533          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9534          sqlite3_finalize(pStmt);
9535          pStmt = 0;
9536          rc = 1;
9537        }
9538      }
9539      sqlite3_step(pStmt);
9540      sqlite3_finalize(pStmt);
9541    }else
9542
9543    /* .parameter unset NAME
9544    ** Remove the NAME binding from the parameter binding table, if it
9545    ** exists.
9546    */
9547    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9548      char *zSql = sqlite3_mprintf(
9549          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9550      shell_check_oom(zSql);
9551      sqlite3_exec(p->db, zSql, 0, 0, 0);
9552      sqlite3_free(zSql);
9553    }else
9554    /* If no command name matches, show a syntax error */
9555    parameter_syntax_error:
9556    showHelp(p->out, "parameter");
9557  }else
9558
9559  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9560    int i;
9561    for(i=1; i<nArg; i++){
9562      if( i>1 ) raw_printf(p->out, " ");
9563      utf8_printf(p->out, "%s", azArg[i]);
9564    }
9565    raw_printf(p->out, "\n");
9566  }else
9567
9568#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9569  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9570    int i;
9571    int nn = 0;
9572    p->flgProgress = 0;
9573    p->mxProgress = 0;
9574    p->nProgress = 0;
9575    for(i=1; i<nArg; i++){
9576      const char *z = azArg[i];
9577      if( z[0]=='-' ){
9578        z++;
9579        if( z[0]=='-' ) z++;
9580        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9581          p->flgProgress |= SHELL_PROGRESS_QUIET;
9582          continue;
9583        }
9584        if( strcmp(z,"reset")==0 ){
9585          p->flgProgress |= SHELL_PROGRESS_RESET;
9586          continue;
9587        }
9588        if( strcmp(z,"once")==0 ){
9589          p->flgProgress |= SHELL_PROGRESS_ONCE;
9590          continue;
9591        }
9592        if( strcmp(z,"limit")==0 ){
9593          if( i+1>=nArg ){
9594            utf8_printf(stderr, "Error: missing argument on --limit\n");
9595            rc = 1;
9596            goto meta_command_exit;
9597          }else{
9598            p->mxProgress = (int)integerValue(azArg[++i]);
9599          }
9600          continue;
9601        }
9602        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9603        rc = 1;
9604        goto meta_command_exit;
9605      }else{
9606        nn = (int)integerValue(z);
9607      }
9608    }
9609    open_db(p, 0);
9610    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9611  }else
9612#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9613
9614  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9615    if( nArg >= 2) {
9616      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9617    }
9618    if( nArg >= 3) {
9619      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9620    }
9621  }else
9622
9623  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9624    rc = 2;
9625  }else
9626
9627  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9628    FILE *inSaved = p->in;
9629    int savedLineno = p->lineno;
9630    failIfSafeMode(p, "cannot run .read in safe mode");
9631    if( nArg!=2 ){
9632      raw_printf(stderr, "Usage: .read FILE\n");
9633      rc = 1;
9634      goto meta_command_exit;
9635    }
9636    if( azArg[1][0]=='|' ){
9637#ifdef SQLITE_OMIT_POPEN
9638      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9639      rc = 1;
9640      p->out = stdout;
9641#else
9642      p->in = popen(azArg[1]+1, "r");
9643      if( p->in==0 ){
9644        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9645        rc = 1;
9646      }else{
9647        rc = process_input(p);
9648        pclose(p->in);
9649      }
9650#endif
9651    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9652      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9653      rc = 1;
9654    }else{
9655      rc = process_input(p);
9656      fclose(p->in);
9657    }
9658    p->in = inSaved;
9659    p->lineno = savedLineno;
9660  }else
9661
9662  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9663    const char *zSrcFile;
9664    const char *zDb;
9665    sqlite3 *pSrc;
9666    sqlite3_backup *pBackup;
9667    int nTimeout = 0;
9668
9669    failIfSafeMode(p, "cannot run .restore in safe mode");
9670    if( nArg==2 ){
9671      zSrcFile = azArg[1];
9672      zDb = "main";
9673    }else if( nArg==3 ){
9674      zSrcFile = azArg[2];
9675      zDb = azArg[1];
9676    }else{
9677      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9678      rc = 1;
9679      goto meta_command_exit;
9680    }
9681    rc = sqlite3_open(zSrcFile, &pSrc);
9682    if( rc!=SQLITE_OK ){
9683      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9684      close_db(pSrc);
9685      return 1;
9686    }
9687    open_db(p, 0);
9688    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9689    if( pBackup==0 ){
9690      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9691      close_db(pSrc);
9692      return 1;
9693    }
9694    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9695          || rc==SQLITE_BUSY  ){
9696      if( rc==SQLITE_BUSY ){
9697        if( nTimeout++ >= 3 ) break;
9698        sqlite3_sleep(100);
9699      }
9700    }
9701    sqlite3_backup_finish(pBackup);
9702    if( rc==SQLITE_DONE ){
9703      rc = 0;
9704    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9705      raw_printf(stderr, "Error: source database is busy\n");
9706      rc = 1;
9707    }else{
9708      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9709      rc = 1;
9710    }
9711    close_db(pSrc);
9712  }else
9713
9714  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9715    if( nArg==2 ){
9716      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9717#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9718      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9719#endif
9720    }else{
9721      raw_printf(stderr, "Usage: .scanstats on|off\n");
9722      rc = 1;
9723    }
9724  }else
9725
9726  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9727    ShellText sSelect;
9728    ShellState data;
9729    char *zErrMsg = 0;
9730    const char *zDiv = "(";
9731    const char *zName = 0;
9732    int iSchema = 0;
9733    int bDebug = 0;
9734    int bNoSystemTabs = 0;
9735    int ii;
9736
9737    open_db(p, 0);
9738    memcpy(&data, p, sizeof(data));
9739    data.showHeader = 0;
9740    data.cMode = data.mode = MODE_Semi;
9741    initText(&sSelect);
9742    for(ii=1; ii<nArg; ii++){
9743      if( optionMatch(azArg[ii],"indent") ){
9744        data.cMode = data.mode = MODE_Pretty;
9745      }else if( optionMatch(azArg[ii],"debug") ){
9746        bDebug = 1;
9747      }else if( optionMatch(azArg[ii],"nosys") ){
9748        bNoSystemTabs = 1;
9749      }else if( azArg[ii][0]=='-' ){
9750        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9751        rc = 1;
9752        goto meta_command_exit;
9753      }else if( zName==0 ){
9754        zName = azArg[ii];
9755      }else{
9756        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9757        rc = 1;
9758        goto meta_command_exit;
9759      }
9760    }
9761    if( zName!=0 ){
9762      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9763                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9764                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9765                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9766      if( isSchema ){
9767        char *new_argv[2], *new_colv[2];
9768        new_argv[0] = sqlite3_mprintf(
9769                      "CREATE TABLE %s (\n"
9770                      "  type text,\n"
9771                      "  name text,\n"
9772                      "  tbl_name text,\n"
9773                      "  rootpage integer,\n"
9774                      "  sql text\n"
9775                      ")", zName);
9776        shell_check_oom(new_argv[0]);
9777        new_argv[1] = 0;
9778        new_colv[0] = "sql";
9779        new_colv[1] = 0;
9780        callback(&data, 1, new_argv, new_colv);
9781        sqlite3_free(new_argv[0]);
9782      }
9783    }
9784    if( zDiv ){
9785      sqlite3_stmt *pStmt = 0;
9786      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9787                              -1, &pStmt, 0);
9788      if( rc ){
9789        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9790        sqlite3_finalize(pStmt);
9791        rc = 1;
9792        goto meta_command_exit;
9793      }
9794      appendText(&sSelect, "SELECT sql FROM", 0);
9795      iSchema = 0;
9796      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9797        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9798        char zScNum[30];
9799        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9800        appendText(&sSelect, zDiv, 0);
9801        zDiv = " UNION ALL ";
9802        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9803        if( sqlite3_stricmp(zDb, "main")!=0 ){
9804          appendText(&sSelect, zDb, '\'');
9805        }else{
9806          appendText(&sSelect, "NULL", 0);
9807        }
9808        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9809        appendText(&sSelect, zScNum, 0);
9810        appendText(&sSelect, " AS snum, ", 0);
9811        appendText(&sSelect, zDb, '\'');
9812        appendText(&sSelect, " AS sname FROM ", 0);
9813        appendText(&sSelect, zDb, quoteChar(zDb));
9814        appendText(&sSelect, ".sqlite_schema", 0);
9815      }
9816      sqlite3_finalize(pStmt);
9817#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9818      if( zName ){
9819        appendText(&sSelect,
9820           " UNION ALL SELECT shell_module_schema(name),"
9821           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9822        0);
9823      }
9824#endif
9825      appendText(&sSelect, ") WHERE ", 0);
9826      if( zName ){
9827        char *zQarg = sqlite3_mprintf("%Q", zName);
9828        int bGlob;
9829        shell_check_oom(zQarg);
9830        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9831                strchr(zName, '[') != 0;
9832        if( strchr(zName, '.') ){
9833          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9834        }else{
9835          appendText(&sSelect, "lower(tbl_name)", 0);
9836        }
9837        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9838        appendText(&sSelect, zQarg, 0);
9839        if( !bGlob ){
9840          appendText(&sSelect, " ESCAPE '\\' ", 0);
9841        }
9842        appendText(&sSelect, " AND ", 0);
9843        sqlite3_free(zQarg);
9844      }
9845      if( bNoSystemTabs ){
9846        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9847      }
9848      appendText(&sSelect, "sql IS NOT NULL"
9849                           " ORDER BY snum, rowid", 0);
9850      if( bDebug ){
9851        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9852      }else{
9853        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9854      }
9855      freeText(&sSelect);
9856    }
9857    if( zErrMsg ){
9858      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9859      sqlite3_free(zErrMsg);
9860      rc = 1;
9861    }else if( rc != SQLITE_OK ){
9862      raw_printf(stderr,"Error: querying schema information\n");
9863      rc = 1;
9864    }else{
9865      rc = 0;
9866    }
9867  }else
9868
9869  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9870    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9871    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9872  }else
9873
9874#if defined(SQLITE_ENABLE_SESSION)
9875  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9876    struct AuxDb *pAuxDb = p->pAuxDb;
9877    OpenSession *pSession = &pAuxDb->aSession[0];
9878    char **azCmd = &azArg[1];
9879    int iSes = 0;
9880    int nCmd = nArg - 1;
9881    int i;
9882    if( nArg<=1 ) goto session_syntax_error;
9883    open_db(p, 0);
9884    if( nArg>=3 ){
9885      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9886        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9887      }
9888      if( iSes<pAuxDb->nSession ){
9889        pSession = &pAuxDb->aSession[iSes];
9890        azCmd++;
9891        nCmd--;
9892      }else{
9893        pSession = &pAuxDb->aSession[0];
9894        iSes = 0;
9895      }
9896    }
9897
9898    /* .session attach TABLE
9899    ** Invoke the sqlite3session_attach() interface to attach a particular
9900    ** table so that it is never filtered.
9901    */
9902    if( strcmp(azCmd[0],"attach")==0 ){
9903      if( nCmd!=2 ) goto session_syntax_error;
9904      if( pSession->p==0 ){
9905        session_not_open:
9906        raw_printf(stderr, "ERROR: No sessions are open\n");
9907      }else{
9908        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9909        if( rc ){
9910          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9911          rc = 0;
9912        }
9913      }
9914    }else
9915
9916    /* .session changeset FILE
9917    ** .session patchset FILE
9918    ** Write a changeset or patchset into a file.  The file is overwritten.
9919    */
9920    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9921      FILE *out = 0;
9922      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9923      if( nCmd!=2 ) goto session_syntax_error;
9924      if( pSession->p==0 ) goto session_not_open;
9925      out = fopen(azCmd[1], "wb");
9926      if( out==0 ){
9927        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9928                    azCmd[1]);
9929      }else{
9930        int szChng;
9931        void *pChng;
9932        if( azCmd[0][0]=='c' ){
9933          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9934        }else{
9935          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9936        }
9937        if( rc ){
9938          printf("Error: error code %d\n", rc);
9939          rc = 0;
9940        }
9941        if( pChng
9942          && fwrite(pChng, szChng, 1, out)!=1 ){
9943          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9944                  szChng);
9945        }
9946        sqlite3_free(pChng);
9947        fclose(out);
9948      }
9949    }else
9950
9951    /* .session close
9952    ** Close the identified session
9953    */
9954    if( strcmp(azCmd[0], "close")==0 ){
9955      if( nCmd!=1 ) goto session_syntax_error;
9956      if( pAuxDb->nSession ){
9957        session_close(pSession);
9958        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9959      }
9960    }else
9961
9962    /* .session enable ?BOOLEAN?
9963    ** Query or set the enable flag
9964    */
9965    if( strcmp(azCmd[0], "enable")==0 ){
9966      int ii;
9967      if( nCmd>2 ) goto session_syntax_error;
9968      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9969      if( pAuxDb->nSession ){
9970        ii = sqlite3session_enable(pSession->p, ii);
9971        utf8_printf(p->out, "session %s enable flag = %d\n",
9972                    pSession->zName, ii);
9973      }
9974    }else
9975
9976    /* .session filter GLOB ....
9977    ** Set a list of GLOB patterns of table names to be excluded.
9978    */
9979    if( strcmp(azCmd[0], "filter")==0 ){
9980      int ii, nByte;
9981      if( nCmd<2 ) goto session_syntax_error;
9982      if( pAuxDb->nSession ){
9983        for(ii=0; ii<pSession->nFilter; ii++){
9984          sqlite3_free(pSession->azFilter[ii]);
9985        }
9986        sqlite3_free(pSession->azFilter);
9987        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9988        pSession->azFilter = sqlite3_malloc( nByte );
9989        if( pSession->azFilter==0 ){
9990          raw_printf(stderr, "Error: out or memory\n");
9991          exit(1);
9992        }
9993        for(ii=1; ii<nCmd; ii++){
9994          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9995          shell_check_oom(x);
9996        }
9997        pSession->nFilter = ii-1;
9998      }
9999    }else
10000
10001    /* .session indirect ?BOOLEAN?
10002    ** Query or set the indirect flag
10003    */
10004    if( strcmp(azCmd[0], "indirect")==0 ){
10005      int ii;
10006      if( nCmd>2 ) goto session_syntax_error;
10007      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10008      if( pAuxDb->nSession ){
10009        ii = sqlite3session_indirect(pSession->p, ii);
10010        utf8_printf(p->out, "session %s indirect flag = %d\n",
10011                    pSession->zName, ii);
10012      }
10013    }else
10014
10015    /* .session isempty
10016    ** Determine if the session is empty
10017    */
10018    if( strcmp(azCmd[0], "isempty")==0 ){
10019      int ii;
10020      if( nCmd!=1 ) goto session_syntax_error;
10021      if( pAuxDb->nSession ){
10022        ii = sqlite3session_isempty(pSession->p);
10023        utf8_printf(p->out, "session %s isempty flag = %d\n",
10024                    pSession->zName, ii);
10025      }
10026    }else
10027
10028    /* .session list
10029    ** List all currently open sessions
10030    */
10031    if( strcmp(azCmd[0],"list")==0 ){
10032      for(i=0; i<pAuxDb->nSession; i++){
10033        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10034      }
10035    }else
10036
10037    /* .session open DB NAME
10038    ** Open a new session called NAME on the attached database DB.
10039    ** DB is normally "main".
10040    */
10041    if( strcmp(azCmd[0],"open")==0 ){
10042      char *zName;
10043      if( nCmd!=3 ) goto session_syntax_error;
10044      zName = azCmd[2];
10045      if( zName[0]==0 ) goto session_syntax_error;
10046      for(i=0; i<pAuxDb->nSession; i++){
10047        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10048          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10049          goto meta_command_exit;
10050        }
10051      }
10052      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10053        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10054        goto meta_command_exit;
10055      }
10056      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10057      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10058      if( rc ){
10059        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10060        rc = 0;
10061        goto meta_command_exit;
10062      }
10063      pSession->nFilter = 0;
10064      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10065      pAuxDb->nSession++;
10066      pSession->zName = sqlite3_mprintf("%s", zName);
10067      shell_check_oom(pSession->zName);
10068    }else
10069    /* If no command name matches, show a syntax error */
10070    session_syntax_error:
10071    showHelp(p->out, "session");
10072  }else
10073#endif
10074
10075#ifdef SQLITE_DEBUG
10076  /* Undocumented commands for internal testing.  Subject to change
10077  ** without notice. */
10078  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10079    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10080      int i, v;
10081      for(i=1; i<nArg; i++){
10082        v = booleanValue(azArg[i]);
10083        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10084      }
10085    }
10086    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10087      int i; sqlite3_int64 v;
10088      for(i=1; i<nArg; i++){
10089        char zBuf[200];
10090        v = integerValue(azArg[i]);
10091        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10092        utf8_printf(p->out, "%s", zBuf);
10093      }
10094    }
10095  }else
10096#endif
10097
10098  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10099    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10100    int bVerbose = 0;        /* Verbose output */
10101    int bSelftestExists;     /* True if SELFTEST already exists */
10102    int i, k;                /* Loop counters */
10103    int nTest = 0;           /* Number of tests runs */
10104    int nErr = 0;            /* Number of errors seen */
10105    ShellText str;           /* Answer for a query */
10106    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10107
10108    open_db(p,0);
10109    for(i=1; i<nArg; i++){
10110      const char *z = azArg[i];
10111      if( z[0]=='-' && z[1]=='-' ) z++;
10112      if( strcmp(z,"-init")==0 ){
10113        bIsInit = 1;
10114      }else
10115      if( strcmp(z,"-v")==0 ){
10116        bVerbose++;
10117      }else
10118      {
10119        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10120                    azArg[i], azArg[0]);
10121        raw_printf(stderr, "Should be one of: --init -v\n");
10122        rc = 1;
10123        goto meta_command_exit;
10124      }
10125    }
10126    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10127           != SQLITE_OK ){
10128      bSelftestExists = 0;
10129    }else{
10130      bSelftestExists = 1;
10131    }
10132    if( bIsInit ){
10133      createSelftestTable(p);
10134      bSelftestExists = 1;
10135    }
10136    initText(&str);
10137    appendText(&str, "x", 0);
10138    for(k=bSelftestExists; k>=0; k--){
10139      if( k==1 ){
10140        rc = sqlite3_prepare_v2(p->db,
10141            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10142            -1, &pStmt, 0);
10143      }else{
10144        rc = sqlite3_prepare_v2(p->db,
10145          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10146          "      (1,'run','PRAGMA integrity_check','ok')",
10147          -1, &pStmt, 0);
10148      }
10149      if( rc ){
10150        raw_printf(stderr, "Error querying the selftest table\n");
10151        rc = 1;
10152        sqlite3_finalize(pStmt);
10153        goto meta_command_exit;
10154      }
10155      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10156        int tno = sqlite3_column_int(pStmt, 0);
10157        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10158        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10159        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10160
10161        if( zOp==0 ) continue;
10162        if( zSql==0 ) continue;
10163        if( zAns==0 ) continue;
10164        k = 0;
10165        if( bVerbose>0 ){
10166          printf("%d: %s %s\n", tno, zOp, zSql);
10167        }
10168        if( strcmp(zOp,"memo")==0 ){
10169          utf8_printf(p->out, "%s\n", zSql);
10170        }else
10171        if( strcmp(zOp,"run")==0 ){
10172          char *zErrMsg = 0;
10173          str.n = 0;
10174          str.z[0] = 0;
10175          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10176          nTest++;
10177          if( bVerbose ){
10178            utf8_printf(p->out, "Result: %s\n", str.z);
10179          }
10180          if( rc || zErrMsg ){
10181            nErr++;
10182            rc = 1;
10183            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10184            sqlite3_free(zErrMsg);
10185          }else if( strcmp(zAns,str.z)!=0 ){
10186            nErr++;
10187            rc = 1;
10188            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10189            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10190          }
10191        }else
10192        {
10193          utf8_printf(stderr,
10194            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10195          rc = 1;
10196          break;
10197        }
10198      } /* End loop over rows of content from SELFTEST */
10199      sqlite3_finalize(pStmt);
10200    } /* End loop over k */
10201    freeText(&str);
10202    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10203  }else
10204
10205  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10206    if( nArg<2 || nArg>3 ){
10207      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10208      rc = 1;
10209    }
10210    if( nArg>=2 ){
10211      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10212                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10213    }
10214    if( nArg>=3 ){
10215      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10216                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10217    }
10218  }else
10219
10220  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10221    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10222    int i;                   /* Loop counter */
10223    int bSchema = 0;         /* Also hash the schema */
10224    int bSeparate = 0;       /* Hash each table separately */
10225    int iSize = 224;         /* Hash algorithm to use */
10226    int bDebug = 0;          /* Only show the query that would have run */
10227    sqlite3_stmt *pStmt;     /* For querying tables names */
10228    char *zSql;              /* SQL to be run */
10229    char *zSep;              /* Separator */
10230    ShellText sSql;          /* Complete SQL for the query to run the hash */
10231    ShellText sQuery;        /* Set of queries used to read all content */
10232    open_db(p, 0);
10233    for(i=1; i<nArg; i++){
10234      const char *z = azArg[i];
10235      if( z[0]=='-' ){
10236        z++;
10237        if( z[0]=='-' ) z++;
10238        if( strcmp(z,"schema")==0 ){
10239          bSchema = 1;
10240        }else
10241        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10242         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10243        ){
10244          iSize = atoi(&z[5]);
10245        }else
10246        if( strcmp(z,"debug")==0 ){
10247          bDebug = 1;
10248        }else
10249        {
10250          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10251                      azArg[i], azArg[0]);
10252          showHelp(p->out, azArg[0]);
10253          rc = 1;
10254          goto meta_command_exit;
10255        }
10256      }else if( zLike ){
10257        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10258        rc = 1;
10259        goto meta_command_exit;
10260      }else{
10261        zLike = z;
10262        bSeparate = 1;
10263        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10264      }
10265    }
10266    if( bSchema ){
10267      zSql = "SELECT lower(name) FROM sqlite_schema"
10268             " WHERE type='table' AND coalesce(rootpage,0)>1"
10269             " UNION ALL SELECT 'sqlite_schema'"
10270             " ORDER BY 1 collate nocase";
10271    }else{
10272      zSql = "SELECT lower(name) FROM sqlite_schema"
10273             " WHERE type='table' AND coalesce(rootpage,0)>1"
10274             " AND name NOT LIKE 'sqlite_%'"
10275             " ORDER BY 1 collate nocase";
10276    }
10277    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10278    initText(&sQuery);
10279    initText(&sSql);
10280    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10281    zSep = "VALUES(";
10282    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10283      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10284      if( zTab==0 ) continue;
10285      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10286      if( strncmp(zTab, "sqlite_",7)!=0 ){
10287        appendText(&sQuery,"SELECT * FROM ", 0);
10288        appendText(&sQuery,zTab,'"');
10289        appendText(&sQuery," NOT INDEXED;", 0);
10290      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10291        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10292                           " ORDER BY name;", 0);
10293      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10294        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10295                           " ORDER BY name;", 0);
10296      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10297        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10298                           " ORDER BY tbl,idx;", 0);
10299      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10300        appendText(&sQuery, "SELECT * FROM ", 0);
10301        appendText(&sQuery, zTab, 0);
10302        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10303      }
10304      appendText(&sSql, zSep, 0);
10305      appendText(&sSql, sQuery.z, '\'');
10306      sQuery.n = 0;
10307      appendText(&sSql, ",", 0);
10308      appendText(&sSql, zTab, '\'');
10309      zSep = "),(";
10310    }
10311    sqlite3_finalize(pStmt);
10312    if( bSeparate ){
10313      zSql = sqlite3_mprintf(
10314          "%s))"
10315          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10316          "   FROM [sha3sum$query]",
10317          sSql.z, iSize);
10318    }else{
10319      zSql = sqlite3_mprintf(
10320          "%s))"
10321          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10322          "   FROM [sha3sum$query]",
10323          sSql.z, iSize);
10324    }
10325    shell_check_oom(zSql);
10326    freeText(&sQuery);
10327    freeText(&sSql);
10328    if( bDebug ){
10329      utf8_printf(p->out, "%s\n", zSql);
10330    }else{
10331      shell_exec(p, zSql, 0);
10332    }
10333    sqlite3_free(zSql);
10334  }else
10335
10336#ifndef SQLITE_NOHAVE_SYSTEM
10337  if( c=='s'
10338   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10339  ){
10340    char *zCmd;
10341    int i, x;
10342    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10343    if( nArg<2 ){
10344      raw_printf(stderr, "Usage: .system COMMAND\n");
10345      rc = 1;
10346      goto meta_command_exit;
10347    }
10348    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10349    for(i=2; i<nArg && zCmd!=0; i++){
10350      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10351                             zCmd, azArg[i]);
10352    }
10353    x = zCmd!=0 ? system(zCmd) : 1;
10354    sqlite3_free(zCmd);
10355    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10356  }else
10357#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
10358
10359  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10360    static const char *azBool[] = { "off", "on", "trigger", "full"};
10361    const char *zOut;
10362    int i;
10363    if( nArg!=1 ){
10364      raw_printf(stderr, "Usage: .show\n");
10365      rc = 1;
10366      goto meta_command_exit;
10367    }
10368    utf8_printf(p->out, "%12.12s: %s\n","echo",
10369                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
10370    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10371    utf8_printf(p->out, "%12.12s: %s\n","explain",
10372         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10373    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10374    if( p->mode==MODE_Column
10375     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10376    ){
10377      utf8_printf
10378        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10379         modeDescr[p->mode], p->cmOpts.iWrap,
10380         p->cmOpts.bWordWrap ? "on" : "off",
10381         p->cmOpts.bQuote ? "" : "no");
10382    }else{
10383      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10384    }
10385    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10386      output_c_string(p->out, p->nullValue);
10387      raw_printf(p->out, "\n");
10388    utf8_printf(p->out,"%12.12s: %s\n","output",
10389            strlen30(p->outfile) ? p->outfile : "stdout");
10390    utf8_printf(p->out,"%12.12s: ", "colseparator");
10391      output_c_string(p->out, p->colSeparator);
10392      raw_printf(p->out, "\n");
10393    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10394      output_c_string(p->out, p->rowSeparator);
10395      raw_printf(p->out, "\n");
10396    switch( p->statsOn ){
10397      case 0:  zOut = "off";     break;
10398      default: zOut = "on";      break;
10399      case 2:  zOut = "stmt";    break;
10400      case 3:  zOut = "vmstep";  break;
10401    }
10402    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10403    utf8_printf(p->out, "%12.12s: ", "width");
10404    for (i=0;i<p->nWidth;i++) {
10405      raw_printf(p->out, "%d ", p->colWidth[i]);
10406    }
10407    raw_printf(p->out, "\n");
10408    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10409                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10410  }else
10411
10412  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10413    if( nArg==2 ){
10414      if( strcmp(azArg[1],"stmt")==0 ){
10415        p->statsOn = 2;
10416      }else if( strcmp(azArg[1],"vmstep")==0 ){
10417        p->statsOn = 3;
10418      }else{
10419        p->statsOn = (u8)booleanValue(azArg[1]);
10420      }
10421    }else if( nArg==1 ){
10422      display_stats(p->db, p, 0);
10423    }else{
10424      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10425      rc = 1;
10426    }
10427  }else
10428
10429  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10430   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10431                 || strncmp(azArg[0], "indexes", n)==0) )
10432  ){
10433    sqlite3_stmt *pStmt;
10434    char **azResult;
10435    int nRow, nAlloc;
10436    int ii;
10437    ShellText s;
10438    initText(&s);
10439    open_db(p, 0);
10440    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10441    if( rc ){
10442      sqlite3_finalize(pStmt);
10443      return shellDatabaseError(p->db);
10444    }
10445
10446    if( nArg>2 && c=='i' ){
10447      /* It is an historical accident that the .indexes command shows an error
10448      ** when called with the wrong number of arguments whereas the .tables
10449      ** command does not. */
10450      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10451      rc = 1;
10452      sqlite3_finalize(pStmt);
10453      goto meta_command_exit;
10454    }
10455    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10456      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10457      if( zDbName==0 ) continue;
10458      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10459      if( sqlite3_stricmp(zDbName, "main")==0 ){
10460        appendText(&s, "SELECT name FROM ", 0);
10461      }else{
10462        appendText(&s, "SELECT ", 0);
10463        appendText(&s, zDbName, '\'');
10464        appendText(&s, "||'.'||name FROM ", 0);
10465      }
10466      appendText(&s, zDbName, '"');
10467      appendText(&s, ".sqlite_schema ", 0);
10468      if( c=='t' ){
10469        appendText(&s," WHERE type IN ('table','view')"
10470                      "   AND name NOT LIKE 'sqlite_%'"
10471                      "   AND name LIKE ?1", 0);
10472      }else{
10473        appendText(&s," WHERE type='index'"
10474                      "   AND tbl_name LIKE ?1", 0);
10475      }
10476    }
10477    rc = sqlite3_finalize(pStmt);
10478    if( rc==SQLITE_OK ){
10479      appendText(&s, " ORDER BY 1", 0);
10480      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10481    }
10482    freeText(&s);
10483    if( rc ) return shellDatabaseError(p->db);
10484
10485    /* Run the SQL statement prepared by the above block. Store the results
10486    ** as an array of nul-terminated strings in azResult[].  */
10487    nRow = nAlloc = 0;
10488    azResult = 0;
10489    if( nArg>1 ){
10490      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10491    }else{
10492      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10493    }
10494    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10495      if( nRow>=nAlloc ){
10496        char **azNew;
10497        int n2 = nAlloc*2 + 10;
10498        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10499        shell_check_oom(azNew);
10500        nAlloc = n2;
10501        azResult = azNew;
10502      }
10503      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10504      shell_check_oom(azResult[nRow]);
10505      nRow++;
10506    }
10507    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10508      rc = shellDatabaseError(p->db);
10509    }
10510
10511    /* Pretty-print the contents of array azResult[] to the output */
10512    if( rc==0 && nRow>0 ){
10513      int len, maxlen = 0;
10514      int i, j;
10515      int nPrintCol, nPrintRow;
10516      for(i=0; i<nRow; i++){
10517        len = strlen30(azResult[i]);
10518        if( len>maxlen ) maxlen = len;
10519      }
10520      nPrintCol = 80/(maxlen+2);
10521      if( nPrintCol<1 ) nPrintCol = 1;
10522      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10523      for(i=0; i<nPrintRow; i++){
10524        for(j=i; j<nRow; j+=nPrintRow){
10525          char *zSp = j<nPrintRow ? "" : "  ";
10526          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10527                      azResult[j] ? azResult[j]:"");
10528        }
10529        raw_printf(p->out, "\n");
10530      }
10531    }
10532
10533    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10534    sqlite3_free(azResult);
10535  }else
10536
10537  /* Begin redirecting output to the file "testcase-out.txt" */
10538  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10539    output_reset(p);
10540    p->out = output_file_open("testcase-out.txt", 0);
10541    if( p->out==0 ){
10542      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10543    }
10544    if( nArg>=2 ){
10545      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10546    }else{
10547      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10548    }
10549  }else
10550
10551#ifndef SQLITE_UNTESTABLE
10552  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10553    static const struct {
10554       const char *zCtrlName;   /* Name of a test-control option */
10555       int ctrlCode;            /* Integer code for that option */
10556       int unSafe;              /* Not valid for --safe mode */
10557       const char *zUsage;      /* Usage notes */
10558    } aCtrl[] = {
10559      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10560      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10561    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10562    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10563      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10564      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10565    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10566      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10567      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10568      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10569      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10570      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10571#ifdef YYCOVERAGE
10572      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10573#endif
10574      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10575      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10576      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10577      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10578      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10579      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10580      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10581    };
10582    int testctrl = -1;
10583    int iCtrl = -1;
10584    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10585    int isOk = 0;
10586    int i, n2;
10587    const char *zCmd = 0;
10588
10589    open_db(p, 0);
10590    zCmd = nArg>=2 ? azArg[1] : "help";
10591
10592    /* The argument can optionally begin with "-" or "--" */
10593    if( zCmd[0]=='-' && zCmd[1] ){
10594      zCmd++;
10595      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10596    }
10597
10598    /* --help lists all test-controls */
10599    if( strcmp(zCmd,"help")==0 ){
10600      utf8_printf(p->out, "Available test-controls:\n");
10601      for(i=0; i<ArraySize(aCtrl); i++){
10602        utf8_printf(p->out, "  .testctrl %s %s\n",
10603                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10604      }
10605      rc = 1;
10606      goto meta_command_exit;
10607    }
10608
10609    /* convert testctrl text option to value. allow any unique prefix
10610    ** of the option name, or a numerical value. */
10611    n2 = strlen30(zCmd);
10612    for(i=0; i<ArraySize(aCtrl); i++){
10613      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10614        if( testctrl<0 ){
10615          testctrl = aCtrl[i].ctrlCode;
10616          iCtrl = i;
10617        }else{
10618          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10619                              "Use \".testctrl --help\" for help\n", zCmd);
10620          rc = 1;
10621          goto meta_command_exit;
10622        }
10623      }
10624    }
10625    if( testctrl<0 ){
10626      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10627                         "Use \".testctrl --help\" for help\n", zCmd);
10628    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10629      utf8_printf(stderr,
10630         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10631         p->lineno, aCtrl[iCtrl].zCtrlName);
10632      exit(1);
10633    }else{
10634      switch(testctrl){
10635
10636        /* sqlite3_test_control(int, db, int) */
10637        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10638          if( nArg==3 ){
10639            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10640            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10641            isOk = 3;
10642          }
10643          break;
10644
10645        /* sqlite3_test_control(int) */
10646        case SQLITE_TESTCTRL_PRNG_SAVE:
10647        case SQLITE_TESTCTRL_PRNG_RESTORE:
10648        case SQLITE_TESTCTRL_BYTEORDER:
10649          if( nArg==2 ){
10650            rc2 = sqlite3_test_control(testctrl);
10651            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10652          }
10653          break;
10654
10655        /* sqlite3_test_control(int, uint) */
10656        case SQLITE_TESTCTRL_PENDING_BYTE:
10657          if( nArg==3 ){
10658            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10659            rc2 = sqlite3_test_control(testctrl, opt);
10660            isOk = 3;
10661          }
10662          break;
10663
10664        /* sqlite3_test_control(int, int, sqlite3*) */
10665        case SQLITE_TESTCTRL_PRNG_SEED:
10666          if( nArg==3 || nArg==4 ){
10667            int ii = (int)integerValue(azArg[2]);
10668            sqlite3 *db;
10669            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10670              sqlite3_randomness(sizeof(ii),&ii);
10671              printf("-- random seed: %d\n", ii);
10672            }
10673            if( nArg==3 ){
10674              db = 0;
10675            }else{
10676              db = p->db;
10677              /* Make sure the schema has been loaded */
10678              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10679            }
10680            rc2 = sqlite3_test_control(testctrl, ii, db);
10681            isOk = 3;
10682          }
10683          break;
10684
10685        /* sqlite3_test_control(int, int) */
10686        case SQLITE_TESTCTRL_ASSERT:
10687        case SQLITE_TESTCTRL_ALWAYS:
10688          if( nArg==3 ){
10689            int opt = booleanValue(azArg[2]);
10690            rc2 = sqlite3_test_control(testctrl, opt);
10691            isOk = 1;
10692          }
10693          break;
10694
10695        /* sqlite3_test_control(int, int) */
10696        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10697        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10698          if( nArg==3 ){
10699            int opt = booleanValue(azArg[2]);
10700            rc2 = sqlite3_test_control(testctrl, opt);
10701            isOk = 3;
10702          }
10703          break;
10704
10705        /* sqlite3_test_control(sqlite3*) */
10706        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10707          rc2 = sqlite3_test_control(testctrl, p->db);
10708          isOk = 3;
10709          break;
10710
10711        case SQLITE_TESTCTRL_IMPOSTER:
10712          if( nArg==5 ){
10713            rc2 = sqlite3_test_control(testctrl, p->db,
10714                          azArg[2],
10715                          integerValue(azArg[3]),
10716                          integerValue(azArg[4]));
10717            isOk = 3;
10718          }
10719          break;
10720
10721        case SQLITE_TESTCTRL_SEEK_COUNT: {
10722          u64 x = 0;
10723          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10724          utf8_printf(p->out, "%llu\n", x);
10725          isOk = 3;
10726          break;
10727        }
10728
10729#ifdef YYCOVERAGE
10730        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10731          if( nArg==2 ){
10732            sqlite3_test_control(testctrl, p->out);
10733            isOk = 3;
10734          }
10735          break;
10736        }
10737#endif
10738#ifdef SQLITE_DEBUG
10739        case SQLITE_TESTCTRL_TUNE: {
10740          if( nArg==4 ){
10741            int id = (int)integerValue(azArg[2]);
10742            int val = (int)integerValue(azArg[3]);
10743            sqlite3_test_control(testctrl, id, &val);
10744            isOk = 3;
10745          }else if( nArg==3 ){
10746            int id = (int)integerValue(azArg[2]);
10747            sqlite3_test_control(testctrl, -id, &rc2);
10748            isOk = 1;
10749          }else if( nArg==2 ){
10750            int id = 1;
10751            while(1){
10752              int val = 0;
10753              rc2 = sqlite3_test_control(testctrl, -id, &val);
10754              if( rc2!=SQLITE_OK ) break;
10755              if( id>1 ) utf8_printf(p->out, "  ");
10756              utf8_printf(p->out, "%d: %d", id, val);
10757              id++;
10758            }
10759            if( id>1 ) utf8_printf(p->out, "\n");
10760            isOk = 3;
10761          }
10762          break;
10763        }
10764#endif
10765        case SQLITE_TESTCTRL_SORTER_MMAP:
10766          if( nArg==3 ){
10767            int opt = (unsigned int)integerValue(azArg[2]);
10768            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10769            isOk = 3;
10770          }
10771          break;
10772      }
10773    }
10774    if( isOk==0 && iCtrl>=0 ){
10775      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10776      rc = 1;
10777    }else if( isOk==1 ){
10778      raw_printf(p->out, "%d\n", rc2);
10779    }else if( isOk==2 ){
10780      raw_printf(p->out, "0x%08x\n", rc2);
10781    }
10782  }else
10783#endif /* !defined(SQLITE_UNTESTABLE) */
10784
10785  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10786    open_db(p, 0);
10787    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10788  }else
10789
10790  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10791    if( nArg==2 ){
10792      enableTimer = booleanValue(azArg[1]);
10793      if( enableTimer && !HAS_TIMER ){
10794        raw_printf(stderr, "Error: timer not available on this system.\n");
10795        enableTimer = 0;
10796      }
10797    }else{
10798      raw_printf(stderr, "Usage: .timer on|off\n");
10799      rc = 1;
10800    }
10801  }else
10802
10803#ifndef SQLITE_OMIT_TRACE
10804  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10805    int mType = 0;
10806    int jj;
10807    open_db(p, 0);
10808    for(jj=1; jj<nArg; jj++){
10809      const char *z = azArg[jj];
10810      if( z[0]=='-' ){
10811        if( optionMatch(z, "expanded") ){
10812          p->eTraceType = SHELL_TRACE_EXPANDED;
10813        }
10814#ifdef SQLITE_ENABLE_NORMALIZE
10815        else if( optionMatch(z, "normalized") ){
10816          p->eTraceType = SHELL_TRACE_NORMALIZED;
10817        }
10818#endif
10819        else if( optionMatch(z, "plain") ){
10820          p->eTraceType = SHELL_TRACE_PLAIN;
10821        }
10822        else if( optionMatch(z, "profile") ){
10823          mType |= SQLITE_TRACE_PROFILE;
10824        }
10825        else if( optionMatch(z, "row") ){
10826          mType |= SQLITE_TRACE_ROW;
10827        }
10828        else if( optionMatch(z, "stmt") ){
10829          mType |= SQLITE_TRACE_STMT;
10830        }
10831        else if( optionMatch(z, "close") ){
10832          mType |= SQLITE_TRACE_CLOSE;
10833        }
10834        else {
10835          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10836          rc = 1;
10837          goto meta_command_exit;
10838        }
10839      }else{
10840        output_file_close(p->traceOut);
10841        p->traceOut = output_file_open(azArg[1], 0);
10842      }
10843    }
10844    if( p->traceOut==0 ){
10845      sqlite3_trace_v2(p->db, 0, 0, 0);
10846    }else{
10847      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10848      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10849    }
10850  }else
10851#endif /* !defined(SQLITE_OMIT_TRACE) */
10852
10853#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10854  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10855    int ii;
10856    int lenOpt;
10857    char *zOpt;
10858    if( nArg<2 ){
10859      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10860      rc = 1;
10861      goto meta_command_exit;
10862    }
10863    open_db(p, 0);
10864    zOpt = azArg[1];
10865    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10866    lenOpt = (int)strlen(zOpt);
10867    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10868      assert( azArg[nArg]==0 );
10869      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10870    }else{
10871      for(ii=1; ii<nArg; ii++){
10872        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10873      }
10874    }
10875  }else
10876#endif
10877
10878#if SQLITE_USER_AUTHENTICATION
10879  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10880    if( nArg<2 ){
10881      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10882      rc = 1;
10883      goto meta_command_exit;
10884    }
10885    open_db(p, 0);
10886    if( strcmp(azArg[1],"login")==0 ){
10887      if( nArg!=4 ){
10888        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10889        rc = 1;
10890        goto meta_command_exit;
10891      }
10892      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10893                                     strlen30(azArg[3]));
10894      if( rc ){
10895        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10896        rc = 1;
10897      }
10898    }else if( strcmp(azArg[1],"add")==0 ){
10899      if( nArg!=5 ){
10900        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10901        rc = 1;
10902        goto meta_command_exit;
10903      }
10904      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10905                            booleanValue(azArg[4]));
10906      if( rc ){
10907        raw_printf(stderr, "User-Add failed: %d\n", rc);
10908        rc = 1;
10909      }
10910    }else if( strcmp(azArg[1],"edit")==0 ){
10911      if( nArg!=5 ){
10912        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10913        rc = 1;
10914        goto meta_command_exit;
10915      }
10916      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10917                              booleanValue(azArg[4]));
10918      if( rc ){
10919        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10920        rc = 1;
10921      }
10922    }else if( strcmp(azArg[1],"delete")==0 ){
10923      if( nArg!=3 ){
10924        raw_printf(stderr, "Usage: .user delete USER\n");
10925        rc = 1;
10926        goto meta_command_exit;
10927      }
10928      rc = sqlite3_user_delete(p->db, azArg[2]);
10929      if( rc ){
10930        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10931        rc = 1;
10932      }
10933    }else{
10934      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10935      rc = 1;
10936      goto meta_command_exit;
10937    }
10938  }else
10939#endif /* SQLITE_USER_AUTHENTICATION */
10940
10941  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10942    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10943        sqlite3_libversion(), sqlite3_sourceid());
10944#if SQLITE_HAVE_ZLIB
10945    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10946#endif
10947#define CTIMEOPT_VAL_(opt) #opt
10948#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10949#if defined(__clang__) && defined(__clang_major__)
10950    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10951                    CTIMEOPT_VAL(__clang_minor__) "."
10952                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10953#elif defined(_MSC_VER)
10954    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10955#elif defined(__GNUC__) && defined(__VERSION__)
10956    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10957#endif
10958  }else
10959
10960  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10961    const char *zDbName = nArg==2 ? azArg[1] : "main";
10962    sqlite3_vfs *pVfs = 0;
10963    if( p->db ){
10964      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10965      if( pVfs ){
10966        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10967        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10968        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10969        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10970      }
10971    }
10972  }else
10973
10974  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10975    sqlite3_vfs *pVfs;
10976    sqlite3_vfs *pCurrent = 0;
10977    if( p->db ){
10978      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10979    }
10980    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10981      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10982           pVfs==pCurrent ? "  <--- CURRENT" : "");
10983      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10984      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10985      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10986      if( pVfs->pNext ){
10987        raw_printf(p->out, "-----------------------------------\n");
10988      }
10989    }
10990  }else
10991
10992  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10993    const char *zDbName = nArg==2 ? azArg[1] : "main";
10994    char *zVfsName = 0;
10995    if( p->db ){
10996      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10997      if( zVfsName ){
10998        utf8_printf(p->out, "%s\n", zVfsName);
10999        sqlite3_free(zVfsName);
11000      }
11001    }
11002  }else
11003
11004  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11005    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11006    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11007  }else
11008
11009  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11010    int j;
11011    assert( nArg<=ArraySize(azArg) );
11012    p->nWidth = nArg-1;
11013    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11014    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11015    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11016    for(j=1; j<nArg; j++){
11017      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11018    }
11019  }else
11020
11021  {
11022    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11023      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11024    rc = 1;
11025  }
11026
11027meta_command_exit:
11028  if( p->outCount ){
11029    p->outCount--;
11030    if( p->outCount==0 ) output_reset(p);
11031  }
11032  p->bSafeMode = p->bSafeModePersist;
11033  return rc;
11034}
11035
11036/* Line scan result and intermediate states (supporting scan resumption)
11037*/
11038#ifndef CHAR_BIT
11039# define CHAR_BIT 8
11040#endif
11041typedef enum {
11042  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11043  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11044  QSS_Start = 0
11045} QuickScanState;
11046#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11047#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11048#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11049#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11050#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11051
11052/*
11053** Scan line for classification to guide shell's handling.
11054** The scan is resumable for subsequent lines when prior
11055** return values are passed as the 2nd argument.
11056*/
11057static QuickScanState quickscan(char *zLine, QuickScanState qss){
11058  char cin;
11059  char cWait = (char)qss; /* intentional narrowing loss */
11060  if( cWait==0 ){
11061  PlainScan:
11062    assert( cWait==0 );
11063    while( (cin = *zLine++)!=0 ){
11064      if( IsSpace(cin) )
11065        continue;
11066      switch (cin){
11067      case '-':
11068        if( *zLine!='-' )
11069          break;
11070        while((cin = *++zLine)!=0 )
11071          if( cin=='\n')
11072            goto PlainScan;
11073        return qss;
11074      case ';':
11075        qss |= QSS_EndingSemi;
11076        continue;
11077      case '/':
11078        if( *zLine=='*' ){
11079          ++zLine;
11080          cWait = '*';
11081          qss = QSS_SETV(qss, cWait);
11082          goto TermScan;
11083        }
11084        break;
11085      case '[':
11086        cin = ']';
11087        /* fall thru */
11088      case '`': case '\'': case '"':
11089        cWait = cin;
11090        qss = QSS_HasDark | cWait;
11091        goto TermScan;
11092      default:
11093        break;
11094      }
11095      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11096    }
11097  }else{
11098  TermScan:
11099    while( (cin = *zLine++)!=0 ){
11100      if( cin==cWait ){
11101        switch( cWait ){
11102        case '*':
11103          if( *zLine != '/' )
11104            continue;
11105          ++zLine;
11106          cWait = 0;
11107          qss = QSS_SETV(qss, 0);
11108          goto PlainScan;
11109        case '`': case '\'': case '"':
11110          if(*zLine==cWait){
11111            ++zLine;
11112            continue;
11113          }
11114          /* fall thru */
11115        case ']':
11116          cWait = 0;
11117          qss = QSS_SETV(qss, 0);
11118          goto PlainScan;
11119        default: assert(0);
11120        }
11121      }
11122    }
11123  }
11124  return qss;
11125}
11126
11127/*
11128** Return TRUE if the line typed in is an SQL command terminator other
11129** than a semi-colon.  The SQL Server style "go" command is understood
11130** as is the Oracle "/".
11131*/
11132static int line_is_command_terminator(char *zLine){
11133  while( IsSpace(zLine[0]) ){ zLine++; };
11134  if( zLine[0]=='/' )
11135    zLine += 1; /* Oracle */
11136  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11137    zLine += 2; /* SQL Server */
11138  else
11139    return 0;
11140  return quickscan(zLine,QSS_Start)==QSS_Start;
11141}
11142
11143/*
11144** We need a default sqlite3_complete() implementation to use in case
11145** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11146** any arbitrary text is a complete SQL statement.  This is not very
11147** user-friendly, but it does seem to work.
11148*/
11149#ifdef SQLITE_OMIT_COMPLETE
11150#define sqlite3_complete(x) 1
11151#endif
11152
11153/*
11154** Return true if zSql is a complete SQL statement.  Return false if it
11155** ends in the middle of a string literal or C-style comment.
11156*/
11157static int line_is_complete(char *zSql, int nSql){
11158  int rc;
11159  if( zSql==0 ) return 1;
11160  zSql[nSql] = ';';
11161  zSql[nSql+1] = 0;
11162  rc = sqlite3_complete(zSql);
11163  zSql[nSql] = 0;
11164  return rc;
11165}
11166
11167/*
11168** Run a single line of SQL.  Return the number of errors.
11169*/
11170static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11171  int rc;
11172  char *zErrMsg = 0;
11173
11174  open_db(p, 0);
11175  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11176  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11177  BEGIN_TIMER;
11178  rc = shell_exec(p, zSql, &zErrMsg);
11179  END_TIMER;
11180  if( rc || zErrMsg ){
11181    char zPrefix[100];
11182    if( in!=0 || !stdin_is_interactive ){
11183      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11184                       "Error: near line %d:", startline);
11185    }else{
11186      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
11187    }
11188    if( zErrMsg!=0 ){
11189      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
11190      sqlite3_free(zErrMsg);
11191      zErrMsg = 0;
11192    }else{
11193      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
11194    }
11195    return 1;
11196  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11197    char zLineBuf[2000];
11198    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11199            "changes: %lld   total_changes: %lld",
11200            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11201    raw_printf(p->out, "%s\n", zLineBuf);
11202  }
11203  return 0;
11204}
11205
11206
11207/*
11208** Read input from *in and process it.  If *in==0 then input
11209** is interactive - the user is typing it it.  Otherwise, input
11210** is coming from a file or device.  A prompt is issued and history
11211** is saved only if input is interactive.  An interrupt signal will
11212** cause this routine to exit immediately, unless input is interactive.
11213**
11214** Return the number of errors.
11215*/
11216static int process_input(ShellState *p){
11217  char *zLine = 0;          /* A single input line */
11218  char *zSql = 0;           /* Accumulated SQL text */
11219  int nLine;                /* Length of current line */
11220  int nSql = 0;             /* Bytes of zSql[] used */
11221  int nAlloc = 0;           /* Allocated zSql[] space */
11222  int rc;                   /* Error code */
11223  int errCnt = 0;           /* Number of errors seen */
11224  int startline = 0;        /* Line number for start of current input */
11225  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11226
11227  if( p->inputNesting==MAX_INPUT_NESTING ){
11228    /* This will be more informative in a later version. */
11229    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11230                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11231    return 1;
11232  }
11233  ++p->inputNesting;
11234  p->lineno = 0;
11235  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11236    fflush(p->out);
11237    zLine = one_input_line(p->in, zLine, nSql>0);
11238    if( zLine==0 ){
11239      /* End of input */
11240      if( p->in==0 && stdin_is_interactive ) printf("\n");
11241      break;
11242    }
11243    if( seenInterrupt ){
11244      if( p->in!=0 ) break;
11245      seenInterrupt = 0;
11246    }
11247    p->lineno++;
11248    if( QSS_INPLAIN(qss)
11249        && line_is_command_terminator(zLine)
11250        && line_is_complete(zSql, nSql) ){
11251      memcpy(zLine,";",2);
11252    }
11253    qss = quickscan(zLine, qss);
11254    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11255      if( ShellHasFlag(p, SHFLG_Echo) )
11256        printf("%s\n", zLine);
11257      /* Just swallow single-line whitespace */
11258      qss = QSS_Start;
11259      continue;
11260    }
11261    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11262      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
11263      if( zLine[0]=='.' ){
11264        rc = do_meta_command(zLine, p);
11265        if( rc==2 ){ /* exit requested */
11266          break;
11267        }else if( rc ){
11268          errCnt++;
11269        }
11270      }
11271      qss = QSS_Start;
11272      continue;
11273    }
11274    /* No single-line dispositions remain; accumulate line(s). */
11275    nLine = strlen30(zLine);
11276    if( nSql+nLine+2>=nAlloc ){
11277      /* Grow buffer by half-again increments when big. */
11278      nAlloc = nSql+(nSql>>1)+nLine+100;
11279      zSql = realloc(zSql, nAlloc);
11280      shell_check_oom(zSql);
11281    }
11282    if( nSql==0 ){
11283      int i;
11284      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11285      assert( nAlloc>0 && zSql!=0 );
11286      memcpy(zSql, zLine+i, nLine+1-i);
11287      startline = p->lineno;
11288      nSql = nLine-i;
11289    }else{
11290      zSql[nSql++] = '\n';
11291      memcpy(zSql+nSql, zLine, nLine+1);
11292      nSql += nLine;
11293    }
11294    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11295      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11296      nSql = 0;
11297      if( p->outCount ){
11298        output_reset(p);
11299        p->outCount = 0;
11300      }else{
11301        clearTempFile(p);
11302      }
11303      p->bSafeMode = p->bSafeModePersist;
11304      qss = QSS_Start;
11305    }else if( nSql && QSS_PLAINWHITE(qss) ){
11306      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
11307      nSql = 0;
11308      qss = QSS_Start;
11309    }
11310  }
11311  if( nSql && QSS_PLAINDARK(qss) ){
11312    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11313  }
11314  free(zSql);
11315  free(zLine);
11316  --p->inputNesting;
11317  return errCnt>0;
11318}
11319
11320/*
11321** Return a pathname which is the user's home directory.  A
11322** 0 return indicates an error of some kind.
11323*/
11324static char *find_home_dir(int clearFlag){
11325  static char *home_dir = NULL;
11326  if( clearFlag ){
11327    free(home_dir);
11328    home_dir = 0;
11329    return 0;
11330  }
11331  if( home_dir ) return home_dir;
11332
11333#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11334     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11335  {
11336    struct passwd *pwent;
11337    uid_t uid = getuid();
11338    if( (pwent=getpwuid(uid)) != NULL) {
11339      home_dir = pwent->pw_dir;
11340    }
11341  }
11342#endif
11343
11344#if defined(_WIN32_WCE)
11345  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11346   */
11347  home_dir = "/";
11348#else
11349
11350#if defined(_WIN32) || defined(WIN32)
11351  if (!home_dir) {
11352    home_dir = getenv("USERPROFILE");
11353  }
11354#endif
11355
11356  if (!home_dir) {
11357    home_dir = getenv("HOME");
11358  }
11359
11360#if defined(_WIN32) || defined(WIN32)
11361  if (!home_dir) {
11362    char *zDrive, *zPath;
11363    int n;
11364    zDrive = getenv("HOMEDRIVE");
11365    zPath = getenv("HOMEPATH");
11366    if( zDrive && zPath ){
11367      n = strlen30(zDrive) + strlen30(zPath) + 1;
11368      home_dir = malloc( n );
11369      if( home_dir==0 ) return 0;
11370      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11371      return home_dir;
11372    }
11373    home_dir = "c:\\";
11374  }
11375#endif
11376
11377#endif /* !_WIN32_WCE */
11378
11379  if( home_dir ){
11380    int n = strlen30(home_dir) + 1;
11381    char *z = malloc( n );
11382    if( z ) memcpy(z, home_dir, n);
11383    home_dir = z;
11384  }
11385
11386  return home_dir;
11387}
11388
11389/*
11390** Read input from the file given by sqliterc_override.  Or if that
11391** parameter is NULL, take input from ~/.sqliterc
11392**
11393** Returns the number of errors.
11394*/
11395static void process_sqliterc(
11396  ShellState *p,                  /* Configuration data */
11397  const char *sqliterc_override   /* Name of config file. NULL to use default */
11398){
11399  char *home_dir = NULL;
11400  const char *sqliterc = sqliterc_override;
11401  char *zBuf = 0;
11402  FILE *inSaved = p->in;
11403  int savedLineno = p->lineno;
11404
11405  if (sqliterc == NULL) {
11406    home_dir = find_home_dir(0);
11407    if( home_dir==0 ){
11408      raw_printf(stderr, "-- warning: cannot find home directory;"
11409                      " cannot read ~/.sqliterc\n");
11410      return;
11411    }
11412    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11413    shell_check_oom(zBuf);
11414    sqliterc = zBuf;
11415  }
11416  p->in = fopen(sqliterc,"rb");
11417  if( p->in ){
11418    if( stdin_is_interactive ){
11419      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11420    }
11421    if( process_input(p) && bail_on_error ) exit(1);
11422    fclose(p->in);
11423  }else if( sqliterc_override!=0 ){
11424    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11425    if( bail_on_error ) exit(1);
11426  }
11427  p->in = inSaved;
11428  p->lineno = savedLineno;
11429  sqlite3_free(zBuf);
11430}
11431
11432/*
11433** Show available command line options
11434*/
11435static const char zOptions[] =
11436#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11437  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11438#endif
11439  "   -append              append the database to the end of the file\n"
11440  "   -ascii               set output mode to 'ascii'\n"
11441  "   -bail                stop after hitting an error\n"
11442  "   -batch               force batch I/O\n"
11443  "   -box                 set output mode to 'box'\n"
11444  "   -column              set output mode to 'column'\n"
11445  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11446  "   -csv                 set output mode to 'csv'\n"
11447#if !defined(SQLITE_OMIT_DESERIALIZE)
11448  "   -deserialize         open the database using sqlite3_deserialize()\n"
11449#endif
11450  "   -echo                print commands before execution\n"
11451  "   -init FILENAME       read/process named file\n"
11452  "   -[no]header          turn headers on or off\n"
11453#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11454  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11455#endif
11456  "   -help                show this message\n"
11457  "   -html                set output mode to HTML\n"
11458  "   -interactive         force interactive I/O\n"
11459  "   -json                set output mode to 'json'\n"
11460  "   -line                set output mode to 'line'\n"
11461  "   -list                set output mode to 'list'\n"
11462  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11463  "   -markdown            set output mode to 'markdown'\n"
11464#if !defined(SQLITE_OMIT_DESERIALIZE)
11465  "   -maxsize N           maximum size for a --deserialize database\n"
11466#endif
11467  "   -memtrace            trace all memory allocations and deallocations\n"
11468  "   -mmap N              default mmap size set to N\n"
11469#ifdef SQLITE_ENABLE_MULTIPLEX
11470  "   -multiplex           enable the multiplexor VFS\n"
11471#endif
11472  "   -newline SEP         set output row separator. Default: '\\n'\n"
11473  "   -nofollow            refuse to open symbolic links to database files\n"
11474  "   -nonce STRING        set the safe-mode escape nonce\n"
11475  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11476  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11477  "   -quote               set output mode to 'quote'\n"
11478  "   -readonly            open the database read-only\n"
11479  "   -safe                enable safe-mode\n"
11480  "   -separator SEP       set output column separator. Default: '|'\n"
11481#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11482  "   -sorterref SIZE      sorter references threshold size\n"
11483#endif
11484  "   -stats               print memory stats before each finalize\n"
11485  "   -table               set output mode to 'table'\n"
11486  "   -tabs                set output mode to 'tabs'\n"
11487  "   -version             show SQLite version\n"
11488  "   -vfs NAME            use NAME as the default VFS\n"
11489#ifdef SQLITE_ENABLE_VFSTRACE
11490  "   -vfstrace            enable tracing of all VFS calls\n"
11491#endif
11492#ifdef SQLITE_HAVE_ZLIB
11493  "   -zip                 open the file as a ZIP Archive\n"
11494#endif
11495;
11496static void usage(int showDetail){
11497  utf8_printf(stderr,
11498      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11499      "FILENAME is the name of an SQLite database. A new database is created\n"
11500      "if the file does not previously exist.\n", Argv0);
11501  if( showDetail ){
11502    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11503  }else{
11504    raw_printf(stderr, "Use the -help option for additional information\n");
11505  }
11506  exit(1);
11507}
11508
11509/*
11510** Internal check:  Verify that the SQLite is uninitialized.  Print a
11511** error message if it is initialized.
11512*/
11513static void verify_uninitialized(void){
11514  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11515    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11516                        " initialization.\n");
11517  }
11518}
11519
11520/*
11521** Initialize the state information in data
11522*/
11523static void main_init(ShellState *data) {
11524  memset(data, 0, sizeof(*data));
11525  data->normalMode = data->cMode = data->mode = MODE_List;
11526  data->autoExplain = 1;
11527  data->pAuxDb = &data->aAuxDb[0];
11528  memcpy(data->colSeparator,SEP_Column, 2);
11529  memcpy(data->rowSeparator,SEP_Row, 2);
11530  data->showHeader = 0;
11531  data->shellFlgs = SHFLG_Lookaside;
11532  verify_uninitialized();
11533  sqlite3_config(SQLITE_CONFIG_URI, 1);
11534  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11535  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11536  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11537  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11538}
11539
11540/*
11541** Output text to the console in a font that attracts extra attention.
11542*/
11543#ifdef _WIN32
11544static void printBold(const char *zText){
11545#if !SQLITE_OS_WINRT
11546  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11547  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11548  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11549  SetConsoleTextAttribute(out,
11550         FOREGROUND_RED|FOREGROUND_INTENSITY
11551  );
11552#endif
11553  printf("%s", zText);
11554#if !SQLITE_OS_WINRT
11555  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11556#endif
11557}
11558#else
11559static void printBold(const char *zText){
11560  printf("\033[1m%s\033[0m", zText);
11561}
11562#endif
11563
11564/*
11565** Get the argument to an --option.  Throw an error and die if no argument
11566** is available.
11567*/
11568static char *cmdline_option_value(int argc, char **argv, int i){
11569  if( i==argc ){
11570    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11571            argv[0], argv[argc-1]);
11572    exit(1);
11573  }
11574  return argv[i];
11575}
11576
11577#ifndef SQLITE_SHELL_IS_UTF8
11578#  if (defined(_WIN32) || defined(WIN32)) \
11579   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11580#    define SQLITE_SHELL_IS_UTF8          (0)
11581#  else
11582#    define SQLITE_SHELL_IS_UTF8          (1)
11583#  endif
11584#endif
11585
11586#if SQLITE_SHELL_IS_UTF8
11587int SQLITE_CDECL main(int argc, char **argv){
11588#else
11589int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11590  char **argv;
11591#endif
11592  char *zErrMsg = 0;
11593  ShellState data;
11594  const char *zInitFile = 0;
11595  int i;
11596  int rc = 0;
11597  int warnInmemoryDb = 0;
11598  int readStdin = 1;
11599  int nCmd = 0;
11600  char **azCmd = 0;
11601  const char *zVfs = 0;           /* Value of -vfs command-line option */
11602#if !SQLITE_SHELL_IS_UTF8
11603  char **argvToFree = 0;
11604  int argcToFree = 0;
11605#endif
11606
11607  setBinaryMode(stdin, 0);
11608  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11609  stdin_is_interactive = isatty(0);
11610  stdout_is_console = isatty(1);
11611
11612#if !defined(_WIN32_WCE)
11613  if( getenv("SQLITE_DEBUG_BREAK") ){
11614    if( isatty(0) && isatty(2) ){
11615      fprintf(stderr,
11616          "attach debugger to process %d and press any key to continue.\n",
11617          GETPID());
11618      fgetc(stdin);
11619    }else{
11620#if defined(_WIN32) || defined(WIN32)
11621#if SQLITE_OS_WINRT
11622      __debugbreak();
11623#else
11624      DebugBreak();
11625#endif
11626#elif defined(SIGTRAP)
11627      raise(SIGTRAP);
11628#endif
11629    }
11630  }
11631#endif
11632
11633#if USE_SYSTEM_SQLITE+0!=1
11634  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11635    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11636            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11637    exit(1);
11638  }
11639#endif
11640  main_init(&data);
11641
11642  /* On Windows, we must translate command-line arguments into UTF-8.
11643  ** The SQLite memory allocator subsystem has to be enabled in order to
11644  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11645  ** subsequent sqlite3_config() calls will work.  So copy all results into
11646  ** memory that does not come from the SQLite memory allocator.
11647  */
11648#if !SQLITE_SHELL_IS_UTF8
11649  sqlite3_initialize();
11650  argvToFree = malloc(sizeof(argv[0])*argc*2);
11651  shell_check_oom(argvToFree);
11652  argcToFree = argc;
11653  argv = argvToFree + argc;
11654  for(i=0; i<argc; i++){
11655    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11656    int n;
11657    shell_check_oom(z);
11658    n = (int)strlen(z);
11659    argv[i] = malloc( n+1 );
11660    shell_check_oom(argv[i]);
11661    memcpy(argv[i], z, n+1);
11662    argvToFree[i] = argv[i];
11663    sqlite3_free(z);
11664  }
11665  sqlite3_shutdown();
11666#endif
11667
11668  assert( argc>=1 && argv && argv[0] );
11669  Argv0 = argv[0];
11670
11671  /* Make sure we have a valid signal handler early, before anything
11672  ** else is done.
11673  */
11674#ifdef SIGINT
11675  signal(SIGINT, interrupt_handler);
11676#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11677  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11678#endif
11679
11680#ifdef SQLITE_SHELL_DBNAME_PROC
11681  {
11682    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11683    ** of a C-function that will provide the name of the database file.  Use
11684    ** this compile-time option to embed this shell program in larger
11685    ** applications. */
11686    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11687    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11688    warnInmemoryDb = 0;
11689  }
11690#endif
11691
11692  /* Do an initial pass through the command-line argument to locate
11693  ** the name of the database file, the name of the initialization file,
11694  ** the size of the alternative malloc heap,
11695  ** and the first command to execute.
11696  */
11697  verify_uninitialized();
11698  for(i=1; i<argc; i++){
11699    char *z;
11700    z = argv[i];
11701    if( z[0]!='-' ){
11702      if( data.aAuxDb->zDbFilename==0 ){
11703        data.aAuxDb->zDbFilename = z;
11704      }else{
11705        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11706        ** mean that nothing is read from stdin */
11707        readStdin = 0;
11708        nCmd++;
11709        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11710        shell_check_oom(azCmd);
11711        azCmd[nCmd-1] = z;
11712      }
11713    }
11714    if( z[1]=='-' ) z++;
11715    if( strcmp(z,"-separator")==0
11716     || strcmp(z,"-nullvalue")==0
11717     || strcmp(z,"-newline")==0
11718     || strcmp(z,"-cmd")==0
11719    ){
11720      (void)cmdline_option_value(argc, argv, ++i);
11721    }else if( strcmp(z,"-init")==0 ){
11722      zInitFile = cmdline_option_value(argc, argv, ++i);
11723    }else if( strcmp(z,"-batch")==0 ){
11724      /* Need to check for batch mode here to so we can avoid printing
11725      ** informational messages (like from process_sqliterc) before
11726      ** we do the actual processing of arguments later in a second pass.
11727      */
11728      stdin_is_interactive = 0;
11729    }else if( strcmp(z,"-heap")==0 ){
11730#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11731      const char *zSize;
11732      sqlite3_int64 szHeap;
11733
11734      zSize = cmdline_option_value(argc, argv, ++i);
11735      szHeap = integerValue(zSize);
11736      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11737      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11738#else
11739      (void)cmdline_option_value(argc, argv, ++i);
11740#endif
11741    }else if( strcmp(z,"-pagecache")==0 ){
11742      sqlite3_int64 n, sz;
11743      sz = integerValue(cmdline_option_value(argc,argv,++i));
11744      if( sz>70000 ) sz = 70000;
11745      if( sz<0 ) sz = 0;
11746      n = integerValue(cmdline_option_value(argc,argv,++i));
11747      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11748        n = 0xffffffffffffLL/sz;
11749      }
11750      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11751                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11752      data.shellFlgs |= SHFLG_Pagecache;
11753    }else if( strcmp(z,"-lookaside")==0 ){
11754      int n, sz;
11755      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11756      if( sz<0 ) sz = 0;
11757      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11758      if( n<0 ) n = 0;
11759      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11760      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11761    }else if( strcmp(z,"-threadsafe")==0 ){
11762      int n;
11763      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11764      switch( n ){
11765         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11766         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11767         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11768      }
11769#ifdef SQLITE_ENABLE_VFSTRACE
11770    }else if( strcmp(z,"-vfstrace")==0 ){
11771      extern int vfstrace_register(
11772         const char *zTraceName,
11773         const char *zOldVfsName,
11774         int (*xOut)(const char*,void*),
11775         void *pOutArg,
11776         int makeDefault
11777      );
11778      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11779#endif
11780#ifdef SQLITE_ENABLE_MULTIPLEX
11781    }else if( strcmp(z,"-multiplex")==0 ){
11782      extern int sqlite3_multiple_initialize(const char*,int);
11783      sqlite3_multiplex_initialize(0, 1);
11784#endif
11785    }else if( strcmp(z,"-mmap")==0 ){
11786      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11787      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11788#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11789    }else if( strcmp(z,"-sorterref")==0 ){
11790      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11791      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11792#endif
11793    }else if( strcmp(z,"-vfs")==0 ){
11794      zVfs = cmdline_option_value(argc, argv, ++i);
11795#ifdef SQLITE_HAVE_ZLIB
11796    }else if( strcmp(z,"-zip")==0 ){
11797      data.openMode = SHELL_OPEN_ZIPFILE;
11798#endif
11799    }else if( strcmp(z,"-append")==0 ){
11800      data.openMode = SHELL_OPEN_APPENDVFS;
11801#ifndef SQLITE_OMIT_DESERIALIZE
11802    }else if( strcmp(z,"-deserialize")==0 ){
11803      data.openMode = SHELL_OPEN_DESERIALIZE;
11804    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11805      data.szMax = integerValue(argv[++i]);
11806#endif
11807    }else if( strcmp(z,"-readonly")==0 ){
11808      data.openMode = SHELL_OPEN_READONLY;
11809    }else if( strcmp(z,"-nofollow")==0 ){
11810      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11811#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11812    }else if( strncmp(z, "-A",2)==0 ){
11813      /* All remaining command-line arguments are passed to the ".archive"
11814      ** command, so ignore them */
11815      break;
11816#endif
11817    }else if( strcmp(z, "-memtrace")==0 ){
11818      sqlite3MemTraceActivate(stderr);
11819    }else if( strcmp(z,"-bail")==0 ){
11820      bail_on_error = 1;
11821    }else if( strcmp(z,"-nonce")==0 ){
11822      free(data.zNonce);
11823      data.zNonce = strdup(argv[++i]);
11824    }else if( strcmp(z,"-safe")==0 ){
11825      /* no-op - catch this on the second pass */
11826    }
11827  }
11828  verify_uninitialized();
11829
11830
11831#ifdef SQLITE_SHELL_INIT_PROC
11832  {
11833    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11834    ** of a C-function that will perform initialization actions on SQLite that
11835    ** occur just before or after sqlite3_initialize(). Use this compile-time
11836    ** option to embed this shell program in larger applications. */
11837    extern void SQLITE_SHELL_INIT_PROC(void);
11838    SQLITE_SHELL_INIT_PROC();
11839  }
11840#else
11841  /* All the sqlite3_config() calls have now been made. So it is safe
11842  ** to call sqlite3_initialize() and process any command line -vfs option. */
11843  sqlite3_initialize();
11844#endif
11845
11846  if( zVfs ){
11847    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11848    if( pVfs ){
11849      sqlite3_vfs_register(pVfs, 1);
11850    }else{
11851      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11852      exit(1);
11853    }
11854  }
11855
11856  if( data.pAuxDb->zDbFilename==0 ){
11857#ifndef SQLITE_OMIT_MEMORYDB
11858    data.pAuxDb->zDbFilename = ":memory:";
11859    warnInmemoryDb = argc==1;
11860#else
11861    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11862    return 1;
11863#endif
11864  }
11865  data.out = stdout;
11866  sqlite3_appendvfs_init(0,0,0);
11867
11868  /* Go ahead and open the database file if it already exists.  If the
11869  ** file does not exist, delay opening it.  This prevents empty database
11870  ** files from being created if a user mistypes the database name argument
11871  ** to the sqlite command-line tool.
11872  */
11873  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11874    open_db(&data, 0);
11875  }
11876
11877  /* Process the initialization file if there is one.  If no -init option
11878  ** is given on the command line, look for a file named ~/.sqliterc and
11879  ** try to process it.
11880  */
11881  process_sqliterc(&data,zInitFile);
11882
11883  /* Make a second pass through the command-line argument and set
11884  ** options.  This second pass is delayed until after the initialization
11885  ** file is processed so that the command-line arguments will override
11886  ** settings in the initialization file.
11887  */
11888  for(i=1; i<argc; i++){
11889    char *z = argv[i];
11890    if( z[0]!='-' ) continue;
11891    if( z[1]=='-' ){ z++; }
11892    if( strcmp(z,"-init")==0 ){
11893      i++;
11894    }else if( strcmp(z,"-html")==0 ){
11895      data.mode = MODE_Html;
11896    }else if( strcmp(z,"-list")==0 ){
11897      data.mode = MODE_List;
11898    }else if( strcmp(z,"-quote")==0 ){
11899      data.mode = MODE_Quote;
11900      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11901      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11902    }else if( strcmp(z,"-line")==0 ){
11903      data.mode = MODE_Line;
11904    }else if( strcmp(z,"-column")==0 ){
11905      data.mode = MODE_Column;
11906    }else if( strcmp(z,"-json")==0 ){
11907      data.mode = MODE_Json;
11908    }else if( strcmp(z,"-markdown")==0 ){
11909      data.mode = MODE_Markdown;
11910    }else if( strcmp(z,"-table")==0 ){
11911      data.mode = MODE_Table;
11912    }else if( strcmp(z,"-box")==0 ){
11913      data.mode = MODE_Box;
11914    }else if( strcmp(z,"-csv")==0 ){
11915      data.mode = MODE_Csv;
11916      memcpy(data.colSeparator,",",2);
11917#ifdef SQLITE_HAVE_ZLIB
11918    }else if( strcmp(z,"-zip")==0 ){
11919      data.openMode = SHELL_OPEN_ZIPFILE;
11920#endif
11921    }else if( strcmp(z,"-append")==0 ){
11922      data.openMode = SHELL_OPEN_APPENDVFS;
11923#ifndef SQLITE_OMIT_DESERIALIZE
11924    }else if( strcmp(z,"-deserialize")==0 ){
11925      data.openMode = SHELL_OPEN_DESERIALIZE;
11926    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11927      data.szMax = integerValue(argv[++i]);
11928#endif
11929    }else if( strcmp(z,"-readonly")==0 ){
11930      data.openMode = SHELL_OPEN_READONLY;
11931    }else if( strcmp(z,"-nofollow")==0 ){
11932      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11933    }else if( strcmp(z,"-ascii")==0 ){
11934      data.mode = MODE_Ascii;
11935      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11936      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11937    }else if( strcmp(z,"-tabs")==0 ){
11938      data.mode = MODE_List;
11939      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11940      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11941    }else if( strcmp(z,"-separator")==0 ){
11942      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11943                       "%s",cmdline_option_value(argc,argv,++i));
11944    }else if( strcmp(z,"-newline")==0 ){
11945      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11946                       "%s",cmdline_option_value(argc,argv,++i));
11947    }else if( strcmp(z,"-nullvalue")==0 ){
11948      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11949                       "%s",cmdline_option_value(argc,argv,++i));
11950    }else if( strcmp(z,"-header")==0 ){
11951      data.showHeader = 1;
11952      ShellSetFlag(&data, SHFLG_HeaderSet);
11953     }else if( strcmp(z,"-noheader")==0 ){
11954      data.showHeader = 0;
11955      ShellSetFlag(&data, SHFLG_HeaderSet);
11956    }else if( strcmp(z,"-echo")==0 ){
11957      ShellSetFlag(&data, SHFLG_Echo);
11958    }else if( strcmp(z,"-eqp")==0 ){
11959      data.autoEQP = AUTOEQP_on;
11960    }else if( strcmp(z,"-eqpfull")==0 ){
11961      data.autoEQP = AUTOEQP_full;
11962    }else if( strcmp(z,"-stats")==0 ){
11963      data.statsOn = 1;
11964    }else if( strcmp(z,"-scanstats")==0 ){
11965      data.scanstatsOn = 1;
11966    }else if( strcmp(z,"-backslash")==0 ){
11967      /* Undocumented command-line option: -backslash
11968      ** Causes C-style backslash escapes to be evaluated in SQL statements
11969      ** prior to sending the SQL into SQLite.  Useful for injecting
11970      ** crazy bytes in the middle of SQL statements for testing and debugging.
11971      */
11972      ShellSetFlag(&data, SHFLG_Backslash);
11973    }else if( strcmp(z,"-bail")==0 ){
11974      /* No-op.  The bail_on_error flag should already be set. */
11975    }else if( strcmp(z,"-version")==0 ){
11976      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11977      return 0;
11978    }else if( strcmp(z,"-interactive")==0 ){
11979      stdin_is_interactive = 1;
11980    }else if( strcmp(z,"-batch")==0 ){
11981      stdin_is_interactive = 0;
11982    }else if( strcmp(z,"-heap")==0 ){
11983      i++;
11984    }else if( strcmp(z,"-pagecache")==0 ){
11985      i+=2;
11986    }else if( strcmp(z,"-lookaside")==0 ){
11987      i+=2;
11988    }else if( strcmp(z,"-threadsafe")==0 ){
11989      i+=2;
11990    }else if( strcmp(z,"-nonce")==0 ){
11991      i += 2;
11992    }else if( strcmp(z,"-mmap")==0 ){
11993      i++;
11994    }else if( strcmp(z,"-memtrace")==0 ){
11995      i++;
11996#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11997    }else if( strcmp(z,"-sorterref")==0 ){
11998      i++;
11999#endif
12000    }else if( strcmp(z,"-vfs")==0 ){
12001      i++;
12002#ifdef SQLITE_ENABLE_VFSTRACE
12003    }else if( strcmp(z,"-vfstrace")==0 ){
12004      i++;
12005#endif
12006#ifdef SQLITE_ENABLE_MULTIPLEX
12007    }else if( strcmp(z,"-multiplex")==0 ){
12008      i++;
12009#endif
12010    }else if( strcmp(z,"-help")==0 ){
12011      usage(1);
12012    }else if( strcmp(z,"-cmd")==0 ){
12013      /* Run commands that follow -cmd first and separately from commands
12014      ** that simply appear on the command-line.  This seems goofy.  It would
12015      ** be better if all commands ran in the order that they appear.  But
12016      ** we retain the goofy behavior for historical compatibility. */
12017      if( i==argc-1 ) break;
12018      z = cmdline_option_value(argc,argv,++i);
12019      if( z[0]=='.' ){
12020        rc = do_meta_command(z, &data);
12021        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12022      }else{
12023        open_db(&data, 0);
12024        rc = shell_exec(&data, z, &zErrMsg);
12025        if( zErrMsg!=0 ){
12026          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12027          if( bail_on_error ) return rc!=0 ? rc : 1;
12028        }else if( rc!=0 ){
12029          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12030          if( bail_on_error ) return rc;
12031        }
12032      }
12033#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12034    }else if( strncmp(z, "-A", 2)==0 ){
12035      if( nCmd>0 ){
12036        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12037                            " with \"%s\"\n", z);
12038        return 1;
12039      }
12040      open_db(&data, OPEN_DB_ZIPFILE);
12041      if( z[2] ){
12042        argv[i] = &z[2];
12043        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12044      }else{
12045        arDotCommand(&data, 1, argv+i, argc-i);
12046      }
12047      readStdin = 0;
12048      break;
12049#endif
12050    }else if( strcmp(z,"-safe")==0 ){
12051      data.bSafeMode = data.bSafeModePersist = 1;
12052    }else{
12053      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12054      raw_printf(stderr,"Use -help for a list of options.\n");
12055      return 1;
12056    }
12057    data.cMode = data.mode;
12058  }
12059
12060  if( !readStdin ){
12061    /* Run all arguments that do not begin with '-' as if they were separate
12062    ** command-line inputs, except for the argToSkip argument which contains
12063    ** the database filename.
12064    */
12065    for(i=0; i<nCmd; i++){
12066      if( azCmd[i][0]=='.' ){
12067        rc = do_meta_command(azCmd[i], &data);
12068        if( rc ){
12069          free(azCmd);
12070          return rc==2 ? 0 : rc;
12071        }
12072      }else{
12073        open_db(&data, 0);
12074        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12075        if( zErrMsg || rc ){
12076          if( zErrMsg!=0 ){
12077            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12078          }else{
12079            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12080          }
12081          sqlite3_free(zErrMsg);
12082          free(azCmd);
12083          return rc!=0 ? rc : 1;
12084        }
12085      }
12086    }
12087  }else{
12088    /* Run commands received from standard input
12089    */
12090    if( stdin_is_interactive ){
12091      char *zHome;
12092      char *zHistory;
12093      int nHistory;
12094      printf(
12095        "SQLite version %s %.19s\n" /*extra-version-info*/
12096        "Enter \".help\" for usage hints.\n",
12097        sqlite3_libversion(), sqlite3_sourceid()
12098      );
12099      if( warnInmemoryDb ){
12100        printf("Connected to a ");
12101        printBold("transient in-memory database");
12102        printf(".\nUse \".open FILENAME\" to reopen on a "
12103               "persistent database.\n");
12104      }
12105      zHistory = getenv("SQLITE_HISTORY");
12106      if( zHistory ){
12107        zHistory = strdup(zHistory);
12108      }else if( (zHome = find_home_dir(0))!=0 ){
12109        nHistory = strlen30(zHome) + 20;
12110        if( (zHistory = malloc(nHistory))!=0 ){
12111          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12112        }
12113      }
12114      if( zHistory ){ shell_read_history(zHistory); }
12115#if HAVE_READLINE || HAVE_EDITLINE
12116      rl_attempted_completion_function = readline_completion;
12117#elif HAVE_LINENOISE
12118      linenoiseSetCompletionCallback(linenoise_completion);
12119#endif
12120      data.in = 0;
12121      rc = process_input(&data);
12122      if( zHistory ){
12123        shell_stifle_history(2000);
12124        shell_write_history(zHistory);
12125        free(zHistory);
12126      }
12127    }else{
12128      data.in = stdin;
12129      rc = process_input(&data);
12130    }
12131  }
12132  free(azCmd);
12133  set_table_name(&data, 0);
12134  if( data.db ){
12135    session_close_all(&data, -1);
12136    close_db(data.db);
12137  }
12138  for(i=0; i<ArraySize(data.aAuxDb); i++){
12139    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12140    if( data.aAuxDb[i].db ){
12141      session_close_all(&data, i);
12142      close_db(data.aAuxDb[i].db);
12143    }
12144  }
12145  find_home_dir(1);
12146  output_reset(&data);
12147  data.doXdgOpen = 0;
12148  clearTempFile(&data);
12149#if !SQLITE_SHELL_IS_UTF8
12150  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12151  free(argvToFree);
12152#endif
12153  free(data.colWidth);
12154  free(data.zNonce);
12155  /* Clear the global data structure so that valgrind will detect memory
12156  ** leaks */
12157  memset(&data, 0, sizeof(data));
12158  return rc;
12159}
12160