xref: /sqlite-3.40.0/src/shell.c.in (revision ed5e6688)
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** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE       1
53# ifndef _FILE_OFFSET_BITS
54#   define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
64typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
66typedef unsigned char u8;
67#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76#  include <pwd.h>
77# endif
78#endif
79#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
80# include <unistd.h>
81# include <dirent.h>
82# define GETPID getpid
83# if defined(__MINGW32__)
84#  define DIRENT dirent
85#  ifndef S_ISLNK
86#   define S_ISLNK(mode) (0)
87#  endif
88# endif
89#else
90# define GETPID (int)GetCurrentProcessId
91#endif
92#include <sys/types.h>
93#include <sys/stat.h>
94
95#if HAVE_READLINE
96# include <readline/readline.h>
97# include <readline/history.h>
98#endif
99
100#if HAVE_EDITLINE
101# include <editline/readline.h>
102#endif
103
104#if HAVE_EDITLINE || HAVE_READLINE
105
106# define shell_add_history(X) add_history(X)
107# define shell_read_history(X) read_history(X)
108# define shell_write_history(X) write_history(X)
109# define shell_stifle_history(X) stifle_history(X)
110# define shell_readline(X) readline(X)
111
112#elif HAVE_LINENOISE
113
114# include "linenoise.h"
115# define shell_add_history(X) linenoiseHistoryAdd(X)
116# define shell_read_history(X) linenoiseHistoryLoad(X)
117# define shell_write_history(X) linenoiseHistorySave(X)
118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119# define shell_readline(X) linenoise(X)
120
121#else
122
123# define shell_read_history(X)
124# define shell_write_history(X)
125# define shell_stifle_history(X)
126
127# define SHELL_USE_LOCAL_GETLINE 1
128#endif
129
130
131#if defined(_WIN32) || defined(WIN32)
132# include <io.h>
133# include <fcntl.h>
134# define isatty(h) _isatty(h)
135# ifndef access
136#  define access(f,m) _access((f),(m))
137# endif
138# ifndef unlink
139#  define unlink _unlink
140# endif
141# ifndef strdup
142#  define strdup _strdup
143# endif
144# undef popen
145# define popen _popen
146# undef pclose
147# define pclose _pclose
148#else
149 /* Make sure isatty() has a prototype. */
150 extern int isatty(int);
151
152# if !defined(__RTP__) && !defined(_WRS_KERNEL)
153  /* popen and pclose are not C89 functions and so are
154  ** sometimes omitted from the <stdio.h> header */
155   extern FILE *popen(const char*,const char*);
156   extern int pclose(FILE*);
157# else
158#  define SQLITE_OMIT_POPEN 1
159# endif
160#endif
161
162#if defined(_WIN32_WCE)
163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
164 * thus we always assume that we have a console. That can be
165 * overridden with the -batch command line option.
166 */
167#define isatty(x) 1
168#endif
169
170/* ctype macros that work with signed characters */
171#define IsSpace(X)  isspace((unsigned char)X)
172#define IsDigit(X)  isdigit((unsigned char)X)
173#define ToLower(X)  (char)tolower((unsigned char)X)
174
175#if defined(_WIN32) || defined(WIN32)
176#include <windows.h>
177
178/* string conversion routines only needed on Win32 */
179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
183#endif
184
185/* On Windows, we normally run with output mode of TEXT so that \n characters
186** are automatically translated into \r\n.  However, this behavior needs
187** to be disabled in some cases (ex: when generating CSV output and when
188** rendering quoted strings that contain \n characters).  The following
189** routines take care of that.
190*/
191#if defined(_WIN32) || defined(WIN32)
192static void setBinaryMode(FILE *file, int isOutput){
193  if( isOutput ) fflush(file);
194  _setmode(_fileno(file), _O_BINARY);
195}
196static void setTextMode(FILE *file, int isOutput){
197  if( isOutput ) fflush(file);
198  _setmode(_fileno(file), _O_TEXT);
199}
200#else
201# define setBinaryMode(X,Y)
202# define setTextMode(X,Y)
203#endif
204
205
206/* True if the timer is enabled */
207static int enableTimer = 0;
208
209/* Return the current wall-clock time */
210static sqlite3_int64 timeOfDay(void){
211  static sqlite3_vfs *clockVfs = 0;
212  sqlite3_int64 t;
213  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
214  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
215    clockVfs->xCurrentTimeInt64(clockVfs, &t);
216  }else{
217    double r;
218    clockVfs->xCurrentTime(clockVfs, &r);
219    t = (sqlite3_int64)(r*86400000.0);
220  }
221  return t;
222}
223
224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
225#include <sys/time.h>
226#include <sys/resource.h>
227
228/* VxWorks does not support getrusage() as far as we can determine */
229#if defined(_WRS_KERNEL) || defined(__RTP__)
230struct rusage {
231  struct timeval ru_utime; /* user CPU time used */
232  struct timeval ru_stime; /* system CPU time used */
233};
234#define getrusage(A,B) memset(B,0,sizeof(*B))
235#endif
236
237/* Saved resource information for the beginning of an operation */
238static struct rusage sBegin;  /* CPU time at start */
239static sqlite3_int64 iBegin;  /* Wall-clock time at start */
240
241/*
242** Begin timing an operation
243*/
244static void beginTimer(void){
245  if( enableTimer ){
246    getrusage(RUSAGE_SELF, &sBegin);
247    iBegin = timeOfDay();
248  }
249}
250
251/* Return the difference of two time_structs in seconds */
252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
253  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
254         (double)(pEnd->tv_sec - pStart->tv_sec);
255}
256
257/*
258** Print the timing results.
259*/
260static void endTimer(void){
261  if( enableTimer ){
262    sqlite3_int64 iEnd = timeOfDay();
263    struct rusage sEnd;
264    getrusage(RUSAGE_SELF, &sEnd);
265    printf("Run Time: real %.3f user %f sys %f\n",
266       (iEnd - iBegin)*0.001,
267       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
268       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
269  }
270}
271
272#define BEGIN_TIMER beginTimer()
273#define END_TIMER endTimer()
274#define HAS_TIMER 1
275
276#elif (defined(_WIN32) || defined(WIN32))
277
278/* Saved resource information for the beginning of an operation */
279static HANDLE hProcess;
280static FILETIME ftKernelBegin;
281static FILETIME ftUserBegin;
282static sqlite3_int64 ftWallBegin;
283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
284                                    LPFILETIME, LPFILETIME);
285static GETPROCTIMES getProcessTimesAddr = NULL;
286
287/*
288** Check to see if we have timer support.  Return 1 if necessary
289** support found (or found previously).
290*/
291static int hasTimer(void){
292  if( getProcessTimesAddr ){
293    return 1;
294  } else {
295    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
296    ** versions. See if the version we are running on has it, and if it
297    ** does, save off a pointer to it and the current process handle.
298    */
299    hProcess = GetCurrentProcess();
300    if( hProcess ){
301      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
302      if( NULL != hinstLib ){
303        getProcessTimesAddr =
304            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
305        if( NULL != getProcessTimesAddr ){
306          return 1;
307        }
308        FreeLibrary(hinstLib);
309      }
310    }
311  }
312  return 0;
313}
314
315/*
316** Begin timing an operation
317*/
318static void beginTimer(void){
319  if( enableTimer && getProcessTimesAddr ){
320    FILETIME ftCreation, ftExit;
321    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
322                        &ftKernelBegin,&ftUserBegin);
323    ftWallBegin = timeOfDay();
324  }
325}
326
327/* Return the difference of two FILETIME structs in seconds */
328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
329  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
330  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
331  return (double) ((i64End - i64Start) / 10000000.0);
332}
333
334/*
335** Print the timing results.
336*/
337static void endTimer(void){
338  if( enableTimer && getProcessTimesAddr){
339    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
340    sqlite3_int64 ftWallEnd = timeOfDay();
341    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
342    printf("Run Time: real %.3f user %f sys %f\n",
343       (ftWallEnd - ftWallBegin)*0.001,
344       timeDiff(&ftUserBegin, &ftUserEnd),
345       timeDiff(&ftKernelBegin, &ftKernelEnd));
346  }
347}
348
349#define BEGIN_TIMER beginTimer()
350#define END_TIMER endTimer()
351#define HAS_TIMER hasTimer()
352
353#else
354#define BEGIN_TIMER
355#define END_TIMER
356#define HAS_TIMER 0
357#endif
358
359/*
360** Used to prevent warnings about unused parameters
361*/
362#define UNUSED_PARAMETER(x) (void)(x)
363
364/*
365** Number of elements in an array
366*/
367#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
368
369/*
370** If the following flag is set, then command execution stops
371** at an error if we are not interactive.
372*/
373static int bail_on_error = 0;
374
375/*
376** Threat stdin as an interactive input if the following variable
377** is true.  Otherwise, assume stdin is connected to a file or pipe.
378*/
379static int stdin_is_interactive = 1;
380
381/*
382** On Windows systems we have to know if standard output is a console
383** in order to translate UTF-8 into MBCS.  The following variable is
384** true if translation is required.
385*/
386static int stdout_is_console = 1;
387
388/*
389** The following is the open SQLite database.  We make a pointer
390** to this database a static variable so that it can be accessed
391** by the SIGINT handler to interrupt database processing.
392*/
393static sqlite3 *globalDb = 0;
394
395/*
396** True if an interrupt (Control-C) has been received.
397*/
398static volatile int seenInterrupt = 0;
399
400#ifdef SQLITE_DEBUG
401/*
402** Out-of-memory simulator variables
403*/
404static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
405static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
406static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
407#endif /* SQLITE_DEBUG */
408
409/*
410** This is the name of our program. It is set in main(), used
411** in a number of other places, mostly for error messages.
412*/
413static char *Argv0;
414
415/*
416** Prompt strings. Initialized in main. Settable with
417**   .prompt main continue
418*/
419static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
420static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
421
422/*
423** Render output like fprintf().  Except, if the output is going to the
424** console and if this is running on a Windows machine, translate the
425** output from UTF-8 into MBCS.
426*/
427#if defined(_WIN32) || defined(WIN32)
428void utf8_printf(FILE *out, const char *zFormat, ...){
429  va_list ap;
430  va_start(ap, zFormat);
431  if( stdout_is_console && (out==stdout || out==stderr) ){
432    char *z1 = sqlite3_vmprintf(zFormat, ap);
433    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
434    sqlite3_free(z1);
435    fputs(z2, out);
436    sqlite3_free(z2);
437  }else{
438    vfprintf(out, zFormat, ap);
439  }
440  va_end(ap);
441}
442#elif !defined(utf8_printf)
443# define utf8_printf fprintf
444#endif
445
446/*
447** Render output like fprintf().  This should not be used on anything that
448** includes string formatting (e.g. "%s").
449*/
450#if !defined(raw_printf)
451# define raw_printf fprintf
452#endif
453
454/* Indicate out-of-memory and exit. */
455static void shell_out_of_memory(void){
456  raw_printf(stderr,"Error: out of memory\n");
457  exit(1);
458}
459
460#ifdef SQLITE_DEBUG
461/* This routine is called when a simulated OOM occurs.  It is broken
462** out as a separate routine to make it easy to set a breakpoint on
463** the OOM
464*/
465void shellOomFault(void){
466  if( oomRepeat>0 ){
467    oomRepeat--;
468  }else{
469    oomCounter--;
470  }
471}
472#endif /* SQLITE_DEBUG */
473
474#ifdef SQLITE_DEBUG
475/* This routine is a replacement malloc() that is used to simulate
476** Out-Of-Memory (OOM) errors for testing purposes.
477*/
478static void *oomMalloc(int nByte){
479  if( oomCounter ){
480    if( oomCounter==1 ){
481      shellOomFault();
482      return 0;
483    }else{
484      oomCounter--;
485    }
486  }
487  return defaultMalloc(nByte);
488}
489#endif /* SQLITE_DEBUG */
490
491#ifdef SQLITE_DEBUG
492/* Register the OOM simulator.  This must occur before any memory
493** allocations */
494static void registerOomSimulator(void){
495  sqlite3_mem_methods mem;
496  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
497  defaultMalloc = mem.xMalloc;
498  mem.xMalloc = oomMalloc;
499  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
500}
501#endif
502
503/*
504** Write I/O traces to the following stream.
505*/
506#ifdef SQLITE_ENABLE_IOTRACE
507static FILE *iotrace = 0;
508#endif
509
510/*
511** This routine works like printf in that its first argument is a
512** format string and subsequent arguments are values to be substituted
513** in place of % fields.  The result of formatting this string
514** is written to iotrace.
515*/
516#ifdef SQLITE_ENABLE_IOTRACE
517static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
518  va_list ap;
519  char *z;
520  if( iotrace==0 ) return;
521  va_start(ap, zFormat);
522  z = sqlite3_vmprintf(zFormat, ap);
523  va_end(ap);
524  utf8_printf(iotrace, "%s", z);
525  sqlite3_free(z);
526}
527#endif
528
529/*
530** Output string zUtf to stream pOut as w characters.  If w is negative,
531** then right-justify the text.  W is the width in UTF-8 characters, not
532** in bytes.  This is different from the %*.*s specification in printf
533** since with %*.*s the width is measured in bytes, not characters.
534*/
535static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
536  int i;
537  int n;
538  int aw = w<0 ? -w : w;
539  char zBuf[1000];
540  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
541  for(i=n=0; zUtf[i]; i++){
542    if( (zUtf[i]&0xc0)!=0x80 ){
543      n++;
544      if( n==aw ){
545        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
546        break;
547      }
548    }
549  }
550  if( n>=aw ){
551    utf8_printf(pOut, "%.*s", i, zUtf);
552  }else if( w<0 ){
553    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
554  }else{
555    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
556  }
557}
558
559
560/*
561** Determines if a string is a number of not.
562*/
563static int isNumber(const char *z, int *realnum){
564  if( *z=='-' || *z=='+' ) z++;
565  if( !IsDigit(*z) ){
566    return 0;
567  }
568  z++;
569  if( realnum ) *realnum = 0;
570  while( IsDigit(*z) ){ z++; }
571  if( *z=='.' ){
572    z++;
573    if( !IsDigit(*z) ) return 0;
574    while( IsDigit(*z) ){ z++; }
575    if( realnum ) *realnum = 1;
576  }
577  if( *z=='e' || *z=='E' ){
578    z++;
579    if( *z=='+' || *z=='-' ) z++;
580    if( !IsDigit(*z) ) return 0;
581    while( IsDigit(*z) ){ z++; }
582    if( realnum ) *realnum = 1;
583  }
584  return *z==0;
585}
586
587/*
588** Compute a string length that is limited to what can be stored in
589** lower 30 bits of a 32-bit signed integer.
590*/
591static int strlen30(const char *z){
592  const char *z2 = z;
593  while( *z2 ){ z2++; }
594  return 0x3fffffff & (int)(z2 - z);
595}
596
597/*
598** Return the length of a string in characters.  Multibyte UTF8 characters
599** count as a single character.
600*/
601static int strlenChar(const char *z){
602  int n = 0;
603  while( *z ){
604    if( (0xc0&*(z++))!=0x80 ) n++;
605  }
606  return n;
607}
608
609/*
610** This routine reads a line of text from FILE in, stores
611** the text in memory obtained from malloc() and returns a pointer
612** to the text.  NULL is returned at end of file, or if malloc()
613** fails.
614**
615** If zLine is not NULL then it is a malloced buffer returned from
616** a previous call to this routine that may be reused.
617*/
618static char *local_getline(char *zLine, FILE *in){
619  int nLine = zLine==0 ? 0 : 100;
620  int n = 0;
621
622  while( 1 ){
623    if( n+100>nLine ){
624      nLine = nLine*2 + 100;
625      zLine = realloc(zLine, nLine);
626      if( zLine==0 ) shell_out_of_memory();
627    }
628    if( fgets(&zLine[n], nLine - n, in)==0 ){
629      if( n==0 ){
630        free(zLine);
631        return 0;
632      }
633      zLine[n] = 0;
634      break;
635    }
636    while( zLine[n] ) n++;
637    if( n>0 && zLine[n-1]=='\n' ){
638      n--;
639      if( n>0 && zLine[n-1]=='\r' ) n--;
640      zLine[n] = 0;
641      break;
642    }
643  }
644#if defined(_WIN32) || defined(WIN32)
645  /* For interactive input on Windows systems, translate the
646  ** multi-byte characterset characters into UTF-8. */
647  if( stdin_is_interactive && in==stdin ){
648    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
649    if( zTrans ){
650      int nTrans = strlen30(zTrans)+1;
651      if( nTrans>nLine ){
652        zLine = realloc(zLine, nTrans);
653        if( zLine==0 ) shell_out_of_memory();
654      }
655      memcpy(zLine, zTrans, nTrans);
656      sqlite3_free(zTrans);
657    }
658  }
659#endif /* defined(_WIN32) || defined(WIN32) */
660  return zLine;
661}
662
663/*
664** Retrieve a single line of input text.
665**
666** If in==0 then read from standard input and prompt before each line.
667** If isContinuation is true, then a continuation prompt is appropriate.
668** If isContinuation is zero, then the main prompt should be used.
669**
670** If zPrior is not NULL then it is a buffer from a prior call to this
671** routine that can be reused.
672**
673** The result is stored in space obtained from malloc() and must either
674** be freed by the caller or else passed back into this routine via the
675** zPrior argument for reuse.
676*/
677static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
678  char *zPrompt;
679  char *zResult;
680  if( in!=0 ){
681    zResult = local_getline(zPrior, in);
682  }else{
683    zPrompt = isContinuation ? continuePrompt : mainPrompt;
684#if SHELL_USE_LOCAL_GETLINE
685    printf("%s", zPrompt);
686    fflush(stdout);
687    zResult = local_getline(zPrior, stdin);
688#else
689    free(zPrior);
690    zResult = shell_readline(zPrompt);
691    if( zResult && *zResult ) shell_add_history(zResult);
692#endif
693  }
694  return zResult;
695}
696
697
698/*
699** Return the value of a hexadecimal digit.  Return -1 if the input
700** is not a hex digit.
701*/
702static int hexDigitValue(char c){
703  if( c>='0' && c<='9' ) return c - '0';
704  if( c>='a' && c<='f' ) return c - 'a' + 10;
705  if( c>='A' && c<='F' ) return c - 'A' + 10;
706  return -1;
707}
708
709/*
710** Interpret zArg as an integer value, possibly with suffixes.
711*/
712static sqlite3_int64 integerValue(const char *zArg){
713  sqlite3_int64 v = 0;
714  static const struct { char *zSuffix; int iMult; } aMult[] = {
715    { "KiB", 1024 },
716    { "MiB", 1024*1024 },
717    { "GiB", 1024*1024*1024 },
718    { "KB",  1000 },
719    { "MB",  1000000 },
720    { "GB",  1000000000 },
721    { "K",   1000 },
722    { "M",   1000000 },
723    { "G",   1000000000 },
724  };
725  int i;
726  int isNeg = 0;
727  if( zArg[0]=='-' ){
728    isNeg = 1;
729    zArg++;
730  }else if( zArg[0]=='+' ){
731    zArg++;
732  }
733  if( zArg[0]=='0' && zArg[1]=='x' ){
734    int x;
735    zArg += 2;
736    while( (x = hexDigitValue(zArg[0]))>=0 ){
737      v = (v<<4) + x;
738      zArg++;
739    }
740  }else{
741    while( IsDigit(zArg[0]) ){
742      v = v*10 + zArg[0] - '0';
743      zArg++;
744    }
745  }
746  for(i=0; i<ArraySize(aMult); i++){
747    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
748      v *= aMult[i].iMult;
749      break;
750    }
751  }
752  return isNeg? -v : v;
753}
754
755/*
756** A variable length string to which one can append text.
757*/
758typedef struct ShellText ShellText;
759struct ShellText {
760  char *z;
761  int n;
762  int nAlloc;
763};
764
765/*
766** Initialize and destroy a ShellText object
767*/
768static void initText(ShellText *p){
769  memset(p, 0, sizeof(*p));
770}
771static void freeText(ShellText *p){
772  free(p->z);
773  initText(p);
774}
775
776/* zIn is either a pointer to a NULL-terminated string in memory obtained
777** from malloc(), or a NULL pointer. The string pointed to by zAppend is
778** added to zIn, and the result returned in memory obtained from malloc().
779** zIn, if it was not NULL, is freed.
780**
781** If the third argument, quote, is not '\0', then it is used as a
782** quote character for zAppend.
783*/
784static void appendText(ShellText *p, char const *zAppend, char quote){
785  int len;
786  int i;
787  int nAppend = strlen30(zAppend);
788
789  len = nAppend+p->n+1;
790  if( quote ){
791    len += 2;
792    for(i=0; i<nAppend; i++){
793      if( zAppend[i]==quote ) len++;
794    }
795  }
796
797  if( p->n+len>=p->nAlloc ){
798    p->nAlloc = p->nAlloc*2 + len + 20;
799    p->z = realloc(p->z, p->nAlloc);
800    if( p->z==0 ) shell_out_of_memory();
801  }
802
803  if( quote ){
804    char *zCsr = p->z+p->n;
805    *zCsr++ = quote;
806    for(i=0; i<nAppend; i++){
807      *zCsr++ = zAppend[i];
808      if( zAppend[i]==quote ) *zCsr++ = quote;
809    }
810    *zCsr++ = quote;
811    p->n = (int)(zCsr - p->z);
812    *zCsr = '\0';
813  }else{
814    memcpy(p->z+p->n, zAppend, nAppend);
815    p->n += nAppend;
816    p->z[p->n] = '\0';
817  }
818}
819
820/*
821** Attempt to determine if identifier zName needs to be quoted, either
822** because it contains non-alphanumeric characters, or because it is an
823** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
824** that quoting is required.
825**
826** Return '"' if quoting is required.  Return 0 if no quoting is required.
827*/
828static char quoteChar(const char *zName){
829  int i;
830  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
831  for(i=0; zName[i]; i++){
832    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
833  }
834  return sqlite3_keyword_check(zName, i) ? '"' : 0;
835}
836
837/*
838** Construct a fake object name and column list to describe the structure
839** of the view, virtual table, or table valued function zSchema.zName.
840*/
841static char *shellFakeSchema(
842  sqlite3 *db,            /* The database connection containing the vtab */
843  const char *zSchema,    /* Schema of the database holding the vtab */
844  const char *zName       /* The name of the virtual table */
845){
846  sqlite3_stmt *pStmt = 0;
847  char *zSql;
848  ShellText s;
849  char cQuote;
850  char *zDiv = "(";
851  int nRow = 0;
852
853  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
854                         zSchema ? zSchema : "main", zName);
855  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
856  sqlite3_free(zSql);
857  initText(&s);
858  if( zSchema ){
859    cQuote = quoteChar(zSchema);
860    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
861    appendText(&s, zSchema, cQuote);
862    appendText(&s, ".", 0);
863  }
864  cQuote = quoteChar(zName);
865  appendText(&s, zName, cQuote);
866  while( sqlite3_step(pStmt)==SQLITE_ROW ){
867    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
868    nRow++;
869    appendText(&s, zDiv, 0);
870    zDiv = ",";
871    cQuote = quoteChar(zCol);
872    appendText(&s, zCol, cQuote);
873  }
874  appendText(&s, ")", 0);
875  sqlite3_finalize(pStmt);
876  if( nRow==0 ){
877    freeText(&s);
878    s.z = 0;
879  }
880  return s.z;
881}
882
883/*
884** SQL function:  shell_module_schema(X)
885**
886** Return a fake schema for the table-valued function or eponymous virtual
887** table X.
888*/
889static void shellModuleSchema(
890  sqlite3_context *pCtx,
891  int nVal,
892  sqlite3_value **apVal
893){
894  const char *zName = (const char*)sqlite3_value_text(apVal[0]);
895  char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
896  UNUSED_PARAMETER(nVal);
897  if( zFake ){
898    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
899                        -1, sqlite3_free);
900    free(zFake);
901  }
902}
903
904/*
905** SQL function:  shell_add_schema(S,X)
906**
907** Add the schema name X to the CREATE statement in S and return the result.
908** Examples:
909**
910**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
911**
912** Also works on
913**
914**    CREATE INDEX
915**    CREATE UNIQUE INDEX
916**    CREATE VIEW
917**    CREATE TRIGGER
918**    CREATE VIRTUAL TABLE
919**
920** This UDF is used by the .schema command to insert the schema name of
921** attached databases into the middle of the sqlite_master.sql field.
922*/
923static void shellAddSchemaName(
924  sqlite3_context *pCtx,
925  int nVal,
926  sqlite3_value **apVal
927){
928  static const char *aPrefix[] = {
929     "TABLE",
930     "INDEX",
931     "UNIQUE INDEX",
932     "VIEW",
933     "TRIGGER",
934     "VIRTUAL TABLE"
935  };
936  int i = 0;
937  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
938  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
939  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
940  sqlite3 *db = sqlite3_context_db_handle(pCtx);
941  UNUSED_PARAMETER(nVal);
942  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
943    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
944      int n = strlen30(aPrefix[i]);
945      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
946        char *z = 0;
947        char *zFake = 0;
948        if( zSchema ){
949          char cQuote = quoteChar(zSchema);
950          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
951            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
952          }else{
953            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
954          }
955        }
956        if( zName
957         && aPrefix[i][0]=='V'
958         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
959        ){
960          if( z==0 ){
961            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
962          }else{
963            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
964          }
965          free(zFake);
966        }
967        if( z ){
968          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
969          return;
970        }
971      }
972    }
973  }
974  sqlite3_result_value(pCtx, apVal[0]);
975}
976
977/*
978** The source code for several run-time loadable extensions is inserted
979** below by the ../tool/mkshellc.tcl script.  Before processing that included
980** code, we need to override some macros to make the included program code
981** work here in the middle of this regular program.
982*/
983#define SQLITE_EXTENSION_INIT1
984#define SQLITE_EXTENSION_INIT2(X) (void)(X)
985
986#if defined(_WIN32) && defined(_MSC_VER)
987INCLUDE test_windirent.h
988INCLUDE test_windirent.c
989#define dirent DIRENT
990#endif
991INCLUDE ../ext/misc/shathree.c
992INCLUDE ../ext/misc/fileio.c
993INCLUDE ../ext/misc/completion.c
994INCLUDE ../ext/misc/appendvfs.c
995INCLUDE ../ext/misc/memtrace.c
996#ifdef SQLITE_HAVE_ZLIB
997INCLUDE ../ext/misc/zipfile.c
998INCLUDE ../ext/misc/sqlar.c
999#endif
1000INCLUDE ../ext/expert/sqlite3expert.h
1001INCLUDE ../ext/expert/sqlite3expert.c
1002
1003#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1004INCLUDE ../ext/misc/dbdata.c
1005#endif
1006
1007#if defined(SQLITE_ENABLE_SESSION)
1008/*
1009** State information for a single open session
1010*/
1011typedef struct OpenSession OpenSession;
1012struct OpenSession {
1013  char *zName;             /* Symbolic name for this session */
1014  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1015  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1016  sqlite3_session *p;      /* The open session */
1017};
1018#endif
1019
1020/*
1021** Shell output mode information from before ".explain on",
1022** saved so that it can be restored by ".explain off"
1023*/
1024typedef struct SavedModeInfo SavedModeInfo;
1025struct SavedModeInfo {
1026  int valid;          /* Is there legit data in here? */
1027  int mode;           /* Mode prior to ".explain on" */
1028  int showHeader;     /* The ".header" setting prior to ".explain on" */
1029  int colWidth[100];  /* Column widths prior to ".explain on" */
1030};
1031
1032typedef struct ExpertInfo ExpertInfo;
1033struct ExpertInfo {
1034  sqlite3expert *pExpert;
1035  int bVerbose;
1036};
1037
1038/* A single line in the EQP output */
1039typedef struct EQPGraphRow EQPGraphRow;
1040struct EQPGraphRow {
1041  int iEqpId;           /* ID for this row */
1042  int iParentId;        /* ID of the parent row */
1043  EQPGraphRow *pNext;   /* Next row in sequence */
1044  char zText[1];        /* Text to display for this row */
1045};
1046
1047/* All EQP output is collected into an instance of the following */
1048typedef struct EQPGraph EQPGraph;
1049struct EQPGraph {
1050  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1051  EQPGraphRow *pLast;   /* Last element of the pRow list */
1052  char zPrefix[100];    /* Graph prefix */
1053};
1054
1055/*
1056** State information about the database connection is contained in an
1057** instance of the following structure.
1058*/
1059typedef struct ShellState ShellState;
1060struct ShellState {
1061  sqlite3 *db;           /* The database */
1062  u8 autoExplain;        /* Automatically turn on .explain mode */
1063  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1064  u8 autoEQPtest;        /* autoEQP is in test mode */
1065  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1066  u8 statsOn;            /* True to display memory stats before each finalize */
1067  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1068  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1069  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1070  u8 nEqpLevel;          /* Depth of the EQP output graph */
1071  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1072  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1073  int outCount;          /* Revert to stdout when reaching zero */
1074  int cnt;               /* Number of records displayed so far */
1075  int lineno;            /* Line number of last line read from in */
1076  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1077  FILE *in;              /* Read commands from this stream */
1078  FILE *out;             /* Write results here */
1079  FILE *traceOut;        /* Output for sqlite3_trace() */
1080  int nErr;              /* Number of errors seen */
1081  int mode;              /* An output mode setting */
1082  int modePrior;         /* Saved mode */
1083  int cMode;             /* temporary output mode for the current query */
1084  int normalMode;        /* Output mode before ".explain on" */
1085  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1086  int showHeader;        /* True to show column names in List or Column mode */
1087  int nCheck;            /* Number of ".check" commands run */
1088  unsigned nProgress;    /* Number of progress callbacks encountered */
1089  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1090  unsigned flgProgress;  /* Flags for the progress callback */
1091  unsigned shellFlgs;    /* Various flags */
1092  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1093  char *zDestTable;      /* Name of destination table when MODE_Insert */
1094  char *zTempFile;       /* Temporary file that might need deleting */
1095  char zTestcase[30];    /* Name of current test case */
1096  char colSeparator[20]; /* Column separator character for several modes */
1097  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1098  char colSepPrior[20];  /* Saved column separator */
1099  char rowSepPrior[20];  /* Saved row separator */
1100  int colWidth[100];     /* Requested width of each column when in column mode*/
1101  int actualWidth[100];  /* Actual width of each column */
1102  char nullValue[20];    /* The text to print when a NULL comes back from
1103                         ** the database */
1104  char outfile[FILENAME_MAX]; /* Filename for *out */
1105  const char *zDbFilename;    /* name of the database file */
1106  char *zFreeOnClose;         /* Filename to free when closing */
1107  const char *zVfs;           /* Name of VFS to use */
1108  sqlite3_stmt *pStmt;   /* Current statement if any. */
1109  FILE *pLog;            /* Write log output here */
1110  int *aiIndent;         /* Array of indents used in MODE_Explain */
1111  int nIndent;           /* Size of array aiIndent[] */
1112  int iIndent;           /* Index of current op in aiIndent[] */
1113  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1114#if defined(SQLITE_ENABLE_SESSION)
1115  int nSession;             /* Number of active sessions */
1116  OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
1117#endif
1118  ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
1119};
1120
1121
1122/* Allowed values for ShellState.autoEQP
1123*/
1124#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1125#define AUTOEQP_on       1           /* Automatic EQP is on */
1126#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1127#define AUTOEQP_full     3           /* Show full EXPLAIN */
1128
1129/* Allowed values for ShellState.openMode
1130*/
1131#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1132#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1133#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1134#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1135#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1136#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1137#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1138
1139/* Allowed values for ShellState.eTraceType
1140*/
1141#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1142#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1143#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1144
1145/* Bits in the ShellState.flgProgress variable */
1146#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1147#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1148                                   ** callback limit is reached, and for each
1149                                   ** top-level SQL statement */
1150#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1151
1152/*
1153** These are the allowed shellFlgs values
1154*/
1155#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1156#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1157#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1158#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1159#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1160#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1161#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1162
1163/*
1164** Macros for testing and setting shellFlgs
1165*/
1166#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1167#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1168#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1169
1170/*
1171** These are the allowed modes.
1172*/
1173#define MODE_Line     0  /* One column per line.  Blank line between records */
1174#define MODE_Column   1  /* One record per line in neat columns */
1175#define MODE_List     2  /* One record per line with a separator */
1176#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1177#define MODE_Html     4  /* Generate an XHTML table */
1178#define MODE_Insert   5  /* Generate SQL "insert" statements */
1179#define MODE_Quote    6  /* Quote values as for SQL */
1180#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1181#define MODE_Csv      8  /* Quote strings, numbers are plain */
1182#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1183#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1184#define MODE_Pretty  11  /* Pretty-print schemas */
1185#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1186
1187static const char *modeDescr[] = {
1188  "line",
1189  "column",
1190  "list",
1191  "semi",
1192  "html",
1193  "insert",
1194  "quote",
1195  "tcl",
1196  "csv",
1197  "explain",
1198  "ascii",
1199  "prettyprint",
1200  "eqp"
1201};
1202
1203/*
1204** These are the column/row/line separators used by the various
1205** import/export modes.
1206*/
1207#define SEP_Column    "|"
1208#define SEP_Row       "\n"
1209#define SEP_Tab       "\t"
1210#define SEP_Space     " "
1211#define SEP_Comma     ","
1212#define SEP_CrLf      "\r\n"
1213#define SEP_Unit      "\x1F"
1214#define SEP_Record    "\x1E"
1215
1216/*
1217** A callback for the sqlite3_log() interface.
1218*/
1219static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1220  ShellState *p = (ShellState*)pArg;
1221  if( p->pLog==0 ) return;
1222  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1223  fflush(p->pLog);
1224}
1225
1226/*
1227** SQL function:  shell_putsnl(X)
1228**
1229** Write the text X to the screen (or whatever output is being directed)
1230** adding a newline at the end, and then return X.
1231*/
1232static void shellPutsFunc(
1233  sqlite3_context *pCtx,
1234  int nVal,
1235  sqlite3_value **apVal
1236){
1237  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1238  (void)nVal;
1239  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1240  sqlite3_result_value(pCtx, apVal[0]);
1241}
1242
1243/*
1244** SQL function:   edit(VALUE)
1245**                 edit(VALUE,EDITOR)
1246**
1247** These steps:
1248**
1249**     (1) Write VALUE into a temporary file.
1250**     (2) Run program EDITOR on that temporary file.
1251**     (3) Read the temporary file back and return its content as the result.
1252**     (4) Delete the temporary file
1253**
1254** If the EDITOR argument is omitted, use the value in the VISUAL
1255** environment variable.  If still there is no EDITOR, through an error.
1256**
1257** Also throw an error if the EDITOR program returns a non-zero exit code.
1258*/
1259#ifndef SQLITE_NOHAVE_SYSTEM
1260static void editFunc(
1261  sqlite3_context *context,
1262  int argc,
1263  sqlite3_value **argv
1264){
1265  const char *zEditor;
1266  char *zTempFile = 0;
1267  sqlite3 *db;
1268  char *zCmd = 0;
1269  int bBin;
1270  int rc;
1271  int hasCRNL = 0;
1272  FILE *f = 0;
1273  sqlite3_int64 sz;
1274  sqlite3_int64 x;
1275  unsigned char *p = 0;
1276
1277  if( argc==2 ){
1278    zEditor = (const char*)sqlite3_value_text(argv[1]);
1279  }else{
1280    zEditor = getenv("VISUAL");
1281  }
1282  if( zEditor==0 ){
1283    sqlite3_result_error(context, "no editor for edit()", -1);
1284    return;
1285  }
1286  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1287    sqlite3_result_error(context, "NULL input to edit()", -1);
1288    return;
1289  }
1290  db = sqlite3_context_db_handle(context);
1291  zTempFile = 0;
1292  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1293  if( zTempFile==0 ){
1294    sqlite3_uint64 r = 0;
1295    sqlite3_randomness(sizeof(r), &r);
1296    zTempFile = sqlite3_mprintf("temp%llx", r);
1297    if( zTempFile==0 ){
1298      sqlite3_result_error_nomem(context);
1299      return;
1300    }
1301  }
1302  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1303  /* When writing the file to be edited, do \n to \r\n conversions on systems
1304  ** that want \r\n line endings */
1305  f = fopen(zTempFile, bBin ? "wb" : "w");
1306  if( f==0 ){
1307    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1308    goto edit_func_end;
1309  }
1310  sz = sqlite3_value_bytes(argv[0]);
1311  if( bBin ){
1312    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1313  }else{
1314    const char *z = (const char*)sqlite3_value_text(argv[0]);
1315    /* Remember whether or not the value originally contained \r\n */
1316    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1317    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1318  }
1319  fclose(f);
1320  f = 0;
1321  if( x!=sz ){
1322    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1323    goto edit_func_end;
1324  }
1325  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1326  if( zCmd==0 ){
1327    sqlite3_result_error_nomem(context);
1328    goto edit_func_end;
1329  }
1330  rc = system(zCmd);
1331  sqlite3_free(zCmd);
1332  if( rc ){
1333    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1334    goto edit_func_end;
1335  }
1336  f = fopen(zTempFile, "rb");
1337  if( f==0 ){
1338    sqlite3_result_error(context,
1339      "edit() cannot reopen temp file after edit", -1);
1340    goto edit_func_end;
1341  }
1342  fseek(f, 0, SEEK_END);
1343  sz = ftell(f);
1344  rewind(f);
1345  p = sqlite3_malloc64( sz+1 );
1346  if( p==0 ){
1347    sqlite3_result_error_nomem(context);
1348    goto edit_func_end;
1349  }
1350  x = fread(p, 1, (size_t)sz, f);
1351  fclose(f);
1352  f = 0;
1353  if( x!=sz ){
1354    sqlite3_result_error(context, "could not read back the whole file", -1);
1355    goto edit_func_end;
1356  }
1357  if( bBin ){
1358    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1359  }else{
1360    sqlite3_int64 i, j;
1361    if( hasCRNL ){
1362      /* If the original contains \r\n then do no conversions back to \n */
1363      j = sz;
1364    }else{
1365      /* If the file did not originally contain \r\n then convert any new
1366      ** \r\n back into \n */
1367      for(i=j=0; i<sz; i++){
1368        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1369        p[j++] = p[i];
1370      }
1371      sz = j;
1372      p[sz] = 0;
1373    }
1374    sqlite3_result_text64(context, (const char*)p, sz,
1375                          sqlite3_free, SQLITE_UTF8);
1376  }
1377  p = 0;
1378
1379edit_func_end:
1380  if( f ) fclose(f);
1381  unlink(zTempFile);
1382  sqlite3_free(zTempFile);
1383  sqlite3_free(p);
1384}
1385#endif /* SQLITE_NOHAVE_SYSTEM */
1386
1387/*
1388** Save or restore the current output mode
1389*/
1390static void outputModePush(ShellState *p){
1391  p->modePrior = p->mode;
1392  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1393  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1394}
1395static void outputModePop(ShellState *p){
1396  p->mode = p->modePrior;
1397  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1398  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1399}
1400
1401/*
1402** Output the given string as a hex-encoded blob (eg. X'1234' )
1403*/
1404static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1405  int i;
1406  char *zBlob = (char *)pBlob;
1407  raw_printf(out,"X'");
1408  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1409  raw_printf(out,"'");
1410}
1411
1412/*
1413** Find a string that is not found anywhere in z[].  Return a pointer
1414** to that string.
1415**
1416** Try to use zA and zB first.  If both of those are already found in z[]
1417** then make up some string and store it in the buffer zBuf.
1418*/
1419static const char *unused_string(
1420  const char *z,                    /* Result must not appear anywhere in z */
1421  const char *zA, const char *zB,   /* Try these first */
1422  char *zBuf                        /* Space to store a generated string */
1423){
1424  unsigned i = 0;
1425  if( strstr(z, zA)==0 ) return zA;
1426  if( strstr(z, zB)==0 ) return zB;
1427  do{
1428    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1429  }while( strstr(z,zBuf)!=0 );
1430  return zBuf;
1431}
1432
1433/*
1434** Output the given string as a quoted string using SQL quoting conventions.
1435**
1436** See also: output_quoted_escaped_string()
1437*/
1438static void output_quoted_string(FILE *out, const char *z){
1439  int i;
1440  char c;
1441  setBinaryMode(out, 1);
1442  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1443  if( c==0 ){
1444    utf8_printf(out,"'%s'",z);
1445  }else{
1446    raw_printf(out, "'");
1447    while( *z ){
1448      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1449      if( c=='\'' ) i++;
1450      if( i ){
1451        utf8_printf(out, "%.*s", i, z);
1452        z += i;
1453      }
1454      if( c=='\'' ){
1455        raw_printf(out, "'");
1456        continue;
1457      }
1458      if( c==0 ){
1459        break;
1460      }
1461      z++;
1462    }
1463    raw_printf(out, "'");
1464  }
1465  setTextMode(out, 1);
1466}
1467
1468/*
1469** Output the given string as a quoted string using SQL quoting conventions.
1470** Additionallly , escape the "\n" and "\r" characters so that they do not
1471** get corrupted by end-of-line translation facilities in some operating
1472** systems.
1473**
1474** This is like output_quoted_string() but with the addition of the \r\n
1475** escape mechanism.
1476*/
1477static void output_quoted_escaped_string(FILE *out, const char *z){
1478  int i;
1479  char c;
1480  setBinaryMode(out, 1);
1481  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1482  if( c==0 ){
1483    utf8_printf(out,"'%s'",z);
1484  }else{
1485    const char *zNL = 0;
1486    const char *zCR = 0;
1487    int nNL = 0;
1488    int nCR = 0;
1489    char zBuf1[20], zBuf2[20];
1490    for(i=0; z[i]; i++){
1491      if( z[i]=='\n' ) nNL++;
1492      if( z[i]=='\r' ) nCR++;
1493    }
1494    if( nNL ){
1495      raw_printf(out, "replace(");
1496      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1497    }
1498    if( nCR ){
1499      raw_printf(out, "replace(");
1500      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1501    }
1502    raw_printf(out, "'");
1503    while( *z ){
1504      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1505      if( c=='\'' ) i++;
1506      if( i ){
1507        utf8_printf(out, "%.*s", i, z);
1508        z += i;
1509      }
1510      if( c=='\'' ){
1511        raw_printf(out, "'");
1512        continue;
1513      }
1514      if( c==0 ){
1515        break;
1516      }
1517      z++;
1518      if( c=='\n' ){
1519        raw_printf(out, "%s", zNL);
1520        continue;
1521      }
1522      raw_printf(out, "%s", zCR);
1523    }
1524    raw_printf(out, "'");
1525    if( nCR ){
1526      raw_printf(out, ",'%s',char(13))", zCR);
1527    }
1528    if( nNL ){
1529      raw_printf(out, ",'%s',char(10))", zNL);
1530    }
1531  }
1532  setTextMode(out, 1);
1533}
1534
1535/*
1536** Output the given string as a quoted according to C or TCL quoting rules.
1537*/
1538static void output_c_string(FILE *out, const char *z){
1539  unsigned int c;
1540  fputc('"', out);
1541  while( (c = *(z++))!=0 ){
1542    if( c=='\\' ){
1543      fputc(c, out);
1544      fputc(c, out);
1545    }else if( c=='"' ){
1546      fputc('\\', out);
1547      fputc('"', out);
1548    }else if( c=='\t' ){
1549      fputc('\\', out);
1550      fputc('t', out);
1551    }else if( c=='\n' ){
1552      fputc('\\', out);
1553      fputc('n', out);
1554    }else if( c=='\r' ){
1555      fputc('\\', out);
1556      fputc('r', out);
1557    }else if( !isprint(c&0xff) ){
1558      raw_printf(out, "\\%03o", c&0xff);
1559    }else{
1560      fputc(c, out);
1561    }
1562  }
1563  fputc('"', out);
1564}
1565
1566/*
1567** Output the given string with characters that are special to
1568** HTML escaped.
1569*/
1570static void output_html_string(FILE *out, const char *z){
1571  int i;
1572  if( z==0 ) z = "";
1573  while( *z ){
1574    for(i=0;   z[i]
1575            && z[i]!='<'
1576            && z[i]!='&'
1577            && z[i]!='>'
1578            && z[i]!='\"'
1579            && z[i]!='\'';
1580        i++){}
1581    if( i>0 ){
1582      utf8_printf(out,"%.*s",i,z);
1583    }
1584    if( z[i]=='<' ){
1585      raw_printf(out,"&lt;");
1586    }else if( z[i]=='&' ){
1587      raw_printf(out,"&amp;");
1588    }else if( z[i]=='>' ){
1589      raw_printf(out,"&gt;");
1590    }else if( z[i]=='\"' ){
1591      raw_printf(out,"&quot;");
1592    }else if( z[i]=='\'' ){
1593      raw_printf(out,"&#39;");
1594    }else{
1595      break;
1596    }
1597    z += i + 1;
1598  }
1599}
1600
1601/*
1602** If a field contains any character identified by a 1 in the following
1603** array, then the string must be quoted for CSV.
1604*/
1605static const char needCsvQuote[] = {
1606  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1607  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1608  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1609  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1610  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1611  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1612  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1613  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1614  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1615  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1616  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1617  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1618  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1619  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1620  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1621  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1622};
1623
1624/*
1625** Output a single term of CSV.  Actually, p->colSeparator is used for
1626** the separator, which may or may not be a comma.  p->nullValue is
1627** the null value.  Strings are quoted if necessary.  The separator
1628** is only issued if bSep is true.
1629*/
1630static void output_csv(ShellState *p, const char *z, int bSep){
1631  FILE *out = p->out;
1632  if( z==0 ){
1633    utf8_printf(out,"%s",p->nullValue);
1634  }else{
1635    int i;
1636    int nSep = strlen30(p->colSeparator);
1637    for(i=0; z[i]; i++){
1638      if( needCsvQuote[((unsigned char*)z)[i]]
1639         || (z[i]==p->colSeparator[0] &&
1640             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1641        i = 0;
1642        break;
1643      }
1644    }
1645    if( i==0 ){
1646      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1647      utf8_printf(out, "%s", zQuoted);
1648      sqlite3_free(zQuoted);
1649    }else{
1650      utf8_printf(out, "%s", z);
1651    }
1652  }
1653  if( bSep ){
1654    utf8_printf(p->out, "%s", p->colSeparator);
1655  }
1656}
1657
1658/*
1659** This routine runs when the user presses Ctrl-C
1660*/
1661static void interrupt_handler(int NotUsed){
1662  UNUSED_PARAMETER(NotUsed);
1663  seenInterrupt++;
1664  if( seenInterrupt>2 ) exit(1);
1665  if( globalDb ) sqlite3_interrupt(globalDb);
1666}
1667
1668#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1669/*
1670** This routine runs for console events (e.g. Ctrl-C) on Win32
1671*/
1672static BOOL WINAPI ConsoleCtrlHandler(
1673  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1674){
1675  if( dwCtrlType==CTRL_C_EVENT ){
1676    interrupt_handler(0);
1677    return TRUE;
1678  }
1679  return FALSE;
1680}
1681#endif
1682
1683#ifndef SQLITE_OMIT_AUTHORIZATION
1684/*
1685** When the ".auth ON" is set, the following authorizer callback is
1686** invoked.  It always returns SQLITE_OK.
1687*/
1688static int shellAuth(
1689  void *pClientData,
1690  int op,
1691  const char *zA1,
1692  const char *zA2,
1693  const char *zA3,
1694  const char *zA4
1695){
1696  ShellState *p = (ShellState*)pClientData;
1697  static const char *azAction[] = { 0,
1698     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1699     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1700     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1701     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1702     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1703     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1704     "PRAGMA",               "READ",                 "SELECT",
1705     "TRANSACTION",          "UPDATE",               "ATTACH",
1706     "DETACH",               "ALTER_TABLE",          "REINDEX",
1707     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1708     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1709  };
1710  int i;
1711  const char *az[4];
1712  az[0] = zA1;
1713  az[1] = zA2;
1714  az[2] = zA3;
1715  az[3] = zA4;
1716  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1717  for(i=0; i<4; i++){
1718    raw_printf(p->out, " ");
1719    if( az[i] ){
1720      output_c_string(p->out, az[i]);
1721    }else{
1722      raw_printf(p->out, "NULL");
1723    }
1724  }
1725  raw_printf(p->out, "\n");
1726  return SQLITE_OK;
1727}
1728#endif
1729
1730/*
1731** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1732**
1733** This routine converts some CREATE TABLE statements for shadow tables
1734** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1735*/
1736static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1737  if( z==0 ) return;
1738  if( zTail==0 ) return;
1739  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1740    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1741  }else{
1742    utf8_printf(out, "%s%s", z, zTail);
1743  }
1744}
1745static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1746  char c = z[n];
1747  z[n] = 0;
1748  printSchemaLine(out, z, zTail);
1749  z[n] = c;
1750}
1751
1752/*
1753** Return true if string z[] has nothing but whitespace and comments to the
1754** end of the first line.
1755*/
1756static int wsToEol(const char *z){
1757  int i;
1758  for(i=0; z[i]; i++){
1759    if( z[i]=='\n' ) return 1;
1760    if( IsSpace(z[i]) ) continue;
1761    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1762    return 0;
1763  }
1764  return 1;
1765}
1766
1767/*
1768** Add a new entry to the EXPLAIN QUERY PLAN data
1769*/
1770static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1771  EQPGraphRow *pNew;
1772  int nText = strlen30(zText);
1773  if( p->autoEQPtest ){
1774    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1775  }
1776  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1777  if( pNew==0 ) shell_out_of_memory();
1778  pNew->iEqpId = iEqpId;
1779  pNew->iParentId = p2;
1780  memcpy(pNew->zText, zText, nText+1);
1781  pNew->pNext = 0;
1782  if( p->sGraph.pLast ){
1783    p->sGraph.pLast->pNext = pNew;
1784  }else{
1785    p->sGraph.pRow = pNew;
1786  }
1787  p->sGraph.pLast = pNew;
1788}
1789
1790/*
1791** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1792** in p->sGraph.
1793*/
1794static void eqp_reset(ShellState *p){
1795  EQPGraphRow *pRow, *pNext;
1796  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1797    pNext = pRow->pNext;
1798    sqlite3_free(pRow);
1799  }
1800  memset(&p->sGraph, 0, sizeof(p->sGraph));
1801}
1802
1803/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1804** pOld, or return the first such line if pOld is NULL
1805*/
1806static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1807  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1808  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1809  return pRow;
1810}
1811
1812/* Render a single level of the graph that has iEqpId as its parent.  Called
1813** recursively to render sublevels.
1814*/
1815static void eqp_render_level(ShellState *p, int iEqpId){
1816  EQPGraphRow *pRow, *pNext;
1817  int n = strlen30(p->sGraph.zPrefix);
1818  char *z;
1819  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1820    pNext = eqp_next_row(p, iEqpId, pRow);
1821    z = pRow->zText;
1822    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1823                pNext ? "|--" : "`--", z);
1824    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1825      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1826      eqp_render_level(p, pRow->iEqpId);
1827      p->sGraph.zPrefix[n] = 0;
1828    }
1829  }
1830}
1831
1832/*
1833** Display and reset the EXPLAIN QUERY PLAN data
1834*/
1835static void eqp_render(ShellState *p){
1836  EQPGraphRow *pRow = p->sGraph.pRow;
1837  if( pRow ){
1838    if( pRow->zText[0]=='-' ){
1839      if( pRow->pNext==0 ){
1840        eqp_reset(p);
1841        return;
1842      }
1843      utf8_printf(p->out, "%s\n", pRow->zText+3);
1844      p->sGraph.pRow = pRow->pNext;
1845      sqlite3_free(pRow);
1846    }else{
1847      utf8_printf(p->out, "QUERY PLAN\n");
1848    }
1849    p->sGraph.zPrefix[0] = 0;
1850    eqp_render_level(p, 0);
1851    eqp_reset(p);
1852  }
1853}
1854
1855#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1856/*
1857** Progress handler callback.
1858*/
1859static int progress_handler(void *pClientData) {
1860  ShellState *p = (ShellState*)pClientData;
1861  p->nProgress++;
1862  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1863    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1864    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1865    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
1866    return 1;
1867  }
1868  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
1869    raw_printf(p->out, "Progress %u\n", p->nProgress);
1870  }
1871  return 0;
1872}
1873#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
1874
1875/*
1876** This is the callback routine that the shell
1877** invokes for each row of a query result.
1878*/
1879static int shell_callback(
1880  void *pArg,
1881  int nArg,        /* Number of result columns */
1882  char **azArg,    /* Text of each result column */
1883  char **azCol,    /* Column names */
1884  int *aiType      /* Column types */
1885){
1886  int i;
1887  ShellState *p = (ShellState*)pArg;
1888
1889  if( azArg==0 ) return 0;
1890  switch( p->cMode ){
1891    case MODE_Line: {
1892      int w = 5;
1893      if( azArg==0 ) break;
1894      for(i=0; i<nArg; i++){
1895        int len = strlen30(azCol[i] ? azCol[i] : "");
1896        if( len>w ) w = len;
1897      }
1898      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1899      for(i=0; i<nArg; i++){
1900        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1901                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1902      }
1903      break;
1904    }
1905    case MODE_Explain:
1906    case MODE_Column: {
1907      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1908      const int *colWidth;
1909      int showHdr;
1910      char *rowSep;
1911      int nWidth;
1912      if( p->cMode==MODE_Column ){
1913        colWidth = p->colWidth;
1914        nWidth = ArraySize(p->colWidth);
1915        showHdr = p->showHeader;
1916        rowSep = p->rowSeparator;
1917      }else{
1918        colWidth = aExplainWidths;
1919        nWidth = ArraySize(aExplainWidths);
1920        showHdr = 1;
1921        rowSep = SEP_Row;
1922      }
1923      if( p->cnt++==0 ){
1924        for(i=0; i<nArg; i++){
1925          int w, n;
1926          if( i<nWidth ){
1927            w = colWidth[i];
1928          }else{
1929            w = 0;
1930          }
1931          if( w==0 ){
1932            w = strlenChar(azCol[i] ? azCol[i] : "");
1933            if( w<10 ) w = 10;
1934            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1935            if( w<n ) w = n;
1936          }
1937          if( i<ArraySize(p->actualWidth) ){
1938            p->actualWidth[i] = w;
1939          }
1940          if( showHdr ){
1941            utf8_width_print(p->out, w, azCol[i]);
1942            utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1943          }
1944        }
1945        if( showHdr ){
1946          for(i=0; i<nArg; i++){
1947            int w;
1948            if( i<ArraySize(p->actualWidth) ){
1949               w = p->actualWidth[i];
1950               if( w<0 ) w = -w;
1951            }else{
1952               w = 10;
1953            }
1954            utf8_printf(p->out,"%-*.*s%s",w,w,
1955                   "----------------------------------------------------------"
1956                   "----------------------------------------------------------",
1957                    i==nArg-1 ? rowSep : "  ");
1958          }
1959        }
1960      }
1961      if( azArg==0 ) break;
1962      for(i=0; i<nArg; i++){
1963        int w;
1964        if( i<ArraySize(p->actualWidth) ){
1965           w = p->actualWidth[i];
1966        }else{
1967           w = 10;
1968        }
1969        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1970          w = strlenChar(azArg[i]);
1971        }
1972        if( i==1 && p->aiIndent && p->pStmt ){
1973          if( p->iIndent<p->nIndent ){
1974            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1975          }
1976          p->iIndent++;
1977        }
1978        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1979        utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1980      }
1981      break;
1982    }
1983    case MODE_Semi: {   /* .schema and .fullschema output */
1984      printSchemaLine(p->out, azArg[0], ";\n");
1985      break;
1986    }
1987    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
1988      char *z;
1989      int j;
1990      int nParen = 0;
1991      char cEnd = 0;
1992      char c;
1993      int nLine = 0;
1994      assert( nArg==1 );
1995      if( azArg[0]==0 ) break;
1996      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1997       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1998      ){
1999        utf8_printf(p->out, "%s;\n", azArg[0]);
2000        break;
2001      }
2002      z = sqlite3_mprintf("%s", azArg[0]);
2003      j = 0;
2004      for(i=0; IsSpace(z[i]); i++){}
2005      for(; (c = z[i])!=0; i++){
2006        if( IsSpace(c) ){
2007          if( z[j-1]=='\r' ) z[j-1] = '\n';
2008          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2009        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2010          j--;
2011        }
2012        z[j++] = c;
2013      }
2014      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2015      z[j] = 0;
2016      if( strlen30(z)>=79 ){
2017        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2018          if( c==cEnd ){
2019            cEnd = 0;
2020          }else if( c=='"' || c=='\'' || c=='`' ){
2021            cEnd = c;
2022          }else if( c=='[' ){
2023            cEnd = ']';
2024          }else if( c=='-' && z[i+1]=='-' ){
2025            cEnd = '\n';
2026          }else if( c=='(' ){
2027            nParen++;
2028          }else if( c==')' ){
2029            nParen--;
2030            if( nLine>0 && nParen==0 && j>0 ){
2031              printSchemaLineN(p->out, z, j, "\n");
2032              j = 0;
2033            }
2034          }
2035          z[j++] = c;
2036          if( nParen==1 && cEnd==0
2037           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2038          ){
2039            if( c=='\n' ) j--;
2040            printSchemaLineN(p->out, z, j, "\n  ");
2041            j = 0;
2042            nLine++;
2043            while( IsSpace(z[i+1]) ){ i++; }
2044          }
2045        }
2046        z[j] = 0;
2047      }
2048      printSchemaLine(p->out, z, ";\n");
2049      sqlite3_free(z);
2050      break;
2051    }
2052    case MODE_List: {
2053      if( p->cnt++==0 && p->showHeader ){
2054        for(i=0; i<nArg; i++){
2055          utf8_printf(p->out,"%s%s",azCol[i],
2056                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2057        }
2058      }
2059      if( azArg==0 ) break;
2060      for(i=0; i<nArg; i++){
2061        char *z = azArg[i];
2062        if( z==0 ) z = p->nullValue;
2063        utf8_printf(p->out, "%s", z);
2064        if( i<nArg-1 ){
2065          utf8_printf(p->out, "%s", p->colSeparator);
2066        }else{
2067          utf8_printf(p->out, "%s", p->rowSeparator);
2068        }
2069      }
2070      break;
2071    }
2072    case MODE_Html: {
2073      if( p->cnt++==0 && p->showHeader ){
2074        raw_printf(p->out,"<TR>");
2075        for(i=0; i<nArg; i++){
2076          raw_printf(p->out,"<TH>");
2077          output_html_string(p->out, azCol[i]);
2078          raw_printf(p->out,"</TH>\n");
2079        }
2080        raw_printf(p->out,"</TR>\n");
2081      }
2082      if( azArg==0 ) break;
2083      raw_printf(p->out,"<TR>");
2084      for(i=0; i<nArg; i++){
2085        raw_printf(p->out,"<TD>");
2086        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2087        raw_printf(p->out,"</TD>\n");
2088      }
2089      raw_printf(p->out,"</TR>\n");
2090      break;
2091    }
2092    case MODE_Tcl: {
2093      if( p->cnt++==0 && p->showHeader ){
2094        for(i=0; i<nArg; i++){
2095          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2096          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2097        }
2098        utf8_printf(p->out, "%s", p->rowSeparator);
2099      }
2100      if( azArg==0 ) break;
2101      for(i=0; i<nArg; i++){
2102        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2103        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2104      }
2105      utf8_printf(p->out, "%s", p->rowSeparator);
2106      break;
2107    }
2108    case MODE_Csv: {
2109      setBinaryMode(p->out, 1);
2110      if( p->cnt++==0 && p->showHeader ){
2111        for(i=0; i<nArg; i++){
2112          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2113        }
2114        utf8_printf(p->out, "%s", p->rowSeparator);
2115      }
2116      if( nArg>0 ){
2117        for(i=0; i<nArg; i++){
2118          output_csv(p, azArg[i], i<nArg-1);
2119        }
2120        utf8_printf(p->out, "%s", p->rowSeparator);
2121      }
2122      setTextMode(p->out, 1);
2123      break;
2124    }
2125    case MODE_Insert: {
2126      if( azArg==0 ) break;
2127      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2128      if( p->showHeader ){
2129        raw_printf(p->out,"(");
2130        for(i=0; i<nArg; i++){
2131          if( i>0 ) raw_printf(p->out, ",");
2132          if( quoteChar(azCol[i]) ){
2133            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2134            utf8_printf(p->out, "%s", z);
2135            sqlite3_free(z);
2136          }else{
2137            raw_printf(p->out, "%s", azCol[i]);
2138          }
2139        }
2140        raw_printf(p->out,")");
2141      }
2142      p->cnt++;
2143      for(i=0; i<nArg; i++){
2144        raw_printf(p->out, i>0 ? "," : " VALUES(");
2145        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2146          utf8_printf(p->out,"NULL");
2147        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2148          if( ShellHasFlag(p, SHFLG_Newlines) ){
2149            output_quoted_string(p->out, azArg[i]);
2150          }else{
2151            output_quoted_escaped_string(p->out, azArg[i]);
2152          }
2153        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2154          utf8_printf(p->out,"%s", azArg[i]);
2155        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2156          char z[50];
2157          double r = sqlite3_column_double(p->pStmt, i);
2158          sqlite3_uint64 ur;
2159          memcpy(&ur,&r,sizeof(r));
2160          if( ur==0x7ff0000000000000LL ){
2161            raw_printf(p->out, "1e999");
2162          }else if( ur==0xfff0000000000000LL ){
2163            raw_printf(p->out, "-1e999");
2164          }else{
2165            sqlite3_snprintf(50,z,"%!.20g", r);
2166            raw_printf(p->out, "%s", z);
2167          }
2168        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2169          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2170          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2171          output_hex_blob(p->out, pBlob, nBlob);
2172        }else if( isNumber(azArg[i], 0) ){
2173          utf8_printf(p->out,"%s", azArg[i]);
2174        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2175          output_quoted_string(p->out, azArg[i]);
2176        }else{
2177          output_quoted_escaped_string(p->out, azArg[i]);
2178        }
2179      }
2180      raw_printf(p->out,");\n");
2181      break;
2182    }
2183    case MODE_Quote: {
2184      if( azArg==0 ) break;
2185      if( p->cnt==0 && p->showHeader ){
2186        for(i=0; i<nArg; i++){
2187          if( i>0 ) raw_printf(p->out, ",");
2188          output_quoted_string(p->out, azCol[i]);
2189        }
2190        raw_printf(p->out,"\n");
2191      }
2192      p->cnt++;
2193      for(i=0; i<nArg; i++){
2194        if( i>0 ) raw_printf(p->out, ",");
2195        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2196          utf8_printf(p->out,"NULL");
2197        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2198          output_quoted_string(p->out, azArg[i]);
2199        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2200          utf8_printf(p->out,"%s", azArg[i]);
2201        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2202          char z[50];
2203          double r = sqlite3_column_double(p->pStmt, i);
2204          sqlite3_snprintf(50,z,"%!.20g", r);
2205          raw_printf(p->out, "%s", z);
2206        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2207          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2208          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2209          output_hex_blob(p->out, pBlob, nBlob);
2210        }else if( isNumber(azArg[i], 0) ){
2211          utf8_printf(p->out,"%s", azArg[i]);
2212        }else{
2213          output_quoted_string(p->out, azArg[i]);
2214        }
2215      }
2216      raw_printf(p->out,"\n");
2217      break;
2218    }
2219    case MODE_Ascii: {
2220      if( p->cnt++==0 && p->showHeader ){
2221        for(i=0; i<nArg; i++){
2222          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2223          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2224        }
2225        utf8_printf(p->out, "%s", p->rowSeparator);
2226      }
2227      if( azArg==0 ) break;
2228      for(i=0; i<nArg; i++){
2229        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2230        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2231      }
2232      utf8_printf(p->out, "%s", p->rowSeparator);
2233      break;
2234    }
2235    case MODE_EQP: {
2236      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2237      break;
2238    }
2239  }
2240  return 0;
2241}
2242
2243/*
2244** This is the callback routine that the SQLite library
2245** invokes for each row of a query result.
2246*/
2247static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2248  /* since we don't have type info, call the shell_callback with a NULL value */
2249  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2250}
2251
2252/*
2253** This is the callback routine from sqlite3_exec() that appends all
2254** output onto the end of a ShellText object.
2255*/
2256static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2257  ShellText *p = (ShellText*)pArg;
2258  int i;
2259  UNUSED_PARAMETER(az);
2260  if( azArg==0 ) return 0;
2261  if( p->n ) appendText(p, "|", 0);
2262  for(i=0; i<nArg; i++){
2263    if( i ) appendText(p, ",", 0);
2264    if( azArg[i] ) appendText(p, azArg[i], 0);
2265  }
2266  return 0;
2267}
2268
2269/*
2270** Generate an appropriate SELFTEST table in the main database.
2271*/
2272static void createSelftestTable(ShellState *p){
2273  char *zErrMsg = 0;
2274  sqlite3_exec(p->db,
2275    "SAVEPOINT selftest_init;\n"
2276    "CREATE TABLE IF NOT EXISTS selftest(\n"
2277    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2278    "  op TEXT,\n"                   /* Operator:  memo run */
2279    "  cmd TEXT,\n"                  /* Command text */
2280    "  ans TEXT\n"                   /* Desired answer */
2281    ");"
2282    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2283    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2284    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2285    "         'memo','Tests generated by --init');\n"
2286    "INSERT INTO [_shell$self]\n"
2287    "  SELECT 'run',\n"
2288    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2289                                 "FROM sqlite_master ORDER BY 2'',224))',\n"
2290    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2291                          "FROM sqlite_master ORDER BY 2',224));\n"
2292    "INSERT INTO [_shell$self]\n"
2293    "  SELECT 'run',"
2294    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2295    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2296    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2297    "  FROM (\n"
2298    "    SELECT name FROM sqlite_master\n"
2299    "     WHERE type='table'\n"
2300    "       AND name<>'selftest'\n"
2301    "       AND coalesce(rootpage,0)>0\n"
2302    "  )\n"
2303    " ORDER BY name;\n"
2304    "INSERT INTO [_shell$self]\n"
2305    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2306    "INSERT INTO selftest(tno,op,cmd,ans)"
2307    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2308    "DROP TABLE [_shell$self];"
2309    ,0,0,&zErrMsg);
2310  if( zErrMsg ){
2311    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2312    sqlite3_free(zErrMsg);
2313  }
2314  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2315}
2316
2317
2318/*
2319** Set the destination table field of the ShellState structure to
2320** the name of the table given.  Escape any quote characters in the
2321** table name.
2322*/
2323static void set_table_name(ShellState *p, const char *zName){
2324  int i, n;
2325  char cQuote;
2326  char *z;
2327
2328  if( p->zDestTable ){
2329    free(p->zDestTable);
2330    p->zDestTable = 0;
2331  }
2332  if( zName==0 ) return;
2333  cQuote = quoteChar(zName);
2334  n = strlen30(zName);
2335  if( cQuote ) n += n+2;
2336  z = p->zDestTable = malloc( n+1 );
2337  if( z==0 ) shell_out_of_memory();
2338  n = 0;
2339  if( cQuote ) z[n++] = cQuote;
2340  for(i=0; zName[i]; i++){
2341    z[n++] = zName[i];
2342    if( zName[i]==cQuote ) z[n++] = cQuote;
2343  }
2344  if( cQuote ) z[n++] = cQuote;
2345  z[n] = 0;
2346}
2347
2348
2349/*
2350** Execute a query statement that will generate SQL output.  Print
2351** the result columns, comma-separated, on a line and then add a
2352** semicolon terminator to the end of that line.
2353**
2354** If the number of columns is 1 and that column contains text "--"
2355** then write the semicolon on a separate line.  That way, if a
2356** "--" comment occurs at the end of the statement, the comment
2357** won't consume the semicolon terminator.
2358*/
2359static int run_table_dump_query(
2360  ShellState *p,           /* Query context */
2361  const char *zSelect,     /* SELECT statement to extract content */
2362  const char *zFirstRow    /* Print before first row, if not NULL */
2363){
2364  sqlite3_stmt *pSelect;
2365  int rc;
2366  int nResult;
2367  int i;
2368  const char *z;
2369  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2370  if( rc!=SQLITE_OK || !pSelect ){
2371    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2372                sqlite3_errmsg(p->db));
2373    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2374    return rc;
2375  }
2376  rc = sqlite3_step(pSelect);
2377  nResult = sqlite3_column_count(pSelect);
2378  while( rc==SQLITE_ROW ){
2379    if( zFirstRow ){
2380      utf8_printf(p->out, "%s", zFirstRow);
2381      zFirstRow = 0;
2382    }
2383    z = (const char*)sqlite3_column_text(pSelect, 0);
2384    utf8_printf(p->out, "%s", z);
2385    for(i=1; i<nResult; i++){
2386      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2387    }
2388    if( z==0 ) z = "";
2389    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2390    if( z[0] ){
2391      raw_printf(p->out, "\n;\n");
2392    }else{
2393      raw_printf(p->out, ";\n");
2394    }
2395    rc = sqlite3_step(pSelect);
2396  }
2397  rc = sqlite3_finalize(pSelect);
2398  if( rc!=SQLITE_OK ){
2399    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2400                sqlite3_errmsg(p->db));
2401    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2402  }
2403  return rc;
2404}
2405
2406/*
2407** Allocate space and save off current error string.
2408*/
2409static char *save_err_msg(
2410  sqlite3 *db            /* Database to query */
2411){
2412  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2413  char *zErrMsg = sqlite3_malloc64(nErrMsg);
2414  if( zErrMsg ){
2415    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2416  }
2417  return zErrMsg;
2418}
2419
2420#ifdef __linux__
2421/*
2422** Attempt to display I/O stats on Linux using /proc/PID/io
2423*/
2424static void displayLinuxIoStats(FILE *out){
2425  FILE *in;
2426  char z[200];
2427  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2428  in = fopen(z, "rb");
2429  if( in==0 ) return;
2430  while( fgets(z, sizeof(z), in)!=0 ){
2431    static const struct {
2432      const char *zPattern;
2433      const char *zDesc;
2434    } aTrans[] = {
2435      { "rchar: ",                  "Bytes received by read():" },
2436      { "wchar: ",                  "Bytes sent to write():"    },
2437      { "syscr: ",                  "Read() system calls:"      },
2438      { "syscw: ",                  "Write() system calls:"     },
2439      { "read_bytes: ",             "Bytes read from storage:"  },
2440      { "write_bytes: ",            "Bytes written to storage:" },
2441      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2442    };
2443    int i;
2444    for(i=0; i<ArraySize(aTrans); i++){
2445      int n = strlen30(aTrans[i].zPattern);
2446      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2447        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2448        break;
2449      }
2450    }
2451  }
2452  fclose(in);
2453}
2454#endif
2455
2456/*
2457** Display a single line of status using 64-bit values.
2458*/
2459static void displayStatLine(
2460  ShellState *p,            /* The shell context */
2461  char *zLabel,             /* Label for this one line */
2462  char *zFormat,            /* Format for the result */
2463  int iStatusCtrl,          /* Which status to display */
2464  int bReset                /* True to reset the stats */
2465){
2466  sqlite3_int64 iCur = -1;
2467  sqlite3_int64 iHiwtr = -1;
2468  int i, nPercent;
2469  char zLine[200];
2470  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2471  for(i=0, nPercent=0; zFormat[i]; i++){
2472    if( zFormat[i]=='%' ) nPercent++;
2473  }
2474  if( nPercent>1 ){
2475    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2476  }else{
2477    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2478  }
2479  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2480}
2481
2482/*
2483** Display memory stats.
2484*/
2485static int display_stats(
2486  sqlite3 *db,                /* Database to query */
2487  ShellState *pArg,           /* Pointer to ShellState */
2488  int bReset                  /* True to reset the stats */
2489){
2490  int iCur;
2491  int iHiwtr;
2492  FILE *out;
2493  if( pArg==0 || pArg->out==0 ) return 0;
2494  out = pArg->out;
2495
2496  if( pArg->pStmt && (pArg->statsOn & 2) ){
2497    int nCol, i, x;
2498    sqlite3_stmt *pStmt = pArg->pStmt;
2499    char z[100];
2500    nCol = sqlite3_column_count(pStmt);
2501    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2502    for(i=0; i<nCol; i++){
2503      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2504      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2505#ifndef SQLITE_OMIT_DECLTYPE
2506      sqlite3_snprintf(30, z+x, "declared type:");
2507      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2508#endif
2509#ifdef SQLITE_ENABLE_COLUMN_METADATA
2510      sqlite3_snprintf(30, z+x, "database name:");
2511      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2512      sqlite3_snprintf(30, z+x, "table name:");
2513      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2514      sqlite3_snprintf(30, z+x, "origin name:");
2515      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2516#endif
2517    }
2518  }
2519
2520  displayStatLine(pArg, "Memory Used:",
2521     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2522  displayStatLine(pArg, "Number of Outstanding Allocations:",
2523     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2524  if( pArg->shellFlgs & SHFLG_Pagecache ){
2525    displayStatLine(pArg, "Number of Pcache Pages Used:",
2526       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2527  }
2528  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2529     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2530  displayStatLine(pArg, "Largest Allocation:",
2531     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2532  displayStatLine(pArg, "Largest Pcache Allocation:",
2533     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2534#ifdef YYTRACKMAXSTACKDEPTH
2535  displayStatLine(pArg, "Deepest Parser Stack:",
2536     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2537#endif
2538
2539  if( db ){
2540    if( pArg->shellFlgs & SHFLG_Lookaside ){
2541      iHiwtr = iCur = -1;
2542      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2543                        &iCur, &iHiwtr, bReset);
2544      raw_printf(pArg->out,
2545              "Lookaside Slots Used:                %d (max %d)\n",
2546              iCur, iHiwtr);
2547      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2548                        &iCur, &iHiwtr, bReset);
2549      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2550              iHiwtr);
2551      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2552                        &iCur, &iHiwtr, bReset);
2553      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2554              iHiwtr);
2555      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2556                        &iCur, &iHiwtr, bReset);
2557      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2558              iHiwtr);
2559    }
2560    iHiwtr = iCur = -1;
2561    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2562    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2563            iCur);
2564    iHiwtr = iCur = -1;
2565    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2566    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2567    iHiwtr = iCur = -1;
2568    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2569    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2570    iHiwtr = iCur = -1;
2571    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2572    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2573    iHiwtr = iCur = -1;
2574    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2575    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2576    iHiwtr = iCur = -1;
2577    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2578    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2579            iCur);
2580    iHiwtr = iCur = -1;
2581    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2582    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2583            iCur);
2584  }
2585
2586  if( pArg->pStmt ){
2587    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2588                               bReset);
2589    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2590    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2591    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2592    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2593    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2594    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2595    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2596    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2597    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2598    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2599    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2600    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2601    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2602  }
2603
2604#ifdef __linux__
2605  displayLinuxIoStats(pArg->out);
2606#endif
2607
2608  /* Do not remove this machine readable comment: extra-stats-output-here */
2609
2610  return 0;
2611}
2612
2613/*
2614** Display scan stats.
2615*/
2616static void display_scanstats(
2617  sqlite3 *db,                    /* Database to query */
2618  ShellState *pArg                /* Pointer to ShellState */
2619){
2620#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2621  UNUSED_PARAMETER(db);
2622  UNUSED_PARAMETER(pArg);
2623#else
2624  int i, k, n, mx;
2625  raw_printf(pArg->out, "-------- scanstats --------\n");
2626  mx = 0;
2627  for(k=0; k<=mx; k++){
2628    double rEstLoop = 1.0;
2629    for(i=n=0; 1; i++){
2630      sqlite3_stmt *p = pArg->pStmt;
2631      sqlite3_int64 nLoop, nVisit;
2632      double rEst;
2633      int iSid;
2634      const char *zExplain;
2635      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2636        break;
2637      }
2638      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2639      if( iSid>mx ) mx = iSid;
2640      if( iSid!=k ) continue;
2641      if( n==0 ){
2642        rEstLoop = (double)nLoop;
2643        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2644      }
2645      n++;
2646      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2647      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2648      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2649      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2650      rEstLoop *= rEst;
2651      raw_printf(pArg->out,
2652          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2653          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2654      );
2655    }
2656  }
2657  raw_printf(pArg->out, "---------------------------\n");
2658#endif
2659}
2660
2661/*
2662** Parameter azArray points to a zero-terminated array of strings. zStr
2663** points to a single nul-terminated string. Return non-zero if zStr
2664** is equal, according to strcmp(), to any of the strings in the array.
2665** Otherwise, return zero.
2666*/
2667static int str_in_array(const char *zStr, const char **azArray){
2668  int i;
2669  for(i=0; azArray[i]; i++){
2670    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2671  }
2672  return 0;
2673}
2674
2675/*
2676** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2677** and populate the ShellState.aiIndent[] array with the number of
2678** spaces each opcode should be indented before it is output.
2679**
2680** The indenting rules are:
2681**
2682**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2683**       all opcodes that occur between the p2 jump destination and the opcode
2684**       itself by 2 spaces.
2685**
2686**     * For each "Goto", if the jump destination is earlier in the program
2687**       and ends on one of:
2688**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2689**       or if the P1 parameter is one instead of zero,
2690**       then indent all opcodes between the earlier instruction
2691**       and "Goto" by 2 spaces.
2692*/
2693static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2694  const char *zSql;               /* The text of the SQL statement */
2695  const char *z;                  /* Used to check if this is an EXPLAIN */
2696  int *abYield = 0;               /* True if op is an OP_Yield */
2697  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2698  int iOp;                        /* Index of operation in p->aiIndent[] */
2699
2700  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2701  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2702                            "Rewind", 0 };
2703  const char *azGoto[] = { "Goto", 0 };
2704
2705  /* Try to figure out if this is really an EXPLAIN statement. If this
2706  ** cannot be verified, return early.  */
2707  if( sqlite3_column_count(pSql)!=8 ){
2708    p->cMode = p->mode;
2709    return;
2710  }
2711  zSql = sqlite3_sql(pSql);
2712  if( zSql==0 ) return;
2713  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2714  if( sqlite3_strnicmp(z, "explain", 7) ){
2715    p->cMode = p->mode;
2716    return;
2717  }
2718
2719  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2720    int i;
2721    int iAddr = sqlite3_column_int(pSql, 0);
2722    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2723
2724    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2725    ** p2 is an instruction address, set variable p2op to the index of that
2726    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2727    ** the current instruction is part of a sub-program generated by an
2728    ** SQL trigger or foreign key.  */
2729    int p2 = sqlite3_column_int(pSql, 3);
2730    int p2op = (p2 + (iOp-iAddr));
2731
2732    /* Grow the p->aiIndent array as required */
2733    if( iOp>=nAlloc ){
2734      if( iOp==0 ){
2735        /* Do further verfication that this is explain output.  Abort if
2736        ** it is not */
2737        static const char *explainCols[] = {
2738           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2739        int jj;
2740        for(jj=0; jj<ArraySize(explainCols); jj++){
2741          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2742            p->cMode = p->mode;
2743            sqlite3_reset(pSql);
2744            return;
2745          }
2746        }
2747      }
2748      nAlloc += 100;
2749      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2750      if( p->aiIndent==0 ) shell_out_of_memory();
2751      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2752      if( abYield==0 ) shell_out_of_memory();
2753    }
2754    abYield[iOp] = str_in_array(zOp, azYield);
2755    p->aiIndent[iOp] = 0;
2756    p->nIndent = iOp+1;
2757
2758    if( str_in_array(zOp, azNext) ){
2759      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2760    }
2761    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2762     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2763    ){
2764      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2765    }
2766  }
2767
2768  p->iIndent = 0;
2769  sqlite3_free(abYield);
2770  sqlite3_reset(pSql);
2771}
2772
2773/*
2774** Free the array allocated by explain_data_prepare().
2775*/
2776static void explain_data_delete(ShellState *p){
2777  sqlite3_free(p->aiIndent);
2778  p->aiIndent = 0;
2779  p->nIndent = 0;
2780  p->iIndent = 0;
2781}
2782
2783/*
2784** Disable and restore .wheretrace and .selecttrace settings.
2785*/
2786#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2787extern int sqlite3SelectTrace;
2788static int savedSelectTrace;
2789#endif
2790#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2791extern int sqlite3WhereTrace;
2792static int savedWhereTrace;
2793#endif
2794static void disable_debug_trace_modes(void){
2795#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2796  savedSelectTrace = sqlite3SelectTrace;
2797  sqlite3SelectTrace = 0;
2798#endif
2799#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2800  savedWhereTrace = sqlite3WhereTrace;
2801  sqlite3WhereTrace = 0;
2802#endif
2803}
2804static void restore_debug_trace_modes(void){
2805#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2806  sqlite3SelectTrace = savedSelectTrace;
2807#endif
2808#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2809  sqlite3WhereTrace = savedWhereTrace;
2810#endif
2811}
2812
2813/* Create the TEMP table used to store parameter bindings */
2814static void bind_table_init(ShellState *p){
2815  int wrSchema = 0;
2816  int defensiveMode = 0;
2817  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
2818  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
2819  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2820  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
2821  sqlite3_exec(p->db,
2822    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
2823    "  key TEXT PRIMARY KEY,\n"
2824    "  value ANY\n"
2825    ") WITHOUT ROWID;",
2826    0, 0, 0);
2827  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
2828  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
2829}
2830
2831/*
2832** Bind parameters on a prepared statement.
2833**
2834** Parameter bindings are taken from a TEMP table of the form:
2835**
2836**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
2837**    WITHOUT ROWID;
2838**
2839** No bindings occur if this table does not exist.  The special character '$'
2840** is included in the table name to help prevent collisions with actual tables.
2841** The table must be in the TEMP schema.
2842*/
2843static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2844  int nVar;
2845  int i;
2846  int rc;
2847  sqlite3_stmt *pQ = 0;
2848
2849  nVar = sqlite3_bind_parameter_count(pStmt);
2850  if( nVar==0 ) return;  /* Nothing to do */
2851  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
2852                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2853    return; /* Parameter table does not exist */
2854  }
2855  rc = sqlite3_prepare_v2(pArg->db,
2856          "SELECT value FROM temp.sqlite_parameters"
2857          " WHERE key=?1", -1, &pQ, 0);
2858  if( rc || pQ==0 ) return;
2859  for(i=1; i<=nVar; i++){
2860    char zNum[30];
2861    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2862    if( zVar==0 ){
2863      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2864      zVar = zNum;
2865    }
2866    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2867    if( sqlite3_step(pQ)==SQLITE_ROW ){
2868      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2869    }else{
2870      sqlite3_bind_null(pStmt, i);
2871    }
2872    sqlite3_reset(pQ);
2873  }
2874  sqlite3_finalize(pQ);
2875}
2876
2877/*
2878** Run a prepared statement
2879*/
2880static void exec_prepared_stmt(
2881  ShellState *pArg,                                /* Pointer to ShellState */
2882  sqlite3_stmt *pStmt                              /* Statment to run */
2883){
2884  int rc;
2885
2886  /* perform the first step.  this will tell us if we
2887  ** have a result set or not and how wide it is.
2888  */
2889  rc = sqlite3_step(pStmt);
2890  /* if we have a result set... */
2891  if( SQLITE_ROW == rc ){
2892    /* allocate space for col name ptr, value ptr, and type */
2893    int nCol = sqlite3_column_count(pStmt);
2894    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2895    if( !pData ){
2896      rc = SQLITE_NOMEM;
2897    }else{
2898      char **azCols = (char **)pData;      /* Names of result columns */
2899      char **azVals = &azCols[nCol];       /* Results */
2900      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2901      int i, x;
2902      assert(sizeof(int) <= sizeof(char *));
2903      /* save off ptrs to column names */
2904      for(i=0; i<nCol; i++){
2905        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2906      }
2907      do{
2908        /* extract the data and data types */
2909        for(i=0; i<nCol; i++){
2910          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2911          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2912            azVals[i] = "";
2913          }else{
2914            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2915          }
2916          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2917            rc = SQLITE_NOMEM;
2918            break; /* from for */
2919          }
2920        } /* end for */
2921
2922        /* if data and types extracted successfully... */
2923        if( SQLITE_ROW == rc ){
2924          /* call the supplied callback with the result row data */
2925          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2926            rc = SQLITE_ABORT;
2927          }else{
2928            rc = sqlite3_step(pStmt);
2929          }
2930        }
2931      } while( SQLITE_ROW == rc );
2932      sqlite3_free(pData);
2933    }
2934  }
2935}
2936
2937#ifndef SQLITE_OMIT_VIRTUALTABLE
2938/*
2939** This function is called to process SQL if the previous shell command
2940** was ".expert". It passes the SQL in the second argument directly to
2941** the sqlite3expert object.
2942**
2943** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2944** code. In this case, (*pzErr) may be set to point to a buffer containing
2945** an English language error message. It is the responsibility of the
2946** caller to eventually free this buffer using sqlite3_free().
2947*/
2948static int expertHandleSQL(
2949  ShellState *pState,
2950  const char *zSql,
2951  char **pzErr
2952){
2953  assert( pState->expert.pExpert );
2954  assert( pzErr==0 || *pzErr==0 );
2955  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2956}
2957
2958/*
2959** This function is called either to silently clean up the object
2960** created by the ".expert" command (if bCancel==1), or to generate a
2961** report from it and then clean it up (if bCancel==0).
2962**
2963** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2964** code. In this case, (*pzErr) may be set to point to a buffer containing
2965** an English language error message. It is the responsibility of the
2966** caller to eventually free this buffer using sqlite3_free().
2967*/
2968static int expertFinish(
2969  ShellState *pState,
2970  int bCancel,
2971  char **pzErr
2972){
2973  int rc = SQLITE_OK;
2974  sqlite3expert *p = pState->expert.pExpert;
2975  assert( p );
2976  assert( bCancel || pzErr==0 || *pzErr==0 );
2977  if( bCancel==0 ){
2978    FILE *out = pState->out;
2979    int bVerbose = pState->expert.bVerbose;
2980
2981    rc = sqlite3_expert_analyze(p, pzErr);
2982    if( rc==SQLITE_OK ){
2983      int nQuery = sqlite3_expert_count(p);
2984      int i;
2985
2986      if( bVerbose ){
2987        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2988        raw_printf(out, "-- Candidates -----------------------------\n");
2989        raw_printf(out, "%s\n", zCand);
2990      }
2991      for(i=0; i<nQuery; i++){
2992        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2993        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2994        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2995        if( zIdx==0 ) zIdx = "(no new indexes)\n";
2996        if( bVerbose ){
2997          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2998          raw_printf(out, "%s\n\n", zSql);
2999        }
3000        raw_printf(out, "%s\n", zIdx);
3001        raw_printf(out, "%s\n", zEQP);
3002      }
3003    }
3004  }
3005  sqlite3_expert_destroy(p);
3006  pState->expert.pExpert = 0;
3007  return rc;
3008}
3009
3010/*
3011** Implementation of ".expert" dot command.
3012*/
3013static int expertDotCommand(
3014  ShellState *pState,             /* Current shell tool state */
3015  char **azArg,                   /* Array of arguments passed to dot command */
3016  int nArg                        /* Number of entries in azArg[] */
3017){
3018  int rc = SQLITE_OK;
3019  char *zErr = 0;
3020  int i;
3021  int iSample = 0;
3022
3023  assert( pState->expert.pExpert==0 );
3024  memset(&pState->expert, 0, sizeof(ExpertInfo));
3025
3026  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3027    char *z = azArg[i];
3028    int n;
3029    if( z[0]=='-' && z[1]=='-' ) z++;
3030    n = strlen30(z);
3031    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3032      pState->expert.bVerbose = 1;
3033    }
3034    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3035      if( i==(nArg-1) ){
3036        raw_printf(stderr, "option requires an argument: %s\n", z);
3037        rc = SQLITE_ERROR;
3038      }else{
3039        iSample = (int)integerValue(azArg[++i]);
3040        if( iSample<0 || iSample>100 ){
3041          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3042          rc = SQLITE_ERROR;
3043        }
3044      }
3045    }
3046    else{
3047      raw_printf(stderr, "unknown option: %s\n", z);
3048      rc = SQLITE_ERROR;
3049    }
3050  }
3051
3052  if( rc==SQLITE_OK ){
3053    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3054    if( pState->expert.pExpert==0 ){
3055      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
3056      rc = SQLITE_ERROR;
3057    }else{
3058      sqlite3_expert_config(
3059          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3060      );
3061    }
3062  }
3063
3064  return rc;
3065}
3066#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3067
3068/*
3069** Execute a statement or set of statements.  Print
3070** any result rows/columns depending on the current mode
3071** set via the supplied callback.
3072**
3073** This is very similar to SQLite's built-in sqlite3_exec()
3074** function except it takes a slightly different callback
3075** and callback data argument.
3076*/
3077static int shell_exec(
3078  ShellState *pArg,                         /* Pointer to ShellState */
3079  const char *zSql,                         /* SQL to be evaluated */
3080  char **pzErrMsg                           /* Error msg written here */
3081){
3082  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3083  int rc = SQLITE_OK;             /* Return Code */
3084  int rc2;
3085  const char *zLeftover;          /* Tail of unprocessed SQL */
3086  sqlite3 *db = pArg->db;
3087
3088  if( pzErrMsg ){
3089    *pzErrMsg = NULL;
3090  }
3091
3092#ifndef SQLITE_OMIT_VIRTUALTABLE
3093  if( pArg->expert.pExpert ){
3094    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3095    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3096  }
3097#endif
3098
3099  while( zSql[0] && (SQLITE_OK == rc) ){
3100    static const char *zStmtSql;
3101    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3102    if( SQLITE_OK != rc ){
3103      if( pzErrMsg ){
3104        *pzErrMsg = save_err_msg(db);
3105      }
3106    }else{
3107      if( !pStmt ){
3108        /* this happens for a comment or white-space */
3109        zSql = zLeftover;
3110        while( IsSpace(zSql[0]) ) zSql++;
3111        continue;
3112      }
3113      zStmtSql = sqlite3_sql(pStmt);
3114      if( zStmtSql==0 ) zStmtSql = "";
3115      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3116
3117      /* save off the prepared statment handle and reset row count */
3118      if( pArg ){
3119        pArg->pStmt = pStmt;
3120        pArg->cnt = 0;
3121      }
3122
3123      /* echo the sql statement if echo on */
3124      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3125        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3126      }
3127
3128      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3129      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3130        sqlite3_stmt *pExplain;
3131        char *zEQP;
3132        int triggerEQP = 0;
3133        disable_debug_trace_modes();
3134        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3135        if( pArg->autoEQP>=AUTOEQP_trigger ){
3136          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3137        }
3138        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3139        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3140        if( rc==SQLITE_OK ){
3141          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3142            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3143            int iEqpId = sqlite3_column_int(pExplain, 0);
3144            int iParentId = sqlite3_column_int(pExplain, 1);
3145            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3146            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3147          }
3148          eqp_render(pArg);
3149        }
3150        sqlite3_finalize(pExplain);
3151        sqlite3_free(zEQP);
3152        if( pArg->autoEQP>=AUTOEQP_full ){
3153          /* Also do an EXPLAIN for ".eqp full" mode */
3154          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3155          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3156          if( rc==SQLITE_OK ){
3157            pArg->cMode = MODE_Explain;
3158            explain_data_prepare(pArg, pExplain);
3159            exec_prepared_stmt(pArg, pExplain);
3160            explain_data_delete(pArg);
3161          }
3162          sqlite3_finalize(pExplain);
3163          sqlite3_free(zEQP);
3164        }
3165        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3166          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3167          /* Reprepare pStmt before reactiving trace modes */
3168          sqlite3_finalize(pStmt);
3169          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3170          if( pArg ) pArg->pStmt = pStmt;
3171        }
3172        restore_debug_trace_modes();
3173      }
3174
3175      if( pArg ){
3176        pArg->cMode = pArg->mode;
3177        if( pArg->autoExplain ){
3178          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3179            pArg->cMode = MODE_Explain;
3180          }
3181          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3182            pArg->cMode = MODE_EQP;
3183          }
3184        }
3185
3186        /* If the shell is currently in ".explain" mode, gather the extra
3187        ** data required to add indents to the output.*/
3188        if( pArg->cMode==MODE_Explain ){
3189          explain_data_prepare(pArg, pStmt);
3190        }
3191      }
3192
3193      bind_prepared_stmt(pArg, pStmt);
3194      exec_prepared_stmt(pArg, pStmt);
3195      explain_data_delete(pArg);
3196      eqp_render(pArg);
3197
3198      /* print usage stats if stats on */
3199      if( pArg && pArg->statsOn ){
3200        display_stats(db, pArg, 0);
3201      }
3202
3203      /* print loop-counters if required */
3204      if( pArg && pArg->scanstatsOn ){
3205        display_scanstats(db, pArg);
3206      }
3207
3208      /* Finalize the statement just executed. If this fails, save a
3209      ** copy of the error message. Otherwise, set zSql to point to the
3210      ** next statement to execute. */
3211      rc2 = sqlite3_finalize(pStmt);
3212      if( rc!=SQLITE_NOMEM ) rc = rc2;
3213      if( rc==SQLITE_OK ){
3214        zSql = zLeftover;
3215        while( IsSpace(zSql[0]) ) zSql++;
3216      }else if( pzErrMsg ){
3217        *pzErrMsg = save_err_msg(db);
3218      }
3219
3220      /* clear saved stmt handle */
3221      if( pArg ){
3222        pArg->pStmt = NULL;
3223      }
3224    }
3225  } /* end while */
3226
3227  return rc;
3228}
3229
3230/*
3231** Release memory previously allocated by tableColumnList().
3232*/
3233static void freeColumnList(char **azCol){
3234  int i;
3235  for(i=1; azCol[i]; i++){
3236    sqlite3_free(azCol[i]);
3237  }
3238  /* azCol[0] is a static string */
3239  sqlite3_free(azCol);
3240}
3241
3242/*
3243** Return a list of pointers to strings which are the names of all
3244** columns in table zTab.   The memory to hold the names is dynamically
3245** allocated and must be released by the caller using a subsequent call
3246** to freeColumnList().
3247**
3248** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3249** value that needs to be preserved, then azCol[0] is filled in with the
3250** name of the rowid column.
3251**
3252** The first regular column in the table is azCol[1].  The list is terminated
3253** by an entry with azCol[i]==0.
3254*/
3255static char **tableColumnList(ShellState *p, const char *zTab){
3256  char **azCol = 0;
3257  sqlite3_stmt *pStmt;
3258  char *zSql;
3259  int nCol = 0;
3260  int nAlloc = 0;
3261  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3262  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3263  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3264  int rc;
3265
3266  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3267  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3268  sqlite3_free(zSql);
3269  if( rc ) return 0;
3270  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3271    if( nCol>=nAlloc-2 ){
3272      nAlloc = nAlloc*2 + nCol + 10;
3273      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3274      if( azCol==0 ) shell_out_of_memory();
3275    }
3276    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3277    if( sqlite3_column_int(pStmt, 5) ){
3278      nPK++;
3279      if( nPK==1
3280       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3281                          "INTEGER")==0
3282      ){
3283        isIPK = 1;
3284      }else{
3285        isIPK = 0;
3286      }
3287    }
3288  }
3289  sqlite3_finalize(pStmt);
3290  if( azCol==0 ) return 0;
3291  azCol[0] = 0;
3292  azCol[nCol+1] = 0;
3293
3294  /* The decision of whether or not a rowid really needs to be preserved
3295  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3296  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3297  ** rowids on tables where the rowid is inaccessible because there are other
3298  ** columns in the table named "rowid", "_rowid_", and "oid".
3299  */
3300  if( preserveRowid && isIPK ){
3301    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3302    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3303    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3304    ** ROWID aliases.  To distinguish these cases, check to see if
3305    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3306    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3307    */
3308    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3309                           " WHERE origin='pk'", zTab);
3310    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3311    sqlite3_free(zSql);
3312    if( rc ){
3313      freeColumnList(azCol);
3314      return 0;
3315    }
3316    rc = sqlite3_step(pStmt);
3317    sqlite3_finalize(pStmt);
3318    preserveRowid = rc==SQLITE_ROW;
3319  }
3320  if( preserveRowid ){
3321    /* Only preserve the rowid if we can find a name to use for the
3322    ** rowid */
3323    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3324    int i, j;
3325    for(j=0; j<3; j++){
3326      for(i=1; i<=nCol; i++){
3327        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3328      }
3329      if( i>nCol ){
3330        /* At this point, we know that azRowid[j] is not the name of any
3331        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3332        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3333        ** tables will fail this last check */
3334        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3335        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3336        break;
3337      }
3338    }
3339  }
3340  return azCol;
3341}
3342
3343/*
3344** Toggle the reverse_unordered_selects setting.
3345*/
3346static void toggleSelectOrder(sqlite3 *db){
3347  sqlite3_stmt *pStmt = 0;
3348  int iSetting = 0;
3349  char zStmt[100];
3350  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3351  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3352    iSetting = sqlite3_column_int(pStmt, 0);
3353  }
3354  sqlite3_finalize(pStmt);
3355  sqlite3_snprintf(sizeof(zStmt), zStmt,
3356       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3357  sqlite3_exec(db, zStmt, 0, 0, 0);
3358}
3359
3360/*
3361** This is a different callback routine used for dumping the database.
3362** Each row received by this callback consists of a table name,
3363** the table type ("index" or "table") and SQL to create the table.
3364** This routine should print text sufficient to recreate the table.
3365*/
3366static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3367  int rc;
3368  const char *zTable;
3369  const char *zType;
3370  const char *zSql;
3371  ShellState *p = (ShellState *)pArg;
3372
3373  UNUSED_PARAMETER(azNotUsed);
3374  if( nArg!=3 || azArg==0 ) return 0;
3375  zTable = azArg[0];
3376  zType = azArg[1];
3377  zSql = azArg[2];
3378
3379  if( strcmp(zTable, "sqlite_sequence")==0 ){
3380    raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3381  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3382    raw_printf(p->out, "ANALYZE sqlite_master;\n");
3383  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3384    return 0;
3385  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3386    char *zIns;
3387    if( !p->writableSchema ){
3388      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3389      p->writableSchema = 1;
3390    }
3391    zIns = sqlite3_mprintf(
3392       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3393       "VALUES('table','%q','%q',0,'%q');",
3394       zTable, zTable, zSql);
3395    utf8_printf(p->out, "%s\n", zIns);
3396    sqlite3_free(zIns);
3397    return 0;
3398  }else{
3399    printSchemaLine(p->out, zSql, ";\n");
3400  }
3401
3402  if( strcmp(zType, "table")==0 ){
3403    ShellText sSelect;
3404    ShellText sTable;
3405    char **azCol;
3406    int i;
3407    char *savedDestTable;
3408    int savedMode;
3409
3410    azCol = tableColumnList(p, zTable);
3411    if( azCol==0 ){
3412      p->nErr++;
3413      return 0;
3414    }
3415
3416    /* Always quote the table name, even if it appears to be pure ascii,
3417    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3418    initText(&sTable);
3419    appendText(&sTable, zTable, quoteChar(zTable));
3420    /* If preserving the rowid, add a column list after the table name.
3421    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3422    ** instead of the usual "INSERT INTO tab VALUES(...)".
3423    */
3424    if( azCol[0] ){
3425      appendText(&sTable, "(", 0);
3426      appendText(&sTable, azCol[0], 0);
3427      for(i=1; azCol[i]; i++){
3428        appendText(&sTable, ",", 0);
3429        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3430      }
3431      appendText(&sTable, ")", 0);
3432    }
3433
3434    /* Build an appropriate SELECT statement */
3435    initText(&sSelect);
3436    appendText(&sSelect, "SELECT ", 0);
3437    if( azCol[0] ){
3438      appendText(&sSelect, azCol[0], 0);
3439      appendText(&sSelect, ",", 0);
3440    }
3441    for(i=1; azCol[i]; i++){
3442      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3443      if( azCol[i+1] ){
3444        appendText(&sSelect, ",", 0);
3445      }
3446    }
3447    freeColumnList(azCol);
3448    appendText(&sSelect, " FROM ", 0);
3449    appendText(&sSelect, zTable, quoteChar(zTable));
3450
3451    savedDestTable = p->zDestTable;
3452    savedMode = p->mode;
3453    p->zDestTable = sTable.z;
3454    p->mode = p->cMode = MODE_Insert;
3455    rc = shell_exec(p, sSelect.z, 0);
3456    if( (rc&0xff)==SQLITE_CORRUPT ){
3457      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3458      toggleSelectOrder(p->db);
3459      shell_exec(p, sSelect.z, 0);
3460      toggleSelectOrder(p->db);
3461    }
3462    p->zDestTable = savedDestTable;
3463    p->mode = savedMode;
3464    freeText(&sTable);
3465    freeText(&sSelect);
3466    if( rc ) p->nErr++;
3467  }
3468  return 0;
3469}
3470
3471/*
3472** Run zQuery.  Use dump_callback() as the callback routine so that
3473** the contents of the query are output as SQL statements.
3474**
3475** If we get a SQLITE_CORRUPT error, rerun the query after appending
3476** "ORDER BY rowid DESC" to the end.
3477*/
3478static int run_schema_dump_query(
3479  ShellState *p,
3480  const char *zQuery
3481){
3482  int rc;
3483  char *zErr = 0;
3484  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3485  if( rc==SQLITE_CORRUPT ){
3486    char *zQ2;
3487    int len = strlen30(zQuery);
3488    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3489    if( zErr ){
3490      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3491      sqlite3_free(zErr);
3492      zErr = 0;
3493    }
3494    zQ2 = malloc( len+100 );
3495    if( zQ2==0 ) return rc;
3496    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3497    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3498    if( rc ){
3499      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3500    }else{
3501      rc = SQLITE_CORRUPT;
3502    }
3503    sqlite3_free(zErr);
3504    free(zQ2);
3505  }
3506  return rc;
3507}
3508
3509/*
3510** Text of help messages.
3511**
3512** The help text for each individual command begins with a line that starts
3513** with ".".  Subsequent lines are supplimental information.
3514**
3515** There must be two or more spaces between the end of the command and the
3516** start of the description of what that command does.
3517*/
3518static const char *(azHelp[]) = {
3519#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3520  ".archive ...             Manage SQL archives",
3521  "   Each command must have exactly one of the following options:",
3522  "     -c, --create               Create a new archive",
3523  "     -u, --update               Add or update files with changed mtime",
3524  "     -i, --insert               Like -u but always add even if unchanged",
3525  "     -t, --list                 List contents of archive",
3526  "     -x, --extract              Extract files from archive",
3527  "   Optional arguments:",
3528  "     -v, --verbose              Print each filename as it is processed",
3529  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
3530  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
3531  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
3532  "     -n, --dryrun               Show the SQL that would have occurred",
3533  "   Examples:",
3534  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
3535  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
3536  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
3537  "   See also:",
3538  "      http://sqlite.org/cli.html#sqlar_archive_support",
3539#endif
3540#ifndef SQLITE_OMIT_AUTHORIZATION
3541  ".auth ON|OFF             Show authorizer callbacks",
3542#endif
3543  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
3544  "       --append            Use the appendvfs",
3545  "       --async             Write to FILE without journal and fsync()",
3546  ".bail on|off             Stop after hitting an error.  Default OFF",
3547  ".binary on|off           Turn binary output on or off.  Default OFF",
3548  ".cd DIRECTORY            Change the working directory to DIRECTORY",
3549  ".changes on|off          Show number of rows changed by SQL",
3550  ".check GLOB              Fail if output since .testcase does not match",
3551  ".clone NEWDB             Clone data into NEWDB from the existing database",
3552  ".databases               List names and files of attached databases",
3553  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
3554  ".dbinfo ?DB?             Show status information about the database",
3555  ".dump ?TABLE? ...        Render all database content as SQL",
3556  "   Options:",
3557  "     --preserve-rowids      Include ROWID values in the output",
3558  "     --newlines             Allow unescaped newline characters in output",
3559  "   TABLE is a LIKE pattern for the tables to dump",
3560  ".echo on|off             Turn command echo on or off",
3561  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
3562  "   Other Modes:",
3563#ifdef SQLITE_DEBUG
3564  "      test                  Show raw EXPLAIN QUERY PLAN output",
3565  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
3566#endif
3567  "      trigger               Like \"full\" but also show trigger bytecode",
3568  ".excel                   Display the output of next command in spreadsheet",
3569  ".exit ?CODE?             Exit this program with return-code CODE",
3570  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
3571  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
3572  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
3573  "                           Run \".filectrl\" with no arguments for details",
3574  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
3575  ".headers on|off          Turn display of headers on or off",
3576  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
3577  ".import FILE TABLE       Import data from FILE into TABLE",
3578#ifndef SQLITE_OMIT_TEST_CONTROL
3579  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
3580#endif
3581  ".indexes ?TABLE?         Show names of indexes",
3582  "                           If TABLE is specified, only show indexes for",
3583  "                           tables matching TABLE using the LIKE operator.",
3584#ifdef SQLITE_ENABLE_IOTRACE
3585  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
3586#endif
3587  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
3588  ".lint OPTIONS            Report potential schema issues.",
3589  "     Options:",
3590  "        fkey-indexes     Find missing foreign key indexes",
3591#ifndef SQLITE_OMIT_LOAD_EXTENSION
3592  ".load FILE ?ENTRY?       Load an extension library",
3593#endif
3594  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
3595  ".mode MODE ?TABLE?       Set output mode",
3596  "   MODE is one of:",
3597  "     ascii    Columns/rows delimited by 0x1F and 0x1E",
3598  "     csv      Comma-separated values",
3599  "     column   Left-aligned columns.  (See .width)",
3600  "     html     HTML <table> code",
3601  "     insert   SQL insert statements for TABLE",
3602  "     line     One value per line",
3603  "     list     Values delimited by \"|\"",
3604  "     quote    Escape answers as for SQL",
3605  "     tabs     Tab-separated values",
3606  "     tcl      TCL list elements",
3607  ".nullvalue STRING        Use STRING in place of NULL values",
3608  ".once (-e|-x|FILE)       Output for the next SQL command only to FILE",
3609  "     If FILE begins with '|' then open as a pipe",
3610  "     Other options:",
3611  "       -e    Invoke system text editor",
3612  "       -x    Open in a spreadsheet",
3613#ifdef SQLITE_DEBUG
3614  ".oom [--repeat M] [N]    Simulate an OOM error on the N-th allocation",
3615#endif
3616  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
3617  "     Options:",
3618  "        --append        Use appendvfs to append database to the end of FILE",
3619#ifdef SQLITE_ENABLE_DESERIALIZE
3620  "        --deserialize   Load into memory useing sqlite3_deserialize()",
3621  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
3622  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
3623#endif
3624  "        --new           Initialize FILE to an empty database",
3625  "        --nofollow      Do not follow symbolic links",
3626  "        --readonly      Open FILE readonly",
3627  "        --zip           FILE is a ZIP archive",
3628  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
3629  "     If FILE begins with '|' then open it as a pipe.",
3630  ".parameter CMD ...       Manage SQL parameter bindings",
3631  "   clear                   Erase all bindings",
3632  "   init                    Initialize the TEMP table that holds bindings",
3633  "   list                    List the current parameter bindings",
3634  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
3635  "                           PARAMETER should start with one of: $ : @ ?",
3636  "   unset PARAMETER         Remove PARAMETER from the binding table",
3637  ".print STRING...         Print literal STRING",
3638#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3639  ".progress N              Invoke progress handler after every N opcodes",
3640  "   --limit N                 Interrupt after N progress callbacks",
3641  "   --once                    Do no more than one progress interrupt",
3642  "   --quiet|-q                No output except at interrupts",
3643  "   --reset                   Reset the count for each input and interrupt",
3644#endif
3645  ".prompt MAIN CONTINUE    Replace the standard prompts",
3646  ".quit                    Exit this program",
3647  ".read FILE               Read input from FILE",
3648#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
3649  ".recover                 Recover as much data as possible from corrupt db.",
3650  "   --freelist-corrupt       Assume the freelist is corrupt",
3651  "   --recovery-db NAME       Store recovery metadata in database file NAME",
3652  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
3653  "   --no-rowids              Do not attempt to recover rowid values",
3654  "                            that are not also INTEGER PRIMARY KEYs",
3655#endif
3656  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
3657  ".save FILE               Write in-memory database into FILE",
3658  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
3659  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
3660  "     Options:",
3661  "         --indent            Try to pretty-print the schema",
3662  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
3663  "    Options:",
3664  "       --init               Create a new SELFTEST table",
3665  "       -v                   Verbose output",
3666  ".separator COL ?ROW?     Change the column and row separators",
3667#if defined(SQLITE_ENABLE_SESSION)
3668  ".session ?NAME? CMD ...  Create or control sessions",
3669  "   Subcommands:",
3670  "     attach TABLE             Attach TABLE",
3671  "     changeset FILE           Write a changeset into FILE",
3672  "     close                    Close one session",
3673  "     enable ?BOOLEAN?         Set or query the enable bit",
3674  "     filter GLOB...           Reject tables matching GLOBs",
3675  "     indirect ?BOOLEAN?       Mark or query the indirect status",
3676  "     isempty                  Query whether the session is empty",
3677  "     list                     List currently open session names",
3678  "     open DB NAME             Open a new session on DB",
3679  "     patchset FILE            Write a patchset into FILE",
3680  "   If ?NAME? is omitted, the first defined session is used.",
3681#endif
3682  ".sha3sum ...             Compute a SHA3 hash of database content",
3683  "    Options:",
3684  "      --schema              Also hash the sqlite_master table",
3685  "      --sha3-224            Use the sha3-224 algorithm",
3686  "      --sha3-256            Use the sha3-256 algorithm (default)",
3687  "      --sha3-384            Use the sha3-384 algorithm",
3688  "      --sha3-512            Use the sha3-512 algorithm",
3689  "    Any other argument is a LIKE pattern for tables to hash",
3690#ifndef SQLITE_NOHAVE_SYSTEM
3691  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
3692#endif
3693  ".show                    Show the current values for various settings",
3694  ".stats ?on|off?          Show stats or turn stats on or off",
3695#ifndef SQLITE_NOHAVE_SYSTEM
3696  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
3697#endif
3698  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
3699  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
3700  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
3701  "                           Run \".testctrl\" with no arguments for details",
3702  ".timeout MS              Try opening locked tables for MS milliseconds",
3703  ".timer on|off            Turn SQL timer on or off",
3704#ifndef SQLITE_OMIT_TRACE
3705  ".trace ?OPTIONS?         Output each SQL statement as it is run",
3706  "    FILE                    Send output to FILE",
3707  "    stdout                  Send output to stdout",
3708  "    stderr                  Send output to stderr",
3709  "    off                     Disable tracing",
3710  "    --expanded              Expand query parameters",
3711#ifdef SQLITE_ENABLE_NORMALIZE
3712  "    --normalized            Normal the SQL statements",
3713#endif
3714  "    --plain                 Show SQL as it is input",
3715  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
3716  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
3717  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
3718  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
3719#endif /* SQLITE_OMIT_TRACE */
3720#ifdef SQLITE_DEBUG
3721  ".unmodule NAME ...       Unregister virtual table modules",
3722  "    --allexcept             Unregister everything except those named",
3723#endif
3724  ".vfsinfo ?AUX?           Information about the top-level VFS",
3725  ".vfslist                 List all available VFSes",
3726  ".vfsname ?AUX?           Print the name of the VFS stack",
3727  ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
3728  "     Negative values right-justify",
3729};
3730
3731/*
3732** Output help text.
3733**
3734** zPattern describes the set of commands for which help text is provided.
3735** If zPattern is NULL, then show all commands, but only give a one-line
3736** description of each.
3737**
3738** Return the number of matches.
3739*/
3740static int showHelp(FILE *out, const char *zPattern){
3741  int i = 0;
3742  int j = 0;
3743  int n = 0;
3744  char *zPat;
3745  if( zPattern==0
3746   || zPattern[0]=='0'
3747   || strcmp(zPattern,"-a")==0
3748   || strcmp(zPattern,"-all")==0
3749  ){
3750    /* Show all commands, but only one line per command */
3751    if( zPattern==0 ) zPattern = "";
3752    for(i=0; i<ArraySize(azHelp); i++){
3753      if( azHelp[i][0]=='.' || zPattern[0] ){
3754        utf8_printf(out, "%s\n", azHelp[i]);
3755        n++;
3756      }
3757    }
3758  }else{
3759    /* Look for commands that for which zPattern is an exact prefix */
3760    zPat = sqlite3_mprintf(".%s*", zPattern);
3761    for(i=0; i<ArraySize(azHelp); i++){
3762      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3763        utf8_printf(out, "%s\n", azHelp[i]);
3764        j = i+1;
3765        n++;
3766      }
3767    }
3768    sqlite3_free(zPat);
3769    if( n ){
3770      if( n==1 ){
3771        /* when zPattern is a prefix of exactly one command, then include the
3772        ** details of that command, which should begin at offset j */
3773        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3774          utf8_printf(out, "%s\n", azHelp[j]);
3775          j++;
3776        }
3777      }
3778      return n;
3779    }
3780    /* Look for commands that contain zPattern anywhere.  Show the complete
3781    ** text of all commands that match. */
3782    zPat = sqlite3_mprintf("%%%s%%", zPattern);
3783    for(i=0; i<ArraySize(azHelp); i++){
3784      if( azHelp[i][0]=='.' ) j = i;
3785      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3786        utf8_printf(out, "%s\n", azHelp[j]);
3787        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3788          j++;
3789          utf8_printf(out, "%s\n", azHelp[j]);
3790        }
3791        i = j;
3792        n++;
3793      }
3794    }
3795    sqlite3_free(zPat);
3796  }
3797  return n;
3798}
3799
3800/* Forward reference */
3801static int process_input(ShellState *p);
3802
3803/*
3804** Read the content of file zName into memory obtained from sqlite3_malloc64()
3805** and return a pointer to the buffer. The caller is responsible for freeing
3806** the memory.
3807**
3808** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3809** read.
3810**
3811** For convenience, a nul-terminator byte is always appended to the data read
3812** from the file before the buffer is returned. This byte is not included in
3813** the final value of (*pnByte), if applicable.
3814**
3815** NULL is returned if any error is encountered. The final value of *pnByte
3816** is undefined in this case.
3817*/
3818static char *readFile(const char *zName, int *pnByte){
3819  FILE *in = fopen(zName, "rb");
3820  long nIn;
3821  size_t nRead;
3822  char *pBuf;
3823  if( in==0 ) return 0;
3824  fseek(in, 0, SEEK_END);
3825  nIn = ftell(in);
3826  rewind(in);
3827  pBuf = sqlite3_malloc64( nIn+1 );
3828  if( pBuf==0 ){ fclose(in); return 0; }
3829  nRead = fread(pBuf, nIn, 1, in);
3830  fclose(in);
3831  if( nRead!=1 ){
3832    sqlite3_free(pBuf);
3833    return 0;
3834  }
3835  pBuf[nIn] = 0;
3836  if( pnByte ) *pnByte = nIn;
3837  return pBuf;
3838}
3839
3840#if defined(SQLITE_ENABLE_SESSION)
3841/*
3842** Close a single OpenSession object and release all of its associated
3843** resources.
3844*/
3845static void session_close(OpenSession *pSession){
3846  int i;
3847  sqlite3session_delete(pSession->p);
3848  sqlite3_free(pSession->zName);
3849  for(i=0; i<pSession->nFilter; i++){
3850    sqlite3_free(pSession->azFilter[i]);
3851  }
3852  sqlite3_free(pSession->azFilter);
3853  memset(pSession, 0, sizeof(OpenSession));
3854}
3855#endif
3856
3857/*
3858** Close all OpenSession objects and release all associated resources.
3859*/
3860#if defined(SQLITE_ENABLE_SESSION)
3861static void session_close_all(ShellState *p){
3862  int i;
3863  for(i=0; i<p->nSession; i++){
3864    session_close(&p->aSession[i]);
3865  }
3866  p->nSession = 0;
3867}
3868#else
3869# define session_close_all(X)
3870#endif
3871
3872/*
3873** Implementation of the xFilter function for an open session.  Omit
3874** any tables named by ".session filter" but let all other table through.
3875*/
3876#if defined(SQLITE_ENABLE_SESSION)
3877static int session_filter(void *pCtx, const char *zTab){
3878  OpenSession *pSession = (OpenSession*)pCtx;
3879  int i;
3880  for(i=0; i<pSession->nFilter; i++){
3881    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3882  }
3883  return 1;
3884}
3885#endif
3886
3887/*
3888** Try to deduce the type of file for zName based on its content.  Return
3889** one of the SHELL_OPEN_* constants.
3890**
3891** If the file does not exist or is empty but its name looks like a ZIP
3892** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3893** Otherwise, assume an ordinary database regardless of the filename if
3894** the type cannot be determined from content.
3895*/
3896int deduceDatabaseType(const char *zName, int dfltZip){
3897  FILE *f = fopen(zName, "rb");
3898  size_t n;
3899  int rc = SHELL_OPEN_UNSPEC;
3900  char zBuf[100];
3901  if( f==0 ){
3902    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3903       return SHELL_OPEN_ZIPFILE;
3904    }else{
3905       return SHELL_OPEN_NORMAL;
3906    }
3907  }
3908  n = fread(zBuf, 16, 1, f);
3909  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3910    fclose(f);
3911    return SHELL_OPEN_NORMAL;
3912  }
3913  fseek(f, -25, SEEK_END);
3914  n = fread(zBuf, 25, 1, f);
3915  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3916    rc = SHELL_OPEN_APPENDVFS;
3917  }else{
3918    fseek(f, -22, SEEK_END);
3919    n = fread(zBuf, 22, 1, f);
3920    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3921       && zBuf[3]==0x06 ){
3922      rc = SHELL_OPEN_ZIPFILE;
3923    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3924      rc = SHELL_OPEN_ZIPFILE;
3925    }
3926  }
3927  fclose(f);
3928  return rc;
3929}
3930
3931#ifdef SQLITE_ENABLE_DESERIALIZE
3932/*
3933** Reconstruct an in-memory database using the output from the "dbtotxt"
3934** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
3935** is 0, then read from standard input.
3936*/
3937static unsigned char *readHexDb(ShellState *p, int *pnData){
3938  unsigned char *a = 0;
3939  int nLine;
3940  int n = 0;
3941  int pgsz = 0;
3942  int iOffset = 0;
3943  int j, k;
3944  int rc;
3945  FILE *in;
3946  unsigned int x[16];
3947  char zLine[1000];
3948  if( p->zDbFilename ){
3949    in = fopen(p->zDbFilename, "r");
3950    if( in==0 ){
3951      utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3952      return 0;
3953    }
3954    nLine = 0;
3955  }else{
3956    in = p->in;
3957    nLine = p->lineno;
3958    if( in==0 ) in = stdin;
3959  }
3960  *pnData = 0;
3961  nLine++;
3962  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3963  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3964  if( rc!=2 ) goto readHexDb_error;
3965  if( n<0 ) goto readHexDb_error;
3966  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
3967  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
3968  a = sqlite3_malloc( n ? n : 1 );
3969  if( a==0 ){
3970    utf8_printf(stderr, "Out of memory!\n");
3971    goto readHexDb_error;
3972  }
3973  memset(a, 0, n);
3974  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3975    utf8_printf(stderr, "invalid pagesize\n");
3976    goto readHexDb_error;
3977  }
3978  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
3979    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3980    if( rc==2 ){
3981      iOffset = k;
3982      continue;
3983    }
3984    if( strncmp(zLine, "| end ", 6)==0 ){
3985      break;
3986    }
3987    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
3988                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3989                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3990    if( rc==17 ){
3991      k = iOffset+j;
3992      if( k+16<=n ){
3993        int ii;
3994        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
3995      }
3996    }
3997  }
3998  *pnData = n;
3999  if( in!=p->in ){
4000    fclose(in);
4001  }else{
4002    p->lineno = nLine;
4003  }
4004  return a;
4005
4006readHexDb_error:
4007  if( in!=p->in ){
4008    fclose(in);
4009  }else{
4010    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4011      nLine++;
4012      if(strncmp(zLine, "| end ", 6)==0 ) break;
4013    }
4014    p->lineno = nLine;
4015  }
4016  sqlite3_free(a);
4017  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4018  return 0;
4019}
4020#endif /* SQLITE_ENABLE_DESERIALIZE */
4021
4022/*
4023** Scalar function "shell_int32". The first argument to this function
4024** must be a blob. The second a non-negative integer. This function
4025** reads and returns a 32-bit big-endian integer from byte
4026** offset (4*<arg2>) of the blob.
4027*/
4028static void shellInt32(
4029  sqlite3_context *context,
4030  int argc,
4031  sqlite3_value **argv
4032){
4033  const unsigned char *pBlob;
4034  int nBlob;
4035  int iInt;
4036
4037  UNUSED_PARAMETER(argc);
4038  nBlob = sqlite3_value_bytes(argv[0]);
4039  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4040  iInt = sqlite3_value_int(argv[1]);
4041
4042  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4043    const unsigned char *a = &pBlob[iInt*4];
4044    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4045                       + ((sqlite3_int64)a[1]<<16)
4046                       + ((sqlite3_int64)a[2]<< 8)
4047                       + ((sqlite3_int64)a[3]<< 0);
4048    sqlite3_result_int64(context, iVal);
4049  }
4050}
4051
4052/*
4053** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4054** using "..." with internal double-quote characters doubled.
4055*/
4056static void shellIdQuote(
4057  sqlite3_context *context,
4058  int argc,
4059  sqlite3_value **argv
4060){
4061  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4062  UNUSED_PARAMETER(argc);
4063  if( zName ){
4064    char *z = sqlite3_mprintf("\"%w\"", zName);
4065    sqlite3_result_text(context, z, -1, sqlite3_free);
4066  }
4067}
4068
4069/*
4070** Scalar function "shell_escape_crnl" used by the .recover command.
4071** The argument passed to this function is the output of built-in
4072** function quote(). If the first character of the input is "'",
4073** indicating that the value passed to quote() was a text value,
4074** then this function searches the input for "\n" and "\r" characters
4075** and adds a wrapper similar to the following:
4076**
4077**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4078**
4079** Or, if the first character of the input is not "'", then a copy
4080** of the input is returned.
4081*/
4082static void shellEscapeCrnl(
4083  sqlite3_context *context,
4084  int argc,
4085  sqlite3_value **argv
4086){
4087  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4088  UNUSED_PARAMETER(argc);
4089  if( zText[0]=='\'' ){
4090    int nText = sqlite3_value_bytes(argv[0]);
4091    int i;
4092    char zBuf1[20];
4093    char zBuf2[20];
4094    const char *zNL = 0;
4095    const char *zCR = 0;
4096    int nCR = 0;
4097    int nNL = 0;
4098
4099    for(i=0; zText[i]; i++){
4100      if( zNL==0 && zText[i]=='\n' ){
4101        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4102        nNL = (int)strlen(zNL);
4103      }
4104      if( zCR==0 && zText[i]=='\r' ){
4105        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4106        nCR = (int)strlen(zCR);
4107      }
4108    }
4109
4110    if( zNL || zCR ){
4111      int iOut = 0;
4112      i64 nMax = (nNL > nCR) ? nNL : nCR;
4113      i64 nAlloc = nMax * nText + (nMax+64)*2;
4114      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4115      if( zOut==0 ){
4116        sqlite3_result_error_nomem(context);
4117        return;
4118      }
4119
4120      if( zNL && zCR ){
4121        memcpy(&zOut[iOut], "replace(replace(", 16);
4122        iOut += 16;
4123      }else{
4124        memcpy(&zOut[iOut], "replace(", 8);
4125        iOut += 8;
4126      }
4127      for(i=0; zText[i]; i++){
4128        if( zText[i]=='\n' ){
4129          memcpy(&zOut[iOut], zNL, nNL);
4130          iOut += nNL;
4131        }else if( zText[i]=='\r' ){
4132          memcpy(&zOut[iOut], zCR, nCR);
4133          iOut += nCR;
4134        }else{
4135          zOut[iOut] = zText[i];
4136          iOut++;
4137        }
4138      }
4139
4140      if( zNL ){
4141        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4142        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4143        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4144      }
4145      if( zCR ){
4146        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4147        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4148        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4149      }
4150
4151      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4152      sqlite3_free(zOut);
4153      return;
4154    }
4155  }
4156
4157  sqlite3_result_value(context, argv[0]);
4158}
4159
4160/* Flags for open_db().
4161**
4162** The default behavior of open_db() is to exit(1) if the database fails to
4163** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4164** but still returns without calling exit.
4165**
4166** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4167** ZIP archive if the file does not exist or is empty and its name matches
4168** the *.zip pattern.
4169*/
4170#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4171#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4172
4173/*
4174** Make sure the database is open.  If it is not, then open it.  If
4175** the database fails to open, print an error message and exit.
4176*/
4177static void open_db(ShellState *p, int openFlags){
4178  if( p->db==0 ){
4179    if( p->openMode==SHELL_OPEN_UNSPEC ){
4180      if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4181        p->openMode = SHELL_OPEN_NORMAL;
4182      }else{
4183        p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4184                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4185      }
4186    }
4187    switch( p->openMode ){
4188      case SHELL_OPEN_APPENDVFS: {
4189        sqlite3_open_v2(p->zDbFilename, &p->db,
4190           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4191        break;
4192      }
4193      case SHELL_OPEN_HEXDB:
4194      case SHELL_OPEN_DESERIALIZE: {
4195        sqlite3_open(0, &p->db);
4196        break;
4197      }
4198      case SHELL_OPEN_ZIPFILE: {
4199        sqlite3_open(":memory:", &p->db);
4200        break;
4201      }
4202      case SHELL_OPEN_READONLY: {
4203        sqlite3_open_v2(p->zDbFilename, &p->db,
4204            SQLITE_OPEN_READONLY|p->openFlags, 0);
4205        break;
4206      }
4207      case SHELL_OPEN_UNSPEC:
4208      case SHELL_OPEN_NORMAL: {
4209        sqlite3_open_v2(p->zDbFilename, &p->db,
4210           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4211        break;
4212      }
4213    }
4214    globalDb = p->db;
4215    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4216      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4217          p->zDbFilename, sqlite3_errmsg(p->db));
4218      if( openFlags & OPEN_DB_KEEPALIVE ){
4219        sqlite3_open(":memory:", &p->db);
4220        return;
4221      }
4222      exit(1);
4223    }
4224#ifndef SQLITE_OMIT_LOAD_EXTENSION
4225    sqlite3_enable_load_extension(p->db, 1);
4226#endif
4227    sqlite3_fileio_init(p->db, 0, 0);
4228    sqlite3_shathree_init(p->db, 0, 0);
4229    sqlite3_completion_init(p->db, 0, 0);
4230#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4231    sqlite3_dbdata_init(p->db, 0, 0);
4232#endif
4233#ifdef SQLITE_HAVE_ZLIB
4234    sqlite3_zipfile_init(p->db, 0, 0);
4235    sqlite3_sqlar_init(p->db, 0, 0);
4236#endif
4237    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4238                            shellAddSchemaName, 0, 0);
4239    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4240                            shellModuleSchema, 0, 0);
4241    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4242                            shellPutsFunc, 0, 0);
4243    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4244                            shellEscapeCrnl, 0, 0);
4245    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4246                            shellInt32, 0, 0);
4247    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4248                            shellIdQuote, 0, 0);
4249#ifndef SQLITE_NOHAVE_SYSTEM
4250    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4251                            editFunc, 0, 0);
4252    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4253                            editFunc, 0, 0);
4254#endif
4255    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4256      char *zSql = sqlite3_mprintf(
4257         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4258      sqlite3_exec(p->db, zSql, 0, 0, 0);
4259      sqlite3_free(zSql);
4260    }
4261#ifdef SQLITE_ENABLE_DESERIALIZE
4262    else
4263    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4264      int rc;
4265      int nData = 0;
4266      unsigned char *aData;
4267      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4268        aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4269      }else{
4270        aData = readHexDb(p, &nData);
4271        if( aData==0 ){
4272          return;
4273        }
4274      }
4275      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4276                   SQLITE_DESERIALIZE_RESIZEABLE |
4277                   SQLITE_DESERIALIZE_FREEONCLOSE);
4278      if( rc ){
4279        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4280      }
4281      if( p->szMax>0 ){
4282        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4283      }
4284    }
4285#endif
4286  }
4287}
4288
4289/*
4290** Attempt to close the databaes connection.  Report errors.
4291*/
4292void close_db(sqlite3 *db){
4293  int rc = sqlite3_close(db);
4294  if( rc ){
4295    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4296        rc, sqlite3_errmsg(db));
4297  }
4298}
4299
4300#if HAVE_READLINE || HAVE_EDITLINE
4301/*
4302** Readline completion callbacks
4303*/
4304static char *readline_completion_generator(const char *text, int state){
4305  static sqlite3_stmt *pStmt = 0;
4306  char *zRet;
4307  if( state==0 ){
4308    char *zSql;
4309    sqlite3_finalize(pStmt);
4310    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4311                           "  FROM completion(%Q) ORDER BY 1", text);
4312    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4313    sqlite3_free(zSql);
4314  }
4315  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4316    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4317  }else{
4318    sqlite3_finalize(pStmt);
4319    pStmt = 0;
4320    zRet = 0;
4321  }
4322  return zRet;
4323}
4324static char **readline_completion(const char *zText, int iStart, int iEnd){
4325  rl_attempted_completion_over = 1;
4326  return rl_completion_matches(zText, readline_completion_generator);
4327}
4328
4329#elif HAVE_LINENOISE
4330/*
4331** Linenoise completion callback
4332*/
4333static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4334  int nLine = strlen30(zLine);
4335  int i, iStart;
4336  sqlite3_stmt *pStmt = 0;
4337  char *zSql;
4338  char zBuf[1000];
4339
4340  if( nLine>sizeof(zBuf)-30 ) return;
4341  if( zLine[0]=='.' || zLine[0]=='#') return;
4342  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4343  if( i==nLine-1 ) return;
4344  iStart = i+1;
4345  memcpy(zBuf, zLine, iStart);
4346  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4347                         "  FROM completion(%Q,%Q) ORDER BY 1",
4348                         &zLine[iStart], zLine);
4349  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4350  sqlite3_free(zSql);
4351  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4352  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4353    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4354    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4355    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4356      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4357      linenoiseAddCompletion(lc, zBuf);
4358    }
4359  }
4360  sqlite3_finalize(pStmt);
4361}
4362#endif
4363
4364/*
4365** Do C-language style dequoting.
4366**
4367**    \a    -> alarm
4368**    \b    -> backspace
4369**    \t    -> tab
4370**    \n    -> newline
4371**    \v    -> vertical tab
4372**    \f    -> form feed
4373**    \r    -> carriage return
4374**    \s    -> space
4375**    \"    -> "
4376**    \'    -> '
4377**    \\    -> backslash
4378**    \NNN  -> ascii character NNN in octal
4379*/
4380static void resolve_backslashes(char *z){
4381  int i, j;
4382  char c;
4383  while( *z && *z!='\\' ) z++;
4384  for(i=j=0; (c = z[i])!=0; i++, j++){
4385    if( c=='\\' && z[i+1]!=0 ){
4386      c = z[++i];
4387      if( c=='a' ){
4388        c = '\a';
4389      }else if( c=='b' ){
4390        c = '\b';
4391      }else if( c=='t' ){
4392        c = '\t';
4393      }else if( c=='n' ){
4394        c = '\n';
4395      }else if( c=='v' ){
4396        c = '\v';
4397      }else if( c=='f' ){
4398        c = '\f';
4399      }else if( c=='r' ){
4400        c = '\r';
4401      }else if( c=='"' ){
4402        c = '"';
4403      }else if( c=='\'' ){
4404        c = '\'';
4405      }else if( c=='\\' ){
4406        c = '\\';
4407      }else if( c>='0' && c<='7' ){
4408        c -= '0';
4409        if( z[i+1]>='0' && z[i+1]<='7' ){
4410          i++;
4411          c = (c<<3) + z[i] - '0';
4412          if( z[i+1]>='0' && z[i+1]<='7' ){
4413            i++;
4414            c = (c<<3) + z[i] - '0';
4415          }
4416        }
4417      }
4418    }
4419    z[j] = c;
4420  }
4421  if( j<i ) z[j] = 0;
4422}
4423
4424/*
4425** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4426** for TRUE and FALSE.  Return the integer value if appropriate.
4427*/
4428static int booleanValue(const char *zArg){
4429  int i;
4430  if( zArg[0]=='0' && zArg[1]=='x' ){
4431    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4432  }else{
4433    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4434  }
4435  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4436  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4437    return 1;
4438  }
4439  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4440    return 0;
4441  }
4442  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4443          zArg);
4444  return 0;
4445}
4446
4447/*
4448** Set or clear a shell flag according to a boolean value.
4449*/
4450static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4451  if( booleanValue(zArg) ){
4452    ShellSetFlag(p, mFlag);
4453  }else{
4454    ShellClearFlag(p, mFlag);
4455  }
4456}
4457
4458/*
4459** Close an output file, assuming it is not stderr or stdout
4460*/
4461static void output_file_close(FILE *f){
4462  if( f && f!=stdout && f!=stderr ) fclose(f);
4463}
4464
4465/*
4466** Try to open an output file.   The names "stdout" and "stderr" are
4467** recognized and do the right thing.  NULL is returned if the output
4468** filename is "off".
4469*/
4470static FILE *output_file_open(const char *zFile, int bTextMode){
4471  FILE *f;
4472  if( strcmp(zFile,"stdout")==0 ){
4473    f = stdout;
4474  }else if( strcmp(zFile, "stderr")==0 ){
4475    f = stderr;
4476  }else if( strcmp(zFile, "off")==0 ){
4477    f = 0;
4478  }else{
4479    f = fopen(zFile, bTextMode ? "w" : "wb");
4480    if( f==0 ){
4481      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4482    }
4483  }
4484  return f;
4485}
4486
4487#ifndef SQLITE_OMIT_TRACE
4488/*
4489** A routine for handling output from sqlite3_trace().
4490*/
4491static int sql_trace_callback(
4492  unsigned mType,         /* The trace type */
4493  void *pArg,             /* The ShellState pointer */
4494  void *pP,               /* Usually a pointer to sqlite_stmt */
4495  void *pX                /* Auxiliary output */
4496){
4497  ShellState *p = (ShellState*)pArg;
4498  sqlite3_stmt *pStmt;
4499  const char *zSql;
4500  int nSql;
4501  if( p->traceOut==0 ) return 0;
4502  if( mType==SQLITE_TRACE_CLOSE ){
4503    utf8_printf(p->traceOut, "-- closing database connection\n");
4504    return 0;
4505  }
4506  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4507    zSql = (const char*)pX;
4508  }else{
4509    pStmt = (sqlite3_stmt*)pP;
4510    switch( p->eTraceType ){
4511      case SHELL_TRACE_EXPANDED: {
4512        zSql = sqlite3_expanded_sql(pStmt);
4513        break;
4514      }
4515#ifdef SQLITE_ENABLE_NORMALIZE
4516      case SHELL_TRACE_NORMALIZED: {
4517        zSql = sqlite3_normalized_sql(pStmt);
4518        break;
4519      }
4520#endif
4521      default: {
4522        zSql = sqlite3_sql(pStmt);
4523        break;
4524      }
4525    }
4526  }
4527  if( zSql==0 ) return 0;
4528  nSql = strlen30(zSql);
4529  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4530  switch( mType ){
4531    case SQLITE_TRACE_ROW:
4532    case SQLITE_TRACE_STMT: {
4533      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4534      break;
4535    }
4536    case SQLITE_TRACE_PROFILE: {
4537      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4538      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4539      break;
4540    }
4541  }
4542  return 0;
4543}
4544#endif
4545
4546/*
4547** A no-op routine that runs with the ".breakpoint" doc-command.  This is
4548** a useful spot to set a debugger breakpoint.
4549*/
4550static void test_breakpoint(void){
4551  static int nCall = 0;
4552  nCall++;
4553}
4554
4555/*
4556** An object used to read a CSV and other files for import.
4557*/
4558typedef struct ImportCtx ImportCtx;
4559struct ImportCtx {
4560  const char *zFile;  /* Name of the input file */
4561  FILE *in;           /* Read the CSV text from this input stream */
4562  char *z;            /* Accumulated text for a field */
4563  int n;              /* Number of bytes in z */
4564  int nAlloc;         /* Space allocated for z[] */
4565  int nLine;          /* Current line number */
4566  int bNotFirst;      /* True if one or more bytes already read */
4567  int cTerm;          /* Character that terminated the most recent field */
4568  int cColSep;        /* The column separator character.  (Usually ",") */
4569  int cRowSep;        /* The row separator character.  (Usually "\n") */
4570};
4571
4572/* Append a single byte to z[] */
4573static void import_append_char(ImportCtx *p, int c){
4574  if( p->n+1>=p->nAlloc ){
4575    p->nAlloc += p->nAlloc + 100;
4576    p->z = sqlite3_realloc64(p->z, p->nAlloc);
4577    if( p->z==0 ) shell_out_of_memory();
4578  }
4579  p->z[p->n++] = (char)c;
4580}
4581
4582/* Read a single field of CSV text.  Compatible with rfc4180 and extended
4583** with the option of having a separator other than ",".
4584**
4585**   +  Input comes from p->in.
4586**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4587**      from sqlite3_malloc64().
4588**   +  Use p->cSep as the column separator.  The default is ",".
4589**   +  Use p->rSep as the row separator.  The default is "\n".
4590**   +  Keep track of the line number in p->nLine.
4591**   +  Store the character that terminates the field in p->cTerm.  Store
4592**      EOF on end-of-file.
4593**   +  Report syntax errors on stderr
4594*/
4595static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4596  int c;
4597  int cSep = p->cColSep;
4598  int rSep = p->cRowSep;
4599  p->n = 0;
4600  c = fgetc(p->in);
4601  if( c==EOF || seenInterrupt ){
4602    p->cTerm = EOF;
4603    return 0;
4604  }
4605  if( c=='"' ){
4606    int pc, ppc;
4607    int startLine = p->nLine;
4608    int cQuote = c;
4609    pc = ppc = 0;
4610    while( 1 ){
4611      c = fgetc(p->in);
4612      if( c==rSep ) p->nLine++;
4613      if( c==cQuote ){
4614        if( pc==cQuote ){
4615          pc = 0;
4616          continue;
4617        }
4618      }
4619      if( (c==cSep && pc==cQuote)
4620       || (c==rSep && pc==cQuote)
4621       || (c==rSep && pc=='\r' && ppc==cQuote)
4622       || (c==EOF && pc==cQuote)
4623      ){
4624        do{ p->n--; }while( p->z[p->n]!=cQuote );
4625        p->cTerm = c;
4626        break;
4627      }
4628      if( pc==cQuote && c!='\r' ){
4629        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4630                p->zFile, p->nLine, cQuote);
4631      }
4632      if( c==EOF ){
4633        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4634                p->zFile, startLine, cQuote);
4635        p->cTerm = c;
4636        break;
4637      }
4638      import_append_char(p, c);
4639      ppc = pc;
4640      pc = c;
4641    }
4642  }else{
4643    /* If this is the first field being parsed and it begins with the
4644    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
4645    if( (c&0xff)==0xef && p->bNotFirst==0 ){
4646      import_append_char(p, c);
4647      c = fgetc(p->in);
4648      if( (c&0xff)==0xbb ){
4649        import_append_char(p, c);
4650        c = fgetc(p->in);
4651        if( (c&0xff)==0xbf ){
4652          p->bNotFirst = 1;
4653          p->n = 0;
4654          return csv_read_one_field(p);
4655        }
4656      }
4657    }
4658    while( c!=EOF && c!=cSep && c!=rSep ){
4659      import_append_char(p, c);
4660      c = fgetc(p->in);
4661    }
4662    if( c==rSep ){
4663      p->nLine++;
4664      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4665    }
4666    p->cTerm = c;
4667  }
4668  if( p->z ) p->z[p->n] = 0;
4669  p->bNotFirst = 1;
4670  return p->z;
4671}
4672
4673/* Read a single field of ASCII delimited text.
4674**
4675**   +  Input comes from p->in.
4676**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4677**      from sqlite3_malloc64().
4678**   +  Use p->cSep as the column separator.  The default is "\x1F".
4679**   +  Use p->rSep as the row separator.  The default is "\x1E".
4680**   +  Keep track of the row number in p->nLine.
4681**   +  Store the character that terminates the field in p->cTerm.  Store
4682**      EOF on end-of-file.
4683**   +  Report syntax errors on stderr
4684*/
4685static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4686  int c;
4687  int cSep = p->cColSep;
4688  int rSep = p->cRowSep;
4689  p->n = 0;
4690  c = fgetc(p->in);
4691  if( c==EOF || seenInterrupt ){
4692    p->cTerm = EOF;
4693    return 0;
4694  }
4695  while( c!=EOF && c!=cSep && c!=rSep ){
4696    import_append_char(p, c);
4697    c = fgetc(p->in);
4698  }
4699  if( c==rSep ){
4700    p->nLine++;
4701  }
4702  p->cTerm = c;
4703  if( p->z ) p->z[p->n] = 0;
4704  return p->z;
4705}
4706
4707/*
4708** Try to transfer data for table zTable.  If an error is seen while
4709** moving forward, try to go backwards.  The backwards movement won't
4710** work for WITHOUT ROWID tables.
4711*/
4712static void tryToCloneData(
4713  ShellState *p,
4714  sqlite3 *newDb,
4715  const char *zTable
4716){
4717  sqlite3_stmt *pQuery = 0;
4718  sqlite3_stmt *pInsert = 0;
4719  char *zQuery = 0;
4720  char *zInsert = 0;
4721  int rc;
4722  int i, j, n;
4723  int nTable = strlen30(zTable);
4724  int k = 0;
4725  int cnt = 0;
4726  const int spinRate = 10000;
4727
4728  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4729  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4730  if( rc ){
4731    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4732            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4733            zQuery);
4734    goto end_data_xfer;
4735  }
4736  n = sqlite3_column_count(pQuery);
4737  zInsert = sqlite3_malloc64(200 + nTable + n*3);
4738  if( zInsert==0 ) shell_out_of_memory();
4739  sqlite3_snprintf(200+nTable,zInsert,
4740                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4741  i = strlen30(zInsert);
4742  for(j=1; j<n; j++){
4743    memcpy(zInsert+i, ",?", 2);
4744    i += 2;
4745  }
4746  memcpy(zInsert+i, ");", 3);
4747  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4748  if( rc ){
4749    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4750            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4751            zQuery);
4752    goto end_data_xfer;
4753  }
4754  for(k=0; k<2; k++){
4755    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4756      for(i=0; i<n; i++){
4757        switch( sqlite3_column_type(pQuery, i) ){
4758          case SQLITE_NULL: {
4759            sqlite3_bind_null(pInsert, i+1);
4760            break;
4761          }
4762          case SQLITE_INTEGER: {
4763            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4764            break;
4765          }
4766          case SQLITE_FLOAT: {
4767            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4768            break;
4769          }
4770          case SQLITE_TEXT: {
4771            sqlite3_bind_text(pInsert, i+1,
4772                             (const char*)sqlite3_column_text(pQuery,i),
4773                             -1, SQLITE_STATIC);
4774            break;
4775          }
4776          case SQLITE_BLOB: {
4777            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4778                                            sqlite3_column_bytes(pQuery,i),
4779                                            SQLITE_STATIC);
4780            break;
4781          }
4782        }
4783      } /* End for */
4784      rc = sqlite3_step(pInsert);
4785      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4786        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4787                        sqlite3_errmsg(newDb));
4788      }
4789      sqlite3_reset(pInsert);
4790      cnt++;
4791      if( (cnt%spinRate)==0 ){
4792        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4793        fflush(stdout);
4794      }
4795    } /* End while */
4796    if( rc==SQLITE_DONE ) break;
4797    sqlite3_finalize(pQuery);
4798    sqlite3_free(zQuery);
4799    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4800                             zTable);
4801    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4802    if( rc ){
4803      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4804      break;
4805    }
4806  } /* End for(k=0...) */
4807
4808end_data_xfer:
4809  sqlite3_finalize(pQuery);
4810  sqlite3_finalize(pInsert);
4811  sqlite3_free(zQuery);
4812  sqlite3_free(zInsert);
4813}
4814
4815
4816/*
4817** Try to transfer all rows of the schema that match zWhere.  For
4818** each row, invoke xForEach() on the object defined by that row.
4819** If an error is encountered while moving forward through the
4820** sqlite_master table, try again moving backwards.
4821*/
4822static void tryToCloneSchema(
4823  ShellState *p,
4824  sqlite3 *newDb,
4825  const char *zWhere,
4826  void (*xForEach)(ShellState*,sqlite3*,const char*)
4827){
4828  sqlite3_stmt *pQuery = 0;
4829  char *zQuery = 0;
4830  int rc;
4831  const unsigned char *zName;
4832  const unsigned char *zSql;
4833  char *zErrMsg = 0;
4834
4835  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4836                           " WHERE %s", zWhere);
4837  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4838  if( rc ){
4839    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4840                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4841                    zQuery);
4842    goto end_schema_xfer;
4843  }
4844  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4845    zName = sqlite3_column_text(pQuery, 0);
4846    zSql = sqlite3_column_text(pQuery, 1);
4847    printf("%s... ", zName); fflush(stdout);
4848    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4849    if( zErrMsg ){
4850      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4851      sqlite3_free(zErrMsg);
4852      zErrMsg = 0;
4853    }
4854    if( xForEach ){
4855      xForEach(p, newDb, (const char*)zName);
4856    }
4857    printf("done\n");
4858  }
4859  if( rc!=SQLITE_DONE ){
4860    sqlite3_finalize(pQuery);
4861    sqlite3_free(zQuery);
4862    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4863                             " WHERE %s ORDER BY rowid DESC", zWhere);
4864    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4865    if( rc ){
4866      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4867                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4868                      zQuery);
4869      goto end_schema_xfer;
4870    }
4871    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4872      zName = sqlite3_column_text(pQuery, 0);
4873      zSql = sqlite3_column_text(pQuery, 1);
4874      printf("%s... ", zName); fflush(stdout);
4875      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4876      if( zErrMsg ){
4877        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4878        sqlite3_free(zErrMsg);
4879        zErrMsg = 0;
4880      }
4881      if( xForEach ){
4882        xForEach(p, newDb, (const char*)zName);
4883      }
4884      printf("done\n");
4885    }
4886  }
4887end_schema_xfer:
4888  sqlite3_finalize(pQuery);
4889  sqlite3_free(zQuery);
4890}
4891
4892/*
4893** Open a new database file named "zNewDb".  Try to recover as much information
4894** as possible out of the main database (which might be corrupt) and write it
4895** into zNewDb.
4896*/
4897static void tryToClone(ShellState *p, const char *zNewDb){
4898  int rc;
4899  sqlite3 *newDb = 0;
4900  if( access(zNewDb,0)==0 ){
4901    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4902    return;
4903  }
4904  rc = sqlite3_open(zNewDb, &newDb);
4905  if( rc ){
4906    utf8_printf(stderr, "Cannot create output database: %s\n",
4907            sqlite3_errmsg(newDb));
4908  }else{
4909    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4910    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4911    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4912    tryToCloneSchema(p, newDb, "type!='table'", 0);
4913    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4914    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4915  }
4916  close_db(newDb);
4917}
4918
4919/*
4920** Change the output file back to stdout.
4921**
4922** If the p->doXdgOpen flag is set, that means the output was being
4923** redirected to a temporary file named by p->zTempFile.  In that case,
4924** launch start/open/xdg-open on that temporary file.
4925*/
4926static void output_reset(ShellState *p){
4927  if( p->outfile[0]=='|' ){
4928#ifndef SQLITE_OMIT_POPEN
4929    pclose(p->out);
4930#endif
4931  }else{
4932    output_file_close(p->out);
4933#ifndef SQLITE_NOHAVE_SYSTEM
4934    if( p->doXdgOpen ){
4935      const char *zXdgOpenCmd =
4936#if defined(_WIN32)
4937      "start";
4938#elif defined(__APPLE__)
4939      "open";
4940#else
4941      "xdg-open";
4942#endif
4943      char *zCmd;
4944      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
4945      if( system(zCmd) ){
4946        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4947      }
4948      sqlite3_free(zCmd);
4949      outputModePop(p);
4950      p->doXdgOpen = 0;
4951      sqlite3_sleep(100);
4952    }
4953#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4954  }
4955  p->outfile[0] = 0;
4956  p->out = stdout;
4957}
4958
4959/*
4960** Run an SQL command and return the single integer result.
4961*/
4962static int db_int(ShellState *p, const char *zSql){
4963  sqlite3_stmt *pStmt;
4964  int res = 0;
4965  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4966  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4967    res = sqlite3_column_int(pStmt,0);
4968  }
4969  sqlite3_finalize(pStmt);
4970  return res;
4971}
4972
4973/*
4974** Convert a 2-byte or 4-byte big-endian integer into a native integer
4975*/
4976static unsigned int get2byteInt(unsigned char *a){
4977  return (a[0]<<8) + a[1];
4978}
4979static unsigned int get4byteInt(unsigned char *a){
4980  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4981}
4982
4983/*
4984** Implementation of the ".dbinfo" command.
4985**
4986** Return 1 on error, 2 to exit, and 0 otherwise.
4987*/
4988static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4989  static const struct { const char *zName; int ofst; } aField[] = {
4990     { "file change counter:",  24  },
4991     { "database page count:",  28  },
4992     { "freelist page count:",  36  },
4993     { "schema cookie:",        40  },
4994     { "schema format:",        44  },
4995     { "default cache size:",   48  },
4996     { "autovacuum top root:",  52  },
4997     { "incremental vacuum:",   64  },
4998     { "text encoding:",        56  },
4999     { "user version:",         60  },
5000     { "application id:",       68  },
5001     { "software version:",     96  },
5002  };
5003  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5004     { "number of tables:",
5005       "SELECT count(*) FROM %s WHERE type='table'" },
5006     { "number of indexes:",
5007       "SELECT count(*) FROM %s WHERE type='index'" },
5008     { "number of triggers:",
5009       "SELECT count(*) FROM %s WHERE type='trigger'" },
5010     { "number of views:",
5011       "SELECT count(*) FROM %s WHERE type='view'" },
5012     { "schema size:",
5013       "SELECT total(length(sql)) FROM %s" },
5014  };
5015  int i, rc;
5016  unsigned iDataVersion;
5017  char *zSchemaTab;
5018  char *zDb = nArg>=2 ? azArg[1] : "main";
5019  sqlite3_stmt *pStmt = 0;
5020  unsigned char aHdr[100];
5021  open_db(p, 0);
5022  if( p->db==0 ) return 1;
5023  rc = sqlite3_prepare_v2(p->db,
5024             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5025             -1, &pStmt, 0);
5026  if( rc ){
5027    if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
5028      utf8_printf(stderr, "the \".dbinfo\" command requires the "
5029                          "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
5030    }else{
5031      utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5032    }
5033    sqlite3_finalize(pStmt);
5034    return 1;
5035  }
5036  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5037  if( sqlite3_step(pStmt)==SQLITE_ROW
5038   && sqlite3_column_bytes(pStmt,0)>100
5039  ){
5040    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5041    sqlite3_finalize(pStmt);
5042  }else{
5043    raw_printf(stderr, "unable to read database header\n");
5044    sqlite3_finalize(pStmt);
5045    return 1;
5046  }
5047  i = get2byteInt(aHdr+16);
5048  if( i==1 ) i = 65536;
5049  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5050  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5051  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5052  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5053  for(i=0; i<ArraySize(aField); i++){
5054    int ofst = aField[i].ofst;
5055    unsigned int val = get4byteInt(aHdr + ofst);
5056    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5057    switch( ofst ){
5058      case 56: {
5059        if( val==1 ) raw_printf(p->out, " (utf8)");
5060        if( val==2 ) raw_printf(p->out, " (utf16le)");
5061        if( val==3 ) raw_printf(p->out, " (utf16be)");
5062      }
5063    }
5064    raw_printf(p->out, "\n");
5065  }
5066  if( zDb==0 ){
5067    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
5068  }else if( strcmp(zDb,"temp")==0 ){
5069    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
5070  }else{
5071    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
5072  }
5073  for(i=0; i<ArraySize(aQuery); i++){
5074    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5075    int val = db_int(p, zSql);
5076    sqlite3_free(zSql);
5077    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5078  }
5079  sqlite3_free(zSchemaTab);
5080  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5081  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5082  return 0;
5083}
5084
5085/*
5086** Print the current sqlite3_errmsg() value to stderr and return 1.
5087*/
5088static int shellDatabaseError(sqlite3 *db){
5089  const char *zErr = sqlite3_errmsg(db);
5090  utf8_printf(stderr, "Error: %s\n", zErr);
5091  return 1;
5092}
5093
5094/*
5095** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5096** if they match and FALSE (0) if they do not match.
5097**
5098** Globbing rules:
5099**
5100**      '*'       Matches any sequence of zero or more characters.
5101**
5102**      '?'       Matches exactly one character.
5103**
5104**     [...]      Matches one character from the enclosed list of
5105**                characters.
5106**
5107**     [^...]     Matches one character not in the enclosed list.
5108**
5109**      '#'       Matches any sequence of one or more digits with an
5110**                optional + or - sign in front
5111**
5112**      ' '       Any span of whitespace matches any other span of
5113**                whitespace.
5114**
5115** Extra whitespace at the end of z[] is ignored.
5116*/
5117static int testcase_glob(const char *zGlob, const char *z){
5118  int c, c2;
5119  int invert;
5120  int seen;
5121
5122  while( (c = (*(zGlob++)))!=0 ){
5123    if( IsSpace(c) ){
5124      if( !IsSpace(*z) ) return 0;
5125      while( IsSpace(*zGlob) ) zGlob++;
5126      while( IsSpace(*z) ) z++;
5127    }else if( c=='*' ){
5128      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5129        if( c=='?' && (*(z++))==0 ) return 0;
5130      }
5131      if( c==0 ){
5132        return 1;
5133      }else if( c=='[' ){
5134        while( *z && testcase_glob(zGlob-1,z)==0 ){
5135          z++;
5136        }
5137        return (*z)!=0;
5138      }
5139      while( (c2 = (*(z++)))!=0 ){
5140        while( c2!=c ){
5141          c2 = *(z++);
5142          if( c2==0 ) return 0;
5143        }
5144        if( testcase_glob(zGlob,z) ) return 1;
5145      }
5146      return 0;
5147    }else if( c=='?' ){
5148      if( (*(z++))==0 ) return 0;
5149    }else if( c=='[' ){
5150      int prior_c = 0;
5151      seen = 0;
5152      invert = 0;
5153      c = *(z++);
5154      if( c==0 ) return 0;
5155      c2 = *(zGlob++);
5156      if( c2=='^' ){
5157        invert = 1;
5158        c2 = *(zGlob++);
5159      }
5160      if( c2==']' ){
5161        if( c==']' ) seen = 1;
5162        c2 = *(zGlob++);
5163      }
5164      while( c2 && c2!=']' ){
5165        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5166          c2 = *(zGlob++);
5167          if( c>=prior_c && c<=c2 ) seen = 1;
5168          prior_c = 0;
5169        }else{
5170          if( c==c2 ){
5171            seen = 1;
5172          }
5173          prior_c = c2;
5174        }
5175        c2 = *(zGlob++);
5176      }
5177      if( c2==0 || (seen ^ invert)==0 ) return 0;
5178    }else if( c=='#' ){
5179      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5180      if( !IsDigit(z[0]) ) return 0;
5181      z++;
5182      while( IsDigit(z[0]) ){ z++; }
5183    }else{
5184      if( c!=(*(z++)) ) return 0;
5185    }
5186  }
5187  while( IsSpace(*z) ){ z++; }
5188  return *z==0;
5189}
5190
5191
5192/*
5193** Compare the string as a command-line option with either one or two
5194** initial "-" characters.
5195*/
5196static int optionMatch(const char *zStr, const char *zOpt){
5197  if( zStr[0]!='-' ) return 0;
5198  zStr++;
5199  if( zStr[0]=='-' ) zStr++;
5200  return strcmp(zStr, zOpt)==0;
5201}
5202
5203/*
5204** Delete a file.
5205*/
5206int shellDeleteFile(const char *zFilename){
5207  int rc;
5208#ifdef _WIN32
5209  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5210  rc = _wunlink(z);
5211  sqlite3_free(z);
5212#else
5213  rc = unlink(zFilename);
5214#endif
5215  return rc;
5216}
5217
5218/*
5219** Try to delete the temporary file (if there is one) and free the
5220** memory used to hold the name of the temp file.
5221*/
5222static void clearTempFile(ShellState *p){
5223  if( p->zTempFile==0 ) return;
5224  if( p->doXdgOpen ) return;
5225  if( shellDeleteFile(p->zTempFile) ) return;
5226  sqlite3_free(p->zTempFile);
5227  p->zTempFile = 0;
5228}
5229
5230/*
5231** Create a new temp file name with the given suffix.
5232*/
5233static void newTempFile(ShellState *p, const char *zSuffix){
5234  clearTempFile(p);
5235  sqlite3_free(p->zTempFile);
5236  p->zTempFile = 0;
5237  if( p->db ){
5238    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5239  }
5240  if( p->zTempFile==0 ){
5241    sqlite3_uint64 r;
5242    sqlite3_randomness(sizeof(r), &r);
5243    p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5244  }else{
5245    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5246  }
5247  if( p->zTempFile==0 ){
5248    raw_printf(stderr, "out of memory\n");
5249    exit(1);
5250  }
5251}
5252
5253
5254/*
5255** The implementation of SQL scalar function fkey_collate_clause(), used
5256** by the ".lint fkey-indexes" command. This scalar function is always
5257** called with four arguments - the parent table name, the parent column name,
5258** the child table name and the child column name.
5259**
5260**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5261**
5262** If either of the named tables or columns do not exist, this function
5263** returns an empty string. An empty string is also returned if both tables
5264** and columns exist but have the same default collation sequence. Or,
5265** if both exist but the default collation sequences are different, this
5266** function returns the string " COLLATE <parent-collation>", where
5267** <parent-collation> is the default collation sequence of the parent column.
5268*/
5269static void shellFkeyCollateClause(
5270  sqlite3_context *pCtx,
5271  int nVal,
5272  sqlite3_value **apVal
5273){
5274  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5275  const char *zParent;
5276  const char *zParentCol;
5277  const char *zParentSeq;
5278  const char *zChild;
5279  const char *zChildCol;
5280  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5281  int rc;
5282
5283  assert( nVal==4 );
5284  zParent = (const char*)sqlite3_value_text(apVal[0]);
5285  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5286  zChild = (const char*)sqlite3_value_text(apVal[2]);
5287  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5288
5289  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5290  rc = sqlite3_table_column_metadata(
5291      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5292  );
5293  if( rc==SQLITE_OK ){
5294    rc = sqlite3_table_column_metadata(
5295        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5296    );
5297  }
5298
5299  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5300    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5301    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5302    sqlite3_free(z);
5303  }
5304}
5305
5306
5307/*
5308** The implementation of dot-command ".lint fkey-indexes".
5309*/
5310static int lintFkeyIndexes(
5311  ShellState *pState,             /* Current shell tool state */
5312  char **azArg,                   /* Array of arguments passed to dot command */
5313  int nArg                        /* Number of entries in azArg[] */
5314){
5315  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5316  FILE *out = pState->out;        /* Stream to write non-error output to */
5317  int bVerbose = 0;               /* If -verbose is present */
5318  int bGroupByParent = 0;         /* If -groupbyparent is present */
5319  int i;                          /* To iterate through azArg[] */
5320  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5321  int rc;                         /* Return code */
5322  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5323
5324  /*
5325  ** This SELECT statement returns one row for each foreign key constraint
5326  ** in the schema of the main database. The column values are:
5327  **
5328  ** 0. The text of an SQL statement similar to:
5329  **
5330  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5331  **
5332  **    This SELECT is similar to the one that the foreign keys implementation
5333  **    needs to run internally on child tables. If there is an index that can
5334  **    be used to optimize this query, then it can also be used by the FK
5335  **    implementation to optimize DELETE or UPDATE statements on the parent
5336  **    table.
5337  **
5338  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5339  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5340  **    contains an index that can be used to optimize the query.
5341  **
5342  ** 2. Human readable text that describes the child table and columns. e.g.
5343  **
5344  **       "child_table(child_key1, child_key2)"
5345  **
5346  ** 3. Human readable text that describes the parent table and columns. e.g.
5347  **
5348  **       "parent_table(parent_key1, parent_key2)"
5349  **
5350  ** 4. A full CREATE INDEX statement for an index that could be used to
5351  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5352  **
5353  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5354  **
5355  ** 5. The name of the parent table.
5356  **
5357  ** These six values are used by the C logic below to generate the report.
5358  */
5359  const char *zSql =
5360  "SELECT "
5361    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5362    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5363    "  || fkey_collate_clause("
5364    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5365    ", "
5366    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5367    "  || group_concat('*=?', ' AND ') || ')'"
5368    ", "
5369    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5370    ", "
5371    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5372    ", "
5373    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5374    "  || ' ON ' || quote(s.name) || '('"
5375    "  || group_concat(quote(f.[from]) ||"
5376    "        fkey_collate_clause("
5377    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5378    "  || ');'"
5379    ", "
5380    "     f.[table] "
5381    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5382    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5383    "GROUP BY s.name, f.id "
5384    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5385  ;
5386  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5387
5388  for(i=2; i<nArg; i++){
5389    int n = strlen30(azArg[i]);
5390    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5391      bVerbose = 1;
5392    }
5393    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5394      bGroupByParent = 1;
5395      zIndent = "    ";
5396    }
5397    else{
5398      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5399          azArg[0], azArg[1]
5400      );
5401      return SQLITE_ERROR;
5402    }
5403  }
5404
5405  /* Register the fkey_collate_clause() SQL function */
5406  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5407      0, shellFkeyCollateClause, 0, 0
5408  );
5409
5410
5411  if( rc==SQLITE_OK ){
5412    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5413  }
5414  if( rc==SQLITE_OK ){
5415    sqlite3_bind_int(pSql, 1, bGroupByParent);
5416  }
5417
5418  if( rc==SQLITE_OK ){
5419    int rc2;
5420    char *zPrev = 0;
5421    while( SQLITE_ROW==sqlite3_step(pSql) ){
5422      int res = -1;
5423      sqlite3_stmt *pExplain = 0;
5424      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5425      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5426      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5427      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5428      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5429      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5430
5431      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5432      if( rc!=SQLITE_OK ) break;
5433      if( SQLITE_ROW==sqlite3_step(pExplain) ){
5434        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5435        res = (
5436              0==sqlite3_strglob(zGlob, zPlan)
5437           || 0==sqlite3_strglob(zGlobIPK, zPlan)
5438        );
5439      }
5440      rc = sqlite3_finalize(pExplain);
5441      if( rc!=SQLITE_OK ) break;
5442
5443      if( res<0 ){
5444        raw_printf(stderr, "Error: internal error");
5445        break;
5446      }else{
5447        if( bGroupByParent
5448        && (bVerbose || res==0)
5449        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5450        ){
5451          raw_printf(out, "-- Parent table %s\n", zParent);
5452          sqlite3_free(zPrev);
5453          zPrev = sqlite3_mprintf("%s", zParent);
5454        }
5455
5456        if( res==0 ){
5457          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5458        }else if( bVerbose ){
5459          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5460              zIndent, zFrom, zTarget
5461          );
5462        }
5463      }
5464    }
5465    sqlite3_free(zPrev);
5466
5467    if( rc!=SQLITE_OK ){
5468      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5469    }
5470
5471    rc2 = sqlite3_finalize(pSql);
5472    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5473      rc = rc2;
5474      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5475    }
5476  }else{
5477    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5478  }
5479
5480  return rc;
5481}
5482
5483/*
5484** Implementation of ".lint" dot command.
5485*/
5486static int lintDotCommand(
5487  ShellState *pState,             /* Current shell tool state */
5488  char **azArg,                   /* Array of arguments passed to dot command */
5489  int nArg                        /* Number of entries in azArg[] */
5490){
5491  int n;
5492  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5493  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5494  return lintFkeyIndexes(pState, azArg, nArg);
5495
5496 usage:
5497  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5498  raw_printf(stderr, "Where sub-commands are:\n");
5499  raw_printf(stderr, "    fkey-indexes\n");
5500  return SQLITE_ERROR;
5501}
5502
5503#if !defined SQLITE_OMIT_VIRTUALTABLE
5504static void shellPrepare(
5505  sqlite3 *db,
5506  int *pRc,
5507  const char *zSql,
5508  sqlite3_stmt **ppStmt
5509){
5510  *ppStmt = 0;
5511  if( *pRc==SQLITE_OK ){
5512    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5513    if( rc!=SQLITE_OK ){
5514      raw_printf(stderr, "sql error: %s (%d)\n",
5515          sqlite3_errmsg(db), sqlite3_errcode(db)
5516      );
5517      *pRc = rc;
5518    }
5519  }
5520}
5521
5522/*
5523** Create a prepared statement using printf-style arguments for the SQL.
5524**
5525** This routine is could be marked "static".  But it is not always used,
5526** depending on compile-time options.  By omitting the "static", we avoid
5527** nuisance compiler warnings about "defined but not used".
5528*/
5529void shellPreparePrintf(
5530  sqlite3 *db,
5531  int *pRc,
5532  sqlite3_stmt **ppStmt,
5533  const char *zFmt,
5534  ...
5535){
5536  *ppStmt = 0;
5537  if( *pRc==SQLITE_OK ){
5538    va_list ap;
5539    char *z;
5540    va_start(ap, zFmt);
5541    z = sqlite3_vmprintf(zFmt, ap);
5542    va_end(ap);
5543    if( z==0 ){
5544      *pRc = SQLITE_NOMEM;
5545    }else{
5546      shellPrepare(db, pRc, z, ppStmt);
5547      sqlite3_free(z);
5548    }
5549  }
5550}
5551
5552/* Finalize the prepared statement created using shellPreparePrintf().
5553**
5554** This routine is could be marked "static".  But it is not always used,
5555** depending on compile-time options.  By omitting the "static", we avoid
5556** nuisance compiler warnings about "defined but not used".
5557*/
5558void shellFinalize(
5559  int *pRc,
5560  sqlite3_stmt *pStmt
5561){
5562  if( pStmt ){
5563    sqlite3 *db = sqlite3_db_handle(pStmt);
5564    int rc = sqlite3_finalize(pStmt);
5565    if( *pRc==SQLITE_OK ){
5566      if( rc!=SQLITE_OK ){
5567        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5568      }
5569      *pRc = rc;
5570    }
5571  }
5572}
5573
5574/* Reset the prepared statement created using shellPreparePrintf().
5575**
5576** This routine is could be marked "static".  But it is not always used,
5577** depending on compile-time options.  By omitting the "static", we avoid
5578** nuisance compiler warnings about "defined but not used".
5579*/
5580void shellReset(
5581  int *pRc,
5582  sqlite3_stmt *pStmt
5583){
5584  int rc = sqlite3_reset(pStmt);
5585  if( *pRc==SQLITE_OK ){
5586    if( rc!=SQLITE_OK ){
5587      sqlite3 *db = sqlite3_db_handle(pStmt);
5588      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5589    }
5590    *pRc = rc;
5591  }
5592}
5593#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
5594
5595#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5596/******************************************************************************
5597** The ".archive" or ".ar" command.
5598*/
5599/*
5600** Structure representing a single ".ar" command.
5601*/
5602typedef struct ArCommand ArCommand;
5603struct ArCommand {
5604  u8 eCmd;                        /* An AR_CMD_* value */
5605  u8 bVerbose;                    /* True if --verbose */
5606  u8 bZip;                        /* True if the archive is a ZIP */
5607  u8 bDryRun;                     /* True if --dry-run */
5608  u8 bAppend;                     /* True if --append */
5609  u8 fromCmdLine;                 /* Run from -A instead of .archive */
5610  int nArg;                       /* Number of command arguments */
5611  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
5612  const char *zFile;              /* --file argument, or NULL */
5613  const char *zDir;               /* --directory argument, or NULL */
5614  char **azArg;                   /* Array of command arguments */
5615  ShellState *p;                  /* Shell state */
5616  sqlite3 *db;                    /* Database containing the archive */
5617};
5618
5619/*
5620** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5621*/
5622static int arUsage(FILE *f){
5623  showHelp(f,"archive");
5624  return SQLITE_ERROR;
5625}
5626
5627/*
5628** Print an error message for the .ar command to stderr and return
5629** SQLITE_ERROR.
5630*/
5631static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
5632  va_list ap;
5633  char *z;
5634  va_start(ap, zFmt);
5635  z = sqlite3_vmprintf(zFmt, ap);
5636  va_end(ap);
5637  utf8_printf(stderr, "Error: %s\n", z);
5638  if( pAr->fromCmdLine ){
5639    utf8_printf(stderr, "Use \"-A\" for more help\n");
5640  }else{
5641    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5642  }
5643  sqlite3_free(z);
5644  return SQLITE_ERROR;
5645}
5646
5647/*
5648** Values for ArCommand.eCmd.
5649*/
5650#define AR_CMD_CREATE       1
5651#define AR_CMD_UPDATE       2
5652#define AR_CMD_INSERT       3
5653#define AR_CMD_EXTRACT      4
5654#define AR_CMD_LIST         5
5655#define AR_CMD_HELP         6
5656
5657/*
5658** Other (non-command) switches.
5659*/
5660#define AR_SWITCH_VERBOSE     7
5661#define AR_SWITCH_FILE        8
5662#define AR_SWITCH_DIRECTORY   9
5663#define AR_SWITCH_APPEND     10
5664#define AR_SWITCH_DRYRUN     11
5665
5666static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5667  switch( eSwitch ){
5668    case AR_CMD_CREATE:
5669    case AR_CMD_EXTRACT:
5670    case AR_CMD_LIST:
5671    case AR_CMD_UPDATE:
5672    case AR_CMD_INSERT:
5673    case AR_CMD_HELP:
5674      if( pAr->eCmd ){
5675        return arErrorMsg(pAr, "multiple command options");
5676      }
5677      pAr->eCmd = eSwitch;
5678      break;
5679
5680    case AR_SWITCH_DRYRUN:
5681      pAr->bDryRun = 1;
5682      break;
5683    case AR_SWITCH_VERBOSE:
5684      pAr->bVerbose = 1;
5685      break;
5686    case AR_SWITCH_APPEND:
5687      pAr->bAppend = 1;
5688      /* Fall thru into --file */
5689    case AR_SWITCH_FILE:
5690      pAr->zFile = zArg;
5691      break;
5692    case AR_SWITCH_DIRECTORY:
5693      pAr->zDir = zArg;
5694      break;
5695  }
5696
5697  return SQLITE_OK;
5698}
5699
5700/*
5701** Parse the command line for an ".ar" command. The results are written into
5702** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5703** successfully, otherwise an error message is written to stderr and
5704** SQLITE_ERROR returned.
5705*/
5706static int arParseCommand(
5707  char **azArg,                   /* Array of arguments passed to dot command */
5708  int nArg,                       /* Number of entries in azArg[] */
5709  ArCommand *pAr                  /* Populate this object */
5710){
5711  struct ArSwitch {
5712    const char *zLong;
5713    char cShort;
5714    u8 eSwitch;
5715    u8 bArg;
5716  } aSwitch[] = {
5717    { "create",    'c', AR_CMD_CREATE,       0 },
5718    { "extract",   'x', AR_CMD_EXTRACT,      0 },
5719    { "insert",    'i', AR_CMD_INSERT,       0 },
5720    { "list",      't', AR_CMD_LIST,         0 },
5721    { "update",    'u', AR_CMD_UPDATE,       0 },
5722    { "help",      'h', AR_CMD_HELP,         0 },
5723    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
5724    { "file",      'f', AR_SWITCH_FILE,      1 },
5725    { "append",    'a', AR_SWITCH_APPEND,    1 },
5726    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
5727    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
5728  };
5729  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5730  struct ArSwitch *pEnd = &aSwitch[nSwitch];
5731
5732  if( nArg<=1 ){
5733    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
5734    return arUsage(stderr);
5735  }else{
5736    char *z = azArg[1];
5737    if( z[0]!='-' ){
5738      /* Traditional style [tar] invocation */
5739      int i;
5740      int iArg = 2;
5741      for(i=0; z[i]; i++){
5742        const char *zArg = 0;
5743        struct ArSwitch *pOpt;
5744        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5745          if( z[i]==pOpt->cShort ) break;
5746        }
5747        if( pOpt==pEnd ){
5748          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5749        }
5750        if( pOpt->bArg ){
5751          if( iArg>=nArg ){
5752            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5753          }
5754          zArg = azArg[iArg++];
5755        }
5756        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5757      }
5758      pAr->nArg = nArg-iArg;
5759      if( pAr->nArg>0 ){
5760        pAr->azArg = &azArg[iArg];
5761      }
5762    }else{
5763      /* Non-traditional invocation */
5764      int iArg;
5765      for(iArg=1; iArg<nArg; iArg++){
5766        int n;
5767        z = azArg[iArg];
5768        if( z[0]!='-' ){
5769          /* All remaining command line words are command arguments. */
5770          pAr->azArg = &azArg[iArg];
5771          pAr->nArg = nArg-iArg;
5772          break;
5773        }
5774        n = strlen30(z);
5775
5776        if( z[1]!='-' ){
5777          int i;
5778          /* One or more short options */
5779          for(i=1; i<n; i++){
5780            const char *zArg = 0;
5781            struct ArSwitch *pOpt;
5782            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5783              if( z[i]==pOpt->cShort ) break;
5784            }
5785            if( pOpt==pEnd ){
5786              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5787            }
5788            if( pOpt->bArg ){
5789              if( i<(n-1) ){
5790                zArg = &z[i+1];
5791                i = n;
5792              }else{
5793                if( iArg>=(nArg-1) ){
5794                  return arErrorMsg(pAr, "option requires an argument: %c",
5795                                    z[i]);
5796                }
5797                zArg = azArg[++iArg];
5798              }
5799            }
5800            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5801          }
5802        }else if( z[2]=='\0' ){
5803          /* A -- option, indicating that all remaining command line words
5804          ** are command arguments.  */
5805          pAr->azArg = &azArg[iArg+1];
5806          pAr->nArg = nArg-iArg-1;
5807          break;
5808        }else{
5809          /* A long option */
5810          const char *zArg = 0;             /* Argument for option, if any */
5811          struct ArSwitch *pMatch = 0;      /* Matching option */
5812          struct ArSwitch *pOpt;            /* Iterator */
5813          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5814            const char *zLong = pOpt->zLong;
5815            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
5816              if( pMatch ){
5817                return arErrorMsg(pAr, "ambiguous option: %s",z);
5818              }else{
5819                pMatch = pOpt;
5820              }
5821            }
5822          }
5823
5824          if( pMatch==0 ){
5825            return arErrorMsg(pAr, "unrecognized option: %s", z);
5826          }
5827          if( pMatch->bArg ){
5828            if( iArg>=(nArg-1) ){
5829              return arErrorMsg(pAr, "option requires an argument: %s", z);
5830            }
5831            zArg = azArg[++iArg];
5832          }
5833          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5834        }
5835      }
5836    }
5837  }
5838
5839  return SQLITE_OK;
5840}
5841
5842/*
5843** This function assumes that all arguments within the ArCommand.azArg[]
5844** array refer to archive members, as for the --extract or --list commands.
5845** It checks that each of them are present. If any specified file is not
5846** present in the archive, an error is printed to stderr and an error
5847** code returned. Otherwise, if all specified arguments are present in
5848** the archive, SQLITE_OK is returned.
5849**
5850** This function strips any trailing '/' characters from each argument.
5851** This is consistent with the way the [tar] command seems to work on
5852** Linux.
5853*/
5854static int arCheckEntries(ArCommand *pAr){
5855  int rc = SQLITE_OK;
5856  if( pAr->nArg ){
5857    int i, j;
5858    sqlite3_stmt *pTest = 0;
5859
5860    shellPreparePrintf(pAr->db, &rc, &pTest,
5861        "SELECT name FROM %s WHERE name=$name",
5862        pAr->zSrcTable
5863    );
5864    j = sqlite3_bind_parameter_index(pTest, "$name");
5865    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5866      char *z = pAr->azArg[i];
5867      int n = strlen30(z);
5868      int bOk = 0;
5869      while( n>0 && z[n-1]=='/' ) n--;
5870      z[n] = '\0';
5871      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
5872      if( SQLITE_ROW==sqlite3_step(pTest) ){
5873        bOk = 1;
5874      }
5875      shellReset(&rc, pTest);
5876      if( rc==SQLITE_OK && bOk==0 ){
5877        utf8_printf(stderr, "not found in archive: %s\n", z);
5878        rc = SQLITE_ERROR;
5879      }
5880    }
5881    shellFinalize(&rc, pTest);
5882  }
5883  return rc;
5884}
5885
5886/*
5887** Format a WHERE clause that can be used against the "sqlar" table to
5888** identify all archive members that match the command arguments held
5889** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5890** The caller is responsible for eventually calling sqlite3_free() on
5891** any non-NULL (*pzWhere) value.
5892*/
5893static void arWhereClause(
5894  int *pRc,
5895  ArCommand *pAr,
5896  char **pzWhere                  /* OUT: New WHERE clause */
5897){
5898  char *zWhere = 0;
5899  if( *pRc==SQLITE_OK ){
5900    if( pAr->nArg==0 ){
5901      zWhere = sqlite3_mprintf("1");
5902    }else{
5903      int i;
5904      const char *zSep = "";
5905      for(i=0; i<pAr->nArg; i++){
5906        const char *z = pAr->azArg[i];
5907        zWhere = sqlite3_mprintf(
5908          "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5909          zWhere, zSep, z, strlen30(z)+1, z
5910        );
5911        if( zWhere==0 ){
5912          *pRc = SQLITE_NOMEM;
5913          break;
5914        }
5915        zSep = " OR ";
5916      }
5917    }
5918  }
5919  *pzWhere = zWhere;
5920}
5921
5922/*
5923** Implementation of .ar "lisT" command.
5924*/
5925static int arListCommand(ArCommand *pAr){
5926  const char *zSql = "SELECT %s FROM %s WHERE %s";
5927  const char *azCols[] = {
5928    "name",
5929    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5930  };
5931
5932  char *zWhere = 0;
5933  sqlite3_stmt *pSql = 0;
5934  int rc;
5935
5936  rc = arCheckEntries(pAr);
5937  arWhereClause(&rc, pAr, &zWhere);
5938
5939  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5940                     pAr->zSrcTable, zWhere);
5941  if( pAr->bDryRun ){
5942    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5943  }else{
5944    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5945      if( pAr->bVerbose ){
5946        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
5947            sqlite3_column_text(pSql, 0),
5948            sqlite3_column_int(pSql, 1),
5949            sqlite3_column_text(pSql, 2),
5950            sqlite3_column_text(pSql, 3)
5951        );
5952      }else{
5953        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5954      }
5955    }
5956  }
5957  shellFinalize(&rc, pSql);
5958  sqlite3_free(zWhere);
5959  return rc;
5960}
5961
5962
5963/*
5964** Implementation of .ar "eXtract" command.
5965*/
5966static int arExtractCommand(ArCommand *pAr){
5967  const char *zSql1 =
5968    "SELECT "
5969    " ($dir || name),"
5970    " writefile(($dir || name), %s, mode, mtime) "
5971    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5972    " AND name NOT GLOB '*..[/\\]*'";
5973
5974  const char *azExtraArg[] = {
5975    "sqlar_uncompress(data, sz)",
5976    "data"
5977  };
5978
5979  sqlite3_stmt *pSql = 0;
5980  int rc = SQLITE_OK;
5981  char *zDir = 0;
5982  char *zWhere = 0;
5983  int i, j;
5984
5985  /* If arguments are specified, check that they actually exist within
5986  ** the archive before proceeding. And formulate a WHERE clause to
5987  ** match them.  */
5988  rc = arCheckEntries(pAr);
5989  arWhereClause(&rc, pAr, &zWhere);
5990
5991  if( rc==SQLITE_OK ){
5992    if( pAr->zDir ){
5993      zDir = sqlite3_mprintf("%s/", pAr->zDir);
5994    }else{
5995      zDir = sqlite3_mprintf("");
5996    }
5997    if( zDir==0 ) rc = SQLITE_NOMEM;
5998  }
5999
6000  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6001      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6002  );
6003
6004  if( rc==SQLITE_OK ){
6005    j = sqlite3_bind_parameter_index(pSql, "$dir");
6006    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6007
6008    /* Run the SELECT statement twice. The first time, writefile() is called
6009    ** for all archive members that should be extracted. The second time,
6010    ** only for the directories. This is because the timestamps for
6011    ** extracted directories must be reset after they are populated (as
6012    ** populating them changes the timestamp).  */
6013    for(i=0; i<2; i++){
6014      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6015      sqlite3_bind_int(pSql, j, i);
6016      if( pAr->bDryRun ){
6017        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6018      }else{
6019        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6020          if( i==0 && pAr->bVerbose ){
6021            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6022          }
6023        }
6024      }
6025      shellReset(&rc, pSql);
6026    }
6027    shellFinalize(&rc, pSql);
6028  }
6029
6030  sqlite3_free(zDir);
6031  sqlite3_free(zWhere);
6032  return rc;
6033}
6034
6035/*
6036** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6037*/
6038static int arExecSql(ArCommand *pAr, const char *zSql){
6039  int rc;
6040  if( pAr->bDryRun ){
6041    utf8_printf(pAr->p->out, "%s\n", zSql);
6042    rc = SQLITE_OK;
6043  }else{
6044    char *zErr = 0;
6045    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6046    if( zErr ){
6047      utf8_printf(stdout, "ERROR: %s\n", zErr);
6048      sqlite3_free(zErr);
6049    }
6050  }
6051  return rc;
6052}
6053
6054
6055/*
6056** Implementation of .ar "create", "insert", and "update" commands.
6057**
6058**     create    ->     Create a new SQL archive
6059**     insert    ->     Insert or reinsert all files listed
6060**     update    ->     Insert files that have changed or that were not
6061**                      previously in the archive
6062**
6063** Create the "sqlar" table in the database if it does not already exist.
6064** Then add each file in the azFile[] array to the archive. Directories
6065** are added recursively. If argument bVerbose is non-zero, a message is
6066** printed on stdout for each file archived.
6067**
6068** The create command is the same as update, except that it drops
6069** any existing "sqlar" table before beginning.  The "insert" command
6070** always overwrites every file named on the command-line, where as
6071** "update" only overwrites if the size or mtime or mode has changed.
6072*/
6073static int arCreateOrUpdateCommand(
6074  ArCommand *pAr,                 /* Command arguments and options */
6075  int bUpdate,                    /* true for a --create. */
6076  int bOnlyIfChanged              /* Only update if file has changed */
6077){
6078  const char *zCreate =
6079      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6080      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6081      "  mode INT,               -- access permissions\n"
6082      "  mtime INT,              -- last modification time\n"
6083      "  sz INT,                 -- original file size\n"
6084      "  data BLOB               -- compressed content\n"
6085      ")";
6086  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6087  const char *zInsertFmt[2] = {
6088     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6089     "  SELECT\n"
6090     "    %s,\n"
6091     "    mode,\n"
6092     "    mtime,\n"
6093     "    CASE substr(lsmode(mode),1,1)\n"
6094     "      WHEN '-' THEN length(data)\n"
6095     "      WHEN 'd' THEN 0\n"
6096     "      ELSE -1 END,\n"
6097     "    sqlar_compress(data)\n"
6098     "  FROM fsdir(%Q,%Q) AS disk\n"
6099     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6100     ,
6101     "REPLACE INTO %s(name,mode,mtime,data)\n"
6102     "  SELECT\n"
6103     "    %s,\n"
6104     "    mode,\n"
6105     "    mtime,\n"
6106     "    data\n"
6107     "  FROM fsdir(%Q,%Q) AS disk\n"
6108     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6109  };
6110  int i;                          /* For iterating through azFile[] */
6111  int rc;                         /* Return code */
6112  const char *zTab = 0;           /* SQL table into which to insert */
6113  char *zSql;
6114  char zTemp[50];
6115  char *zExists = 0;
6116
6117  arExecSql(pAr, "PRAGMA page_size=512");
6118  rc = arExecSql(pAr, "SAVEPOINT ar;");
6119  if( rc!=SQLITE_OK ) return rc;
6120  zTemp[0] = 0;
6121  if( pAr->bZip ){
6122    /* Initialize the zipfile virtual table, if necessary */
6123    if( pAr->zFile ){
6124      sqlite3_uint64 r;
6125      sqlite3_randomness(sizeof(r),&r);
6126      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6127      zTab = zTemp;
6128      zSql = sqlite3_mprintf(
6129         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6130         zTab, pAr->zFile
6131      );
6132      rc = arExecSql(pAr, zSql);
6133      sqlite3_free(zSql);
6134    }else{
6135      zTab = "zip";
6136    }
6137  }else{
6138    /* Initialize the table for an SQLAR */
6139    zTab = "sqlar";
6140    if( bUpdate==0 ){
6141      rc = arExecSql(pAr, zDrop);
6142      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6143    }
6144    rc = arExecSql(pAr, zCreate);
6145  }
6146  if( bOnlyIfChanged ){
6147    zExists = sqlite3_mprintf(
6148      " AND NOT EXISTS("
6149          "SELECT 1 FROM %s AS mem"
6150          " WHERE mem.name=disk.name"
6151          " AND mem.mtime=disk.mtime"
6152          " AND mem.mode=disk.mode)", zTab);
6153  }else{
6154    zExists = sqlite3_mprintf("");
6155  }
6156  if( zExists==0 ) rc = SQLITE_NOMEM;
6157  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6158    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6159        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6160        pAr->azArg[i], pAr->zDir, zExists);
6161    rc = arExecSql(pAr, zSql2);
6162    sqlite3_free(zSql2);
6163  }
6164end_ar_transaction:
6165  if( rc!=SQLITE_OK ){
6166    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6167  }else{
6168    rc = arExecSql(pAr, "RELEASE ar;");
6169    if( pAr->bZip && pAr->zFile ){
6170      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6171      arExecSql(pAr, zSql);
6172      sqlite3_free(zSql);
6173    }
6174  }
6175  sqlite3_free(zExists);
6176  return rc;
6177}
6178
6179/*
6180** Implementation of ".ar" dot command.
6181*/
6182static int arDotCommand(
6183  ShellState *pState,          /* Current shell tool state */
6184  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
6185  char **azArg,                /* Array of arguments passed to dot command */
6186  int nArg                     /* Number of entries in azArg[] */
6187){
6188  ArCommand cmd;
6189  int rc;
6190  memset(&cmd, 0, sizeof(cmd));
6191  cmd.fromCmdLine = fromCmdLine;
6192  rc = arParseCommand(azArg, nArg, &cmd);
6193  if( rc==SQLITE_OK ){
6194    int eDbType = SHELL_OPEN_UNSPEC;
6195    cmd.p = pState;
6196    cmd.db = pState->db;
6197    if( cmd.zFile ){
6198      eDbType = deduceDatabaseType(cmd.zFile, 1);
6199    }else{
6200      eDbType = pState->openMode;
6201    }
6202    if( eDbType==SHELL_OPEN_ZIPFILE ){
6203      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6204        if( cmd.zFile==0 ){
6205          cmd.zSrcTable = sqlite3_mprintf("zip");
6206        }else{
6207          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6208        }
6209      }
6210      cmd.bZip = 1;
6211    }else if( cmd.zFile ){
6212      int flags;
6213      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6214      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6215           || cmd.eCmd==AR_CMD_UPDATE ){
6216        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6217      }else{
6218        flags = SQLITE_OPEN_READONLY;
6219      }
6220      cmd.db = 0;
6221      if( cmd.bDryRun ){
6222        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6223             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6224      }
6225      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6226             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6227      if( rc!=SQLITE_OK ){
6228        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6229            cmd.zFile, sqlite3_errmsg(cmd.db)
6230        );
6231        goto end_ar_command;
6232      }
6233      sqlite3_fileio_init(cmd.db, 0, 0);
6234      sqlite3_sqlar_init(cmd.db, 0, 0);
6235      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6236                              shellPutsFunc, 0, 0);
6237
6238    }
6239    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6240      if( cmd.eCmd!=AR_CMD_CREATE
6241       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6242      ){
6243        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6244        rc = SQLITE_ERROR;
6245        goto end_ar_command;
6246      }
6247      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6248    }
6249
6250    switch( cmd.eCmd ){
6251      case AR_CMD_CREATE:
6252        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6253        break;
6254
6255      case AR_CMD_EXTRACT:
6256        rc = arExtractCommand(&cmd);
6257        break;
6258
6259      case AR_CMD_LIST:
6260        rc = arListCommand(&cmd);
6261        break;
6262
6263      case AR_CMD_HELP:
6264        arUsage(pState->out);
6265        break;
6266
6267      case AR_CMD_INSERT:
6268        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6269        break;
6270
6271      default:
6272        assert( cmd.eCmd==AR_CMD_UPDATE );
6273        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6274        break;
6275    }
6276  }
6277end_ar_command:
6278  if( cmd.db!=pState->db ){
6279    close_db(cmd.db);
6280  }
6281  sqlite3_free(cmd.zSrcTable);
6282
6283  return rc;
6284}
6285/* End of the ".archive" or ".ar" command logic
6286*******************************************************************************/
6287#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6288
6289#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6290/*
6291** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6292** Otherwise, the SQL statement or statements in zSql are executed using
6293** database connection db and the error code written to *pRc before
6294** this function returns.
6295*/
6296static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6297  int rc = *pRc;
6298  if( rc==SQLITE_OK ){
6299    char *zErr = 0;
6300    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6301    if( rc!=SQLITE_OK ){
6302      raw_printf(stderr, "SQL error: %s\n", zErr);
6303    }
6304    *pRc = rc;
6305  }
6306}
6307
6308/*
6309** Like shellExec(), except that zFmt is a printf() style format string.
6310*/
6311static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6312  char *z = 0;
6313  if( *pRc==SQLITE_OK ){
6314    va_list ap;
6315    va_start(ap, zFmt);
6316    z = sqlite3_vmprintf(zFmt, ap);
6317    va_end(ap);
6318    if( z==0 ){
6319      *pRc = SQLITE_NOMEM;
6320    }else{
6321      shellExec(db, pRc, z);
6322    }
6323    sqlite3_free(z);
6324  }
6325}
6326
6327/*
6328** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6329** Otherwise, an attempt is made to allocate, zero and return a pointer
6330** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6331** to SQLITE_NOMEM and NULL returned.
6332*/
6333static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6334  void *pRet = 0;
6335  if( *pRc==SQLITE_OK ){
6336    pRet = sqlite3_malloc64(nByte);
6337    if( pRet==0 ){
6338      *pRc = SQLITE_NOMEM;
6339    }else{
6340      memset(pRet, 0, nByte);
6341    }
6342  }
6343  return pRet;
6344}
6345
6346/*
6347** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6348** Otherwise, zFmt is treated as a printf() style string. The result of
6349** formatting it along with any trailing arguments is written into a
6350** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6351** It is the responsibility of the caller to eventually free this buffer
6352** using a call to sqlite3_free().
6353**
6354** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6355** pointer returned.
6356*/
6357static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6358  char *z = 0;
6359  if( *pRc==SQLITE_OK ){
6360    va_list ap;
6361    va_start(ap, zFmt);
6362    z = sqlite3_vmprintf(zFmt, ap);
6363    va_end(ap);
6364    if( z==0 ){
6365      *pRc = SQLITE_NOMEM;
6366    }
6367  }
6368  return z;
6369}
6370
6371/*
6372** When running the ".recover" command, each output table, and the special
6373** orphaned row table if it is required, is represented by an instance
6374** of the following struct.
6375*/
6376typedef struct RecoverTable RecoverTable;
6377struct RecoverTable {
6378  char *zQuoted;                  /* Quoted version of table name */
6379  int nCol;                       /* Number of columns in table */
6380  char **azlCol;                  /* Array of column lists */
6381  int iPk;                        /* Index of IPK column */
6382};
6383
6384/*
6385** Free a RecoverTable object allocated by recoverFindTable() or
6386** recoverOrphanTable().
6387*/
6388static void recoverFreeTable(RecoverTable *pTab){
6389  if( pTab ){
6390    sqlite3_free(pTab->zQuoted);
6391    if( pTab->azlCol ){
6392      int i;
6393      for(i=0; i<=pTab->nCol; i++){
6394        sqlite3_free(pTab->azlCol[i]);
6395      }
6396      sqlite3_free(pTab->azlCol);
6397    }
6398    sqlite3_free(pTab);
6399  }
6400}
6401
6402/*
6403** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6404** Otherwise, it allocates and returns a RecoverTable object based on the
6405** final four arguments passed to this function. It is the responsibility
6406** of the caller to eventually free the returned object using
6407** recoverFreeTable().
6408*/
6409static RecoverTable *recoverNewTable(
6410  int *pRc,                       /* IN/OUT: Error code */
6411  const char *zName,              /* Name of table */
6412  const char *zSql,               /* CREATE TABLE statement */
6413  int bIntkey,
6414  int nCol
6415){
6416  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
6417  int rc = *pRc;
6418  RecoverTable *pTab = 0;
6419
6420  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
6421  if( rc==SQLITE_OK ){
6422    int nSqlCol = 0;
6423    int bSqlIntkey = 0;
6424    sqlite3_stmt *pStmt = 0;
6425
6426    rc = sqlite3_open("", &dbtmp);
6427    if( rc==SQLITE_OK ){
6428      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
6429                              shellIdQuote, 0, 0);
6430    }
6431    if( rc==SQLITE_OK ){
6432      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6433    }
6434    if( rc==SQLITE_OK ){
6435      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6436      if( rc==SQLITE_ERROR ){
6437        rc = SQLITE_OK;
6438        goto finished;
6439      }
6440    }
6441    shellPreparePrintf(dbtmp, &rc, &pStmt,
6442        "SELECT count(*) FROM pragma_table_info(%Q)", zName
6443    );
6444    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6445      nSqlCol = sqlite3_column_int(pStmt, 0);
6446    }
6447    shellFinalize(&rc, pStmt);
6448
6449    if( rc!=SQLITE_OK || nSqlCol<nCol ){
6450      goto finished;
6451    }
6452
6453    shellPreparePrintf(dbtmp, &rc, &pStmt,
6454      "SELECT ("
6455      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6456      ") FROM sqlite_master WHERE name = %Q", zName
6457    );
6458    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6459      bSqlIntkey = sqlite3_column_int(pStmt, 0);
6460    }
6461    shellFinalize(&rc, pStmt);
6462
6463    if( bIntkey==bSqlIntkey ){
6464      int i;
6465      const char *zPk = "_rowid_";
6466      sqlite3_stmt *pPkFinder = 0;
6467
6468      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6469      ** set zPk to the name of the PK column, and pTab->iPk to the index
6470      ** of the column, where columns are 0-numbered from left to right.
6471      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6472      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
6473      pTab->iPk = -2;
6474      if( bIntkey ){
6475        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6476          "SELECT cid, name FROM pragma_table_info(%Q) "
6477          "  WHERE pk=1 AND type='integer' COLLATE nocase"
6478          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6479          , zName, zName
6480        );
6481        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6482          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6483          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6484        }
6485      }
6486
6487      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
6488      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
6489      pTab->nCol = nSqlCol;
6490
6491      if( bIntkey ){
6492        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
6493      }else{
6494        pTab->azlCol[0] = shellMPrintf(&rc, "");
6495      }
6496      i = 1;
6497      shellPreparePrintf(dbtmp, &rc, &pStmt,
6498          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
6499          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
6500          "FROM pragma_table_info(%Q)",
6501          bIntkey ? ", " : "", pTab->iPk,
6502          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6503          zName
6504      );
6505      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6506        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6507        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6508        i++;
6509      }
6510      shellFinalize(&rc, pStmt);
6511
6512      shellFinalize(&rc, pPkFinder);
6513    }
6514  }
6515
6516 finished:
6517  sqlite3_close(dbtmp);
6518  *pRc = rc;
6519  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
6520    recoverFreeTable(pTab);
6521    pTab = 0;
6522  }
6523  return pTab;
6524}
6525
6526/*
6527** This function is called to search the schema recovered from the
6528** sqlite_master table of the (possibly) corrupt database as part
6529** of a ".recover" command. Specifically, for a table with root page
6530** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6531** table must be a WITHOUT ROWID table, or if non-zero, not one of
6532** those.
6533**
6534** If a table is found, a (RecoverTable*) object is returned. Or, if
6535** no such table is found, but bIntkey is false and iRoot is the
6536** root page of an index in the recovered schema, then (*pbNoop) is
6537** set to true and NULL returned. Or, if there is no such table or
6538** index, NULL is returned and (*pbNoop) set to 0, indicating that
6539** the caller should write data to the orphans table.
6540*/
6541static RecoverTable *recoverFindTable(
6542  ShellState *pState,             /* Shell state object */
6543  int *pRc,                       /* IN/OUT: Error code */
6544  int iRoot,                      /* Root page of table */
6545  int bIntkey,                    /* True for an intkey table */
6546  int nCol,                       /* Number of columns in table */
6547  int *pbNoop                     /* OUT: True if iRoot is root of index */
6548){
6549  sqlite3_stmt *pStmt = 0;
6550  RecoverTable *pRet = 0;
6551  int bNoop = 0;
6552  const char *zSql = 0;
6553  const char *zName = 0;
6554
6555  /* Search the recovered schema for an object with root page iRoot. */
6556  shellPreparePrintf(pState->db, pRc, &pStmt,
6557      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6558  );
6559  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6560    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6561    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6562      bNoop = 1;
6563      break;
6564    }
6565    if( sqlite3_stricmp(zType, "table")==0 ){
6566      zName = (const char*)sqlite3_column_text(pStmt, 1);
6567      zSql = (const char*)sqlite3_column_text(pStmt, 2);
6568      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
6569      break;
6570    }
6571  }
6572
6573  shellFinalize(pRc, pStmt);
6574  *pbNoop = bNoop;
6575  return pRet;
6576}
6577
6578/*
6579** Return a RecoverTable object representing the orphans table.
6580*/
6581static RecoverTable *recoverOrphanTable(
6582  ShellState *pState,             /* Shell state object */
6583  int *pRc,                       /* IN/OUT: Error code */
6584  const char *zLostAndFound,      /* Base name for orphans table */
6585  int nCol                        /* Number of user data columns */
6586){
6587  RecoverTable *pTab = 0;
6588  if( nCol>=0 && *pRc==SQLITE_OK ){
6589    int i;
6590
6591    /* This block determines the name of the orphan table. The prefered
6592    ** name is zLostAndFound. But if that clashes with another name
6593    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
6594    ** and so on until a non-clashing name is found.  */
6595    int iTab = 0;
6596    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
6597    sqlite3_stmt *pTest = 0;
6598    shellPrepare(pState->db, pRc,
6599        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
6600    );
6601    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6602    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
6603      shellReset(pRc, pTest);
6604      sqlite3_free(zTab);
6605      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
6606      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6607    }
6608    shellFinalize(pRc, pTest);
6609
6610    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
6611    if( pTab ){
6612      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
6613      pTab->nCol = nCol;
6614      pTab->iPk = -2;
6615      if( nCol>0 ){
6616        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
6617        if( pTab->azlCol ){
6618          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
6619          for(i=nCol-1; i>=0; i--){
6620            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
6621          }
6622        }
6623      }
6624
6625      if( *pRc!=SQLITE_OK ){
6626        recoverFreeTable(pTab);
6627        pTab = 0;
6628      }else{
6629        raw_printf(pState->out,
6630            "CREATE TABLE %s(rootpgno INTEGER, "
6631            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
6632        );
6633        for(i=0; i<nCol; i++){
6634          raw_printf(pState->out, ", c%d", i);
6635        }
6636        raw_printf(pState->out, ");\n");
6637      }
6638    }
6639    sqlite3_free(zTab);
6640  }
6641  return pTab;
6642}
6643
6644/*
6645** This function is called to recover data from the database. A script
6646** to construct a new database containing all recovered data is output
6647** on stream pState->out.
6648*/
6649static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
6650  int rc = SQLITE_OK;
6651  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
6652  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
6653  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
6654  const char *zRecoveryDb = "";   /* Name of "recovery" database */
6655  const char *zLostAndFound = "lost_and_found";
6656  int i;
6657  int nOrphan = -1;
6658  RecoverTable *pOrphan = 0;
6659
6660  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
6661  int bRowids = 1;                /* 0 if --no-rowids */
6662  for(i=1; i<nArg; i++){
6663    char *z = azArg[i];
6664    int n;
6665    if( z[0]=='-' && z[1]=='-' ) z++;
6666    n = strlen30(z);
6667    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
6668      bFreelist = 0;
6669    }else
6670    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
6671      i++;
6672      zRecoveryDb = azArg[i];
6673    }else
6674    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
6675      i++;
6676      zLostAndFound = azArg[i];
6677    }else
6678    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
6679      bRowids = 0;
6680    }
6681    else{
6682      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
6683      showHelp(pState->out, azArg[0]);
6684      return 1;
6685    }
6686  }
6687
6688  shellExecPrintf(pState->db, &rc,
6689    /* Attach an in-memory database named 'recovery'. Create an indexed
6690    ** cache of the sqlite_dbptr virtual table. */
6691    "PRAGMA writable_schema = on;"
6692    "ATTACH %Q AS recovery;"
6693    "DROP TABLE IF EXISTS recovery.dbptr;"
6694    "DROP TABLE IF EXISTS recovery.freelist;"
6695    "DROP TABLE IF EXISTS recovery.map;"
6696    "DROP TABLE IF EXISTS recovery.schema;"
6697    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
6698  );
6699
6700  if( bFreelist ){
6701    shellExec(pState->db, &rc,
6702      "WITH trunk(pgno) AS ("
6703      "  SELECT shell_int32("
6704      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
6705      "      WHERE x>0"
6706      "    UNION"
6707      "  SELECT shell_int32("
6708      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
6709      "      FROM trunk WHERE x>0"
6710      "),"
6711      "freelist(data, n, freepgno) AS ("
6712      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
6713      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
6714      "    UNION ALL"
6715      "  SELECT data, n-1, shell_int32(data, 2+n) "
6716      "      FROM freelist WHERE n>=0"
6717      ")"
6718      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
6719    );
6720  }
6721
6722  /* If this is an auto-vacuum database, add all pointer-map pages to
6723  ** the freelist table. Do this regardless of whether or not
6724  ** --freelist-corrupt was specified.  */
6725  shellExec(pState->db, &rc,
6726    "WITH ptrmap(pgno) AS ("
6727    "  SELECT 2 WHERE shell_int32("
6728    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
6729    "  )"
6730    "    UNION ALL "
6731    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
6732    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
6733    ")"
6734    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
6735  );
6736
6737  shellExec(pState->db, &rc,
6738    "CREATE TABLE recovery.dbptr("
6739    "      pgno, child, PRIMARY KEY(child, pgno)"
6740    ") WITHOUT ROWID;"
6741    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
6742    "    SELECT * FROM sqlite_dbptr"
6743    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
6744
6745    /* Delete any pointer to page 1. This ensures that page 1 is considered
6746    ** a root page, regardless of how corrupt the db is. */
6747    "DELETE FROM recovery.dbptr WHERE child = 1;"
6748
6749    /* Delete all pointers to any pages that have more than one pointer
6750    ** to them. Such pages will be treated as root pages when recovering
6751    ** data.  */
6752    "DELETE FROM recovery.dbptr WHERE child IN ("
6753    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6754    ");"
6755
6756    /* Create the "map" table that will (eventually) contain instructions
6757    ** for dealing with each page in the db that contains one or more
6758    ** records. */
6759    "CREATE TABLE recovery.map("
6760      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6761    ");"
6762
6763    /* Populate table [map]. If there are circular loops of pages in the
6764    ** database, the following adds all pages in such a loop to the map
6765    ** as individual root pages. This could be handled better.  */
6766    "WITH pages(i, maxlen) AS ("
6767    "  SELECT page_count, ("
6768    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
6769    "  ) FROM pragma_page_count WHERE page_count>0"
6770    "    UNION ALL"
6771    "  SELECT i-1, ("
6772    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6773    "  ) FROM pages WHERE i>=2"
6774    ")"
6775    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6776    "  SELECT i, maxlen, NULL, ("
6777    "    WITH p(orig, pgno, parent) AS ("
6778    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
6779    "        UNION "
6780    "      SELECT i, p.parent, "
6781    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6782    "    )"
6783    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6784    ") "
6785    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
6786    "UPDATE recovery.map AS o SET intkey = ("
6787    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6788    ");"
6789
6790    /* Extract data from page 1 and any linked pages into table
6791    ** recovery.schema. With the same schema as an sqlite_master table.  */
6792    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6793    "INSERT INTO recovery.schema SELECT "
6794    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
6795    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
6796    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
6797    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
6798    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
6799    "FROM sqlite_dbdata WHERE pgno IN ("
6800    "  SELECT pgno FROM recovery.map WHERE root=1"
6801    ")"
6802    "GROUP BY pgno, cell;"
6803    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
6804  );
6805
6806  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6807  ** CREATE TABLE statements that extracted from the existing schema.  */
6808  if( rc==SQLITE_OK ){
6809    sqlite3_stmt *pStmt = 0;
6810    /* ".recover" might output content in an order which causes immediate
6811    ** foreign key constraints to be violated. So disable foreign-key
6812    ** constraint enforcement to prevent problems when running the output
6813    ** script. */
6814    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
6815    raw_printf(pState->out, "BEGIN;\n");
6816    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6817    shellPrepare(pState->db, &rc,
6818        "SELECT sql FROM recovery.schema "
6819        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
6820    );
6821    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6822      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
6823      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6824          &zCreateTable[12]
6825      );
6826    }
6827    shellFinalize(&rc, pStmt);
6828  }
6829
6830  /* Figure out if an orphan table will be required. And if so, how many
6831  ** user columns it should contain */
6832  shellPrepare(pState->db, &rc,
6833      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
6834      , &pLoop
6835  );
6836  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6837    nOrphan = sqlite3_column_int(pLoop, 0);
6838  }
6839  shellFinalize(&rc, pLoop);
6840  pLoop = 0;
6841
6842  shellPrepare(pState->db, &rc,
6843      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6844  );
6845
6846  shellPrepare(pState->db, &rc,
6847      "SELECT max(field), group_concat(shell_escape_crnl(quote"
6848      "(case when (? AND field<0) then NULL else value end)"
6849      "), ', ')"
6850      ", min(field) "
6851      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6852      "GROUP BY cell", &pCells
6853  );
6854
6855  /* Loop through each root page. */
6856  shellPrepare(pState->db, &rc,
6857      "SELECT root, intkey, max(maxlen) FROM recovery.map"
6858      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6859      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6860      ")", &pLoop
6861  );
6862  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6863    int iRoot = sqlite3_column_int(pLoop, 0);
6864    int bIntkey = sqlite3_column_int(pLoop, 1);
6865    int nCol = sqlite3_column_int(pLoop, 2);
6866    int bNoop = 0;
6867    RecoverTable *pTab;
6868
6869    assert( bIntkey==0 || bIntkey==1 );
6870    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
6871    if( bNoop || rc ) continue;
6872    if( pTab==0 ){
6873      if( pOrphan==0 ){
6874        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6875      }
6876      pTab = pOrphan;
6877      if( pTab==0 ) break;
6878    }
6879
6880    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
6881      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6882    }
6883    sqlite3_bind_int(pPages, 1, iRoot);
6884    if( bRowids==0 && pTab->iPk<0 ){
6885      sqlite3_bind_int(pCells, 1, 1);
6886    }else{
6887      sqlite3_bind_int(pCells, 1, 0);
6888    }
6889    sqlite3_bind_int(pCells, 3, pTab->iPk);
6890
6891    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6892      int iPgno = sqlite3_column_int(pPages, 0);
6893      sqlite3_bind_int(pCells, 2, iPgno);
6894      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6895        int nField = sqlite3_column_int(pCells, 0);
6896        int iMin = sqlite3_column_int(pCells, 2);
6897        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6898
6899        RecoverTable *pTab2 = pTab;
6900        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
6901          if( pOrphan==0 ){
6902            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6903          }
6904          pTab2 = pOrphan;
6905          if( pTab2==0 ) break;
6906        }
6907
6908        nField = nField+1;
6909        if( pTab2==pOrphan ){
6910          raw_printf(pState->out,
6911              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
6912              pTab2->zQuoted, iRoot, iPgno, nField,
6913              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
6914          );
6915        }else{
6916          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
6917              pTab2->zQuoted, pTab2->azlCol[nField], zVal
6918          );
6919        }
6920      }
6921      shellReset(&rc, pCells);
6922    }
6923    shellReset(&rc, pPages);
6924    if( pTab!=pOrphan ) recoverFreeTable(pTab);
6925  }
6926  shellFinalize(&rc, pLoop);
6927  shellFinalize(&rc, pPages);
6928  shellFinalize(&rc, pCells);
6929  recoverFreeTable(pOrphan);
6930
6931  /* The rest of the schema */
6932  if( rc==SQLITE_OK ){
6933    sqlite3_stmt *pStmt = 0;
6934    shellPrepare(pState->db, &rc,
6935        "SELECT sql, name FROM recovery.schema "
6936        "WHERE sql NOT LIKE 'create table%'", &pStmt
6937    );
6938    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6939      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6940      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6941        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6942        char *zPrint = shellMPrintf(&rc,
6943          "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6944          zName, zName, zSql
6945        );
6946        raw_printf(pState->out, "%s;\n", zPrint);
6947        sqlite3_free(zPrint);
6948      }else{
6949        raw_printf(pState->out, "%s;\n", zSql);
6950      }
6951    }
6952    shellFinalize(&rc, pStmt);
6953  }
6954
6955  if( rc==SQLITE_OK ){
6956    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
6957    raw_printf(pState->out, "COMMIT;\n");
6958  }
6959  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6960  return rc;
6961}
6962#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
6963
6964
6965/*
6966** If an input line begins with "." then invoke this routine to
6967** process that line.
6968**
6969** Return 1 on error, 2 to exit, and 0 otherwise.
6970*/
6971static int do_meta_command(char *zLine, ShellState *p){
6972  int h = 1;
6973  int nArg = 0;
6974  int n, c;
6975  int rc = 0;
6976  char *azArg[52];
6977
6978#ifndef SQLITE_OMIT_VIRTUALTABLE
6979  if( p->expert.pExpert ){
6980    expertFinish(p, 1, 0);
6981  }
6982#endif
6983
6984  /* Parse the input line into tokens.
6985  */
6986  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
6987    while( IsSpace(zLine[h]) ){ h++; }
6988    if( zLine[h]==0 ) break;
6989    if( zLine[h]=='\'' || zLine[h]=='"' ){
6990      int delim = zLine[h++];
6991      azArg[nArg++] = &zLine[h];
6992      while( zLine[h] && zLine[h]!=delim ){
6993        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6994        h++;
6995      }
6996      if( zLine[h]==delim ){
6997        zLine[h++] = 0;
6998      }
6999      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7000    }else{
7001      azArg[nArg++] = &zLine[h];
7002      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7003      if( zLine[h] ) zLine[h++] = 0;
7004      resolve_backslashes(azArg[nArg-1]);
7005    }
7006  }
7007  azArg[nArg] = 0;
7008
7009  /* Process the input line.
7010  */
7011  if( nArg==0 ) return 0; /* no tokens, no error */
7012  n = strlen30(azArg[0]);
7013  c = azArg[0][0];
7014  clearTempFile(p);
7015
7016#ifndef SQLITE_OMIT_AUTHORIZATION
7017  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7018    if( nArg!=2 ){
7019      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7020      rc = 1;
7021      goto meta_command_exit;
7022    }
7023    open_db(p, 0);
7024    if( booleanValue(azArg[1]) ){
7025      sqlite3_set_authorizer(p->db, shellAuth, p);
7026    }else{
7027      sqlite3_set_authorizer(p->db, 0, 0);
7028    }
7029  }else
7030#endif
7031
7032#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7033  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7034    open_db(p, 0);
7035    rc = arDotCommand(p, 0, azArg, nArg);
7036  }else
7037#endif
7038
7039  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7040   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7041  ){
7042    const char *zDestFile = 0;
7043    const char *zDb = 0;
7044    sqlite3 *pDest;
7045    sqlite3_backup *pBackup;
7046    int j;
7047    int bAsync = 0;
7048    const char *zVfs = 0;
7049    for(j=1; j<nArg; j++){
7050      const char *z = azArg[j];
7051      if( z[0]=='-' ){
7052        if( z[1]=='-' ) z++;
7053        if( strcmp(z, "-append")==0 ){
7054          zVfs = "apndvfs";
7055        }else
7056        if( strcmp(z, "-async")==0 ){
7057          bAsync = 1;
7058        }else
7059        {
7060          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7061          return 1;
7062        }
7063      }else if( zDestFile==0 ){
7064        zDestFile = azArg[j];
7065      }else if( zDb==0 ){
7066        zDb = zDestFile;
7067        zDestFile = azArg[j];
7068      }else{
7069        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7070        return 1;
7071      }
7072    }
7073    if( zDestFile==0 ){
7074      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7075      return 1;
7076    }
7077    if( zDb==0 ) zDb = "main";
7078    rc = sqlite3_open_v2(zDestFile, &pDest,
7079                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7080    if( rc!=SQLITE_OK ){
7081      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7082      close_db(pDest);
7083      return 1;
7084    }
7085    if( bAsync ){
7086      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7087                   0, 0, 0);
7088    }
7089    open_db(p, 0);
7090    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7091    if( pBackup==0 ){
7092      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7093      close_db(pDest);
7094      return 1;
7095    }
7096    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7097    sqlite3_backup_finish(pBackup);
7098    if( rc==SQLITE_DONE ){
7099      rc = 0;
7100    }else{
7101      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7102      rc = 1;
7103    }
7104    close_db(pDest);
7105  }else
7106
7107  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7108    if( nArg==2 ){
7109      bail_on_error = booleanValue(azArg[1]);
7110    }else{
7111      raw_printf(stderr, "Usage: .bail on|off\n");
7112      rc = 1;
7113    }
7114  }else
7115
7116  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7117    if( nArg==2 ){
7118      if( booleanValue(azArg[1]) ){
7119        setBinaryMode(p->out, 1);
7120      }else{
7121        setTextMode(p->out, 1);
7122      }
7123    }else{
7124      raw_printf(stderr, "Usage: .binary on|off\n");
7125      rc = 1;
7126    }
7127  }else
7128
7129  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7130    if( nArg==2 ){
7131#if defined(_WIN32) || defined(WIN32)
7132      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7133      rc = !SetCurrentDirectoryW(z);
7134      sqlite3_free(z);
7135#else
7136      rc = chdir(azArg[1]);
7137#endif
7138      if( rc ){
7139        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7140        rc = 1;
7141      }
7142    }else{
7143      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7144      rc = 1;
7145    }
7146  }else
7147
7148  /* The undocumented ".breakpoint" command causes a call to the no-op
7149  ** routine named test_breakpoint().
7150  */
7151  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7152    test_breakpoint();
7153  }else
7154
7155  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7156    if( nArg==2 ){
7157      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7158    }else{
7159      raw_printf(stderr, "Usage: .changes on|off\n");
7160      rc = 1;
7161    }
7162  }else
7163
7164  /* Cancel output redirection, if it is currently set (by .testcase)
7165  ** Then read the content of the testcase-out.txt file and compare against
7166  ** azArg[1].  If there are differences, report an error and exit.
7167  */
7168  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7169    char *zRes = 0;
7170    output_reset(p);
7171    if( nArg!=2 ){
7172      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7173      rc = 2;
7174    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7175      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7176      rc = 2;
7177    }else if( testcase_glob(azArg[1],zRes)==0 ){
7178      utf8_printf(stderr,
7179                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7180                 p->zTestcase, azArg[1], zRes);
7181      rc = 1;
7182    }else{
7183      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7184      p->nCheck++;
7185    }
7186    sqlite3_free(zRes);
7187  }else
7188
7189  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7190    if( nArg==2 ){
7191      tryToClone(p, azArg[1]);
7192    }else{
7193      raw_printf(stderr, "Usage: .clone FILENAME\n");
7194      rc = 1;
7195    }
7196  }else
7197
7198  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7199    ShellState data;
7200    char *zErrMsg = 0;
7201    open_db(p, 0);
7202    memcpy(&data, p, sizeof(data));
7203    data.showHeader = 0;
7204    data.cMode = data.mode = MODE_List;
7205    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
7206    data.cnt = 0;
7207    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
7208                 callback, &data, &zErrMsg);
7209    if( zErrMsg ){
7210      utf8_printf(stderr,"Error: %s\n", zErrMsg);
7211      sqlite3_free(zErrMsg);
7212      rc = 1;
7213    }
7214  }else
7215
7216  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7217    static const struct DbConfigChoices {
7218      const char *zName;
7219      int op;
7220    } aDbConfig[] = {
7221        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7222        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7223        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7224        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7225        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7226        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7227        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7228        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7229        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7230        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7231        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7232        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7233        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7234        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7235        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7236        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7237    };
7238    int ii, v;
7239    open_db(p, 0);
7240    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7241      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7242      if( nArg>=3 ){
7243        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7244      }
7245      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7246      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7247      if( nArg>1 ) break;
7248    }
7249    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7250      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7251      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7252    }
7253  }else
7254
7255  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7256    rc = shell_dbinfo_command(p, nArg, azArg);
7257  }else
7258
7259#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7260  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7261    open_db(p, 0);
7262    rc = recoverDatabaseCmd(p, nArg, azArg);
7263  }else
7264#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7265
7266  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7267    const char *zLike = 0;
7268    int i;
7269    int savedShowHeader = p->showHeader;
7270    int savedShellFlags = p->shellFlgs;
7271    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
7272    for(i=1; i<nArg; i++){
7273      if( azArg[i][0]=='-' ){
7274        const char *z = azArg[i]+1;
7275        if( z[0]=='-' ) z++;
7276        if( strcmp(z,"preserve-rowids")==0 ){
7277#ifdef SQLITE_OMIT_VIRTUALTABLE
7278          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7279                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7280          rc = 1;
7281          goto meta_command_exit;
7282#else
7283          ShellSetFlag(p, SHFLG_PreserveRowid);
7284#endif
7285        }else
7286        if( strcmp(z,"newlines")==0 ){
7287          ShellSetFlag(p, SHFLG_Newlines);
7288        }else
7289        {
7290          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7291          rc = 1;
7292          goto meta_command_exit;
7293        }
7294      }else if( zLike ){
7295        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
7296                           "?--newlines? ?LIKE-PATTERN?\n");
7297        rc = 1;
7298        goto meta_command_exit;
7299      }else{
7300        zLike = azArg[i];
7301      }
7302    }
7303
7304    open_db(p, 0);
7305
7306    /* When playing back a "dump", the content might appear in an order
7307    ** which causes immediate foreign key constraints to be violated.
7308    ** So disable foreign-key constraint enforcement to prevent problems. */
7309    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7310    raw_printf(p->out, "BEGIN TRANSACTION;\n");
7311    p->writableSchema = 0;
7312    p->showHeader = 0;
7313    /* Set writable_schema=ON since doing so forces SQLite to initialize
7314    ** as much of the schema as it can even if the sqlite_master table is
7315    ** corrupt. */
7316    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7317    p->nErr = 0;
7318    if( zLike==0 ){
7319      run_schema_dump_query(p,
7320        "SELECT name, type, sql FROM sqlite_master "
7321        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
7322      );
7323      run_schema_dump_query(p,
7324        "SELECT name, type, sql FROM sqlite_master "
7325        "WHERE name=='sqlite_sequence'"
7326      );
7327      run_table_dump_query(p,
7328        "SELECT sql FROM sqlite_master "
7329        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
7330      );
7331    }else{
7332      char *zSql;
7333      zSql = sqlite3_mprintf(
7334        "SELECT name, type, sql FROM sqlite_master "
7335        "WHERE tbl_name LIKE %Q AND type=='table'"
7336        "  AND sql NOT NULL", zLike);
7337      run_schema_dump_query(p,zSql);
7338      sqlite3_free(zSql);
7339      zSql = sqlite3_mprintf(
7340        "SELECT sql FROM sqlite_master "
7341        "WHERE sql NOT NULL"
7342        "  AND type IN ('index','trigger','view')"
7343        "  AND tbl_name LIKE %Q", zLike);
7344      run_table_dump_query(p, zSql, 0);
7345      sqlite3_free(zSql);
7346    }
7347    if( p->writableSchema ){
7348      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7349      p->writableSchema = 0;
7350    }
7351    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7352    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
7353    raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
7354    p->showHeader = savedShowHeader;
7355    p->shellFlgs = savedShellFlags;
7356  }else
7357
7358  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7359    if( nArg==2 ){
7360      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7361    }else{
7362      raw_printf(stderr, "Usage: .echo on|off\n");
7363      rc = 1;
7364    }
7365  }else
7366
7367  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7368    if( nArg==2 ){
7369      p->autoEQPtest = 0;
7370      if( p->autoEQPtrace ){
7371        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7372        p->autoEQPtrace = 0;
7373      }
7374      if( strcmp(azArg[1],"full")==0 ){
7375        p->autoEQP = AUTOEQP_full;
7376      }else if( strcmp(azArg[1],"trigger")==0 ){
7377        p->autoEQP = AUTOEQP_trigger;
7378#ifdef SQLITE_DEBUG
7379      }else if( strcmp(azArg[1],"test")==0 ){
7380        p->autoEQP = AUTOEQP_on;
7381        p->autoEQPtest = 1;
7382      }else if( strcmp(azArg[1],"trace")==0 ){
7383        p->autoEQP = AUTOEQP_full;
7384        p->autoEQPtrace = 1;
7385        open_db(p, 0);
7386        sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
7387        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7388#endif
7389      }else{
7390        p->autoEQP = (u8)booleanValue(azArg[1]);
7391      }
7392    }else{
7393      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
7394      rc = 1;
7395    }
7396  }else
7397
7398  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7399    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7400    rc = 2;
7401  }else
7402
7403  /* The ".explain" command is automatic now.  It is largely pointless.  It
7404  ** retained purely for backwards compatibility */
7405  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7406    int val = 1;
7407    if( nArg>=2 ){
7408      if( strcmp(azArg[1],"auto")==0 ){
7409        val = 99;
7410      }else{
7411        val =  booleanValue(azArg[1]);
7412      }
7413    }
7414    if( val==1 && p->mode!=MODE_Explain ){
7415      p->normalMode = p->mode;
7416      p->mode = MODE_Explain;
7417      p->autoExplain = 0;
7418    }else if( val==0 ){
7419      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7420      p->autoExplain = 0;
7421    }else if( val==99 ){
7422      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7423      p->autoExplain = 1;
7424    }
7425  }else
7426
7427#ifndef SQLITE_OMIT_VIRTUALTABLE
7428  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7429    open_db(p, 0);
7430    expertDotCommand(p, azArg, nArg);
7431  }else
7432#endif
7433
7434  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7435    static const struct {
7436       const char *zCtrlName;   /* Name of a test-control option */
7437       int ctrlCode;            /* Integer code for that option */
7438       const char *zUsage;      /* Usage notes */
7439    } aCtrl[] = {
7440      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
7441      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
7442   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
7443      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
7444      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
7445   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
7446      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
7447      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
7448      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
7449    };
7450    int filectrl = -1;
7451    int iCtrl = -1;
7452    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
7453    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
7454    int n2, i;
7455    const char *zCmd = 0;
7456
7457    open_db(p, 0);
7458    zCmd = nArg>=2 ? azArg[1] : "help";
7459
7460    /* The argument can optionally begin with "-" or "--" */
7461    if( zCmd[0]=='-' && zCmd[1] ){
7462      zCmd++;
7463      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7464    }
7465
7466    /* --help lists all file-controls */
7467    if( strcmp(zCmd,"help")==0 ){
7468      utf8_printf(p->out, "Available file-controls:\n");
7469      for(i=0; i<ArraySize(aCtrl); i++){
7470        utf8_printf(p->out, "  .filectrl %s %s\n",
7471                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7472      }
7473      rc = 1;
7474      goto meta_command_exit;
7475    }
7476
7477    /* convert filectrl text option to value. allow any unique prefix
7478    ** of the option name, or a numerical value. */
7479    n2 = strlen30(zCmd);
7480    for(i=0; i<ArraySize(aCtrl); i++){
7481      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7482        if( filectrl<0 ){
7483          filectrl = aCtrl[i].ctrlCode;
7484          iCtrl = i;
7485        }else{
7486          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
7487                              "Use \".filectrl --help\" for help\n", zCmd);
7488          rc = 1;
7489          goto meta_command_exit;
7490        }
7491      }
7492    }
7493    if( filectrl<0 ){
7494      utf8_printf(stderr,"Error: unknown file-control: %s\n"
7495                         "Use \".filectrl --help\" for help\n", zCmd);
7496    }else{
7497      switch(filectrl){
7498        case SQLITE_FCNTL_SIZE_LIMIT: {
7499          if( nArg!=2 && nArg!=3 ) break;
7500          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
7501          sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
7502          isOk = 1;
7503          break;
7504        }
7505        case SQLITE_FCNTL_LOCK_TIMEOUT:
7506        case SQLITE_FCNTL_CHUNK_SIZE: {
7507          int x;
7508          if( nArg!=3 ) break;
7509          x = (int)integerValue(azArg[2]);
7510          sqlite3_file_control(p->db, 0, filectrl, &x);
7511          isOk = 2;
7512          break;
7513        }
7514        case SQLITE_FCNTL_PERSIST_WAL:
7515        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
7516          int x;
7517          if( nArg!=2 && nArg!=3 ) break;
7518          x = nArg==3 ? booleanValue(azArg[2]) : -1;
7519          sqlite3_file_control(p->db, 0, filectrl, &x);
7520          iRes = x;
7521          isOk = 1;
7522          break;
7523        }
7524        case SQLITE_FCNTL_HAS_MOVED: {
7525          int x;
7526          if( nArg!=2 ) break;
7527          sqlite3_file_control(p->db, 0, filectrl, &x);
7528          iRes = x;
7529          isOk = 1;
7530          break;
7531        }
7532        case SQLITE_FCNTL_TEMPFILENAME: {
7533          char *z = 0;
7534          if( nArg!=2 ) break;
7535          sqlite3_file_control(p->db, 0, filectrl, &z);
7536          if( z ){
7537            utf8_printf(p->out, "%s\n", z);
7538            sqlite3_free(z);
7539          }
7540          isOk = 2;
7541          break;
7542        }
7543      }
7544    }
7545    if( isOk==0 && iCtrl>=0 ){
7546      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
7547      rc = 1;
7548    }else if( isOk==1 ){
7549      char zBuf[100];
7550      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
7551      raw_printf(p->out, "%s\n", zBuf);
7552    }
7553  }else
7554
7555  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7556    ShellState data;
7557    char *zErrMsg = 0;
7558    int doStats = 0;
7559    memcpy(&data, p, sizeof(data));
7560    data.showHeader = 0;
7561    data.cMode = data.mode = MODE_Semi;
7562    if( nArg==2 && optionMatch(azArg[1], "indent") ){
7563      data.cMode = data.mode = MODE_Pretty;
7564      nArg = 1;
7565    }
7566    if( nArg!=1 ){
7567      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7568      rc = 1;
7569      goto meta_command_exit;
7570    }
7571    open_db(p, 0);
7572    rc = sqlite3_exec(p->db,
7573       "SELECT sql FROM"
7574       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7575       "     FROM sqlite_master UNION ALL"
7576       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7577       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7578       "ORDER BY rowid",
7579       callback, &data, &zErrMsg
7580    );
7581    if( rc==SQLITE_OK ){
7582      sqlite3_stmt *pStmt;
7583      rc = sqlite3_prepare_v2(p->db,
7584               "SELECT rowid FROM sqlite_master"
7585               " WHERE name GLOB 'sqlite_stat[134]'",
7586               -1, &pStmt, 0);
7587      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7588      sqlite3_finalize(pStmt);
7589    }
7590    if( doStats==0 ){
7591      raw_printf(p->out, "/* No STAT tables available */\n");
7592    }else{
7593      raw_printf(p->out, "ANALYZE sqlite_master;\n");
7594      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7595                   callback, &data, &zErrMsg);
7596      data.cMode = data.mode = MODE_Insert;
7597      data.zDestTable = "sqlite_stat1";
7598      shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
7599      data.zDestTable = "sqlite_stat4";
7600      shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
7601      raw_printf(p->out, "ANALYZE sqlite_master;\n");
7602    }
7603  }else
7604
7605  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7606    if( nArg==2 ){
7607      p->showHeader = booleanValue(azArg[1]);
7608    }else{
7609      raw_printf(stderr, "Usage: .headers on|off\n");
7610      rc = 1;
7611    }
7612  }else
7613
7614  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
7615    if( nArg>=2 ){
7616      n = showHelp(p->out, azArg[1]);
7617      if( n==0 ){
7618        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7619      }
7620    }else{
7621      showHelp(p->out, 0);
7622    }
7623  }else
7624
7625  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7626    char *zTable;               /* Insert data into this table */
7627    char *zFile;                /* Name of file to extra content from */
7628    sqlite3_stmt *pStmt = NULL; /* A statement */
7629    int nCol;                   /* Number of columns in the table */
7630    int nByte;                  /* Number of bytes in an SQL string */
7631    int i, j;                   /* Loop counters */
7632    int needCommit;             /* True to COMMIT or ROLLBACK at end */
7633    int nSep;                   /* Number of bytes in p->colSeparator[] */
7634    char *zSql;                 /* An SQL statement */
7635    ImportCtx sCtx;             /* Reader context */
7636    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7637    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
7638
7639    if( nArg!=3 ){
7640      raw_printf(stderr, "Usage: .import FILE TABLE\n");
7641      goto meta_command_exit;
7642    }
7643    zFile = azArg[1];
7644    zTable = azArg[2];
7645    seenInterrupt = 0;
7646    memset(&sCtx, 0, sizeof(sCtx));
7647    open_db(p, 0);
7648    nSep = strlen30(p->colSeparator);
7649    if( nSep==0 ){
7650      raw_printf(stderr,
7651                 "Error: non-null column separator required for import\n");
7652      return 1;
7653    }
7654    if( nSep>1 ){
7655      raw_printf(stderr, "Error: multi-character column separators not allowed"
7656                      " for import\n");
7657      return 1;
7658    }
7659    nSep = strlen30(p->rowSeparator);
7660    if( nSep==0 ){
7661      raw_printf(stderr, "Error: non-null row separator required for import\n");
7662      return 1;
7663    }
7664    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7665      /* When importing CSV (only), if the row separator is set to the
7666      ** default output row separator, change it to the default input
7667      ** row separator.  This avoids having to maintain different input
7668      ** and output row separators. */
7669      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7670      nSep = strlen30(p->rowSeparator);
7671    }
7672    if( nSep>1 ){
7673      raw_printf(stderr, "Error: multi-character row separators not allowed"
7674                      " for import\n");
7675      return 1;
7676    }
7677    sCtx.zFile = zFile;
7678    sCtx.nLine = 1;
7679    if( sCtx.zFile[0]=='|' ){
7680#ifdef SQLITE_OMIT_POPEN
7681      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7682      return 1;
7683#else
7684      sCtx.in = popen(sCtx.zFile+1, "r");
7685      sCtx.zFile = "<pipe>";
7686      xCloser = pclose;
7687#endif
7688    }else{
7689      sCtx.in = fopen(sCtx.zFile, "rb");
7690      xCloser = fclose;
7691    }
7692    if( p->mode==MODE_Ascii ){
7693      xRead = ascii_read_one_field;
7694    }else{
7695      xRead = csv_read_one_field;
7696    }
7697    if( sCtx.in==0 ){
7698      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7699      return 1;
7700    }
7701    sCtx.cColSep = p->colSeparator[0];
7702    sCtx.cRowSep = p->rowSeparator[0];
7703    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7704    if( zSql==0 ){
7705      xCloser(sCtx.in);
7706      shell_out_of_memory();
7707    }
7708    nByte = strlen30(zSql);
7709    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7710    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
7711    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7712      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7713      char cSep = '(';
7714      while( xRead(&sCtx) ){
7715        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
7716        cSep = ',';
7717        if( sCtx.cTerm!=sCtx.cColSep ) break;
7718      }
7719      if( cSep=='(' ){
7720        sqlite3_free(zCreate);
7721        sqlite3_free(sCtx.z);
7722        xCloser(sCtx.in);
7723        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7724        return 1;
7725      }
7726      zCreate = sqlite3_mprintf("%z\n)", zCreate);
7727      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7728      sqlite3_free(zCreate);
7729      if( rc ){
7730        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7731                sqlite3_errmsg(p->db));
7732        sqlite3_free(sCtx.z);
7733        xCloser(sCtx.in);
7734        return 1;
7735      }
7736      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7737    }
7738    sqlite3_free(zSql);
7739    if( rc ){
7740      if (pStmt) sqlite3_finalize(pStmt);
7741      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7742      xCloser(sCtx.in);
7743      return 1;
7744    }
7745    nCol = sqlite3_column_count(pStmt);
7746    sqlite3_finalize(pStmt);
7747    pStmt = 0;
7748    if( nCol==0 ) return 0; /* no columns, no error */
7749    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7750    if( zSql==0 ){
7751      xCloser(sCtx.in);
7752      shell_out_of_memory();
7753    }
7754    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7755    j = strlen30(zSql);
7756    for(i=1; i<nCol; i++){
7757      zSql[j++] = ',';
7758      zSql[j++] = '?';
7759    }
7760    zSql[j++] = ')';
7761    zSql[j] = 0;
7762    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7763    sqlite3_free(zSql);
7764    if( rc ){
7765      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7766      if (pStmt) sqlite3_finalize(pStmt);
7767      xCloser(sCtx.in);
7768      return 1;
7769    }
7770    needCommit = sqlite3_get_autocommit(p->db);
7771    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7772    do{
7773      int startLine = sCtx.nLine;
7774      for(i=0; i<nCol; i++){
7775        char *z = xRead(&sCtx);
7776        /*
7777        ** Did we reach end-of-file before finding any columns?
7778        ** If so, stop instead of NULL filling the remaining columns.
7779        */
7780        if( z==0 && i==0 ) break;
7781        /*
7782        ** Did we reach end-of-file OR end-of-line before finding any
7783        ** columns in ASCII mode?  If so, stop instead of NULL filling
7784        ** the remaining columns.
7785        */
7786        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7787        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7788        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7789          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7790                          "filling the rest with NULL\n",
7791                          sCtx.zFile, startLine, nCol, i+1);
7792          i += 2;
7793          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7794        }
7795      }
7796      if( sCtx.cTerm==sCtx.cColSep ){
7797        do{
7798          xRead(&sCtx);
7799          i++;
7800        }while( sCtx.cTerm==sCtx.cColSep );
7801        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7802                        "extras ignored\n",
7803                        sCtx.zFile, startLine, nCol, i);
7804      }
7805      if( i>=nCol ){
7806        sqlite3_step(pStmt);
7807        rc = sqlite3_reset(pStmt);
7808        if( rc!=SQLITE_OK ){
7809          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7810                      startLine, sqlite3_errmsg(p->db));
7811        }
7812      }
7813    }while( sCtx.cTerm!=EOF );
7814
7815    xCloser(sCtx.in);
7816    sqlite3_free(sCtx.z);
7817    sqlite3_finalize(pStmt);
7818    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7819  }else
7820
7821#ifndef SQLITE_UNTESTABLE
7822  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7823    char *zSql;
7824    char *zCollist = 0;
7825    sqlite3_stmt *pStmt;
7826    int tnum = 0;
7827    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
7828    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
7829    int i;
7830    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7831      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7832                          "       .imposter off\n");
7833      /* Also allowed, but not documented:
7834      **
7835      **    .imposter TABLE IMPOSTER
7836      **
7837      ** where TABLE is a WITHOUT ROWID table.  In that case, the
7838      ** imposter is another WITHOUT ROWID table with the columns in
7839      ** storage order. */
7840      rc = 1;
7841      goto meta_command_exit;
7842    }
7843    open_db(p, 0);
7844    if( nArg==2 ){
7845      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7846      goto meta_command_exit;
7847    }
7848    zSql = sqlite3_mprintf(
7849      "SELECT rootpage, 0 FROM sqlite_master"
7850      " WHERE name='%q' AND type='index'"
7851      "UNION ALL "
7852      "SELECT rootpage, 1 FROM sqlite_master"
7853      " WHERE name='%q' AND type='table'"
7854      "   AND sql LIKE '%%without%%rowid%%'",
7855      azArg[1], azArg[1]
7856    );
7857    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7858    sqlite3_free(zSql);
7859    if( sqlite3_step(pStmt)==SQLITE_ROW ){
7860      tnum = sqlite3_column_int(pStmt, 0);
7861      isWO = sqlite3_column_int(pStmt, 1);
7862    }
7863    sqlite3_finalize(pStmt);
7864    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7865    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7866    sqlite3_free(zSql);
7867    i = 0;
7868    while( sqlite3_step(pStmt)==SQLITE_ROW ){
7869      char zLabel[20];
7870      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7871      i++;
7872      if( zCol==0 ){
7873        if( sqlite3_column_int(pStmt,1)==-1 ){
7874          zCol = "_ROWID_";
7875        }else{
7876          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7877          zCol = zLabel;
7878        }
7879      }
7880      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
7881        lenPK = (int)strlen(zCollist);
7882      }
7883      if( zCollist==0 ){
7884        zCollist = sqlite3_mprintf("\"%w\"", zCol);
7885      }else{
7886        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7887      }
7888    }
7889    sqlite3_finalize(pStmt);
7890    if( i==0 || tnum==0 ){
7891      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7892      rc = 1;
7893      sqlite3_free(zCollist);
7894      goto meta_command_exit;
7895    }
7896    if( lenPK==0 ) lenPK = 100000;
7897    zSql = sqlite3_mprintf(
7898          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
7899          azArg[2], zCollist, lenPK, zCollist);
7900    sqlite3_free(zCollist);
7901    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7902    if( rc==SQLITE_OK ){
7903      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7904      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7905      if( rc ){
7906        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7907      }else{
7908        utf8_printf(stdout, "%s;\n", zSql);
7909        raw_printf(stdout,
7910          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
7911          azArg[1], isWO ? "table" : "index"
7912        );
7913      }
7914    }else{
7915      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7916      rc = 1;
7917    }
7918    sqlite3_free(zSql);
7919  }else
7920#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7921
7922#ifdef SQLITE_ENABLE_IOTRACE
7923  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7924    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7925    if( iotrace && iotrace!=stdout ) fclose(iotrace);
7926    iotrace = 0;
7927    if( nArg<2 ){
7928      sqlite3IoTrace = 0;
7929    }else if( strcmp(azArg[1], "-")==0 ){
7930      sqlite3IoTrace = iotracePrintf;
7931      iotrace = stdout;
7932    }else{
7933      iotrace = fopen(azArg[1], "w");
7934      if( iotrace==0 ){
7935        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7936        sqlite3IoTrace = 0;
7937        rc = 1;
7938      }else{
7939        sqlite3IoTrace = iotracePrintf;
7940      }
7941    }
7942  }else
7943#endif
7944
7945  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7946    static const struct {
7947       const char *zLimitName;   /* Name of a limit */
7948       int limitCode;            /* Integer code for that limit */
7949    } aLimit[] = {
7950      { "length",                SQLITE_LIMIT_LENGTH                    },
7951      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
7952      { "column",                SQLITE_LIMIT_COLUMN                    },
7953      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
7954      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
7955      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
7956      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
7957      { "attached",              SQLITE_LIMIT_ATTACHED                  },
7958      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
7959      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
7960      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
7961      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
7962    };
7963    int i, n2;
7964    open_db(p, 0);
7965    if( nArg==1 ){
7966      for(i=0; i<ArraySize(aLimit); i++){
7967        printf("%20s %d\n", aLimit[i].zLimitName,
7968               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7969      }
7970    }else if( nArg>3 ){
7971      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7972      rc = 1;
7973      goto meta_command_exit;
7974    }else{
7975      int iLimit = -1;
7976      n2 = strlen30(azArg[1]);
7977      for(i=0; i<ArraySize(aLimit); i++){
7978        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7979          if( iLimit<0 ){
7980            iLimit = i;
7981          }else{
7982            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7983            rc = 1;
7984            goto meta_command_exit;
7985          }
7986        }
7987      }
7988      if( iLimit<0 ){
7989        utf8_printf(stderr, "unknown limit: \"%s\"\n"
7990                        "enter \".limits\" with no arguments for a list.\n",
7991                         azArg[1]);
7992        rc = 1;
7993        goto meta_command_exit;
7994      }
7995      if( nArg==3 ){
7996        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7997                      (int)integerValue(azArg[2]));
7998      }
7999      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8000             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8001    }
8002  }else
8003
8004  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8005    open_db(p, 0);
8006    lintDotCommand(p, azArg, nArg);
8007  }else
8008
8009#ifndef SQLITE_OMIT_LOAD_EXTENSION
8010  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8011    const char *zFile, *zProc;
8012    char *zErrMsg = 0;
8013    if( nArg<2 ){
8014      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8015      rc = 1;
8016      goto meta_command_exit;
8017    }
8018    zFile = azArg[1];
8019    zProc = nArg>=3 ? azArg[2] : 0;
8020    open_db(p, 0);
8021    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8022    if( rc!=SQLITE_OK ){
8023      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8024      sqlite3_free(zErrMsg);
8025      rc = 1;
8026    }
8027  }else
8028#endif
8029
8030  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8031    if( nArg!=2 ){
8032      raw_printf(stderr, "Usage: .log FILENAME\n");
8033      rc = 1;
8034    }else{
8035      const char *zFile = azArg[1];
8036      output_file_close(p->pLog);
8037      p->pLog = output_file_open(zFile, 0);
8038    }
8039  }else
8040
8041  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8042    const char *zMode = nArg>=2 ? azArg[1] : "";
8043    int n2 = strlen30(zMode);
8044    int c2 = zMode[0];
8045    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8046      p->mode = MODE_Line;
8047      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8048    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8049      p->mode = MODE_Column;
8050      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8051    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8052      p->mode = MODE_List;
8053      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8054      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8055    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8056      p->mode = MODE_Html;
8057    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8058      p->mode = MODE_Tcl;
8059      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8060      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8061    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8062      p->mode = MODE_Csv;
8063      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8064      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8065    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8066      p->mode = MODE_List;
8067      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8068    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8069      p->mode = MODE_Insert;
8070      set_table_name(p, nArg>=3 ? azArg[2] : "table");
8071    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8072      p->mode = MODE_Quote;
8073    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8074      p->mode = MODE_Ascii;
8075      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8076      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8077    }else if( nArg==1 ){
8078      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8079    }else{
8080      raw_printf(stderr, "Error: mode should be one of: "
8081         "ascii column csv html insert line list quote tabs tcl\n");
8082      rc = 1;
8083    }
8084    p->cMode = p->mode;
8085  }else
8086
8087  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8088    if( nArg==2 ){
8089      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8090                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8091    }else{
8092      raw_printf(stderr, "Usage: .nullvalue STRING\n");
8093      rc = 1;
8094    }
8095  }else
8096
8097#ifdef SQLITE_DEBUG
8098  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8099    int i;
8100    for(i=1; i<nArg; i++){
8101      const char *z = azArg[i];
8102      if( z[0]=='-' && z[1]=='-' ) z++;
8103      if( strcmp(z,"-repeat")==0 ){
8104        if( i==nArg-1 ){
8105          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8106          rc = 1;
8107        }else{
8108          oomRepeat = (int)integerValue(azArg[++i]);
8109        }
8110      }else if( IsDigit(z[0]) ){
8111        oomCounter = (int)integerValue(azArg[i]);
8112      }else{
8113        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8114        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8115        rc = 1;
8116      }
8117    }
8118    if( rc==0 ){
8119      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8120      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
8121    }
8122  }else
8123#endif /* SQLITE_DEBUG */
8124
8125  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8126    char *zNewFilename;  /* Name of the database file to open */
8127    int iName = 1;       /* Index in azArg[] of the filename */
8128    int newFlag = 0;     /* True to delete file before opening */
8129    /* Close the existing database */
8130    session_close_all(p);
8131    close_db(p->db);
8132    p->db = 0;
8133    p->zDbFilename = 0;
8134    sqlite3_free(p->zFreeOnClose);
8135    p->zFreeOnClose = 0;
8136    p->openMode = SHELL_OPEN_UNSPEC;
8137    p->openFlags = 0;
8138    p->szMax = 0;
8139    /* Check for command-line arguments */
8140    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
8141      const char *z = azArg[iName];
8142      if( optionMatch(z,"new") ){
8143        newFlag = 1;
8144#ifdef SQLITE_HAVE_ZLIB
8145      }else if( optionMatch(z, "zip") ){
8146        p->openMode = SHELL_OPEN_ZIPFILE;
8147#endif
8148      }else if( optionMatch(z, "append") ){
8149        p->openMode = SHELL_OPEN_APPENDVFS;
8150      }else if( optionMatch(z, "readonly") ){
8151        p->openMode = SHELL_OPEN_READONLY;
8152      }else if( optionMatch(z, "nofollow") ){
8153        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8154#ifdef SQLITE_ENABLE_DESERIALIZE
8155      }else if( optionMatch(z, "deserialize") ){
8156        p->openMode = SHELL_OPEN_DESERIALIZE;
8157      }else if( optionMatch(z, "hexdb") ){
8158        p->openMode = SHELL_OPEN_HEXDB;
8159      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8160        p->szMax = integerValue(azArg[++iName]);
8161#endif /* SQLITE_ENABLE_DESERIALIZE */
8162      }else if( z[0]=='-' ){
8163        utf8_printf(stderr, "unknown option: %s\n", z);
8164        rc = 1;
8165        goto meta_command_exit;
8166      }
8167    }
8168    /* If a filename is specified, try to open it first */
8169    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
8170    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8171      if( newFlag ) shellDeleteFile(zNewFilename);
8172      p->zDbFilename = zNewFilename;
8173      open_db(p, OPEN_DB_KEEPALIVE);
8174      if( p->db==0 ){
8175        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8176        sqlite3_free(zNewFilename);
8177      }else{
8178        p->zFreeOnClose = zNewFilename;
8179      }
8180    }
8181    if( p->db==0 ){
8182      /* As a fall-back open a TEMP database */
8183      p->zDbFilename = 0;
8184      open_db(p, 0);
8185    }
8186  }else
8187
8188  if( (c=='o'
8189        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8190   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
8191  ){
8192    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
8193    int bTxtMode = 0;
8194    if( azArg[0][0]=='e' ){
8195      /* Transform the ".excel" command into ".once -x" */
8196      nArg = 2;
8197      azArg[0] = "once";
8198      zFile = azArg[1] = "-x";
8199      n = 4;
8200    }
8201    if( nArg>2 ){
8202      utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
8203      rc = 1;
8204      goto meta_command_exit;
8205    }
8206    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
8207      if( nArg<2 ){
8208        raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
8209        rc = 1;
8210        goto meta_command_exit;
8211      }
8212      p->outCount = 2;
8213    }else{
8214      p->outCount = 0;
8215    }
8216    output_reset(p);
8217    if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
8218#ifndef SQLITE_NOHAVE_SYSTEM
8219    if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
8220      p->doXdgOpen = 1;
8221      outputModePush(p);
8222      if( zFile[1]=='x' ){
8223        newTempFile(p, "csv");
8224        p->mode = MODE_Csv;
8225        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8226        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8227      }else{
8228        newTempFile(p, "txt");
8229        bTxtMode = 1;
8230      }
8231      zFile = p->zTempFile;
8232    }
8233#endif /* SQLITE_NOHAVE_SYSTEM */
8234    if( zFile[0]=='|' ){
8235#ifdef SQLITE_OMIT_POPEN
8236      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8237      rc = 1;
8238      p->out = stdout;
8239#else
8240      p->out = popen(zFile + 1, "w");
8241      if( p->out==0 ){
8242        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8243        p->out = stdout;
8244        rc = 1;
8245      }else{
8246        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8247      }
8248#endif
8249    }else{
8250      p->out = output_file_open(zFile, bTxtMode);
8251      if( p->out==0 ){
8252        if( strcmp(zFile,"off")!=0 ){
8253          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8254        }
8255        p->out = stdout;
8256        rc = 1;
8257      } else {
8258        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8259      }
8260    }
8261  }else
8262
8263  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8264    open_db(p,0);
8265    if( nArg<=1 ) goto parameter_syntax_error;
8266
8267    /* .parameter clear
8268    ** Clear all bind parameters by dropping the TEMP table that holds them.
8269    */
8270    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
8271      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
8272                   0, 0, 0);
8273    }else
8274
8275    /* .parameter list
8276    ** List all bind parameters.
8277    */
8278    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8279      sqlite3_stmt *pStmt = 0;
8280      int rx;
8281      int len = 0;
8282      rx = sqlite3_prepare_v2(p->db,
8283             "SELECT max(length(key)) "
8284             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8285      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8286        len = sqlite3_column_int(pStmt, 0);
8287        if( len>40 ) len = 40;
8288      }
8289      sqlite3_finalize(pStmt);
8290      pStmt = 0;
8291      if( len ){
8292        rx = sqlite3_prepare_v2(p->db,
8293             "SELECT key, quote(value) "
8294             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8295        while( sqlite3_step(pStmt)==SQLITE_ROW ){
8296          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8297                      sqlite3_column_text(pStmt,1));
8298        }
8299        sqlite3_finalize(pStmt);
8300      }
8301    }else
8302
8303    /* .parameter init
8304    ** Make sure the TEMP table used to hold bind parameters exists.
8305    ** Create it if necessary.
8306    */
8307    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8308      bind_table_init(p);
8309    }else
8310
8311    /* .parameter set NAME VALUE
8312    ** Set or reset a bind parameter.  NAME should be the full parameter
8313    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
8314    ** VALUE can be in either SQL literal notation, or if not it will be
8315    ** understood to be a text string.
8316    */
8317    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8318      int rx;
8319      char *zSql;
8320      sqlite3_stmt *pStmt;
8321      const char *zKey = azArg[2];
8322      const char *zValue = azArg[3];
8323      bind_table_init(p);
8324      zSql = sqlite3_mprintf(
8325                  "REPLACE INTO temp.sqlite_parameters(key,value)"
8326                  "VALUES(%Q,%s);", zKey, zValue);
8327      if( zSql==0 ) shell_out_of_memory();
8328      pStmt = 0;
8329      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8330      sqlite3_free(zSql);
8331      if( rx!=SQLITE_OK ){
8332        sqlite3_finalize(pStmt);
8333        pStmt = 0;
8334        zSql = sqlite3_mprintf(
8335                   "REPLACE INTO temp.sqlite_parameters(key,value)"
8336                   "VALUES(%Q,%Q);", zKey, zValue);
8337        if( zSql==0 ) shell_out_of_memory();
8338        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8339        sqlite3_free(zSql);
8340        if( rx!=SQLITE_OK ){
8341          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
8342          sqlite3_finalize(pStmt);
8343          pStmt = 0;
8344          rc = 1;
8345        }
8346      }
8347      sqlite3_step(pStmt);
8348      sqlite3_finalize(pStmt);
8349    }else
8350
8351    /* .parameter unset NAME
8352    ** Remove the NAME binding from the parameter binding table, if it
8353    ** exists.
8354    */
8355    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
8356      char *zSql = sqlite3_mprintf(
8357          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
8358      if( zSql==0 ) shell_out_of_memory();
8359      sqlite3_exec(p->db, zSql, 0, 0, 0);
8360      sqlite3_free(zSql);
8361    }else
8362    /* If no command name matches, show a syntax error */
8363    parameter_syntax_error:
8364    showHelp(p->out, "parameter");
8365  }else
8366
8367  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
8368    int i;
8369    for(i=1; i<nArg; i++){
8370      if( i>1 ) raw_printf(p->out, " ");
8371      utf8_printf(p->out, "%s", azArg[i]);
8372    }
8373    raw_printf(p->out, "\n");
8374  }else
8375
8376#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8377  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
8378    int i;
8379    int nn = 0;
8380    p->flgProgress = 0;
8381    p->mxProgress = 0;
8382    p->nProgress = 0;
8383    for(i=1; i<nArg; i++){
8384      const char *z = azArg[i];
8385      if( z[0]=='-' ){
8386        z++;
8387        if( z[0]=='-' ) z++;
8388        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
8389          p->flgProgress |= SHELL_PROGRESS_QUIET;
8390          continue;
8391        }
8392        if( strcmp(z,"reset")==0 ){
8393          p->flgProgress |= SHELL_PROGRESS_RESET;
8394          continue;
8395        }
8396        if( strcmp(z,"once")==0 ){
8397          p->flgProgress |= SHELL_PROGRESS_ONCE;
8398          continue;
8399        }
8400        if( strcmp(z,"limit")==0 ){
8401          if( i+1>=nArg ){
8402            utf8_printf(stderr, "Error: missing argument on --limit\n");
8403            rc = 1;
8404            goto meta_command_exit;
8405          }else{
8406            p->mxProgress = (int)integerValue(azArg[++i]);
8407          }
8408          continue;
8409        }
8410        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
8411        rc = 1;
8412        goto meta_command_exit;
8413      }else{
8414        nn = (int)integerValue(z);
8415      }
8416    }
8417    open_db(p, 0);
8418    sqlite3_progress_handler(p->db, nn, progress_handler, p);
8419  }else
8420#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
8421
8422  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
8423    if( nArg >= 2) {
8424      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
8425    }
8426    if( nArg >= 3) {
8427      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
8428    }
8429  }else
8430
8431  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
8432    rc = 2;
8433  }else
8434
8435  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
8436    FILE *inSaved = p->in;
8437    int savedLineno = p->lineno;
8438    if( nArg!=2 ){
8439      raw_printf(stderr, "Usage: .read FILE\n");
8440      rc = 1;
8441      goto meta_command_exit;
8442    }
8443    p->in = fopen(azArg[1], "rb");
8444    if( p->in==0 ){
8445      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8446      rc = 1;
8447    }else{
8448      rc = process_input(p);
8449      fclose(p->in);
8450    }
8451    p->in = inSaved;
8452    p->lineno = savedLineno;
8453  }else
8454
8455  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8456    const char *zSrcFile;
8457    const char *zDb;
8458    sqlite3 *pSrc;
8459    sqlite3_backup *pBackup;
8460    int nTimeout = 0;
8461
8462    if( nArg==2 ){
8463      zSrcFile = azArg[1];
8464      zDb = "main";
8465    }else if( nArg==3 ){
8466      zSrcFile = azArg[2];
8467      zDb = azArg[1];
8468    }else{
8469      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
8470      rc = 1;
8471      goto meta_command_exit;
8472    }
8473    rc = sqlite3_open(zSrcFile, &pSrc);
8474    if( rc!=SQLITE_OK ){
8475      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
8476      close_db(pSrc);
8477      return 1;
8478    }
8479    open_db(p, 0);
8480    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
8481    if( pBackup==0 ){
8482      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8483      close_db(pSrc);
8484      return 1;
8485    }
8486    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
8487          || rc==SQLITE_BUSY  ){
8488      if( rc==SQLITE_BUSY ){
8489        if( nTimeout++ >= 3 ) break;
8490        sqlite3_sleep(100);
8491      }
8492    }
8493    sqlite3_backup_finish(pBackup);
8494    if( rc==SQLITE_DONE ){
8495      rc = 0;
8496    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
8497      raw_printf(stderr, "Error: source database is busy\n");
8498      rc = 1;
8499    }else{
8500      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8501      rc = 1;
8502    }
8503    close_db(pSrc);
8504  }else
8505
8506  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
8507    if( nArg==2 ){
8508      p->scanstatsOn = (u8)booleanValue(azArg[1]);
8509#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
8510      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
8511#endif
8512    }else{
8513      raw_printf(stderr, "Usage: .scanstats on|off\n");
8514      rc = 1;
8515    }
8516  }else
8517
8518  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
8519    ShellText sSelect;
8520    ShellState data;
8521    char *zErrMsg = 0;
8522    const char *zDiv = "(";
8523    const char *zName = 0;
8524    int iSchema = 0;
8525    int bDebug = 0;
8526    int ii;
8527
8528    open_db(p, 0);
8529    memcpy(&data, p, sizeof(data));
8530    data.showHeader = 0;
8531    data.cMode = data.mode = MODE_Semi;
8532    initText(&sSelect);
8533    for(ii=1; ii<nArg; ii++){
8534      if( optionMatch(azArg[ii],"indent") ){
8535        data.cMode = data.mode = MODE_Pretty;
8536      }else if( optionMatch(azArg[ii],"debug") ){
8537        bDebug = 1;
8538      }else if( zName==0 ){
8539        zName = azArg[ii];
8540      }else{
8541        raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
8542        rc = 1;
8543        goto meta_command_exit;
8544      }
8545    }
8546    if( zName!=0 ){
8547      int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
8548      if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
8549        char *new_argv[2], *new_colv[2];
8550        new_argv[0] = sqlite3_mprintf(
8551                      "CREATE TABLE %s (\n"
8552                      "  type text,\n"
8553                      "  name text,\n"
8554                      "  tbl_name text,\n"
8555                      "  rootpage integer,\n"
8556                      "  sql text\n"
8557                      ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
8558        new_argv[1] = 0;
8559        new_colv[0] = "sql";
8560        new_colv[1] = 0;
8561        callback(&data, 1, new_argv, new_colv);
8562        sqlite3_free(new_argv[0]);
8563      }
8564    }
8565    if( zDiv ){
8566      sqlite3_stmt *pStmt = 0;
8567      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
8568                              -1, &pStmt, 0);
8569      if( rc ){
8570        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8571        sqlite3_finalize(pStmt);
8572        rc = 1;
8573        goto meta_command_exit;
8574      }
8575      appendText(&sSelect, "SELECT sql FROM", 0);
8576      iSchema = 0;
8577      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8578        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
8579        char zScNum[30];
8580        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
8581        appendText(&sSelect, zDiv, 0);
8582        zDiv = " UNION ALL ";
8583        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
8584        if( sqlite3_stricmp(zDb, "main")!=0 ){
8585          appendText(&sSelect, zDb, '\'');
8586        }else{
8587          appendText(&sSelect, "NULL", 0);
8588        }
8589        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
8590        appendText(&sSelect, zScNum, 0);
8591        appendText(&sSelect, " AS snum, ", 0);
8592        appendText(&sSelect, zDb, '\'');
8593        appendText(&sSelect, " AS sname FROM ", 0);
8594        appendText(&sSelect, zDb, quoteChar(zDb));
8595        appendText(&sSelect, ".sqlite_master", 0);
8596      }
8597      sqlite3_finalize(pStmt);
8598#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
8599      if( zName ){
8600        appendText(&sSelect,
8601           " UNION ALL SELECT shell_module_schema(name),"
8602           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
8603        0);
8604      }
8605#endif
8606      appendText(&sSelect, ") WHERE ", 0);
8607      if( zName ){
8608        char *zQarg = sqlite3_mprintf("%Q", zName);
8609        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8610                    strchr(zName, '[') != 0;
8611        if( strchr(zName, '.') ){
8612          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8613        }else{
8614          appendText(&sSelect, "lower(tbl_name)", 0);
8615        }
8616        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
8617        appendText(&sSelect, zQarg, 0);
8618        if( !bGlob ){
8619          appendText(&sSelect, " ESCAPE '\\' ", 0);
8620        }
8621        appendText(&sSelect, " AND ", 0);
8622        sqlite3_free(zQarg);
8623      }
8624      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8625                           " ORDER BY snum, rowid", 0);
8626      if( bDebug ){
8627        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8628      }else{
8629        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8630      }
8631      freeText(&sSelect);
8632    }
8633    if( zErrMsg ){
8634      utf8_printf(stderr,"Error: %s\n", zErrMsg);
8635      sqlite3_free(zErrMsg);
8636      rc = 1;
8637    }else if( rc != SQLITE_OK ){
8638      raw_printf(stderr,"Error: querying schema information\n");
8639      rc = 1;
8640    }else{
8641      rc = 0;
8642    }
8643  }else
8644
8645#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8646  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8647    sqlite3SelectTrace = (int)integerValue(azArg[1]);
8648  }else
8649#endif
8650
8651#if defined(SQLITE_ENABLE_SESSION)
8652  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8653    OpenSession *pSession = &p->aSession[0];
8654    char **azCmd = &azArg[1];
8655    int iSes = 0;
8656    int nCmd = nArg - 1;
8657    int i;
8658    if( nArg<=1 ) goto session_syntax_error;
8659    open_db(p, 0);
8660    if( nArg>=3 ){
8661      for(iSes=0; iSes<p->nSession; iSes++){
8662        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8663      }
8664      if( iSes<p->nSession ){
8665        pSession = &p->aSession[iSes];
8666        azCmd++;
8667        nCmd--;
8668      }else{
8669        pSession = &p->aSession[0];
8670        iSes = 0;
8671      }
8672    }
8673
8674    /* .session attach TABLE
8675    ** Invoke the sqlite3session_attach() interface to attach a particular
8676    ** table so that it is never filtered.
8677    */
8678    if( strcmp(azCmd[0],"attach")==0 ){
8679      if( nCmd!=2 ) goto session_syntax_error;
8680      if( pSession->p==0 ){
8681        session_not_open:
8682        raw_printf(stderr, "ERROR: No sessions are open\n");
8683      }else{
8684        rc = sqlite3session_attach(pSession->p, azCmd[1]);
8685        if( rc ){
8686          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8687          rc = 0;
8688        }
8689      }
8690    }else
8691
8692    /* .session changeset FILE
8693    ** .session patchset FILE
8694    ** Write a changeset or patchset into a file.  The file is overwritten.
8695    */
8696    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8697      FILE *out = 0;
8698      if( nCmd!=2 ) goto session_syntax_error;
8699      if( pSession->p==0 ) goto session_not_open;
8700      out = fopen(azCmd[1], "wb");
8701      if( out==0 ){
8702        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
8703                    azCmd[1]);
8704      }else{
8705        int szChng;
8706        void *pChng;
8707        if( azCmd[0][0]=='c' ){
8708          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8709        }else{
8710          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8711        }
8712        if( rc ){
8713          printf("Error: error code %d\n", rc);
8714          rc = 0;
8715        }
8716        if( pChng
8717          && fwrite(pChng, szChng, 1, out)!=1 ){
8718          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8719                  szChng);
8720        }
8721        sqlite3_free(pChng);
8722        fclose(out);
8723      }
8724    }else
8725
8726    /* .session close
8727    ** Close the identified session
8728    */
8729    if( strcmp(azCmd[0], "close")==0 ){
8730      if( nCmd!=1 ) goto session_syntax_error;
8731      if( p->nSession ){
8732        session_close(pSession);
8733        p->aSession[iSes] = p->aSession[--p->nSession];
8734      }
8735    }else
8736
8737    /* .session enable ?BOOLEAN?
8738    ** Query or set the enable flag
8739    */
8740    if( strcmp(azCmd[0], "enable")==0 ){
8741      int ii;
8742      if( nCmd>2 ) goto session_syntax_error;
8743      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8744      if( p->nSession ){
8745        ii = sqlite3session_enable(pSession->p, ii);
8746        utf8_printf(p->out, "session %s enable flag = %d\n",
8747                    pSession->zName, ii);
8748      }
8749    }else
8750
8751    /* .session filter GLOB ....
8752    ** Set a list of GLOB patterns of table names to be excluded.
8753    */
8754    if( strcmp(azCmd[0], "filter")==0 ){
8755      int ii, nByte;
8756      if( nCmd<2 ) goto session_syntax_error;
8757      if( p->nSession ){
8758        for(ii=0; ii<pSession->nFilter; ii++){
8759          sqlite3_free(pSession->azFilter[ii]);
8760        }
8761        sqlite3_free(pSession->azFilter);
8762        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8763        pSession->azFilter = sqlite3_malloc( nByte );
8764        if( pSession->azFilter==0 ){
8765          raw_printf(stderr, "Error: out or memory\n");
8766          exit(1);
8767        }
8768        for(ii=1; ii<nCmd; ii++){
8769          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8770        }
8771        pSession->nFilter = ii-1;
8772      }
8773    }else
8774
8775    /* .session indirect ?BOOLEAN?
8776    ** Query or set the indirect flag
8777    */
8778    if( strcmp(azCmd[0], "indirect")==0 ){
8779      int ii;
8780      if( nCmd>2 ) goto session_syntax_error;
8781      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8782      if( p->nSession ){
8783        ii = sqlite3session_indirect(pSession->p, ii);
8784        utf8_printf(p->out, "session %s indirect flag = %d\n",
8785                    pSession->zName, ii);
8786      }
8787    }else
8788
8789    /* .session isempty
8790    ** Determine if the session is empty
8791    */
8792    if( strcmp(azCmd[0], "isempty")==0 ){
8793      int ii;
8794      if( nCmd!=1 ) goto session_syntax_error;
8795      if( p->nSession ){
8796        ii = sqlite3session_isempty(pSession->p);
8797        utf8_printf(p->out, "session %s isempty flag = %d\n",
8798                    pSession->zName, ii);
8799      }
8800    }else
8801
8802    /* .session list
8803    ** List all currently open sessions
8804    */
8805    if( strcmp(azCmd[0],"list")==0 ){
8806      for(i=0; i<p->nSession; i++){
8807        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8808      }
8809    }else
8810
8811    /* .session open DB NAME
8812    ** Open a new session called NAME on the attached database DB.
8813    ** DB is normally "main".
8814    */
8815    if( strcmp(azCmd[0],"open")==0 ){
8816      char *zName;
8817      if( nCmd!=3 ) goto session_syntax_error;
8818      zName = azCmd[2];
8819      if( zName[0]==0 ) goto session_syntax_error;
8820      for(i=0; i<p->nSession; i++){
8821        if( strcmp(p->aSession[i].zName,zName)==0 ){
8822          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8823          goto meta_command_exit;
8824        }
8825      }
8826      if( p->nSession>=ArraySize(p->aSession) ){
8827        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8828        goto meta_command_exit;
8829      }
8830      pSession = &p->aSession[p->nSession];
8831      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8832      if( rc ){
8833        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8834        rc = 0;
8835        goto meta_command_exit;
8836      }
8837      pSession->nFilter = 0;
8838      sqlite3session_table_filter(pSession->p, session_filter, pSession);
8839      p->nSession++;
8840      pSession->zName = sqlite3_mprintf("%s", zName);
8841    }else
8842    /* If no command name matches, show a syntax error */
8843    session_syntax_error:
8844    showHelp(p->out, "session");
8845  }else
8846#endif
8847
8848#ifdef SQLITE_DEBUG
8849  /* Undocumented commands for internal testing.  Subject to change
8850  ** without notice. */
8851  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8852    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8853      int i, v;
8854      for(i=1; i<nArg; i++){
8855        v = booleanValue(azArg[i]);
8856        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8857      }
8858    }
8859    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8860      int i; sqlite3_int64 v;
8861      for(i=1; i<nArg; i++){
8862        char zBuf[200];
8863        v = integerValue(azArg[i]);
8864        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8865        utf8_printf(p->out, "%s", zBuf);
8866      }
8867    }
8868  }else
8869#endif
8870
8871  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8872    int bIsInit = 0;         /* True to initialize the SELFTEST table */
8873    int bVerbose = 0;        /* Verbose output */
8874    int bSelftestExists;     /* True if SELFTEST already exists */
8875    int i, k;                /* Loop counters */
8876    int nTest = 0;           /* Number of tests runs */
8877    int nErr = 0;            /* Number of errors seen */
8878    ShellText str;           /* Answer for a query */
8879    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8880
8881    open_db(p,0);
8882    for(i=1; i<nArg; i++){
8883      const char *z = azArg[i];
8884      if( z[0]=='-' && z[1]=='-' ) z++;
8885      if( strcmp(z,"-init")==0 ){
8886        bIsInit = 1;
8887      }else
8888      if( strcmp(z,"-v")==0 ){
8889        bVerbose++;
8890      }else
8891      {
8892        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8893                    azArg[i], azArg[0]);
8894        raw_printf(stderr, "Should be one of: --init -v\n");
8895        rc = 1;
8896        goto meta_command_exit;
8897      }
8898    }
8899    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8900           != SQLITE_OK ){
8901      bSelftestExists = 0;
8902    }else{
8903      bSelftestExists = 1;
8904    }
8905    if( bIsInit ){
8906      createSelftestTable(p);
8907      bSelftestExists = 1;
8908    }
8909    initText(&str);
8910    appendText(&str, "x", 0);
8911    for(k=bSelftestExists; k>=0; k--){
8912      if( k==1 ){
8913        rc = sqlite3_prepare_v2(p->db,
8914            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8915            -1, &pStmt, 0);
8916      }else{
8917        rc = sqlite3_prepare_v2(p->db,
8918          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8919          "      (1,'run','PRAGMA integrity_check','ok')",
8920          -1, &pStmt, 0);
8921      }
8922      if( rc ){
8923        raw_printf(stderr, "Error querying the selftest table\n");
8924        rc = 1;
8925        sqlite3_finalize(pStmt);
8926        goto meta_command_exit;
8927      }
8928      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8929        int tno = sqlite3_column_int(pStmt, 0);
8930        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8931        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8932        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8933
8934        k = 0;
8935        if( bVerbose>0 ){
8936          char *zQuote = sqlite3_mprintf("%q", zSql);
8937          printf("%d: %s %s\n", tno, zOp, zSql);
8938          sqlite3_free(zQuote);
8939        }
8940        if( strcmp(zOp,"memo")==0 ){
8941          utf8_printf(p->out, "%s\n", zSql);
8942        }else
8943        if( strcmp(zOp,"run")==0 ){
8944          char *zErrMsg = 0;
8945          str.n = 0;
8946          str.z[0] = 0;
8947          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8948          nTest++;
8949          if( bVerbose ){
8950            utf8_printf(p->out, "Result: %s\n", str.z);
8951          }
8952          if( rc || zErrMsg ){
8953            nErr++;
8954            rc = 1;
8955            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8956            sqlite3_free(zErrMsg);
8957          }else if( strcmp(zAns,str.z)!=0 ){
8958            nErr++;
8959            rc = 1;
8960            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8961            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
8962          }
8963        }else
8964        {
8965          utf8_printf(stderr,
8966            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8967          rc = 1;
8968          break;
8969        }
8970      } /* End loop over rows of content from SELFTEST */
8971      sqlite3_finalize(pStmt);
8972    } /* End loop over k */
8973    freeText(&str);
8974    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8975  }else
8976
8977  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8978    if( nArg<2 || nArg>3 ){
8979      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8980      rc = 1;
8981    }
8982    if( nArg>=2 ){
8983      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8984                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8985    }
8986    if( nArg>=3 ){
8987      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8988                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8989    }
8990  }else
8991
8992  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8993    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
8994    int i;                   /* Loop counter */
8995    int bSchema = 0;         /* Also hash the schema */
8996    int bSeparate = 0;       /* Hash each table separately */
8997    int iSize = 224;         /* Hash algorithm to use */
8998    int bDebug = 0;          /* Only show the query that would have run */
8999    sqlite3_stmt *pStmt;     /* For querying tables names */
9000    char *zSql;              /* SQL to be run */
9001    char *zSep;              /* Separator */
9002    ShellText sSql;          /* Complete SQL for the query to run the hash */
9003    ShellText sQuery;        /* Set of queries used to read all content */
9004    open_db(p, 0);
9005    for(i=1; i<nArg; i++){
9006      const char *z = azArg[i];
9007      if( z[0]=='-' ){
9008        z++;
9009        if( z[0]=='-' ) z++;
9010        if( strcmp(z,"schema")==0 ){
9011          bSchema = 1;
9012        }else
9013        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9014         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9015        ){
9016          iSize = atoi(&z[5]);
9017        }else
9018        if( strcmp(z,"debug")==0 ){
9019          bDebug = 1;
9020        }else
9021        {
9022          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9023                      azArg[i], azArg[0]);
9024          showHelp(p->out, azArg[0]);
9025          rc = 1;
9026          goto meta_command_exit;
9027        }
9028      }else if( zLike ){
9029        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9030        rc = 1;
9031        goto meta_command_exit;
9032      }else{
9033        zLike = z;
9034        bSeparate = 1;
9035        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9036      }
9037    }
9038    if( bSchema ){
9039      zSql = "SELECT lower(name) FROM sqlite_master"
9040             " WHERE type='table' AND coalesce(rootpage,0)>1"
9041             " UNION ALL SELECT 'sqlite_master'"
9042             " ORDER BY 1 collate nocase";
9043    }else{
9044      zSql = "SELECT lower(name) FROM sqlite_master"
9045             " WHERE type='table' AND coalesce(rootpage,0)>1"
9046             " AND name NOT LIKE 'sqlite_%'"
9047             " ORDER BY 1 collate nocase";
9048    }
9049    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9050    initText(&sQuery);
9051    initText(&sSql);
9052    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9053    zSep = "VALUES(";
9054    while( SQLITE_ROW==sqlite3_step(pStmt) ){
9055      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
9056      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
9057      if( strncmp(zTab, "sqlite_",7)!=0 ){
9058        appendText(&sQuery,"SELECT * FROM ", 0);
9059        appendText(&sQuery,zTab,'"');
9060        appendText(&sQuery," NOT INDEXED;", 0);
9061      }else if( strcmp(zTab, "sqlite_master")==0 ){
9062        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
9063                           " ORDER BY name;", 0);
9064      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
9065        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
9066                           " ORDER BY name;", 0);
9067      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
9068        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
9069                           " ORDER BY tbl,idx;", 0);
9070      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
9071        appendText(&sQuery, "SELECT * FROM ", 0);
9072        appendText(&sQuery, zTab, 0);
9073        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
9074      }
9075      appendText(&sSql, zSep, 0);
9076      appendText(&sSql, sQuery.z, '\'');
9077      sQuery.n = 0;
9078      appendText(&sSql, ",", 0);
9079      appendText(&sSql, zTab, '\'');
9080      zSep = "),(";
9081    }
9082    sqlite3_finalize(pStmt);
9083    if( bSeparate ){
9084      zSql = sqlite3_mprintf(
9085          "%s))"
9086          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
9087          "   FROM [sha3sum$query]",
9088          sSql.z, iSize);
9089    }else{
9090      zSql = sqlite3_mprintf(
9091          "%s))"
9092          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
9093          "   FROM [sha3sum$query]",
9094          sSql.z, iSize);
9095    }
9096    freeText(&sQuery);
9097    freeText(&sSql);
9098    if( bDebug ){
9099      utf8_printf(p->out, "%s\n", zSql);
9100    }else{
9101      shell_exec(p, zSql, 0);
9102    }
9103    sqlite3_free(zSql);
9104  }else
9105
9106#ifndef SQLITE_NOHAVE_SYSTEM
9107  if( c=='s'
9108   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
9109  ){
9110    char *zCmd;
9111    int i, x;
9112    if( nArg<2 ){
9113      raw_printf(stderr, "Usage: .system COMMAND\n");
9114      rc = 1;
9115      goto meta_command_exit;
9116    }
9117    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
9118    for(i=2; i<nArg; i++){
9119      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
9120                             zCmd, azArg[i]);
9121    }
9122    x = system(zCmd);
9123    sqlite3_free(zCmd);
9124    if( x ) raw_printf(stderr, "System command returns %d\n", x);
9125  }else
9126#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
9127
9128  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
9129    static const char *azBool[] = { "off", "on", "trigger", "full"};
9130    int i;
9131    if( nArg!=1 ){
9132      raw_printf(stderr, "Usage: .show\n");
9133      rc = 1;
9134      goto meta_command_exit;
9135    }
9136    utf8_printf(p->out, "%12.12s: %s\n","echo",
9137                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
9138    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
9139    utf8_printf(p->out, "%12.12s: %s\n","explain",
9140         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
9141    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
9142    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
9143    utf8_printf(p->out, "%12.12s: ", "nullvalue");
9144      output_c_string(p->out, p->nullValue);
9145      raw_printf(p->out, "\n");
9146    utf8_printf(p->out,"%12.12s: %s\n","output",
9147            strlen30(p->outfile) ? p->outfile : "stdout");
9148    utf8_printf(p->out,"%12.12s: ", "colseparator");
9149      output_c_string(p->out, p->colSeparator);
9150      raw_printf(p->out, "\n");
9151    utf8_printf(p->out,"%12.12s: ", "rowseparator");
9152      output_c_string(p->out, p->rowSeparator);
9153      raw_printf(p->out, "\n");
9154    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
9155    utf8_printf(p->out, "%12.12s: ", "width");
9156    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
9157      raw_printf(p->out, "%d ", p->colWidth[i]);
9158    }
9159    raw_printf(p->out, "\n");
9160    utf8_printf(p->out, "%12.12s: %s\n", "filename",
9161                p->zDbFilename ? p->zDbFilename : "");
9162  }else
9163
9164  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9165    if( nArg==2 ){
9166      p->statsOn = (u8)booleanValue(azArg[1]);
9167    }else if( nArg==1 ){
9168      display_stats(p->db, p, 0);
9169    }else{
9170      raw_printf(stderr, "Usage: .stats ?on|off?\n");
9171      rc = 1;
9172    }
9173  }else
9174
9175  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9176   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9177                 || strncmp(azArg[0], "indexes", n)==0) )
9178  ){
9179    sqlite3_stmt *pStmt;
9180    char **azResult;
9181    int nRow, nAlloc;
9182    int ii;
9183    ShellText s;
9184    initText(&s);
9185    open_db(p, 0);
9186    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
9187    if( rc ){
9188      sqlite3_finalize(pStmt);
9189      return shellDatabaseError(p->db);
9190    }
9191
9192    if( nArg>2 && c=='i' ){
9193      /* It is an historical accident that the .indexes command shows an error
9194      ** when called with the wrong number of arguments whereas the .tables
9195      ** command does not. */
9196      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9197      rc = 1;
9198      sqlite3_finalize(pStmt);
9199      goto meta_command_exit;
9200    }
9201    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9202      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9203      if( zDbName==0 ) continue;
9204      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9205      if( sqlite3_stricmp(zDbName, "main")==0 ){
9206        appendText(&s, "SELECT name FROM ", 0);
9207      }else{
9208        appendText(&s, "SELECT ", 0);
9209        appendText(&s, zDbName, '\'');
9210        appendText(&s, "||'.'||name FROM ", 0);
9211      }
9212      appendText(&s, zDbName, '"');
9213      appendText(&s, ".sqlite_master ", 0);
9214      if( c=='t' ){
9215        appendText(&s," WHERE type IN ('table','view')"
9216                      "   AND name NOT LIKE 'sqlite_%'"
9217                      "   AND name LIKE ?1", 0);
9218      }else{
9219        appendText(&s," WHERE type='index'"
9220                      "   AND tbl_name LIKE ?1", 0);
9221      }
9222    }
9223    rc = sqlite3_finalize(pStmt);
9224    appendText(&s, " ORDER BY 1", 0);
9225    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9226    freeText(&s);
9227    if( rc ) return shellDatabaseError(p->db);
9228
9229    /* Run the SQL statement prepared by the above block. Store the results
9230    ** as an array of nul-terminated strings in azResult[].  */
9231    nRow = nAlloc = 0;
9232    azResult = 0;
9233    if( nArg>1 ){
9234      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9235    }else{
9236      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9237    }
9238    while( sqlite3_step(pStmt)==SQLITE_ROW ){
9239      if( nRow>=nAlloc ){
9240        char **azNew;
9241        int n2 = nAlloc*2 + 10;
9242        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
9243        if( azNew==0 ) shell_out_of_memory();
9244        nAlloc = n2;
9245        azResult = azNew;
9246      }
9247      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
9248      if( 0==azResult[nRow] ) shell_out_of_memory();
9249      nRow++;
9250    }
9251    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9252      rc = shellDatabaseError(p->db);
9253    }
9254
9255    /* Pretty-print the contents of array azResult[] to the output */
9256    if( rc==0 && nRow>0 ){
9257      int len, maxlen = 0;
9258      int i, j;
9259      int nPrintCol, nPrintRow;
9260      for(i=0; i<nRow; i++){
9261        len = strlen30(azResult[i]);
9262        if( len>maxlen ) maxlen = len;
9263      }
9264      nPrintCol = 80/(maxlen+2);
9265      if( nPrintCol<1 ) nPrintCol = 1;
9266      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9267      for(i=0; i<nPrintRow; i++){
9268        for(j=i; j<nRow; j+=nPrintRow){
9269          char *zSp = j<nPrintRow ? "" : "  ";
9270          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9271                      azResult[j] ? azResult[j]:"");
9272        }
9273        raw_printf(p->out, "\n");
9274      }
9275    }
9276
9277    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9278    sqlite3_free(azResult);
9279  }else
9280
9281  /* Begin redirecting output to the file "testcase-out.txt" */
9282  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
9283    output_reset(p);
9284    p->out = output_file_open("testcase-out.txt", 0);
9285    if( p->out==0 ){
9286      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
9287    }
9288    if( nArg>=2 ){
9289      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
9290    }else{
9291      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
9292    }
9293  }else
9294
9295#ifndef SQLITE_UNTESTABLE
9296  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
9297    static const struct {
9298       const char *zCtrlName;   /* Name of a test-control option */
9299       int ctrlCode;            /* Integer code for that option */
9300       const char *zUsage;      /* Usage notes */
9301    } aCtrl[] = {
9302      { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
9303      { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
9304    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
9305    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
9306      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
9307      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
9308    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
9309      { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
9310      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
9311      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
9312      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
9313      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
9314#ifdef YYCOVERAGE
9315      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
9316#endif
9317      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
9318      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
9319      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
9320      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
9321      { "reserve",            SQLITE_TESTCTRL_RESERVE,      "BYTES-OF-RESERVE"},
9322    };
9323    int testctrl = -1;
9324    int iCtrl = -1;
9325    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
9326    int isOk = 0;
9327    int i, n2;
9328    const char *zCmd = 0;
9329
9330    open_db(p, 0);
9331    zCmd = nArg>=2 ? azArg[1] : "help";
9332
9333    /* The argument can optionally begin with "-" or "--" */
9334    if( zCmd[0]=='-' && zCmd[1] ){
9335      zCmd++;
9336      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
9337    }
9338
9339    /* --help lists all test-controls */
9340    if( strcmp(zCmd,"help")==0 ){
9341      utf8_printf(p->out, "Available test-controls:\n");
9342      for(i=0; i<ArraySize(aCtrl); i++){
9343        utf8_printf(p->out, "  .testctrl %s %s\n",
9344                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
9345      }
9346      rc = 1;
9347      goto meta_command_exit;
9348    }
9349
9350    /* convert testctrl text option to value. allow any unique prefix
9351    ** of the option name, or a numerical value. */
9352    n2 = strlen30(zCmd);
9353    for(i=0; i<ArraySize(aCtrl); i++){
9354      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
9355        if( testctrl<0 ){
9356          testctrl = aCtrl[i].ctrlCode;
9357          iCtrl = i;
9358        }else{
9359          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
9360                              "Use \".testctrl --help\" for help\n", zCmd);
9361          rc = 1;
9362          goto meta_command_exit;
9363        }
9364      }
9365    }
9366    if( testctrl<0 ){
9367      utf8_printf(stderr,"Error: unknown test-control: %s\n"
9368                         "Use \".testctrl --help\" for help\n", zCmd);
9369    }else{
9370      switch(testctrl){
9371
9372        /* sqlite3_test_control(int, db, int) */
9373        case SQLITE_TESTCTRL_OPTIMIZATIONS:
9374        case SQLITE_TESTCTRL_RESERVE:
9375          if( nArg==3 ){
9376            int opt = (int)strtol(azArg[2], 0, 0);
9377            rc2 = sqlite3_test_control(testctrl, p->db, opt);
9378            isOk = 3;
9379          }
9380          break;
9381
9382        /* sqlite3_test_control(int) */
9383        case SQLITE_TESTCTRL_PRNG_SAVE:
9384        case SQLITE_TESTCTRL_PRNG_RESTORE:
9385        case SQLITE_TESTCTRL_PRNG_RESET:
9386        case SQLITE_TESTCTRL_BYTEORDER:
9387          if( nArg==2 ){
9388            rc2 = sqlite3_test_control(testctrl);
9389            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
9390          }
9391          break;
9392
9393        /* sqlite3_test_control(int, uint) */
9394        case SQLITE_TESTCTRL_PENDING_BYTE:
9395          if( nArg==3 ){
9396            unsigned int opt = (unsigned int)integerValue(azArg[2]);
9397            rc2 = sqlite3_test_control(testctrl, opt);
9398            isOk = 3;
9399          }
9400          break;
9401
9402        /* sqlite3_test_control(int, int, sqlite3*) */
9403        case SQLITE_TESTCTRL_PRNG_SEED:
9404          if( nArg==3 || nArg==4 ){
9405            int ii = (int)integerValue(azArg[2]);
9406            sqlite3 *db;
9407            if( ii==0 && strcmp(azArg[2],"random")==0 ){
9408              sqlite3_randomness(sizeof(ii),&ii);
9409              printf("-- random seed: %d\n", ii);
9410            }
9411            if( nArg==3 ){
9412              db = 0;
9413            }else{
9414              db = p->db;
9415              /* Make sure the schema has been loaded */
9416              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
9417            }
9418            rc2 = sqlite3_test_control(testctrl, ii, db);
9419            isOk = 3;
9420          }
9421          break;
9422
9423        /* sqlite3_test_control(int, int) */
9424        case SQLITE_TESTCTRL_ASSERT:
9425        case SQLITE_TESTCTRL_ALWAYS:
9426          if( nArg==3 ){
9427            int opt = booleanValue(azArg[2]);
9428            rc2 = sqlite3_test_control(testctrl, opt);
9429            isOk = 1;
9430          }
9431          break;
9432
9433        /* sqlite3_test_control(int, int) */
9434        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
9435        case SQLITE_TESTCTRL_NEVER_CORRUPT:
9436          if( nArg==3 ){
9437            int opt = booleanValue(azArg[2]);
9438            rc2 = sqlite3_test_control(testctrl, opt);
9439            isOk = 3;
9440          }
9441          break;
9442
9443        /* sqlite3_test_control(sqlite3*) */
9444        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
9445          rc2 = sqlite3_test_control(testctrl, p->db);
9446          isOk = 3;
9447          break;
9448
9449        case SQLITE_TESTCTRL_IMPOSTER:
9450          if( nArg==5 ){
9451            rc2 = sqlite3_test_control(testctrl, p->db,
9452                          azArg[2],
9453                          integerValue(azArg[3]),
9454                          integerValue(azArg[4]));
9455            isOk = 3;
9456          }
9457          break;
9458
9459#ifdef YYCOVERAGE
9460        case SQLITE_TESTCTRL_PARSER_COVERAGE:
9461          if( nArg==2 ){
9462            sqlite3_test_control(testctrl, p->out);
9463            isOk = 3;
9464          }
9465#endif
9466      }
9467    }
9468    if( isOk==0 && iCtrl>=0 ){
9469      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
9470      rc = 1;
9471    }else if( isOk==1 ){
9472      raw_printf(p->out, "%d\n", rc2);
9473    }else if( isOk==2 ){
9474      raw_printf(p->out, "0x%08x\n", rc2);
9475    }
9476  }else
9477#endif /* !defined(SQLITE_UNTESTABLE) */
9478
9479  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
9480    open_db(p, 0);
9481    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
9482  }else
9483
9484  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
9485    if( nArg==2 ){
9486      enableTimer = booleanValue(azArg[1]);
9487      if( enableTimer && !HAS_TIMER ){
9488        raw_printf(stderr, "Error: timer not available on this system.\n");
9489        enableTimer = 0;
9490      }
9491    }else{
9492      raw_printf(stderr, "Usage: .timer on|off\n");
9493      rc = 1;
9494    }
9495  }else
9496
9497#ifndef SQLITE_OMIT_TRACE
9498  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
9499    int mType = 0;
9500    int jj;
9501    open_db(p, 0);
9502    for(jj=1; jj<nArg; jj++){
9503      const char *z = azArg[jj];
9504      if( z[0]=='-' ){
9505        if( optionMatch(z, "expanded") ){
9506          p->eTraceType = SHELL_TRACE_EXPANDED;
9507        }
9508#ifdef SQLITE_ENABLE_NORMALIZE
9509        else if( optionMatch(z, "normalized") ){
9510          p->eTraceType = SHELL_TRACE_NORMALIZED;
9511        }
9512#endif
9513        else if( optionMatch(z, "plain") ){
9514          p->eTraceType = SHELL_TRACE_PLAIN;
9515        }
9516        else if( optionMatch(z, "profile") ){
9517          mType |= SQLITE_TRACE_PROFILE;
9518        }
9519        else if( optionMatch(z, "row") ){
9520          mType |= SQLITE_TRACE_ROW;
9521        }
9522        else if( optionMatch(z, "stmt") ){
9523          mType |= SQLITE_TRACE_STMT;
9524        }
9525        else if( optionMatch(z, "close") ){
9526          mType |= SQLITE_TRACE_CLOSE;
9527        }
9528        else {
9529          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
9530          rc = 1;
9531          goto meta_command_exit;
9532        }
9533      }else{
9534        output_file_close(p->traceOut);
9535        p->traceOut = output_file_open(azArg[1], 0);
9536      }
9537    }
9538    if( p->traceOut==0 ){
9539      sqlite3_trace_v2(p->db, 0, 0, 0);
9540    }else{
9541      if( mType==0 ) mType = SQLITE_TRACE_STMT;
9542      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
9543    }
9544  }else
9545#endif /* !defined(SQLITE_OMIT_TRACE) */
9546
9547#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
9548  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
9549    int ii;
9550    int lenOpt;
9551    char *zOpt;
9552    if( nArg<2 ){
9553      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
9554      rc = 1;
9555      goto meta_command_exit;
9556    }
9557    open_db(p, 0);
9558    zOpt = azArg[1];
9559    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
9560    lenOpt = (int)strlen(zOpt);
9561    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
9562      assert( azArg[nArg]==0 );
9563      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
9564    }else{
9565      for(ii=1; ii<nArg; ii++){
9566        sqlite3_create_module(p->db, azArg[ii], 0, 0);
9567      }
9568    }
9569  }else
9570#endif
9571
9572#if SQLITE_USER_AUTHENTICATION
9573  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
9574    if( nArg<2 ){
9575      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
9576      rc = 1;
9577      goto meta_command_exit;
9578    }
9579    open_db(p, 0);
9580    if( strcmp(azArg[1],"login")==0 ){
9581      if( nArg!=4 ){
9582        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
9583        rc = 1;
9584        goto meta_command_exit;
9585      }
9586      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
9587                                     strlen30(azArg[3]));
9588      if( rc ){
9589        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
9590        rc = 1;
9591      }
9592    }else if( strcmp(azArg[1],"add")==0 ){
9593      if( nArg!=5 ){
9594        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
9595        rc = 1;
9596        goto meta_command_exit;
9597      }
9598      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
9599                            booleanValue(azArg[4]));
9600      if( rc ){
9601        raw_printf(stderr, "User-Add failed: %d\n", rc);
9602        rc = 1;
9603      }
9604    }else if( strcmp(azArg[1],"edit")==0 ){
9605      if( nArg!=5 ){
9606        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
9607        rc = 1;
9608        goto meta_command_exit;
9609      }
9610      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
9611                              booleanValue(azArg[4]));
9612      if( rc ){
9613        raw_printf(stderr, "User-Edit failed: %d\n", rc);
9614        rc = 1;
9615      }
9616    }else if( strcmp(azArg[1],"delete")==0 ){
9617      if( nArg!=3 ){
9618        raw_printf(stderr, "Usage: .user delete USER\n");
9619        rc = 1;
9620        goto meta_command_exit;
9621      }
9622      rc = sqlite3_user_delete(p->db, azArg[2]);
9623      if( rc ){
9624        raw_printf(stderr, "User-Delete failed: %d\n", rc);
9625        rc = 1;
9626      }
9627    }else{
9628      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
9629      rc = 1;
9630      goto meta_command_exit;
9631    }
9632  }else
9633#endif /* SQLITE_USER_AUTHENTICATION */
9634
9635  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
9636    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
9637        sqlite3_libversion(), sqlite3_sourceid());
9638#if SQLITE_HAVE_ZLIB
9639    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
9640#endif
9641#define CTIMEOPT_VAL_(opt) #opt
9642#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
9643#if defined(__clang__) && defined(__clang_major__)
9644    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
9645                    CTIMEOPT_VAL(__clang_minor__) "."
9646                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
9647#elif defined(_MSC_VER)
9648    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
9649#elif defined(__GNUC__) && defined(__VERSION__)
9650    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9651#endif
9652  }else
9653
9654  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9655    const char *zDbName = nArg==2 ? azArg[1] : "main";
9656    sqlite3_vfs *pVfs = 0;
9657    if( p->db ){
9658      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9659      if( pVfs ){
9660        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
9661        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
9662        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
9663        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9664      }
9665    }
9666  }else
9667
9668  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9669    sqlite3_vfs *pVfs;
9670    sqlite3_vfs *pCurrent = 0;
9671    if( p->db ){
9672      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9673    }
9674    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9675      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
9676           pVfs==pCurrent ? "  <--- CURRENT" : "");
9677      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
9678      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
9679      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9680      if( pVfs->pNext ){
9681        raw_printf(p->out, "-----------------------------------\n");
9682      }
9683    }
9684  }else
9685
9686  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9687    const char *zDbName = nArg==2 ? azArg[1] : "main";
9688    char *zVfsName = 0;
9689    if( p->db ){
9690      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9691      if( zVfsName ){
9692        utf8_printf(p->out, "%s\n", zVfsName);
9693        sqlite3_free(zVfsName);
9694      }
9695    }
9696  }else
9697
9698#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9699  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9700    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9701  }else
9702#endif
9703
9704  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9705    int j;
9706    assert( nArg<=ArraySize(azArg) );
9707    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9708      p->colWidth[j-1] = (int)integerValue(azArg[j]);
9709    }
9710  }else
9711
9712  {
9713    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9714      " \"%s\". Enter \".help\" for help\n", azArg[0]);
9715    rc = 1;
9716  }
9717
9718meta_command_exit:
9719  if( p->outCount ){
9720    p->outCount--;
9721    if( p->outCount==0 ) output_reset(p);
9722  }
9723  return rc;
9724}
9725
9726/*
9727** Return TRUE if a semicolon occurs anywhere in the first N characters
9728** of string z[].
9729*/
9730static int line_contains_semicolon(const char *z, int N){
9731  int i;
9732  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
9733  return 0;
9734}
9735
9736/*
9737** Test to see if a line consists entirely of whitespace.
9738*/
9739static int _all_whitespace(const char *z){
9740  for(; *z; z++){
9741    if( IsSpace(z[0]) ) continue;
9742    if( *z=='/' && z[1]=='*' ){
9743      z += 2;
9744      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9745      if( *z==0 ) return 0;
9746      z++;
9747      continue;
9748    }
9749    if( *z=='-' && z[1]=='-' ){
9750      z += 2;
9751      while( *z && *z!='\n' ){ z++; }
9752      if( *z==0 ) return 1;
9753      continue;
9754    }
9755    return 0;
9756  }
9757  return 1;
9758}
9759
9760/*
9761** Return TRUE if the line typed in is an SQL command terminator other
9762** than a semi-colon.  The SQL Server style "go" command is understood
9763** as is the Oracle "/".
9764*/
9765static int line_is_command_terminator(const char *zLine){
9766  while( IsSpace(zLine[0]) ){ zLine++; };
9767  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9768    return 1;  /* Oracle */
9769  }
9770  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9771         && _all_whitespace(&zLine[2]) ){
9772    return 1;  /* SQL Server */
9773  }
9774  return 0;
9775}
9776
9777/*
9778** We need a default sqlite3_complete() implementation to use in case
9779** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
9780** any arbitrary text is a complete SQL statement.  This is not very
9781** user-friendly, but it does seem to work.
9782*/
9783#ifdef SQLITE_OMIT_COMPLETE
9784#define sqlite3_complete(x) 1
9785#endif
9786
9787/*
9788** Return true if zSql is a complete SQL statement.  Return false if it
9789** ends in the middle of a string literal or C-style comment.
9790*/
9791static int line_is_complete(char *zSql, int nSql){
9792  int rc;
9793  if( zSql==0 ) return 1;
9794  zSql[nSql] = ';';
9795  zSql[nSql+1] = 0;
9796  rc = sqlite3_complete(zSql);
9797  zSql[nSql] = 0;
9798  return rc;
9799}
9800
9801/*
9802** Run a single line of SQL.  Return the number of errors.
9803*/
9804static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9805  int rc;
9806  char *zErrMsg = 0;
9807
9808  open_db(p, 0);
9809  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
9810  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
9811  BEGIN_TIMER;
9812  rc = shell_exec(p, zSql, &zErrMsg);
9813  END_TIMER;
9814  if( rc || zErrMsg ){
9815    char zPrefix[100];
9816    if( in!=0 || !stdin_is_interactive ){
9817      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9818                       "Error: near line %d:", startline);
9819    }else{
9820      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9821    }
9822    if( zErrMsg!=0 ){
9823      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9824      sqlite3_free(zErrMsg);
9825      zErrMsg = 0;
9826    }else{
9827      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9828    }
9829    return 1;
9830  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9831    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
9832            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9833  }
9834  return 0;
9835}
9836
9837
9838/*
9839** Read input from *in and process it.  If *in==0 then input
9840** is interactive - the user is typing it it.  Otherwise, input
9841** is coming from a file or device.  A prompt is issued and history
9842** is saved only if input is interactive.  An interrupt signal will
9843** cause this routine to exit immediately, unless input is interactive.
9844**
9845** Return the number of errors.
9846*/
9847static int process_input(ShellState *p){
9848  char *zLine = 0;          /* A single input line */
9849  char *zSql = 0;           /* Accumulated SQL text */
9850  int nLine;                /* Length of current line */
9851  int nSql = 0;             /* Bytes of zSql[] used */
9852  int nAlloc = 0;           /* Allocated zSql[] space */
9853  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
9854  int rc;                   /* Error code */
9855  int errCnt = 0;           /* Number of errors seen */
9856  int startline = 0;        /* Line number for start of current input */
9857
9858  p->lineno = 0;
9859  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
9860    fflush(p->out);
9861    zLine = one_input_line(p->in, zLine, nSql>0);
9862    if( zLine==0 ){
9863      /* End of input */
9864      if( p->in==0 && stdin_is_interactive ) printf("\n");
9865      break;
9866    }
9867    if( seenInterrupt ){
9868      if( p->in!=0 ) break;
9869      seenInterrupt = 0;
9870    }
9871    p->lineno++;
9872    if( nSql==0 && _all_whitespace(zLine) ){
9873      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9874      continue;
9875    }
9876    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
9877      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9878      if( zLine[0]=='.' ){
9879        rc = do_meta_command(zLine, p);
9880        if( rc==2 ){ /* exit requested */
9881          break;
9882        }else if( rc ){
9883          errCnt++;
9884        }
9885      }
9886      continue;
9887    }
9888    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9889      memcpy(zLine,";",2);
9890    }
9891    nLine = strlen30(zLine);
9892    if( nSql+nLine+2>=nAlloc ){
9893      nAlloc = nSql+nLine+100;
9894      zSql = realloc(zSql, nAlloc);
9895      if( zSql==0 ) shell_out_of_memory();
9896    }
9897    nSqlPrior = nSql;
9898    if( nSql==0 ){
9899      int i;
9900      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9901      assert( nAlloc>0 && zSql!=0 );
9902      memcpy(zSql, zLine+i, nLine+1-i);
9903      startline = p->lineno;
9904      nSql = nLine-i;
9905    }else{
9906      zSql[nSql++] = '\n';
9907      memcpy(zSql+nSql, zLine, nLine+1);
9908      nSql += nLine;
9909    }
9910    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9911                && sqlite3_complete(zSql) ){
9912      errCnt += runOneSqlLine(p, zSql, p->in, startline);
9913      nSql = 0;
9914      if( p->outCount ){
9915        output_reset(p);
9916        p->outCount = 0;
9917      }else{
9918        clearTempFile(p);
9919      }
9920    }else if( nSql && _all_whitespace(zSql) ){
9921      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9922      nSql = 0;
9923    }
9924  }
9925  if( nSql && !_all_whitespace(zSql) ){
9926    errCnt += runOneSqlLine(p, zSql, p->in, startline);
9927  }
9928  free(zSql);
9929  free(zLine);
9930  return errCnt>0;
9931}
9932
9933/*
9934** Return a pathname which is the user's home directory.  A
9935** 0 return indicates an error of some kind.
9936*/
9937static char *find_home_dir(int clearFlag){
9938  static char *home_dir = NULL;
9939  if( clearFlag ){
9940    free(home_dir);
9941    home_dir = 0;
9942    return 0;
9943  }
9944  if( home_dir ) return home_dir;
9945
9946#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9947     && !defined(__RTP__) && !defined(_WRS_KERNEL)
9948  {
9949    struct passwd *pwent;
9950    uid_t uid = getuid();
9951    if( (pwent=getpwuid(uid)) != NULL) {
9952      home_dir = pwent->pw_dir;
9953    }
9954  }
9955#endif
9956
9957#if defined(_WIN32_WCE)
9958  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9959   */
9960  home_dir = "/";
9961#else
9962
9963#if defined(_WIN32) || defined(WIN32)
9964  if (!home_dir) {
9965    home_dir = getenv("USERPROFILE");
9966  }
9967#endif
9968
9969  if (!home_dir) {
9970    home_dir = getenv("HOME");
9971  }
9972
9973#if defined(_WIN32) || defined(WIN32)
9974  if (!home_dir) {
9975    char *zDrive, *zPath;
9976    int n;
9977    zDrive = getenv("HOMEDRIVE");
9978    zPath = getenv("HOMEPATH");
9979    if( zDrive && zPath ){
9980      n = strlen30(zDrive) + strlen30(zPath) + 1;
9981      home_dir = malloc( n );
9982      if( home_dir==0 ) return 0;
9983      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9984      return home_dir;
9985    }
9986    home_dir = "c:\\";
9987  }
9988#endif
9989
9990#endif /* !_WIN32_WCE */
9991
9992  if( home_dir ){
9993    int n = strlen30(home_dir) + 1;
9994    char *z = malloc( n );
9995    if( z ) memcpy(z, home_dir, n);
9996    home_dir = z;
9997  }
9998
9999  return home_dir;
10000}
10001
10002/*
10003** Read input from the file given by sqliterc_override.  Or if that
10004** parameter is NULL, take input from ~/.sqliterc
10005**
10006** Returns the number of errors.
10007*/
10008static void process_sqliterc(
10009  ShellState *p,                  /* Configuration data */
10010  const char *sqliterc_override   /* Name of config file. NULL to use default */
10011){
10012  char *home_dir = NULL;
10013  const char *sqliterc = sqliterc_override;
10014  char *zBuf = 0;
10015  FILE *inSaved = p->in;
10016  int savedLineno = p->lineno;
10017
10018  if (sqliterc == NULL) {
10019    home_dir = find_home_dir(0);
10020    if( home_dir==0 ){
10021      raw_printf(stderr, "-- warning: cannot find home directory;"
10022                      " cannot read ~/.sqliterc\n");
10023      return;
10024    }
10025    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
10026    sqliterc = zBuf;
10027  }
10028  p->in = fopen(sqliterc,"rb");
10029  if( p->in ){
10030    if( stdin_is_interactive ){
10031      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
10032    }
10033    process_input(p);
10034    fclose(p->in);
10035  }
10036  p->in = inSaved;
10037  p->lineno = savedLineno;
10038  sqlite3_free(zBuf);
10039}
10040
10041/*
10042** Show available command line options
10043*/
10044static const char zOptions[] =
10045#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10046  "   -A ARGS...           run \".archive ARGS\" and exit\n"
10047#endif
10048  "   -append              append the database to the end of the file\n"
10049  "   -ascii               set output mode to 'ascii'\n"
10050  "   -bail                stop after hitting an error\n"
10051  "   -batch               force batch I/O\n"
10052  "   -column              set output mode to 'column'\n"
10053  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
10054  "   -csv                 set output mode to 'csv'\n"
10055#if defined(SQLITE_ENABLE_DESERIALIZE)
10056  "   -deserialize         open the database using sqlite3_deserialize()\n"
10057#endif
10058  "   -echo                print commands before execution\n"
10059  "   -init FILENAME       read/process named file\n"
10060  "   -[no]header          turn headers on or off\n"
10061#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10062  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
10063#endif
10064  "   -help                show this message\n"
10065  "   -html                set output mode to HTML\n"
10066  "   -interactive         force interactive I/O\n"
10067  "   -line                set output mode to 'line'\n"
10068  "   -list                set output mode to 'list'\n"
10069  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
10070#if defined(SQLITE_ENABLE_DESERIALIZE)
10071  "   -maxsize N           maximum size for a --deserialize database\n"
10072#endif
10073  "   -memtrace            trace all memory allocations and deallocations\n"
10074  "   -mmap N              default mmap size set to N\n"
10075#ifdef SQLITE_ENABLE_MULTIPLEX
10076  "   -multiplex           enable the multiplexor VFS\n"
10077#endif
10078  "   -newline SEP         set output row separator. Default: '\\n'\n"
10079  "   -nofollow            refuse to open symbolic links to database files\n"
10080  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
10081  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
10082  "   -quote               set output mode to 'quote'\n"
10083  "   -readonly            open the database read-only\n"
10084  "   -separator SEP       set output column separator. Default: '|'\n"
10085#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10086  "   -sorterref SIZE      sorter references threshold size\n"
10087#endif
10088  "   -stats               print memory stats before each finalize\n"
10089  "   -version             show SQLite version\n"
10090  "   -vfs NAME            use NAME as the default VFS\n"
10091#ifdef SQLITE_ENABLE_VFSTRACE
10092  "   -vfstrace            enable tracing of all VFS calls\n"
10093#endif
10094#ifdef SQLITE_HAVE_ZLIB
10095  "   -zip                 open the file as a ZIP Archive\n"
10096#endif
10097;
10098static void usage(int showDetail){
10099  utf8_printf(stderr,
10100      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
10101      "FILENAME is the name of an SQLite database. A new database is created\n"
10102      "if the file does not previously exist.\n", Argv0);
10103  if( showDetail ){
10104    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
10105  }else{
10106    raw_printf(stderr, "Use the -help option for additional information\n");
10107  }
10108  exit(1);
10109}
10110
10111/*
10112** Internal check:  Verify that the SQLite is uninitialized.  Print a
10113** error message if it is initialized.
10114*/
10115static void verify_uninitialized(void){
10116  if( sqlite3_config(-1)==SQLITE_MISUSE ){
10117    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
10118                        " initialization.\n");
10119  }
10120}
10121
10122/*
10123** Initialize the state information in data
10124*/
10125static void main_init(ShellState *data) {
10126  memset(data, 0, sizeof(*data));
10127  data->normalMode = data->cMode = data->mode = MODE_List;
10128  data->autoExplain = 1;
10129  memcpy(data->colSeparator,SEP_Column, 2);
10130  memcpy(data->rowSeparator,SEP_Row, 2);
10131  data->showHeader = 0;
10132  data->shellFlgs = SHFLG_Lookaside;
10133  verify_uninitialized();
10134  sqlite3_config(SQLITE_CONFIG_URI, 1);
10135  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
10136  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
10137  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
10138  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
10139}
10140
10141/*
10142** Output text to the console in a font that attracts extra attention.
10143*/
10144#ifdef _WIN32
10145static void printBold(const char *zText){
10146  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
10147  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
10148  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
10149  SetConsoleTextAttribute(out,
10150         FOREGROUND_RED|FOREGROUND_INTENSITY
10151  );
10152  printf("%s", zText);
10153  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
10154}
10155#else
10156static void printBold(const char *zText){
10157  printf("\033[1m%s\033[0m", zText);
10158}
10159#endif
10160
10161/*
10162** Get the argument to an --option.  Throw an error and die if no argument
10163** is available.
10164*/
10165static char *cmdline_option_value(int argc, char **argv, int i){
10166  if( i==argc ){
10167    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
10168            argv[0], argv[argc-1]);
10169    exit(1);
10170  }
10171  return argv[i];
10172}
10173
10174#ifndef SQLITE_SHELL_IS_UTF8
10175#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
10176#    define SQLITE_SHELL_IS_UTF8          (0)
10177#  else
10178#    define SQLITE_SHELL_IS_UTF8          (1)
10179#  endif
10180#endif
10181
10182#if SQLITE_SHELL_IS_UTF8
10183int SQLITE_CDECL main(int argc, char **argv){
10184#else
10185int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
10186  char **argv;
10187#endif
10188  char *zErrMsg = 0;
10189  ShellState data;
10190  const char *zInitFile = 0;
10191  int i;
10192  int rc = 0;
10193  int warnInmemoryDb = 0;
10194  int readStdin = 1;
10195  int nCmd = 0;
10196  char **azCmd = 0;
10197  const char *zVfs = 0;           /* Value of -vfs command-line option */
10198#if !SQLITE_SHELL_IS_UTF8
10199  char **argvToFree = 0;
10200  int argcToFree = 0;
10201#endif
10202
10203  setBinaryMode(stdin, 0);
10204  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
10205  stdin_is_interactive = isatty(0);
10206  stdout_is_console = isatty(1);
10207
10208#ifdef SQLITE_DEBUG
10209  registerOomSimulator();
10210#endif
10211
10212#if !defined(_WIN32_WCE)
10213  if( getenv("SQLITE_DEBUG_BREAK") ){
10214    if( isatty(0) && isatty(2) ){
10215      fprintf(stderr,
10216          "attach debugger to process %d and press any key to continue.\n",
10217          GETPID());
10218      fgetc(stdin);
10219    }else{
10220#if defined(_WIN32) || defined(WIN32)
10221      DebugBreak();
10222#elif defined(SIGTRAP)
10223      raise(SIGTRAP);
10224#endif
10225    }
10226  }
10227#endif
10228
10229#if USE_SYSTEM_SQLITE+0!=1
10230  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
10231    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
10232            sqlite3_sourceid(), SQLITE_SOURCE_ID);
10233    exit(1);
10234  }
10235#endif
10236  main_init(&data);
10237
10238  /* On Windows, we must translate command-line arguments into UTF-8.
10239  ** The SQLite memory allocator subsystem has to be enabled in order to
10240  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
10241  ** subsequent sqlite3_config() calls will work.  So copy all results into
10242  ** memory that does not come from the SQLite memory allocator.
10243  */
10244#if !SQLITE_SHELL_IS_UTF8
10245  sqlite3_initialize();
10246  argvToFree = malloc(sizeof(argv[0])*argc*2);
10247  argcToFree = argc;
10248  argv = argvToFree + argc;
10249  if( argv==0 ) shell_out_of_memory();
10250  for(i=0; i<argc; i++){
10251    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
10252    int n;
10253    if( z==0 ) shell_out_of_memory();
10254    n = (int)strlen(z);
10255    argv[i] = malloc( n+1 );
10256    if( argv[i]==0 ) shell_out_of_memory();
10257    memcpy(argv[i], z, n+1);
10258    argvToFree[i] = argv[i];
10259    sqlite3_free(z);
10260  }
10261  sqlite3_shutdown();
10262#endif
10263
10264  assert( argc>=1 && argv && argv[0] );
10265  Argv0 = argv[0];
10266
10267  /* Make sure we have a valid signal handler early, before anything
10268  ** else is done.
10269  */
10270#ifdef SIGINT
10271  signal(SIGINT, interrupt_handler);
10272#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10273  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
10274#endif
10275
10276#ifdef SQLITE_SHELL_DBNAME_PROC
10277  {
10278    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
10279    ** of a C-function that will provide the name of the database file.  Use
10280    ** this compile-time option to embed this shell program in larger
10281    ** applications. */
10282    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
10283    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
10284    warnInmemoryDb = 0;
10285  }
10286#endif
10287
10288  /* Do an initial pass through the command-line argument to locate
10289  ** the name of the database file, the name of the initialization file,
10290  ** the size of the alternative malloc heap,
10291  ** and the first command to execute.
10292  */
10293  verify_uninitialized();
10294  for(i=1; i<argc; i++){
10295    char *z;
10296    z = argv[i];
10297    if( z[0]!='-' ){
10298      if( data.zDbFilename==0 ){
10299        data.zDbFilename = z;
10300      }else{
10301        /* Excesss arguments are interpreted as SQL (or dot-commands) and
10302        ** mean that nothing is read from stdin */
10303        readStdin = 0;
10304        nCmd++;
10305        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
10306        if( azCmd==0 ) shell_out_of_memory();
10307        azCmd[nCmd-1] = z;
10308      }
10309    }
10310    if( z[1]=='-' ) z++;
10311    if( strcmp(z,"-separator")==0
10312     || strcmp(z,"-nullvalue")==0
10313     || strcmp(z,"-newline")==0
10314     || strcmp(z,"-cmd")==0
10315    ){
10316      (void)cmdline_option_value(argc, argv, ++i);
10317    }else if( strcmp(z,"-init")==0 ){
10318      zInitFile = cmdline_option_value(argc, argv, ++i);
10319    }else if( strcmp(z,"-batch")==0 ){
10320      /* Need to check for batch mode here to so we can avoid printing
10321      ** informational messages (like from process_sqliterc) before
10322      ** we do the actual processing of arguments later in a second pass.
10323      */
10324      stdin_is_interactive = 0;
10325    }else if( strcmp(z,"-heap")==0 ){
10326#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10327      const char *zSize;
10328      sqlite3_int64 szHeap;
10329
10330      zSize = cmdline_option_value(argc, argv, ++i);
10331      szHeap = integerValue(zSize);
10332      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
10333      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
10334#else
10335      (void)cmdline_option_value(argc, argv, ++i);
10336#endif
10337    }else if( strcmp(z,"-pagecache")==0 ){
10338      int n, sz;
10339      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10340      if( sz>70000 ) sz = 70000;
10341      if( sz<0 ) sz = 0;
10342      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10343      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
10344                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
10345      data.shellFlgs |= SHFLG_Pagecache;
10346    }else if( strcmp(z,"-lookaside")==0 ){
10347      int n, sz;
10348      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10349      if( sz<0 ) sz = 0;
10350      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10351      if( n<0 ) n = 0;
10352      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
10353      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
10354#ifdef SQLITE_ENABLE_VFSTRACE
10355    }else if( strcmp(z,"-vfstrace")==0 ){
10356      extern int vfstrace_register(
10357         const char *zTraceName,
10358         const char *zOldVfsName,
10359         int (*xOut)(const char*,void*),
10360         void *pOutArg,
10361         int makeDefault
10362      );
10363      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
10364#endif
10365#ifdef SQLITE_ENABLE_MULTIPLEX
10366    }else if( strcmp(z,"-multiplex")==0 ){
10367      extern int sqlite3_multiple_initialize(const char*,int);
10368      sqlite3_multiplex_initialize(0, 1);
10369#endif
10370    }else if( strcmp(z,"-mmap")==0 ){
10371      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10372      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
10373#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10374    }else if( strcmp(z,"-sorterref")==0 ){
10375      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10376      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
10377#endif
10378    }else if( strcmp(z,"-vfs")==0 ){
10379      zVfs = cmdline_option_value(argc, argv, ++i);
10380#ifdef SQLITE_HAVE_ZLIB
10381    }else if( strcmp(z,"-zip")==0 ){
10382      data.openMode = SHELL_OPEN_ZIPFILE;
10383#endif
10384    }else if( strcmp(z,"-append")==0 ){
10385      data.openMode = SHELL_OPEN_APPENDVFS;
10386#ifdef SQLITE_ENABLE_DESERIALIZE
10387    }else if( strcmp(z,"-deserialize")==0 ){
10388      data.openMode = SHELL_OPEN_DESERIALIZE;
10389    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10390      data.szMax = integerValue(argv[++i]);
10391#endif
10392    }else if( strcmp(z,"-readonly")==0 ){
10393      data.openMode = SHELL_OPEN_READONLY;
10394    }else if( strcmp(z,"-nofollow")==0 ){
10395      data.openFlags = SQLITE_OPEN_NOFOLLOW;
10396#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
10397    }else if( strncmp(z, "-A",2)==0 ){
10398      /* All remaining command-line arguments are passed to the ".archive"
10399      ** command, so ignore them */
10400      break;
10401#endif
10402    }else if( strcmp(z, "-memtrace")==0 ){
10403      sqlite3MemTraceActivate(stderr);
10404    }
10405  }
10406  verify_uninitialized();
10407
10408
10409#ifdef SQLITE_SHELL_INIT_PROC
10410  {
10411    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
10412    ** of a C-function that will perform initialization actions on SQLite that
10413    ** occur just before or after sqlite3_initialize(). Use this compile-time
10414    ** option to embed this shell program in larger applications. */
10415    extern void SQLITE_SHELL_INIT_PROC(void);
10416    SQLITE_SHELL_INIT_PROC();
10417  }
10418#else
10419  /* All the sqlite3_config() calls have now been made. So it is safe
10420  ** to call sqlite3_initialize() and process any command line -vfs option. */
10421  sqlite3_initialize();
10422#endif
10423
10424  if( zVfs ){
10425    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
10426    if( pVfs ){
10427      sqlite3_vfs_register(pVfs, 1);
10428    }else{
10429      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
10430      exit(1);
10431    }
10432  }
10433
10434  if( data.zDbFilename==0 ){
10435#ifndef SQLITE_OMIT_MEMORYDB
10436    data.zDbFilename = ":memory:";
10437    warnInmemoryDb = argc==1;
10438#else
10439    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
10440    return 1;
10441#endif
10442  }
10443  data.out = stdout;
10444  sqlite3_appendvfs_init(0,0,0);
10445
10446  /* Go ahead and open the database file if it already exists.  If the
10447  ** file does not exist, delay opening it.  This prevents empty database
10448  ** files from being created if a user mistypes the database name argument
10449  ** to the sqlite command-line tool.
10450  */
10451  if( access(data.zDbFilename, 0)==0 ){
10452    open_db(&data, 0);
10453  }
10454
10455  /* Process the initialization file if there is one.  If no -init option
10456  ** is given on the command line, look for a file named ~/.sqliterc and
10457  ** try to process it.
10458  */
10459  process_sqliterc(&data,zInitFile);
10460
10461  /* Make a second pass through the command-line argument and set
10462  ** options.  This second pass is delayed until after the initialization
10463  ** file is processed so that the command-line arguments will override
10464  ** settings in the initialization file.
10465  */
10466  for(i=1; i<argc; i++){
10467    char *z = argv[i];
10468    if( z[0]!='-' ) continue;
10469    if( z[1]=='-' ){ z++; }
10470    if( strcmp(z,"-init")==0 ){
10471      i++;
10472    }else if( strcmp(z,"-html")==0 ){
10473      data.mode = MODE_Html;
10474    }else if( strcmp(z,"-list")==0 ){
10475      data.mode = MODE_List;
10476    }else if( strcmp(z,"-quote")==0 ){
10477      data.mode = MODE_Quote;
10478    }else if( strcmp(z,"-line")==0 ){
10479      data.mode = MODE_Line;
10480    }else if( strcmp(z,"-column")==0 ){
10481      data.mode = MODE_Column;
10482    }else if( strcmp(z,"-csv")==0 ){
10483      data.mode = MODE_Csv;
10484      memcpy(data.colSeparator,",",2);
10485#ifdef SQLITE_HAVE_ZLIB
10486    }else if( strcmp(z,"-zip")==0 ){
10487      data.openMode = SHELL_OPEN_ZIPFILE;
10488#endif
10489    }else if( strcmp(z,"-append")==0 ){
10490      data.openMode = SHELL_OPEN_APPENDVFS;
10491#ifdef SQLITE_ENABLE_DESERIALIZE
10492    }else if( strcmp(z,"-deserialize")==0 ){
10493      data.openMode = SHELL_OPEN_DESERIALIZE;
10494    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10495      data.szMax = integerValue(argv[++i]);
10496#endif
10497    }else if( strcmp(z,"-readonly")==0 ){
10498      data.openMode = SHELL_OPEN_READONLY;
10499    }else if( strcmp(z,"-nofollow")==0 ){
10500      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
10501    }else if( strcmp(z,"-ascii")==0 ){
10502      data.mode = MODE_Ascii;
10503      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10504                       SEP_Unit);
10505      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10506                       SEP_Record);
10507    }else if( strcmp(z,"-separator")==0 ){
10508      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10509                       "%s",cmdline_option_value(argc,argv,++i));
10510    }else if( strcmp(z,"-newline")==0 ){
10511      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10512                       "%s",cmdline_option_value(argc,argv,++i));
10513    }else if( strcmp(z,"-nullvalue")==0 ){
10514      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
10515                       "%s",cmdline_option_value(argc,argv,++i));
10516    }else if( strcmp(z,"-header")==0 ){
10517      data.showHeader = 1;
10518    }else if( strcmp(z,"-noheader")==0 ){
10519      data.showHeader = 0;
10520    }else if( strcmp(z,"-echo")==0 ){
10521      ShellSetFlag(&data, SHFLG_Echo);
10522    }else if( strcmp(z,"-eqp")==0 ){
10523      data.autoEQP = AUTOEQP_on;
10524    }else if( strcmp(z,"-eqpfull")==0 ){
10525      data.autoEQP = AUTOEQP_full;
10526    }else if( strcmp(z,"-stats")==0 ){
10527      data.statsOn = 1;
10528    }else if( strcmp(z,"-scanstats")==0 ){
10529      data.scanstatsOn = 1;
10530    }else if( strcmp(z,"-backslash")==0 ){
10531      /* Undocumented command-line option: -backslash
10532      ** Causes C-style backslash escapes to be evaluated in SQL statements
10533      ** prior to sending the SQL into SQLite.  Useful for injecting
10534      ** crazy bytes in the middle of SQL statements for testing and debugging.
10535      */
10536      ShellSetFlag(&data, SHFLG_Backslash);
10537    }else if( strcmp(z,"-bail")==0 ){
10538      bail_on_error = 1;
10539    }else if( strcmp(z,"-version")==0 ){
10540      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
10541      return 0;
10542    }else if( strcmp(z,"-interactive")==0 ){
10543      stdin_is_interactive = 1;
10544    }else if( strcmp(z,"-batch")==0 ){
10545      stdin_is_interactive = 0;
10546    }else if( strcmp(z,"-heap")==0 ){
10547      i++;
10548    }else if( strcmp(z,"-pagecache")==0 ){
10549      i+=2;
10550    }else if( strcmp(z,"-lookaside")==0 ){
10551      i+=2;
10552    }else if( strcmp(z,"-mmap")==0 ){
10553      i++;
10554    }else if( strcmp(z,"-memtrace")==0 ){
10555      i++;
10556#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10557    }else if( strcmp(z,"-sorterref")==0 ){
10558      i++;
10559#endif
10560    }else if( strcmp(z,"-vfs")==0 ){
10561      i++;
10562#ifdef SQLITE_ENABLE_VFSTRACE
10563    }else if( strcmp(z,"-vfstrace")==0 ){
10564      i++;
10565#endif
10566#ifdef SQLITE_ENABLE_MULTIPLEX
10567    }else if( strcmp(z,"-multiplex")==0 ){
10568      i++;
10569#endif
10570    }else if( strcmp(z,"-help")==0 ){
10571      usage(1);
10572    }else if( strcmp(z,"-cmd")==0 ){
10573      /* Run commands that follow -cmd first and separately from commands
10574      ** that simply appear on the command-line.  This seems goofy.  It would
10575      ** be better if all commands ran in the order that they appear.  But
10576      ** we retain the goofy behavior for historical compatibility. */
10577      if( i==argc-1 ) break;
10578      z = cmdline_option_value(argc,argv,++i);
10579      if( z[0]=='.' ){
10580        rc = do_meta_command(z, &data);
10581        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
10582      }else{
10583        open_db(&data, 0);
10584        rc = shell_exec(&data, z, &zErrMsg);
10585        if( zErrMsg!=0 ){
10586          utf8_printf(stderr,"Error: %s\n", zErrMsg);
10587          if( bail_on_error ) return rc!=0 ? rc : 1;
10588        }else if( rc!=0 ){
10589          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
10590          if( bail_on_error ) return rc;
10591        }
10592      }
10593#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
10594    }else if( strncmp(z, "-A", 2)==0 ){
10595      if( nCmd>0 ){
10596        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
10597                            " with \"%s\"\n", z);
10598        return 1;
10599      }
10600      open_db(&data, OPEN_DB_ZIPFILE);
10601      if( z[2] ){
10602        argv[i] = &z[2];
10603        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
10604      }else{
10605        arDotCommand(&data, 1, argv+i, argc-i);
10606      }
10607      readStdin = 0;
10608      break;
10609#endif
10610    }else{
10611      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
10612      raw_printf(stderr,"Use -help for a list of options.\n");
10613      return 1;
10614    }
10615    data.cMode = data.mode;
10616  }
10617
10618  if( !readStdin ){
10619    /* Run all arguments that do not begin with '-' as if they were separate
10620    ** command-line inputs, except for the argToSkip argument which contains
10621    ** the database filename.
10622    */
10623    for(i=0; i<nCmd; i++){
10624      if( azCmd[i][0]=='.' ){
10625        rc = do_meta_command(azCmd[i], &data);
10626        if( rc ) return rc==2 ? 0 : rc;
10627      }else{
10628        open_db(&data, 0);
10629        rc = shell_exec(&data, azCmd[i], &zErrMsg);
10630        if( zErrMsg!=0 ){
10631          utf8_printf(stderr,"Error: %s\n", zErrMsg);
10632          return rc!=0 ? rc : 1;
10633        }else if( rc!=0 ){
10634          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
10635          return rc;
10636        }
10637      }
10638    }
10639    free(azCmd);
10640  }else{
10641    /* Run commands received from standard input
10642    */
10643    if( stdin_is_interactive ){
10644      char *zHome;
10645      char *zHistory;
10646      int nHistory;
10647      printf(
10648        "SQLite version %s %.19s\n" /*extra-version-info*/
10649        "Enter \".help\" for usage hints.\n",
10650        sqlite3_libversion(), sqlite3_sourceid()
10651      );
10652      if( warnInmemoryDb ){
10653        printf("Connected to a ");
10654        printBold("transient in-memory database");
10655        printf(".\nUse \".open FILENAME\" to reopen on a "
10656               "persistent database.\n");
10657      }
10658      zHistory = getenv("SQLITE_HISTORY");
10659      if( zHistory ){
10660        zHistory = strdup(zHistory);
10661      }else if( (zHome = find_home_dir(0))!=0 ){
10662        nHistory = strlen30(zHome) + 20;
10663        if( (zHistory = malloc(nHistory))!=0 ){
10664          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10665        }
10666      }
10667      if( zHistory ){ shell_read_history(zHistory); }
10668#if HAVE_READLINE || HAVE_EDITLINE
10669      rl_attempted_completion_function = readline_completion;
10670#elif HAVE_LINENOISE
10671      linenoiseSetCompletionCallback(linenoise_completion);
10672#endif
10673      data.in = 0;
10674      rc = process_input(&data);
10675      if( zHistory ){
10676        shell_stifle_history(2000);
10677        shell_write_history(zHistory);
10678        free(zHistory);
10679      }
10680    }else{
10681      data.in = stdin;
10682      rc = process_input(&data);
10683    }
10684  }
10685  set_table_name(&data, 0);
10686  if( data.db ){
10687    session_close_all(&data);
10688    close_db(data.db);
10689  }
10690  sqlite3_free(data.zFreeOnClose);
10691  find_home_dir(1);
10692  output_reset(&data);
10693  data.doXdgOpen = 0;
10694  clearTempFile(&data);
10695#if !SQLITE_SHELL_IS_UTF8
10696  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10697  free(argvToFree);
10698#endif
10699  /* Clear the global data structure so that valgrind will detect memory
10700  ** leaks */
10701  memset(&data, 0, sizeof(data));
10702  return rc;
10703}
10704