xref: /sqlite-3.40.0/src/shell.c.in (revision 7ac2ee0a)
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/*
401** This is the name of our program. It is set in main(), used
402** in a number of other places, mostly for error messages.
403*/
404static char *Argv0;
405
406/*
407** Prompt strings. Initialized in main. Settable with
408**   .prompt main continue
409*/
410static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
411static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
412
413/*
414** Render output like fprintf().  Except, if the output is going to the
415** console and if this is running on a Windows machine, translate the
416** output from UTF-8 into MBCS.
417*/
418#if defined(_WIN32) || defined(WIN32)
419void utf8_printf(FILE *out, const char *zFormat, ...){
420  va_list ap;
421  va_start(ap, zFormat);
422  if( stdout_is_console && (out==stdout || out==stderr) ){
423    char *z1 = sqlite3_vmprintf(zFormat, ap);
424    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
425    sqlite3_free(z1);
426    fputs(z2, out);
427    sqlite3_free(z2);
428  }else{
429    vfprintf(out, zFormat, ap);
430  }
431  va_end(ap);
432}
433#elif !defined(utf8_printf)
434# define utf8_printf fprintf
435#endif
436
437/*
438** Render output like fprintf().  This should not be used on anything that
439** includes string formatting (e.g. "%s").
440*/
441#if !defined(raw_printf)
442# define raw_printf fprintf
443#endif
444
445/* Indicate out-of-memory and exit. */
446static void shell_out_of_memory(void){
447  raw_printf(stderr,"Error: out of memory\n");
448  exit(1);
449}
450
451/*
452** Write I/O traces to the following stream.
453*/
454#ifdef SQLITE_ENABLE_IOTRACE
455static FILE *iotrace = 0;
456#endif
457
458/*
459** This routine works like printf in that its first argument is a
460** format string and subsequent arguments are values to be substituted
461** in place of % fields.  The result of formatting this string
462** is written to iotrace.
463*/
464#ifdef SQLITE_ENABLE_IOTRACE
465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
466  va_list ap;
467  char *z;
468  if( iotrace==0 ) return;
469  va_start(ap, zFormat);
470  z = sqlite3_vmprintf(zFormat, ap);
471  va_end(ap);
472  utf8_printf(iotrace, "%s", z);
473  sqlite3_free(z);
474}
475#endif
476
477/*
478** Output string zUtf to stream pOut as w characters.  If w is negative,
479** then right-justify the text.  W is the width in UTF-8 characters, not
480** in bytes.  This is different from the %*.*s specification in printf
481** since with %*.*s the width is measured in bytes, not characters.
482*/
483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
484  int i;
485  int n;
486  int aw = w<0 ? -w : w;
487  char zBuf[1000];
488  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
489  for(i=n=0; zUtf[i]; i++){
490    if( (zUtf[i]&0xc0)!=0x80 ){
491      n++;
492      if( n==aw ){
493        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
494        break;
495      }
496    }
497  }
498  if( n>=aw ){
499    utf8_printf(pOut, "%.*s", i, zUtf);
500  }else if( w<0 ){
501    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
502  }else{
503    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
504  }
505}
506
507
508/*
509** Determines if a string is a number of not.
510*/
511static int isNumber(const char *z, int *realnum){
512  if( *z=='-' || *z=='+' ) z++;
513  if( !IsDigit(*z) ){
514    return 0;
515  }
516  z++;
517  if( realnum ) *realnum = 0;
518  while( IsDigit(*z) ){ z++; }
519  if( *z=='.' ){
520    z++;
521    if( !IsDigit(*z) ) return 0;
522    while( IsDigit(*z) ){ z++; }
523    if( realnum ) *realnum = 1;
524  }
525  if( *z=='e' || *z=='E' ){
526    z++;
527    if( *z=='+' || *z=='-' ) z++;
528    if( !IsDigit(*z) ) return 0;
529    while( IsDigit(*z) ){ z++; }
530    if( realnum ) *realnum = 1;
531  }
532  return *z==0;
533}
534
535/*
536** Compute a string length that is limited to what can be stored in
537** lower 30 bits of a 32-bit signed integer.
538*/
539static int strlen30(const char *z){
540  const char *z2 = z;
541  while( *z2 ){ z2++; }
542  return 0x3fffffff & (int)(z2 - z);
543}
544
545/*
546** Return the length of a string in characters.  Multibyte UTF8 characters
547** count as a single character.
548*/
549static int strlenChar(const char *z){
550  int n = 0;
551  while( *z ){
552    if( (0xc0&*(z++))!=0x80 ) n++;
553  }
554  return n;
555}
556
557/*
558** This routine reads a line of text from FILE in, stores
559** the text in memory obtained from malloc() and returns a pointer
560** to the text.  NULL is returned at end of file, or if malloc()
561** fails.
562**
563** If zLine is not NULL then it is a malloced buffer returned from
564** a previous call to this routine that may be reused.
565*/
566static char *local_getline(char *zLine, FILE *in){
567  int nLine = zLine==0 ? 0 : 100;
568  int n = 0;
569
570  while( 1 ){
571    if( n+100>nLine ){
572      nLine = nLine*2 + 100;
573      zLine = realloc(zLine, nLine);
574      if( zLine==0 ) shell_out_of_memory();
575    }
576    if( fgets(&zLine[n], nLine - n, in)==0 ){
577      if( n==0 ){
578        free(zLine);
579        return 0;
580      }
581      zLine[n] = 0;
582      break;
583    }
584    while( zLine[n] ) n++;
585    if( n>0 && zLine[n-1]=='\n' ){
586      n--;
587      if( n>0 && zLine[n-1]=='\r' ) n--;
588      zLine[n] = 0;
589      break;
590    }
591  }
592#if defined(_WIN32) || defined(WIN32)
593  /* For interactive input on Windows systems, translate the
594  ** multi-byte characterset characters into UTF-8. */
595  if( stdin_is_interactive && in==stdin ){
596    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
597    if( zTrans ){
598      int nTrans = strlen30(zTrans)+1;
599      if( nTrans>nLine ){
600        zLine = realloc(zLine, nTrans);
601        if( zLine==0 ) shell_out_of_memory();
602      }
603      memcpy(zLine, zTrans, nTrans);
604      sqlite3_free(zTrans);
605    }
606  }
607#endif /* defined(_WIN32) || defined(WIN32) */
608  return zLine;
609}
610
611/*
612** Retrieve a single line of input text.
613**
614** If in==0 then read from standard input and prompt before each line.
615** If isContinuation is true, then a continuation prompt is appropriate.
616** If isContinuation is zero, then the main prompt should be used.
617**
618** If zPrior is not NULL then it is a buffer from a prior call to this
619** routine that can be reused.
620**
621** The result is stored in space obtained from malloc() and must either
622** be freed by the caller or else passed back into this routine via the
623** zPrior argument for reuse.
624*/
625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
626  char *zPrompt;
627  char *zResult;
628  if( in!=0 ){
629    zResult = local_getline(zPrior, in);
630  }else{
631    zPrompt = isContinuation ? continuePrompt : mainPrompt;
632#if SHELL_USE_LOCAL_GETLINE
633    printf("%s", zPrompt);
634    fflush(stdout);
635    zResult = local_getline(zPrior, stdin);
636#else
637    free(zPrior);
638    zResult = shell_readline(zPrompt);
639    if( zResult && *zResult ) shell_add_history(zResult);
640#endif
641  }
642  return zResult;
643}
644
645
646/*
647** Return the value of a hexadecimal digit.  Return -1 if the input
648** is not a hex digit.
649*/
650static int hexDigitValue(char c){
651  if( c>='0' && c<='9' ) return c - '0';
652  if( c>='a' && c<='f' ) return c - 'a' + 10;
653  if( c>='A' && c<='F' ) return c - 'A' + 10;
654  return -1;
655}
656
657/*
658** Interpret zArg as an integer value, possibly with suffixes.
659*/
660static sqlite3_int64 integerValue(const char *zArg){
661  sqlite3_int64 v = 0;
662  static const struct { char *zSuffix; int iMult; } aMult[] = {
663    { "KiB", 1024 },
664    { "MiB", 1024*1024 },
665    { "GiB", 1024*1024*1024 },
666    { "KB",  1000 },
667    { "MB",  1000000 },
668    { "GB",  1000000000 },
669    { "K",   1000 },
670    { "M",   1000000 },
671    { "G",   1000000000 },
672  };
673  int i;
674  int isNeg = 0;
675  if( zArg[0]=='-' ){
676    isNeg = 1;
677    zArg++;
678  }else if( zArg[0]=='+' ){
679    zArg++;
680  }
681  if( zArg[0]=='0' && zArg[1]=='x' ){
682    int x;
683    zArg += 2;
684    while( (x = hexDigitValue(zArg[0]))>=0 ){
685      v = (v<<4) + x;
686      zArg++;
687    }
688  }else{
689    while( IsDigit(zArg[0]) ){
690      v = v*10 + zArg[0] - '0';
691      zArg++;
692    }
693  }
694  for(i=0; i<ArraySize(aMult); i++){
695    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
696      v *= aMult[i].iMult;
697      break;
698    }
699  }
700  return isNeg? -v : v;
701}
702
703/*
704** A variable length string to which one can append text.
705*/
706typedef struct ShellText ShellText;
707struct ShellText {
708  char *z;
709  int n;
710  int nAlloc;
711};
712
713/*
714** Initialize and destroy a ShellText object
715*/
716static void initText(ShellText *p){
717  memset(p, 0, sizeof(*p));
718}
719static void freeText(ShellText *p){
720  free(p->z);
721  initText(p);
722}
723
724/* zIn is either a pointer to a NULL-terminated string in memory obtained
725** from malloc(), or a NULL pointer. The string pointed to by zAppend is
726** added to zIn, and the result returned in memory obtained from malloc().
727** zIn, if it was not NULL, is freed.
728**
729** If the third argument, quote, is not '\0', then it is used as a
730** quote character for zAppend.
731*/
732static void appendText(ShellText *p, char const *zAppend, char quote){
733  int len;
734  int i;
735  int nAppend = strlen30(zAppend);
736
737  len = nAppend+p->n+1;
738  if( quote ){
739    len += 2;
740    for(i=0; i<nAppend; i++){
741      if( zAppend[i]==quote ) len++;
742    }
743  }
744
745  if( p->n+len>=p->nAlloc ){
746    p->nAlloc = p->nAlloc*2 + len + 20;
747    p->z = realloc(p->z, p->nAlloc);
748    if( p->z==0 ) shell_out_of_memory();
749  }
750
751  if( quote ){
752    char *zCsr = p->z+p->n;
753    *zCsr++ = quote;
754    for(i=0; i<nAppend; i++){
755      *zCsr++ = zAppend[i];
756      if( zAppend[i]==quote ) *zCsr++ = quote;
757    }
758    *zCsr++ = quote;
759    p->n = (int)(zCsr - p->z);
760    *zCsr = '\0';
761  }else{
762    memcpy(p->z+p->n, zAppend, nAppend);
763    p->n += nAppend;
764    p->z[p->n] = '\0';
765  }
766}
767
768/*
769** Attempt to determine if identifier zName needs to be quoted, either
770** because it contains non-alphanumeric characters, or because it is an
771** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
772** that quoting is required.
773**
774** Return '"' if quoting is required.  Return 0 if no quoting is required.
775*/
776static char quoteChar(const char *zName){
777  int i;
778  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779  for(i=0; zName[i]; i++){
780    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
781  }
782  return sqlite3_keyword_check(zName, i) ? '"' : 0;
783}
784
785/*
786** Construct a fake object name and column list to describe the structure
787** of the view, virtual table, or table valued function zSchema.zName.
788*/
789static char *shellFakeSchema(
790  sqlite3 *db,            /* The database connection containing the vtab */
791  const char *zSchema,    /* Schema of the database holding the vtab */
792  const char *zName       /* The name of the virtual table */
793){
794  sqlite3_stmt *pStmt = 0;
795  char *zSql;
796  ShellText s;
797  char cQuote;
798  char *zDiv = "(";
799  int nRow = 0;
800
801  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802                         zSchema ? zSchema : "main", zName);
803  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804  sqlite3_free(zSql);
805  initText(&s);
806  if( zSchema ){
807    cQuote = quoteChar(zSchema);
808    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809    appendText(&s, zSchema, cQuote);
810    appendText(&s, ".", 0);
811  }
812  cQuote = quoteChar(zName);
813  appendText(&s, zName, cQuote);
814  while( sqlite3_step(pStmt)==SQLITE_ROW ){
815    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
816    nRow++;
817    appendText(&s, zDiv, 0);
818    zDiv = ",";
819    cQuote = quoteChar(zCol);
820    appendText(&s, zCol, cQuote);
821  }
822  appendText(&s, ")", 0);
823  sqlite3_finalize(pStmt);
824  if( nRow==0 ){
825    freeText(&s);
826    s.z = 0;
827  }
828  return s.z;
829}
830
831/*
832** SQL function:  shell_module_schema(X)
833**
834** Return a fake schema for the table-valued function or eponymous virtual
835** table X.
836*/
837static void shellModuleSchema(
838  sqlite3_context *pCtx,
839  int nVal,
840  sqlite3_value **apVal
841){
842  const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843  char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
844  UNUSED_PARAMETER(nVal);
845  if( zFake ){
846    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
847                        -1, sqlite3_free);
848    free(zFake);
849  }
850}
851
852/*
853** SQL function:  shell_add_schema(S,X)
854**
855** Add the schema name X to the CREATE statement in S and return the result.
856** Examples:
857**
858**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
859**
860** Also works on
861**
862**    CREATE INDEX
863**    CREATE UNIQUE INDEX
864**    CREATE VIEW
865**    CREATE TRIGGER
866**    CREATE VIRTUAL TABLE
867**
868** This UDF is used by the .schema command to insert the schema name of
869** attached databases into the middle of the sqlite_master.sql field.
870*/
871static void shellAddSchemaName(
872  sqlite3_context *pCtx,
873  int nVal,
874  sqlite3_value **apVal
875){
876  static const char *aPrefix[] = {
877     "TABLE",
878     "INDEX",
879     "UNIQUE INDEX",
880     "VIEW",
881     "TRIGGER",
882     "VIRTUAL TABLE"
883  };
884  int i = 0;
885  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
887  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
888  sqlite3 *db = sqlite3_context_db_handle(pCtx);
889  UNUSED_PARAMETER(nVal);
890  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
891    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
892      int n = strlen30(aPrefix[i]);
893      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
894        char *z = 0;
895        char *zFake = 0;
896        if( zSchema ){
897          char cQuote = quoteChar(zSchema);
898          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900          }else{
901            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
902          }
903        }
904        if( zName
905         && aPrefix[i][0]=='V'
906         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
907        ){
908          if( z==0 ){
909            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
910          }else{
911            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
912          }
913          free(zFake);
914        }
915        if( z ){
916          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917          return;
918        }
919      }
920    }
921  }
922  sqlite3_result_value(pCtx, apVal[0]);
923}
924
925/*
926** The source code for several run-time loadable extensions is inserted
927** below by the ../tool/mkshellc.tcl script.  Before processing that included
928** code, we need to override some macros to make the included program code
929** work here in the middle of this regular program.
930*/
931#define SQLITE_EXTENSION_INIT1
932#define SQLITE_EXTENSION_INIT2(X) (void)(X)
933
934#if defined(_WIN32) && defined(_MSC_VER)
935INCLUDE test_windirent.h
936INCLUDE test_windirent.c
937#define dirent DIRENT
938#endif
939INCLUDE ../ext/misc/shathree.c
940INCLUDE ../ext/misc/fileio.c
941INCLUDE ../ext/misc/completion.c
942INCLUDE ../ext/misc/appendvfs.c
943INCLUDE ../ext/misc/memtrace.c
944#ifdef SQLITE_HAVE_ZLIB
945INCLUDE ../ext/misc/zipfile.c
946INCLUDE ../ext/misc/sqlar.c
947#endif
948INCLUDE ../ext/expert/sqlite3expert.h
949INCLUDE ../ext/expert/sqlite3expert.c
950
951#if defined(SQLITE_ENABLE_SESSION)
952/*
953** State information for a single open session
954*/
955typedef struct OpenSession OpenSession;
956struct OpenSession {
957  char *zName;             /* Symbolic name for this session */
958  int nFilter;             /* Number of xFilter rejection GLOB patterns */
959  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
960  sqlite3_session *p;      /* The open session */
961};
962#endif
963
964/*
965** Shell output mode information from before ".explain on",
966** saved so that it can be restored by ".explain off"
967*/
968typedef struct SavedModeInfo SavedModeInfo;
969struct SavedModeInfo {
970  int valid;          /* Is there legit data in here? */
971  int mode;           /* Mode prior to ".explain on" */
972  int showHeader;     /* The ".header" setting prior to ".explain on" */
973  int colWidth[100];  /* Column widths prior to ".explain on" */
974};
975
976typedef struct ExpertInfo ExpertInfo;
977struct ExpertInfo {
978  sqlite3expert *pExpert;
979  int bVerbose;
980};
981
982/* A single line in the EQP output */
983typedef struct EQPGraphRow EQPGraphRow;
984struct EQPGraphRow {
985  int iEqpId;           /* ID for this row */
986  int iParentId;        /* ID of the parent row */
987  EQPGraphRow *pNext;   /* Next row in sequence */
988  char zText[1];        /* Text to display for this row */
989};
990
991/* All EQP output is collected into an instance of the following */
992typedef struct EQPGraph EQPGraph;
993struct EQPGraph {
994  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
995  EQPGraphRow *pLast;   /* Last element of the pRow list */
996  char zPrefix[100];    /* Graph prefix */
997};
998
999/*
1000** State information about the database connection is contained in an
1001** instance of the following structure.
1002*/
1003typedef struct ShellState ShellState;
1004struct ShellState {
1005  sqlite3 *db;           /* The database */
1006  u8 autoExplain;        /* Automatically turn on .explain mode */
1007  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1008  u8 autoEQPtest;        /* autoEQP is in test mode */
1009  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1010  u8 statsOn;            /* True to display memory stats before each finalize */
1011  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1012  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1013  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1014  u8 nEqpLevel;          /* Depth of the EQP output graph */
1015  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1016  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1017  int outCount;          /* Revert to stdout when reaching zero */
1018  int cnt;               /* Number of records displayed so far */
1019  int lineno;            /* Line number of last line read from in */
1020  FILE *in;              /* Read commands from this stream */
1021  FILE *out;             /* Write results here */
1022  FILE *traceOut;        /* Output for sqlite3_trace() */
1023  int nErr;              /* Number of errors seen */
1024  int mode;              /* An output mode setting */
1025  int modePrior;         /* Saved mode */
1026  int cMode;             /* temporary output mode for the current query */
1027  int normalMode;        /* Output mode before ".explain on" */
1028  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1029  int showHeader;        /* True to show column names in List or Column mode */
1030  int nCheck;            /* Number of ".check" commands run */
1031  unsigned nProgress;    /* Number of progress callbacks encountered */
1032  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1033  unsigned flgProgress;  /* Flags for the progress callback */
1034  unsigned shellFlgs;    /* Various flags */
1035  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1036  char *zDestTable;      /* Name of destination table when MODE_Insert */
1037  char *zTempFile;       /* Temporary file that might need deleting */
1038  char zTestcase[30];    /* Name of current test case */
1039  char colSeparator[20]; /* Column separator character for several modes */
1040  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1041  char colSepPrior[20];  /* Saved column separator */
1042  char rowSepPrior[20];  /* Saved row separator */
1043  int colWidth[100];     /* Requested width of each column when in column mode*/
1044  int actualWidth[100];  /* Actual width of each column */
1045  char nullValue[20];    /* The text to print when a NULL comes back from
1046                         ** the database */
1047  char outfile[FILENAME_MAX]; /* Filename for *out */
1048  const char *zDbFilename;    /* name of the database file */
1049  char *zFreeOnClose;         /* Filename to free when closing */
1050  const char *zVfs;           /* Name of VFS to use */
1051  sqlite3_stmt *pStmt;   /* Current statement if any. */
1052  FILE *pLog;            /* Write log output here */
1053  int *aiIndent;         /* Array of indents used in MODE_Explain */
1054  int nIndent;           /* Size of array aiIndent[] */
1055  int iIndent;           /* Index of current op in aiIndent[] */
1056  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1057#if defined(SQLITE_ENABLE_SESSION)
1058  int nSession;             /* Number of active sessions */
1059  OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
1060#endif
1061  ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
1062};
1063
1064
1065/* Allowed values for ShellState.autoEQP
1066*/
1067#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1068#define AUTOEQP_on       1           /* Automatic EQP is on */
1069#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1070#define AUTOEQP_full     3           /* Show full EXPLAIN */
1071
1072/* Allowed values for ShellState.openMode
1073*/
1074#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1075#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1076#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1077#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1078#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1079#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1080#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1081
1082/* Allowed values for ShellState.eTraceType
1083*/
1084#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1085#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1086#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1087
1088/* Bits in the ShellState.flgProgress variable */
1089#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1090#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1091                                   ** callback limit is reached, and for each
1092                                   ** top-level SQL statement */
1093#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1094
1095/*
1096** These are the allowed shellFlgs values
1097*/
1098#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1099#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1100#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1101#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1102#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1103#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1104#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1105
1106/*
1107** Macros for testing and setting shellFlgs
1108*/
1109#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1110#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1111#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1112
1113/*
1114** These are the allowed modes.
1115*/
1116#define MODE_Line     0  /* One column per line.  Blank line between records */
1117#define MODE_Column   1  /* One record per line in neat columns */
1118#define MODE_List     2  /* One record per line with a separator */
1119#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1120#define MODE_Html     4  /* Generate an XHTML table */
1121#define MODE_Insert   5  /* Generate SQL "insert" statements */
1122#define MODE_Quote    6  /* Quote values as for SQL */
1123#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1124#define MODE_Csv      8  /* Quote strings, numbers are plain */
1125#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1126#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1127#define MODE_Pretty  11  /* Pretty-print schemas */
1128#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1129
1130static const char *modeDescr[] = {
1131  "line",
1132  "column",
1133  "list",
1134  "semi",
1135  "html",
1136  "insert",
1137  "quote",
1138  "tcl",
1139  "csv",
1140  "explain",
1141  "ascii",
1142  "prettyprint",
1143  "eqp"
1144};
1145
1146/*
1147** These are the column/row/line separators used by the various
1148** import/export modes.
1149*/
1150#define SEP_Column    "|"
1151#define SEP_Row       "\n"
1152#define SEP_Tab       "\t"
1153#define SEP_Space     " "
1154#define SEP_Comma     ","
1155#define SEP_CrLf      "\r\n"
1156#define SEP_Unit      "\x1F"
1157#define SEP_Record    "\x1E"
1158
1159/*
1160** A callback for the sqlite3_log() interface.
1161*/
1162static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1163  ShellState *p = (ShellState*)pArg;
1164  if( p->pLog==0 ) return;
1165  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1166  fflush(p->pLog);
1167}
1168
1169/*
1170** SQL function:  shell_putsnl(X)
1171**
1172** Write the text X to the screen (or whatever output is being directed)
1173** adding a newline at the end, and then return X.
1174*/
1175static void shellPutsFunc(
1176  sqlite3_context *pCtx,
1177  int nVal,
1178  sqlite3_value **apVal
1179){
1180  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1181  (void)nVal;
1182  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1183  sqlite3_result_value(pCtx, apVal[0]);
1184}
1185
1186/*
1187** SQL function:   edit(VALUE)
1188**                 edit(VALUE,EDITOR)
1189**
1190** These steps:
1191**
1192**     (1) Write VALUE into a temporary file.
1193**     (2) Run program EDITOR on that temporary file.
1194**     (3) Read the temporary file back and return its content as the result.
1195**     (4) Delete the temporary file
1196**
1197** If the EDITOR argument is omitted, use the value in the VISUAL
1198** environment variable.  If still there is no EDITOR, through an error.
1199**
1200** Also throw an error if the EDITOR program returns a non-zero exit code.
1201*/
1202#ifndef SQLITE_NOHAVE_SYSTEM
1203static void editFunc(
1204  sqlite3_context *context,
1205  int argc,
1206  sqlite3_value **argv
1207){
1208  const char *zEditor;
1209  char *zTempFile = 0;
1210  sqlite3 *db;
1211  char *zCmd = 0;
1212  int bBin;
1213  int rc;
1214  int hasCRNL = 0;
1215  FILE *f = 0;
1216  sqlite3_int64 sz;
1217  sqlite3_int64 x;
1218  unsigned char *p = 0;
1219
1220  if( argc==2 ){
1221    zEditor = (const char*)sqlite3_value_text(argv[1]);
1222  }else{
1223    zEditor = getenv("VISUAL");
1224  }
1225  if( zEditor==0 ){
1226    sqlite3_result_error(context, "no editor for edit()", -1);
1227    return;
1228  }
1229  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1230    sqlite3_result_error(context, "NULL input to edit()", -1);
1231    return;
1232  }
1233  db = sqlite3_context_db_handle(context);
1234  zTempFile = 0;
1235  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1236  if( zTempFile==0 ){
1237    sqlite3_uint64 r = 0;
1238    sqlite3_randomness(sizeof(r), &r);
1239    zTempFile = sqlite3_mprintf("temp%llx", r);
1240    if( zTempFile==0 ){
1241      sqlite3_result_error_nomem(context);
1242      return;
1243    }
1244  }
1245  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1246  /* When writing the file to be edited, do \n to \r\n conversions on systems
1247  ** that want \r\n line endings */
1248  f = fopen(zTempFile, bBin ? "wb" : "w");
1249  if( f==0 ){
1250    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1251    goto edit_func_end;
1252  }
1253  sz = sqlite3_value_bytes(argv[0]);
1254  if( bBin ){
1255    x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1256  }else{
1257    const char *z = (const char*)sqlite3_value_text(argv[0]);
1258    /* Remember whether or not the value originally contained \r\n */
1259    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1260    x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1261  }
1262  fclose(f);
1263  f = 0;
1264  if( x!=sz ){
1265    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1266    goto edit_func_end;
1267  }
1268  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1269  if( zCmd==0 ){
1270    sqlite3_result_error_nomem(context);
1271    goto edit_func_end;
1272  }
1273  rc = system(zCmd);
1274  sqlite3_free(zCmd);
1275  if( rc ){
1276    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1277    goto edit_func_end;
1278  }
1279  f = fopen(zTempFile, "rb");
1280  if( f==0 ){
1281    sqlite3_result_error(context,
1282      "edit() cannot reopen temp file after edit", -1);
1283    goto edit_func_end;
1284  }
1285  fseek(f, 0, SEEK_END);
1286  sz = ftell(f);
1287  rewind(f);
1288  p = sqlite3_malloc64( sz+(bBin==0) );
1289  if( p==0 ){
1290    sqlite3_result_error_nomem(context);
1291    goto edit_func_end;
1292  }
1293  x = fread(p, 1, sz, f);
1294  fclose(f);
1295  f = 0;
1296  if( x!=sz ){
1297    sqlite3_result_error(context, "could not read back the whole file", -1);
1298    goto edit_func_end;
1299  }
1300  if( bBin ){
1301    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1302  }else{
1303    sqlite3_int64 i, j;
1304    if( hasCRNL ){
1305      /* If the original contains \r\n then do no conversions back to \n */
1306      j = sz;
1307    }else{
1308      /* If the file did not originally contain \r\n then convert any new
1309      ** \r\n back into \n */
1310      for(i=j=0; i<sz; i++){
1311        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1312        p[j++] = p[i];
1313      }
1314      sz = j;
1315      p[sz] = 0;
1316    }
1317    sqlite3_result_text64(context, (const char*)p, sz,
1318                          sqlite3_free, SQLITE_UTF8);
1319  }
1320  p = 0;
1321
1322edit_func_end:
1323  if( f ) fclose(f);
1324  unlink(zTempFile);
1325  sqlite3_free(zTempFile);
1326  sqlite3_free(p);
1327}
1328#endif /* SQLITE_NOHAVE_SYSTEM */
1329
1330/*
1331** Save or restore the current output mode
1332*/
1333static void outputModePush(ShellState *p){
1334  p->modePrior = p->mode;
1335  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1336  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1337}
1338static void outputModePop(ShellState *p){
1339  p->mode = p->modePrior;
1340  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1341  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1342}
1343
1344/*
1345** Output the given string as a hex-encoded blob (eg. X'1234' )
1346*/
1347static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1348  int i;
1349  char *zBlob = (char *)pBlob;
1350  raw_printf(out,"X'");
1351  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1352  raw_printf(out,"'");
1353}
1354
1355/*
1356** Find a string that is not found anywhere in z[].  Return a pointer
1357** to that string.
1358**
1359** Try to use zA and zB first.  If both of those are already found in z[]
1360** then make up some string and store it in the buffer zBuf.
1361*/
1362static const char *unused_string(
1363  const char *z,                    /* Result must not appear anywhere in z */
1364  const char *zA, const char *zB,   /* Try these first */
1365  char *zBuf                        /* Space to store a generated string */
1366){
1367  unsigned i = 0;
1368  if( strstr(z, zA)==0 ) return zA;
1369  if( strstr(z, zB)==0 ) return zB;
1370  do{
1371    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1372  }while( strstr(z,zBuf)!=0 );
1373  return zBuf;
1374}
1375
1376/*
1377** Output the given string as a quoted string using SQL quoting conventions.
1378**
1379** See also: output_quoted_escaped_string()
1380*/
1381static void output_quoted_string(FILE *out, const char *z){
1382  int i;
1383  char c;
1384  setBinaryMode(out, 1);
1385  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1386  if( c==0 ){
1387    utf8_printf(out,"'%s'",z);
1388  }else{
1389    raw_printf(out, "'");
1390    while( *z ){
1391      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1392      if( c=='\'' ) i++;
1393      if( i ){
1394        utf8_printf(out, "%.*s", i, z);
1395        z += i;
1396      }
1397      if( c=='\'' ){
1398        raw_printf(out, "'");
1399        continue;
1400      }
1401      if( c==0 ){
1402        break;
1403      }
1404      z++;
1405    }
1406    raw_printf(out, "'");
1407  }
1408  setTextMode(out, 1);
1409}
1410
1411/*
1412** Output the given string as a quoted string using SQL quoting conventions.
1413** Additionallly , escape the "\n" and "\r" characters so that they do not
1414** get corrupted by end-of-line translation facilities in some operating
1415** systems.
1416**
1417** This is like output_quoted_string() but with the addition of the \r\n
1418** escape mechanism.
1419*/
1420static void output_quoted_escaped_string(FILE *out, const char *z){
1421  int i;
1422  char c;
1423  setBinaryMode(out, 1);
1424  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1425  if( c==0 ){
1426    utf8_printf(out,"'%s'",z);
1427  }else{
1428    const char *zNL = 0;
1429    const char *zCR = 0;
1430    int nNL = 0;
1431    int nCR = 0;
1432    char zBuf1[20], zBuf2[20];
1433    for(i=0; z[i]; i++){
1434      if( z[i]=='\n' ) nNL++;
1435      if( z[i]=='\r' ) nCR++;
1436    }
1437    if( nNL ){
1438      raw_printf(out, "replace(");
1439      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1440    }
1441    if( nCR ){
1442      raw_printf(out, "replace(");
1443      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1444    }
1445    raw_printf(out, "'");
1446    while( *z ){
1447      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1448      if( c=='\'' ) i++;
1449      if( i ){
1450        utf8_printf(out, "%.*s", i, z);
1451        z += i;
1452      }
1453      if( c=='\'' ){
1454        raw_printf(out, "'");
1455        continue;
1456      }
1457      if( c==0 ){
1458        break;
1459      }
1460      z++;
1461      if( c=='\n' ){
1462        raw_printf(out, "%s", zNL);
1463        continue;
1464      }
1465      raw_printf(out, "%s", zCR);
1466    }
1467    raw_printf(out, "'");
1468    if( nCR ){
1469      raw_printf(out, ",'%s',char(13))", zCR);
1470    }
1471    if( nNL ){
1472      raw_printf(out, ",'%s',char(10))", zNL);
1473    }
1474  }
1475  setTextMode(out, 1);
1476}
1477
1478/*
1479** Output the given string as a quoted according to C or TCL quoting rules.
1480*/
1481static void output_c_string(FILE *out, const char *z){
1482  unsigned int c;
1483  fputc('"', out);
1484  while( (c = *(z++))!=0 ){
1485    if( c=='\\' ){
1486      fputc(c, out);
1487      fputc(c, out);
1488    }else if( c=='"' ){
1489      fputc('\\', out);
1490      fputc('"', out);
1491    }else if( c=='\t' ){
1492      fputc('\\', out);
1493      fputc('t', out);
1494    }else if( c=='\n' ){
1495      fputc('\\', out);
1496      fputc('n', out);
1497    }else if( c=='\r' ){
1498      fputc('\\', out);
1499      fputc('r', out);
1500    }else if( !isprint(c&0xff) ){
1501      raw_printf(out, "\\%03o", c&0xff);
1502    }else{
1503      fputc(c, out);
1504    }
1505  }
1506  fputc('"', out);
1507}
1508
1509/*
1510** Output the given string with characters that are special to
1511** HTML escaped.
1512*/
1513static void output_html_string(FILE *out, const char *z){
1514  int i;
1515  if( z==0 ) z = "";
1516  while( *z ){
1517    for(i=0;   z[i]
1518            && z[i]!='<'
1519            && z[i]!='&'
1520            && z[i]!='>'
1521            && z[i]!='\"'
1522            && z[i]!='\'';
1523        i++){}
1524    if( i>0 ){
1525      utf8_printf(out,"%.*s",i,z);
1526    }
1527    if( z[i]=='<' ){
1528      raw_printf(out,"&lt;");
1529    }else if( z[i]=='&' ){
1530      raw_printf(out,"&amp;");
1531    }else if( z[i]=='>' ){
1532      raw_printf(out,"&gt;");
1533    }else if( z[i]=='\"' ){
1534      raw_printf(out,"&quot;");
1535    }else if( z[i]=='\'' ){
1536      raw_printf(out,"&#39;");
1537    }else{
1538      break;
1539    }
1540    z += i + 1;
1541  }
1542}
1543
1544/*
1545** If a field contains any character identified by a 1 in the following
1546** array, then the string must be quoted for CSV.
1547*/
1548static const char needCsvQuote[] = {
1549  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1550  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1551  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1552  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1553  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1554  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1555  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1556  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1557  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1558  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1559  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1560  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1561  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1562  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1563  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1564  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1565};
1566
1567/*
1568** Output a single term of CSV.  Actually, p->colSeparator is used for
1569** the separator, which may or may not be a comma.  p->nullValue is
1570** the null value.  Strings are quoted if necessary.  The separator
1571** is only issued if bSep is true.
1572*/
1573static void output_csv(ShellState *p, const char *z, int bSep){
1574  FILE *out = p->out;
1575  if( z==0 ){
1576    utf8_printf(out,"%s",p->nullValue);
1577  }else{
1578    int i;
1579    int nSep = strlen30(p->colSeparator);
1580    for(i=0; z[i]; i++){
1581      if( needCsvQuote[((unsigned char*)z)[i]]
1582         || (z[i]==p->colSeparator[0] &&
1583             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1584        i = 0;
1585        break;
1586      }
1587    }
1588    if( i==0 ){
1589      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1590      utf8_printf(out, "%s", zQuoted);
1591      sqlite3_free(zQuoted);
1592    }else{
1593      utf8_printf(out, "%s", z);
1594    }
1595  }
1596  if( bSep ){
1597    utf8_printf(p->out, "%s", p->colSeparator);
1598  }
1599}
1600
1601/*
1602** This routine runs when the user presses Ctrl-C
1603*/
1604static void interrupt_handler(int NotUsed){
1605  UNUSED_PARAMETER(NotUsed);
1606  seenInterrupt++;
1607  if( seenInterrupt>2 ) exit(1);
1608  if( globalDb ) sqlite3_interrupt(globalDb);
1609}
1610
1611#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1612/*
1613** This routine runs for console events (e.g. Ctrl-C) on Win32
1614*/
1615static BOOL WINAPI ConsoleCtrlHandler(
1616  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1617){
1618  if( dwCtrlType==CTRL_C_EVENT ){
1619    interrupt_handler(0);
1620    return TRUE;
1621  }
1622  return FALSE;
1623}
1624#endif
1625
1626#ifndef SQLITE_OMIT_AUTHORIZATION
1627/*
1628** When the ".auth ON" is set, the following authorizer callback is
1629** invoked.  It always returns SQLITE_OK.
1630*/
1631static int shellAuth(
1632  void *pClientData,
1633  int op,
1634  const char *zA1,
1635  const char *zA2,
1636  const char *zA3,
1637  const char *zA4
1638){
1639  ShellState *p = (ShellState*)pClientData;
1640  static const char *azAction[] = { 0,
1641     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1642     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1643     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1644     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1645     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1646     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1647     "PRAGMA",               "READ",                 "SELECT",
1648     "TRANSACTION",          "UPDATE",               "ATTACH",
1649     "DETACH",               "ALTER_TABLE",          "REINDEX",
1650     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1651     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1652  };
1653  int i;
1654  const char *az[4];
1655  az[0] = zA1;
1656  az[1] = zA2;
1657  az[2] = zA3;
1658  az[3] = zA4;
1659  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1660  for(i=0; i<4; i++){
1661    raw_printf(p->out, " ");
1662    if( az[i] ){
1663      output_c_string(p->out, az[i]);
1664    }else{
1665      raw_printf(p->out, "NULL");
1666    }
1667  }
1668  raw_printf(p->out, "\n");
1669  return SQLITE_OK;
1670}
1671#endif
1672
1673/*
1674** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1675**
1676** This routine converts some CREATE TABLE statements for shadow tables
1677** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1678*/
1679static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1680  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1681    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1682  }else{
1683    utf8_printf(out, "%s%s", z, zTail);
1684  }
1685}
1686static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1687  char c = z[n];
1688  z[n] = 0;
1689  printSchemaLine(out, z, zTail);
1690  z[n] = c;
1691}
1692
1693/*
1694** Return true if string z[] has nothing but whitespace and comments to the
1695** end of the first line.
1696*/
1697static int wsToEol(const char *z){
1698  int i;
1699  for(i=0; z[i]; i++){
1700    if( z[i]=='\n' ) return 1;
1701    if( IsSpace(z[i]) ) continue;
1702    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1703    return 0;
1704  }
1705  return 1;
1706}
1707
1708/*
1709** Add a new entry to the EXPLAIN QUERY PLAN data
1710*/
1711static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1712  EQPGraphRow *pNew;
1713  int nText = strlen30(zText);
1714  if( p->autoEQPtest ){
1715    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1716  }
1717  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1718  if( pNew==0 ) shell_out_of_memory();
1719  pNew->iEqpId = iEqpId;
1720  pNew->iParentId = p2;
1721  memcpy(pNew->zText, zText, nText+1);
1722  pNew->pNext = 0;
1723  if( p->sGraph.pLast ){
1724    p->sGraph.pLast->pNext = pNew;
1725  }else{
1726    p->sGraph.pRow = pNew;
1727  }
1728  p->sGraph.pLast = pNew;
1729}
1730
1731/*
1732** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1733** in p->sGraph.
1734*/
1735static void eqp_reset(ShellState *p){
1736  EQPGraphRow *pRow, *pNext;
1737  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1738    pNext = pRow->pNext;
1739    sqlite3_free(pRow);
1740  }
1741  memset(&p->sGraph, 0, sizeof(p->sGraph));
1742}
1743
1744/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1745** pOld, or return the first such line if pOld is NULL
1746*/
1747static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1748  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1749  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1750  return pRow;
1751}
1752
1753/* Render a single level of the graph that has iEqpId as its parent.  Called
1754** recursively to render sublevels.
1755*/
1756static void eqp_render_level(ShellState *p, int iEqpId){
1757  EQPGraphRow *pRow, *pNext;
1758  int n = strlen30(p->sGraph.zPrefix);
1759  char *z;
1760  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1761    pNext = eqp_next_row(p, iEqpId, pRow);
1762    z = pRow->zText;
1763    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
1764    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1765      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1766      eqp_render_level(p, pRow->iEqpId);
1767      p->sGraph.zPrefix[n] = 0;
1768    }
1769  }
1770}
1771
1772/*
1773** Display and reset the EXPLAIN QUERY PLAN data
1774*/
1775static void eqp_render(ShellState *p){
1776  EQPGraphRow *pRow = p->sGraph.pRow;
1777  if( pRow ){
1778    if( pRow->zText[0]=='-' ){
1779      if( pRow->pNext==0 ){
1780        eqp_reset(p);
1781        return;
1782      }
1783      utf8_printf(p->out, "%s\n", pRow->zText+3);
1784      p->sGraph.pRow = pRow->pNext;
1785      sqlite3_free(pRow);
1786    }else{
1787      utf8_printf(p->out, "QUERY PLAN\n");
1788    }
1789    p->sGraph.zPrefix[0] = 0;
1790    eqp_render_level(p, 0);
1791    eqp_reset(p);
1792  }
1793}
1794
1795#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1796/*
1797** Progress handler callback.
1798*/
1799static int progress_handler(void *pClientData) {
1800  ShellState *p = (ShellState*)pClientData;
1801  p->nProgress++;
1802  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1803    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1804    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1805    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
1806    return 1;
1807  }
1808  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
1809    raw_printf(p->out, "Progress %u\n", p->nProgress);
1810  }
1811  return 0;
1812}
1813#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
1814
1815/*
1816** This is the callback routine that the shell
1817** invokes for each row of a query result.
1818*/
1819static int shell_callback(
1820  void *pArg,
1821  int nArg,        /* Number of result columns */
1822  char **azArg,    /* Text of each result column */
1823  char **azCol,    /* Column names */
1824  int *aiType      /* Column types */
1825){
1826  int i;
1827  ShellState *p = (ShellState*)pArg;
1828
1829  if( azArg==0 ) return 0;
1830  switch( p->cMode ){
1831    case MODE_Line: {
1832      int w = 5;
1833      if( azArg==0 ) break;
1834      for(i=0; i<nArg; i++){
1835        int len = strlen30(azCol[i] ? azCol[i] : "");
1836        if( len>w ) w = len;
1837      }
1838      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1839      for(i=0; i<nArg; i++){
1840        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1841                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1842      }
1843      break;
1844    }
1845    case MODE_Explain:
1846    case MODE_Column: {
1847      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1848      const int *colWidth;
1849      int showHdr;
1850      char *rowSep;
1851      if( p->cMode==MODE_Column ){
1852        colWidth = p->colWidth;
1853        showHdr = p->showHeader;
1854        rowSep = p->rowSeparator;
1855      }else{
1856        colWidth = aExplainWidths;
1857        showHdr = 1;
1858        rowSep = SEP_Row;
1859      }
1860      if( p->cnt++==0 ){
1861        for(i=0; i<nArg; i++){
1862          int w, n;
1863          if( i<ArraySize(p->colWidth) ){
1864            w = colWidth[i];
1865          }else{
1866            w = 0;
1867          }
1868          if( w==0 ){
1869            w = strlenChar(azCol[i] ? azCol[i] : "");
1870            if( w<10 ) w = 10;
1871            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1872            if( w<n ) w = n;
1873          }
1874          if( i<ArraySize(p->actualWidth) ){
1875            p->actualWidth[i] = w;
1876          }
1877          if( showHdr ){
1878            utf8_width_print(p->out, w, azCol[i]);
1879            utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1880          }
1881        }
1882        if( showHdr ){
1883          for(i=0; i<nArg; i++){
1884            int w;
1885            if( i<ArraySize(p->actualWidth) ){
1886               w = p->actualWidth[i];
1887               if( w<0 ) w = -w;
1888            }else{
1889               w = 10;
1890            }
1891            utf8_printf(p->out,"%-*.*s%s",w,w,
1892                   "----------------------------------------------------------"
1893                   "----------------------------------------------------------",
1894                    i==nArg-1 ? rowSep : "  ");
1895          }
1896        }
1897      }
1898      if( azArg==0 ) break;
1899      for(i=0; i<nArg; i++){
1900        int w;
1901        if( i<ArraySize(p->actualWidth) ){
1902           w = p->actualWidth[i];
1903        }else{
1904           w = 10;
1905        }
1906        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1907          w = strlenChar(azArg[i]);
1908        }
1909        if( i==1 && p->aiIndent && p->pStmt ){
1910          if( p->iIndent<p->nIndent ){
1911            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1912          }
1913          p->iIndent++;
1914        }
1915        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1916        utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1917      }
1918      break;
1919    }
1920    case MODE_Semi: {   /* .schema and .fullschema output */
1921      printSchemaLine(p->out, azArg[0], ";\n");
1922      break;
1923    }
1924    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
1925      char *z;
1926      int j;
1927      int nParen = 0;
1928      char cEnd = 0;
1929      char c;
1930      int nLine = 0;
1931      assert( nArg==1 );
1932      if( azArg[0]==0 ) break;
1933      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1934       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1935      ){
1936        utf8_printf(p->out, "%s;\n", azArg[0]);
1937        break;
1938      }
1939      z = sqlite3_mprintf("%s", azArg[0]);
1940      j = 0;
1941      for(i=0; IsSpace(z[i]); i++){}
1942      for(; (c = z[i])!=0; i++){
1943        if( IsSpace(c) ){
1944          if( z[j-1]=='\r' ) z[j-1] = '\n';
1945          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1946        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1947          j--;
1948        }
1949        z[j++] = c;
1950      }
1951      while( j>0 && IsSpace(z[j-1]) ){ j--; }
1952      z[j] = 0;
1953      if( strlen30(z)>=79 ){
1954        for(i=j=0; (c = z[i])!=0; i++){  /* Copy changes from z[i] back to z[j] */
1955          if( c==cEnd ){
1956            cEnd = 0;
1957          }else if( c=='"' || c=='\'' || c=='`' ){
1958            cEnd = c;
1959          }else if( c=='[' ){
1960            cEnd = ']';
1961          }else if( c=='-' && z[i+1]=='-' ){
1962            cEnd = '\n';
1963          }else if( c=='(' ){
1964            nParen++;
1965          }else if( c==')' ){
1966            nParen--;
1967            if( nLine>0 && nParen==0 && j>0 ){
1968              printSchemaLineN(p->out, z, j, "\n");
1969              j = 0;
1970            }
1971          }
1972          z[j++] = c;
1973          if( nParen==1 && cEnd==0
1974           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1975          ){
1976            if( c=='\n' ) j--;
1977            printSchemaLineN(p->out, z, j, "\n  ");
1978            j = 0;
1979            nLine++;
1980            while( IsSpace(z[i+1]) ){ i++; }
1981          }
1982        }
1983        z[j] = 0;
1984      }
1985      printSchemaLine(p->out, z, ";\n");
1986      sqlite3_free(z);
1987      break;
1988    }
1989    case MODE_List: {
1990      if( p->cnt++==0 && p->showHeader ){
1991        for(i=0; i<nArg; i++){
1992          utf8_printf(p->out,"%s%s",azCol[i],
1993                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
1994        }
1995      }
1996      if( azArg==0 ) break;
1997      for(i=0; i<nArg; i++){
1998        char *z = azArg[i];
1999        if( z==0 ) z = p->nullValue;
2000        utf8_printf(p->out, "%s", z);
2001        if( i<nArg-1 ){
2002          utf8_printf(p->out, "%s", p->colSeparator);
2003        }else{
2004          utf8_printf(p->out, "%s", p->rowSeparator);
2005        }
2006      }
2007      break;
2008    }
2009    case MODE_Html: {
2010      if( p->cnt++==0 && p->showHeader ){
2011        raw_printf(p->out,"<TR>");
2012        for(i=0; i<nArg; i++){
2013          raw_printf(p->out,"<TH>");
2014          output_html_string(p->out, azCol[i]);
2015          raw_printf(p->out,"</TH>\n");
2016        }
2017        raw_printf(p->out,"</TR>\n");
2018      }
2019      if( azArg==0 ) break;
2020      raw_printf(p->out,"<TR>");
2021      for(i=0; i<nArg; i++){
2022        raw_printf(p->out,"<TD>");
2023        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2024        raw_printf(p->out,"</TD>\n");
2025      }
2026      raw_printf(p->out,"</TR>\n");
2027      break;
2028    }
2029    case MODE_Tcl: {
2030      if( p->cnt++==0 && p->showHeader ){
2031        for(i=0; i<nArg; i++){
2032          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2033          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2034        }
2035        utf8_printf(p->out, "%s", p->rowSeparator);
2036      }
2037      if( azArg==0 ) break;
2038      for(i=0; i<nArg; i++){
2039        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2040        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2041      }
2042      utf8_printf(p->out, "%s", p->rowSeparator);
2043      break;
2044    }
2045    case MODE_Csv: {
2046      setBinaryMode(p->out, 1);
2047      if( p->cnt++==0 && p->showHeader ){
2048        for(i=0; i<nArg; i++){
2049          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2050        }
2051        utf8_printf(p->out, "%s", p->rowSeparator);
2052      }
2053      if( nArg>0 ){
2054        for(i=0; i<nArg; i++){
2055          output_csv(p, azArg[i], i<nArg-1);
2056        }
2057        utf8_printf(p->out, "%s", p->rowSeparator);
2058      }
2059      setTextMode(p->out, 1);
2060      break;
2061    }
2062    case MODE_Insert: {
2063      if( azArg==0 ) break;
2064      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2065      if( p->showHeader ){
2066        raw_printf(p->out,"(");
2067        for(i=0; i<nArg; i++){
2068          if( i>0 ) raw_printf(p->out, ",");
2069          if( quoteChar(azCol[i]) ){
2070            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2071            utf8_printf(p->out, "%s", z);
2072            sqlite3_free(z);
2073          }else{
2074            raw_printf(p->out, "%s", azCol[i]);
2075          }
2076        }
2077        raw_printf(p->out,")");
2078      }
2079      p->cnt++;
2080      for(i=0; i<nArg; i++){
2081        raw_printf(p->out, i>0 ? "," : " VALUES(");
2082        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2083          utf8_printf(p->out,"NULL");
2084        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2085          if( ShellHasFlag(p, SHFLG_Newlines) ){
2086            output_quoted_string(p->out, azArg[i]);
2087          }else{
2088            output_quoted_escaped_string(p->out, azArg[i]);
2089          }
2090        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2091          utf8_printf(p->out,"%s", azArg[i]);
2092        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2093          char z[50];
2094          double r = sqlite3_column_double(p->pStmt, i);
2095          sqlite3_uint64 ur;
2096          memcpy(&ur,&r,sizeof(r));
2097          if( ur==0x7ff0000000000000LL ){
2098            raw_printf(p->out, "1e999");
2099          }else if( ur==0xfff0000000000000LL ){
2100            raw_printf(p->out, "-1e999");
2101          }else{
2102            sqlite3_snprintf(50,z,"%!.20g", r);
2103            raw_printf(p->out, "%s", z);
2104          }
2105        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2106          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2107          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2108          output_hex_blob(p->out, pBlob, nBlob);
2109        }else if( isNumber(azArg[i], 0) ){
2110          utf8_printf(p->out,"%s", azArg[i]);
2111        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2112          output_quoted_string(p->out, azArg[i]);
2113        }else{
2114          output_quoted_escaped_string(p->out, azArg[i]);
2115        }
2116      }
2117      raw_printf(p->out,");\n");
2118      break;
2119    }
2120    case MODE_Quote: {
2121      if( azArg==0 ) break;
2122      if( p->cnt==0 && p->showHeader ){
2123        for(i=0; i<nArg; i++){
2124          if( i>0 ) raw_printf(p->out, ",");
2125          output_quoted_string(p->out, azCol[i]);
2126        }
2127        raw_printf(p->out,"\n");
2128      }
2129      p->cnt++;
2130      for(i=0; i<nArg; i++){
2131        if( i>0 ) raw_printf(p->out, ",");
2132        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2133          utf8_printf(p->out,"NULL");
2134        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2135          output_quoted_string(p->out, azArg[i]);
2136        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2137          utf8_printf(p->out,"%s", azArg[i]);
2138        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2139          char z[50];
2140          double r = sqlite3_column_double(p->pStmt, i);
2141          sqlite3_snprintf(50,z,"%!.20g", r);
2142          raw_printf(p->out, "%s", z);
2143        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2144          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2145          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2146          output_hex_blob(p->out, pBlob, nBlob);
2147        }else if( isNumber(azArg[i], 0) ){
2148          utf8_printf(p->out,"%s", azArg[i]);
2149        }else{
2150          output_quoted_string(p->out, azArg[i]);
2151        }
2152      }
2153      raw_printf(p->out,"\n");
2154      break;
2155    }
2156    case MODE_Ascii: {
2157      if( p->cnt++==0 && p->showHeader ){
2158        for(i=0; i<nArg; i++){
2159          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2160          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2161        }
2162        utf8_printf(p->out, "%s", p->rowSeparator);
2163      }
2164      if( azArg==0 ) break;
2165      for(i=0; i<nArg; i++){
2166        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2167        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2168      }
2169      utf8_printf(p->out, "%s", p->rowSeparator);
2170      break;
2171    }
2172    case MODE_EQP: {
2173      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2174      break;
2175    }
2176  }
2177  return 0;
2178}
2179
2180/*
2181** This is the callback routine that the SQLite library
2182** invokes for each row of a query result.
2183*/
2184static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2185  /* since we don't have type info, call the shell_callback with a NULL value */
2186  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2187}
2188
2189/*
2190** This is the callback routine from sqlite3_exec() that appends all
2191** output onto the end of a ShellText object.
2192*/
2193static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2194  ShellText *p = (ShellText*)pArg;
2195  int i;
2196  UNUSED_PARAMETER(az);
2197  if( azArg==0 ) return 0;
2198  if( p->n ) appendText(p, "|", 0);
2199  for(i=0; i<nArg; i++){
2200    if( i ) appendText(p, ",", 0);
2201    if( azArg[i] ) appendText(p, azArg[i], 0);
2202  }
2203  return 0;
2204}
2205
2206/*
2207** Generate an appropriate SELFTEST table in the main database.
2208*/
2209static void createSelftestTable(ShellState *p){
2210  char *zErrMsg = 0;
2211  sqlite3_exec(p->db,
2212    "SAVEPOINT selftest_init;\n"
2213    "CREATE TABLE IF NOT EXISTS selftest(\n"
2214    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2215    "  op TEXT,\n"                   /* Operator:  memo run */
2216    "  cmd TEXT,\n"                  /* Command text */
2217    "  ans TEXT\n"                   /* Desired answer */
2218    ");"
2219    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2220    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2221    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2222    "         'memo','Tests generated by --init');\n"
2223    "INSERT INTO [_shell$self]\n"
2224    "  SELECT 'run',\n"
2225    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2226                                 "FROM sqlite_master ORDER BY 2'',224))',\n"
2227    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2228                          "FROM sqlite_master ORDER BY 2',224));\n"
2229    "INSERT INTO [_shell$self]\n"
2230    "  SELECT 'run',"
2231    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2232    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2233    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2234    "  FROM (\n"
2235    "    SELECT name FROM sqlite_master\n"
2236    "     WHERE type='table'\n"
2237    "       AND name<>'selftest'\n"
2238    "       AND coalesce(rootpage,0)>0\n"
2239    "  )\n"
2240    " ORDER BY name;\n"
2241    "INSERT INTO [_shell$self]\n"
2242    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2243    "INSERT INTO selftest(tno,op,cmd,ans)"
2244    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2245    "DROP TABLE [_shell$self];"
2246    ,0,0,&zErrMsg);
2247  if( zErrMsg ){
2248    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2249    sqlite3_free(zErrMsg);
2250  }
2251  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2252}
2253
2254
2255/*
2256** Set the destination table field of the ShellState structure to
2257** the name of the table given.  Escape any quote characters in the
2258** table name.
2259*/
2260static void set_table_name(ShellState *p, const char *zName){
2261  int i, n;
2262  char cQuote;
2263  char *z;
2264
2265  if( p->zDestTable ){
2266    free(p->zDestTable);
2267    p->zDestTable = 0;
2268  }
2269  if( zName==0 ) return;
2270  cQuote = quoteChar(zName);
2271  n = strlen30(zName);
2272  if( cQuote ) n += n+2;
2273  z = p->zDestTable = malloc( n+1 );
2274  if( z==0 ) shell_out_of_memory();
2275  n = 0;
2276  if( cQuote ) z[n++] = cQuote;
2277  for(i=0; zName[i]; i++){
2278    z[n++] = zName[i];
2279    if( zName[i]==cQuote ) z[n++] = cQuote;
2280  }
2281  if( cQuote ) z[n++] = cQuote;
2282  z[n] = 0;
2283}
2284
2285
2286/*
2287** Execute a query statement that will generate SQL output.  Print
2288** the result columns, comma-separated, on a line and then add a
2289** semicolon terminator to the end of that line.
2290**
2291** If the number of columns is 1 and that column contains text "--"
2292** then write the semicolon on a separate line.  That way, if a
2293** "--" comment occurs at the end of the statement, the comment
2294** won't consume the semicolon terminator.
2295*/
2296static int run_table_dump_query(
2297  ShellState *p,           /* Query context */
2298  const char *zSelect,     /* SELECT statement to extract content */
2299  const char *zFirstRow    /* Print before first row, if not NULL */
2300){
2301  sqlite3_stmt *pSelect;
2302  int rc;
2303  int nResult;
2304  int i;
2305  const char *z;
2306  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2307  if( rc!=SQLITE_OK || !pSelect ){
2308    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2309                sqlite3_errmsg(p->db));
2310    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2311    return rc;
2312  }
2313  rc = sqlite3_step(pSelect);
2314  nResult = sqlite3_column_count(pSelect);
2315  while( rc==SQLITE_ROW ){
2316    if( zFirstRow ){
2317      utf8_printf(p->out, "%s", zFirstRow);
2318      zFirstRow = 0;
2319    }
2320    z = (const char*)sqlite3_column_text(pSelect, 0);
2321    utf8_printf(p->out, "%s", z);
2322    for(i=1; i<nResult; i++){
2323      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2324    }
2325    if( z==0 ) z = "";
2326    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2327    if( z[0] ){
2328      raw_printf(p->out, "\n;\n");
2329    }else{
2330      raw_printf(p->out, ";\n");
2331    }
2332    rc = sqlite3_step(pSelect);
2333  }
2334  rc = sqlite3_finalize(pSelect);
2335  if( rc!=SQLITE_OK ){
2336    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2337                sqlite3_errmsg(p->db));
2338    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2339  }
2340  return rc;
2341}
2342
2343/*
2344** Allocate space and save off current error string.
2345*/
2346static char *save_err_msg(
2347  sqlite3 *db            /* Database to query */
2348){
2349  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2350  char *zErrMsg = sqlite3_malloc64(nErrMsg);
2351  if( zErrMsg ){
2352    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2353  }
2354  return zErrMsg;
2355}
2356
2357#ifdef __linux__
2358/*
2359** Attempt to display I/O stats on Linux using /proc/PID/io
2360*/
2361static void displayLinuxIoStats(FILE *out){
2362  FILE *in;
2363  char z[200];
2364  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2365  in = fopen(z, "rb");
2366  if( in==0 ) return;
2367  while( fgets(z, sizeof(z), in)!=0 ){
2368    static const struct {
2369      const char *zPattern;
2370      const char *zDesc;
2371    } aTrans[] = {
2372      { "rchar: ",                  "Bytes received by read():" },
2373      { "wchar: ",                  "Bytes sent to write():"    },
2374      { "syscr: ",                  "Read() system calls:"      },
2375      { "syscw: ",                  "Write() system calls:"     },
2376      { "read_bytes: ",             "Bytes read from storage:"  },
2377      { "write_bytes: ",            "Bytes written to storage:" },
2378      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2379    };
2380    int i;
2381    for(i=0; i<ArraySize(aTrans); i++){
2382      int n = strlen30(aTrans[i].zPattern);
2383      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2384        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2385        break;
2386      }
2387    }
2388  }
2389  fclose(in);
2390}
2391#endif
2392
2393/*
2394** Display a single line of status using 64-bit values.
2395*/
2396static void displayStatLine(
2397  ShellState *p,            /* The shell context */
2398  char *zLabel,             /* Label for this one line */
2399  char *zFormat,            /* Format for the result */
2400  int iStatusCtrl,          /* Which status to display */
2401  int bReset                /* True to reset the stats */
2402){
2403  sqlite3_int64 iCur = -1;
2404  sqlite3_int64 iHiwtr = -1;
2405  int i, nPercent;
2406  char zLine[200];
2407  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2408  for(i=0, nPercent=0; zFormat[i]; i++){
2409    if( zFormat[i]=='%' ) nPercent++;
2410  }
2411  if( nPercent>1 ){
2412    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2413  }else{
2414    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2415  }
2416  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2417}
2418
2419/*
2420** Display memory stats.
2421*/
2422static int display_stats(
2423  sqlite3 *db,                /* Database to query */
2424  ShellState *pArg,           /* Pointer to ShellState */
2425  int bReset                  /* True to reset the stats */
2426){
2427  int iCur;
2428  int iHiwtr;
2429  FILE *out;
2430  if( pArg==0 || pArg->out==0 ) return 0;
2431  out = pArg->out;
2432
2433  if( pArg->pStmt && (pArg->statsOn & 2) ){
2434    int nCol, i, x;
2435    sqlite3_stmt *pStmt = pArg->pStmt;
2436    char z[100];
2437    nCol = sqlite3_column_count(pStmt);
2438    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2439    for(i=0; i<nCol; i++){
2440      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2441      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2442#ifndef SQLITE_OMIT_DECLTYPE
2443      sqlite3_snprintf(30, z+x, "declared type:");
2444      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2445#endif
2446#ifdef SQLITE_ENABLE_COLUMN_METADATA
2447      sqlite3_snprintf(30, z+x, "database name:");
2448      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2449      sqlite3_snprintf(30, z+x, "table name:");
2450      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2451      sqlite3_snprintf(30, z+x, "origin name:");
2452      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2453#endif
2454    }
2455  }
2456
2457  displayStatLine(pArg, "Memory Used:",
2458     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2459  displayStatLine(pArg, "Number of Outstanding Allocations:",
2460     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2461  if( pArg->shellFlgs & SHFLG_Pagecache ){
2462    displayStatLine(pArg, "Number of Pcache Pages Used:",
2463       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2464  }
2465  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2466     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2467  displayStatLine(pArg, "Largest Allocation:",
2468     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2469  displayStatLine(pArg, "Largest Pcache Allocation:",
2470     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2471#ifdef YYTRACKMAXSTACKDEPTH
2472  displayStatLine(pArg, "Deepest Parser Stack:",
2473     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2474#endif
2475
2476  if( db ){
2477    if( pArg->shellFlgs & SHFLG_Lookaside ){
2478      iHiwtr = iCur = -1;
2479      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2480                        &iCur, &iHiwtr, bReset);
2481      raw_printf(pArg->out,
2482              "Lookaside Slots Used:                %d (max %d)\n",
2483              iCur, iHiwtr);
2484      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2485                        &iCur, &iHiwtr, bReset);
2486      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2487              iHiwtr);
2488      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2489                        &iCur, &iHiwtr, bReset);
2490      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2491              iHiwtr);
2492      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2493                        &iCur, &iHiwtr, bReset);
2494      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2495              iHiwtr);
2496    }
2497    iHiwtr = iCur = -1;
2498    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2499    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2500            iCur);
2501    iHiwtr = iCur = -1;
2502    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2503    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2504    iHiwtr = iCur = -1;
2505    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2506    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2507    iHiwtr = iCur = -1;
2508    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2509    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2510    iHiwtr = iCur = -1;
2511    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2512    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2513    iHiwtr = iCur = -1;
2514    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2515    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2516            iCur);
2517    iHiwtr = iCur = -1;
2518    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2519    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2520            iCur);
2521  }
2522
2523  if( pArg->pStmt ){
2524    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2525                               bReset);
2526    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2527    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2528    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2529    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2530    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2531    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2532    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2533    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2534    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2535    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2536    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2537    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2538    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2539  }
2540
2541#ifdef __linux__
2542  displayLinuxIoStats(pArg->out);
2543#endif
2544
2545  /* Do not remove this machine readable comment: extra-stats-output-here */
2546
2547  return 0;
2548}
2549
2550/*
2551** Display scan stats.
2552*/
2553static void display_scanstats(
2554  sqlite3 *db,                    /* Database to query */
2555  ShellState *pArg                /* Pointer to ShellState */
2556){
2557#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2558  UNUSED_PARAMETER(db);
2559  UNUSED_PARAMETER(pArg);
2560#else
2561  int i, k, n, mx;
2562  raw_printf(pArg->out, "-------- scanstats --------\n");
2563  mx = 0;
2564  for(k=0; k<=mx; k++){
2565    double rEstLoop = 1.0;
2566    for(i=n=0; 1; i++){
2567      sqlite3_stmt *p = pArg->pStmt;
2568      sqlite3_int64 nLoop, nVisit;
2569      double rEst;
2570      int iSid;
2571      const char *zExplain;
2572      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2573        break;
2574      }
2575      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2576      if( iSid>mx ) mx = iSid;
2577      if( iSid!=k ) continue;
2578      if( n==0 ){
2579        rEstLoop = (double)nLoop;
2580        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2581      }
2582      n++;
2583      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2584      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2585      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2586      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2587      rEstLoop *= rEst;
2588      raw_printf(pArg->out,
2589          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2590          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2591      );
2592    }
2593  }
2594  raw_printf(pArg->out, "---------------------------\n");
2595#endif
2596}
2597
2598/*
2599** Parameter azArray points to a zero-terminated array of strings. zStr
2600** points to a single nul-terminated string. Return non-zero if zStr
2601** is equal, according to strcmp(), to any of the strings in the array.
2602** Otherwise, return zero.
2603*/
2604static int str_in_array(const char *zStr, const char **azArray){
2605  int i;
2606  for(i=0; azArray[i]; i++){
2607    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2608  }
2609  return 0;
2610}
2611
2612/*
2613** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2614** and populate the ShellState.aiIndent[] array with the number of
2615** spaces each opcode should be indented before it is output.
2616**
2617** The indenting rules are:
2618**
2619**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2620**       all opcodes that occur between the p2 jump destination and the opcode
2621**       itself by 2 spaces.
2622**
2623**     * For each "Goto", if the jump destination is earlier in the program
2624**       and ends on one of:
2625**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2626**       or if the P1 parameter is one instead of zero,
2627**       then indent all opcodes between the earlier instruction
2628**       and "Goto" by 2 spaces.
2629*/
2630static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2631  const char *zSql;               /* The text of the SQL statement */
2632  const char *z;                  /* Used to check if this is an EXPLAIN */
2633  int *abYield = 0;               /* True if op is an OP_Yield */
2634  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2635  int iOp;                        /* Index of operation in p->aiIndent[] */
2636
2637  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2638  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2639                            "Rewind", 0 };
2640  const char *azGoto[] = { "Goto", 0 };
2641
2642  /* Try to figure out if this is really an EXPLAIN statement. If this
2643  ** cannot be verified, return early.  */
2644  if( sqlite3_column_count(pSql)!=8 ){
2645    p->cMode = p->mode;
2646    return;
2647  }
2648  zSql = sqlite3_sql(pSql);
2649  if( zSql==0 ) return;
2650  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2651  if( sqlite3_strnicmp(z, "explain", 7) ){
2652    p->cMode = p->mode;
2653    return;
2654  }
2655
2656  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2657    int i;
2658    int iAddr = sqlite3_column_int(pSql, 0);
2659    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2660
2661    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2662    ** p2 is an instruction address, set variable p2op to the index of that
2663    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2664    ** the current instruction is part of a sub-program generated by an
2665    ** SQL trigger or foreign key.  */
2666    int p2 = sqlite3_column_int(pSql, 3);
2667    int p2op = (p2 + (iOp-iAddr));
2668
2669    /* Grow the p->aiIndent array as required */
2670    if( iOp>=nAlloc ){
2671      if( iOp==0 ){
2672        /* Do further verfication that this is explain output.  Abort if
2673        ** it is not */
2674        static const char *explainCols[] = {
2675           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2676        int jj;
2677        for(jj=0; jj<ArraySize(explainCols); jj++){
2678          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2679            p->cMode = p->mode;
2680            sqlite3_reset(pSql);
2681            return;
2682          }
2683        }
2684      }
2685      nAlloc += 100;
2686      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2687      if( p->aiIndent==0 ) shell_out_of_memory();
2688      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2689      if( abYield==0 ) shell_out_of_memory();
2690    }
2691    abYield[iOp] = str_in_array(zOp, azYield);
2692    p->aiIndent[iOp] = 0;
2693    p->nIndent = iOp+1;
2694
2695    if( str_in_array(zOp, azNext) ){
2696      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2697    }
2698    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2699     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2700    ){
2701      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2702    }
2703  }
2704
2705  p->iIndent = 0;
2706  sqlite3_free(abYield);
2707  sqlite3_reset(pSql);
2708}
2709
2710/*
2711** Free the array allocated by explain_data_prepare().
2712*/
2713static void explain_data_delete(ShellState *p){
2714  sqlite3_free(p->aiIndent);
2715  p->aiIndent = 0;
2716  p->nIndent = 0;
2717  p->iIndent = 0;
2718}
2719
2720/*
2721** Disable and restore .wheretrace and .selecttrace settings.
2722*/
2723#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2724extern int sqlite3SelectTrace;
2725static int savedSelectTrace;
2726#endif
2727#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2728extern int sqlite3WhereTrace;
2729static int savedWhereTrace;
2730#endif
2731static void disable_debug_trace_modes(void){
2732#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2733  savedSelectTrace = sqlite3SelectTrace;
2734  sqlite3SelectTrace = 0;
2735#endif
2736#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2737  savedWhereTrace = sqlite3WhereTrace;
2738  sqlite3WhereTrace = 0;
2739#endif
2740}
2741static void restore_debug_trace_modes(void){
2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2743  sqlite3SelectTrace = savedSelectTrace;
2744#endif
2745#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2746  sqlite3WhereTrace = savedWhereTrace;
2747#endif
2748}
2749
2750/* Name of the TEMP table that holds bind parameter values */
2751#define BIND_PARAM_TABLE "$Parameters"
2752
2753/* Create the TEMP table used to store parameter bindings */
2754static void bind_table_init(ShellState *p){
2755  sqlite3_exec(p->db,
2756    "CREATE TABLE IF NOT EXISTS temp.[" BIND_PARAM_TABLE "](\n"
2757    "  key TEXT PRIMARY KEY,\n"
2758    "  value ANY\n"
2759    ") WITHOUT ROWID;",
2760    0, 0, 0);
2761}
2762
2763/*
2764** Bind parameters on a prepared statement.
2765**
2766** Parameter bindings are taken from a TEMP table of the form:
2767**
2768**    CREATE TEMP TABLE "$Parameters"(key TEXT PRIMARY KEY, value)
2769**    WITHOUT ROWID;
2770**
2771** No bindings occur if this table does not exist.  The special character '$'
2772** is included in the table name to help prevent collisions with actual tables.
2773** The table must be in the TEMP schema.
2774*/
2775static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2776  int nVar;
2777  int i;
2778  int rc;
2779  sqlite3_stmt *pQ = 0;
2780
2781  nVar = sqlite3_bind_parameter_count(pStmt);
2782  if( nVar==0 ) return;  /* Nothing to do */
2783  if( sqlite3_table_column_metadata(pArg->db, "TEMP", BIND_PARAM_TABLE,
2784                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2785    return; /* Parameter table does not exist */
2786  }
2787  rc = sqlite3_prepare_v2(pArg->db,
2788          "SELECT value FROM temp.\"" BIND_PARAM_TABLE "\""
2789          " WHERE key=?1", -1, &pQ, 0);
2790  if( rc || pQ==0 ) return;
2791  for(i=1; i<=nVar; i++){
2792    char zNum[30];
2793    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2794    if( zVar==0 ){
2795      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2796      zVar = zNum;
2797    }
2798    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2799    if( sqlite3_step(pQ)==SQLITE_ROW ){
2800      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2801    }else{
2802      sqlite3_bind_null(pStmt, i);
2803    }
2804    sqlite3_reset(pQ);
2805  }
2806  sqlite3_finalize(pQ);
2807}
2808
2809/*
2810** Run a prepared statement
2811*/
2812static void exec_prepared_stmt(
2813  ShellState *pArg,                                /* Pointer to ShellState */
2814  sqlite3_stmt *pStmt                              /* Statment to run */
2815){
2816  int rc;
2817
2818  /* perform the first step.  this will tell us if we
2819  ** have a result set or not and how wide it is.
2820  */
2821  rc = sqlite3_step(pStmt);
2822  /* if we have a result set... */
2823  if( SQLITE_ROW == rc ){
2824    /* allocate space for col name ptr, value ptr, and type */
2825    int nCol = sqlite3_column_count(pStmt);
2826    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2827    if( !pData ){
2828      rc = SQLITE_NOMEM;
2829    }else{
2830      char **azCols = (char **)pData;      /* Names of result columns */
2831      char **azVals = &azCols[nCol];       /* Results */
2832      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2833      int i, x;
2834      assert(sizeof(int) <= sizeof(char *));
2835      /* save off ptrs to column names */
2836      for(i=0; i<nCol; i++){
2837        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2838      }
2839      do{
2840        /* extract the data and data types */
2841        for(i=0; i<nCol; i++){
2842          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2843          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2844            azVals[i] = "";
2845          }else{
2846            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2847          }
2848          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2849            rc = SQLITE_NOMEM;
2850            break; /* from for */
2851          }
2852        } /* end for */
2853
2854        /* if data and types extracted successfully... */
2855        if( SQLITE_ROW == rc ){
2856          /* call the supplied callback with the result row data */
2857          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2858            rc = SQLITE_ABORT;
2859          }else{
2860            rc = sqlite3_step(pStmt);
2861          }
2862        }
2863      } while( SQLITE_ROW == rc );
2864      sqlite3_free(pData);
2865    }
2866  }
2867}
2868
2869#ifndef SQLITE_OMIT_VIRTUALTABLE
2870/*
2871** This function is called to process SQL if the previous shell command
2872** was ".expert". It passes the SQL in the second argument directly to
2873** the sqlite3expert object.
2874**
2875** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2876** code. In this case, (*pzErr) may be set to point to a buffer containing
2877** an English language error message. It is the responsibility of the
2878** caller to eventually free this buffer using sqlite3_free().
2879*/
2880static int expertHandleSQL(
2881  ShellState *pState,
2882  const char *zSql,
2883  char **pzErr
2884){
2885  assert( pState->expert.pExpert );
2886  assert( pzErr==0 || *pzErr==0 );
2887  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2888}
2889
2890/*
2891** This function is called either to silently clean up the object
2892** created by the ".expert" command (if bCancel==1), or to generate a
2893** report from it and then clean it up (if bCancel==0).
2894**
2895** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2896** code. In this case, (*pzErr) may be set to point to a buffer containing
2897** an English language error message. It is the responsibility of the
2898** caller to eventually free this buffer using sqlite3_free().
2899*/
2900static int expertFinish(
2901  ShellState *pState,
2902  int bCancel,
2903  char **pzErr
2904){
2905  int rc = SQLITE_OK;
2906  sqlite3expert *p = pState->expert.pExpert;
2907  assert( p );
2908  assert( bCancel || pzErr==0 || *pzErr==0 );
2909  if( bCancel==0 ){
2910    FILE *out = pState->out;
2911    int bVerbose = pState->expert.bVerbose;
2912
2913    rc = sqlite3_expert_analyze(p, pzErr);
2914    if( rc==SQLITE_OK ){
2915      int nQuery = sqlite3_expert_count(p);
2916      int i;
2917
2918      if( bVerbose ){
2919        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2920        raw_printf(out, "-- Candidates -----------------------------\n");
2921        raw_printf(out, "%s\n", zCand);
2922      }
2923      for(i=0; i<nQuery; i++){
2924        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2925        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2926        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2927        if( zIdx==0 ) zIdx = "(no new indexes)\n";
2928        if( bVerbose ){
2929          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2930          raw_printf(out, "%s\n\n", zSql);
2931        }
2932        raw_printf(out, "%s\n", zIdx);
2933        raw_printf(out, "%s\n", zEQP);
2934      }
2935    }
2936  }
2937  sqlite3_expert_destroy(p);
2938  pState->expert.pExpert = 0;
2939  return rc;
2940}
2941
2942/*
2943** Implementation of ".expert" dot command.
2944*/
2945static int expertDotCommand(
2946  ShellState *pState,             /* Current shell tool state */
2947  char **azArg,                   /* Array of arguments passed to dot command */
2948  int nArg                        /* Number of entries in azArg[] */
2949){
2950  int rc = SQLITE_OK;
2951  char *zErr = 0;
2952  int i;
2953  int iSample = 0;
2954
2955  assert( pState->expert.pExpert==0 );
2956  memset(&pState->expert, 0, sizeof(ExpertInfo));
2957
2958  for(i=1; rc==SQLITE_OK && i<nArg; i++){
2959    char *z = azArg[i];
2960    int n;
2961    if( z[0]=='-' && z[1]=='-' ) z++;
2962    n = strlen30(z);
2963    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2964      pState->expert.bVerbose = 1;
2965    }
2966    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2967      if( i==(nArg-1) ){
2968        raw_printf(stderr, "option requires an argument: %s\n", z);
2969        rc = SQLITE_ERROR;
2970      }else{
2971        iSample = (int)integerValue(azArg[++i]);
2972        if( iSample<0 || iSample>100 ){
2973          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2974          rc = SQLITE_ERROR;
2975        }
2976      }
2977    }
2978    else{
2979      raw_printf(stderr, "unknown option: %s\n", z);
2980      rc = SQLITE_ERROR;
2981    }
2982  }
2983
2984  if( rc==SQLITE_OK ){
2985    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2986    if( pState->expert.pExpert==0 ){
2987      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2988      rc = SQLITE_ERROR;
2989    }else{
2990      sqlite3_expert_config(
2991          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2992      );
2993    }
2994  }
2995
2996  return rc;
2997}
2998#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2999
3000/*
3001** Execute a statement or set of statements.  Print
3002** any result rows/columns depending on the current mode
3003** set via the supplied callback.
3004**
3005** This is very similar to SQLite's built-in sqlite3_exec()
3006** function except it takes a slightly different callback
3007** and callback data argument.
3008*/
3009static int shell_exec(
3010  ShellState *pArg,                         /* Pointer to ShellState */
3011  const char *zSql,                         /* SQL to be evaluated */
3012  char **pzErrMsg                           /* Error msg written here */
3013){
3014  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3015  int rc = SQLITE_OK;             /* Return Code */
3016  int rc2;
3017  const char *zLeftover;          /* Tail of unprocessed SQL */
3018  sqlite3 *db = pArg->db;
3019
3020  if( pzErrMsg ){
3021    *pzErrMsg = NULL;
3022  }
3023
3024#ifndef SQLITE_OMIT_VIRTUALTABLE
3025  if( pArg->expert.pExpert ){
3026    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3027    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3028  }
3029#endif
3030
3031  while( zSql[0] && (SQLITE_OK == rc) ){
3032    static const char *zStmtSql;
3033    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3034    if( SQLITE_OK != rc ){
3035      if( pzErrMsg ){
3036        *pzErrMsg = save_err_msg(db);
3037      }
3038    }else{
3039      if( !pStmt ){
3040        /* this happens for a comment or white-space */
3041        zSql = zLeftover;
3042        while( IsSpace(zSql[0]) ) zSql++;
3043        continue;
3044      }
3045      zStmtSql = sqlite3_sql(pStmt);
3046      if( zStmtSql==0 ) zStmtSql = "";
3047      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3048
3049      /* save off the prepared statment handle and reset row count */
3050      if( pArg ){
3051        pArg->pStmt = pStmt;
3052        pArg->cnt = 0;
3053      }
3054
3055      /* echo the sql statement if echo on */
3056      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3057        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3058      }
3059
3060      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3061      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3062        sqlite3_stmt *pExplain;
3063        char *zEQP;
3064        int triggerEQP = 0;
3065        disable_debug_trace_modes();
3066        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3067        if( pArg->autoEQP>=AUTOEQP_trigger ){
3068          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3069        }
3070        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3071        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3072        if( rc==SQLITE_OK ){
3073          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3074            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3075            int iEqpId = sqlite3_column_int(pExplain, 0);
3076            int iParentId = sqlite3_column_int(pExplain, 1);
3077            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3078            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3079          }
3080          eqp_render(pArg);
3081        }
3082        sqlite3_finalize(pExplain);
3083        sqlite3_free(zEQP);
3084        if( pArg->autoEQP>=AUTOEQP_full ){
3085          /* Also do an EXPLAIN for ".eqp full" mode */
3086          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3087          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3088          if( rc==SQLITE_OK ){
3089            pArg->cMode = MODE_Explain;
3090            explain_data_prepare(pArg, pExplain);
3091            exec_prepared_stmt(pArg, pExplain);
3092            explain_data_delete(pArg);
3093          }
3094          sqlite3_finalize(pExplain);
3095          sqlite3_free(zEQP);
3096        }
3097        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3098          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3099          /* Reprepare pStmt before reactiving trace modes */
3100          sqlite3_finalize(pStmt);
3101          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3102          if( pArg ) pArg->pStmt = pStmt;
3103        }
3104        restore_debug_trace_modes();
3105      }
3106
3107      if( pArg ){
3108        pArg->cMode = pArg->mode;
3109        if( pArg->autoExplain ){
3110          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3111            pArg->cMode = MODE_Explain;
3112          }
3113          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3114            pArg->cMode = MODE_EQP;
3115          }
3116        }
3117
3118        /* If the shell is currently in ".explain" mode, gather the extra
3119        ** data required to add indents to the output.*/
3120        if( pArg->cMode==MODE_Explain ){
3121          explain_data_prepare(pArg, pStmt);
3122        }
3123      }
3124
3125      bind_prepared_stmt(pArg, pStmt);
3126      exec_prepared_stmt(pArg, pStmt);
3127      explain_data_delete(pArg);
3128      eqp_render(pArg);
3129
3130      /* print usage stats if stats on */
3131      if( pArg && pArg->statsOn ){
3132        display_stats(db, pArg, 0);
3133      }
3134
3135      /* print loop-counters if required */
3136      if( pArg && pArg->scanstatsOn ){
3137        display_scanstats(db, pArg);
3138      }
3139
3140      /* Finalize the statement just executed. If this fails, save a
3141      ** copy of the error message. Otherwise, set zSql to point to the
3142      ** next statement to execute. */
3143      rc2 = sqlite3_finalize(pStmt);
3144      if( rc!=SQLITE_NOMEM ) rc = rc2;
3145      if( rc==SQLITE_OK ){
3146        zSql = zLeftover;
3147        while( IsSpace(zSql[0]) ) zSql++;
3148      }else if( pzErrMsg ){
3149        *pzErrMsg = save_err_msg(db);
3150      }
3151
3152      /* clear saved stmt handle */
3153      if( pArg ){
3154        pArg->pStmt = NULL;
3155      }
3156    }
3157  } /* end while */
3158
3159  return rc;
3160}
3161
3162/*
3163** Release memory previously allocated by tableColumnList().
3164*/
3165static void freeColumnList(char **azCol){
3166  int i;
3167  for(i=1; azCol[i]; i++){
3168    sqlite3_free(azCol[i]);
3169  }
3170  /* azCol[0] is a static string */
3171  sqlite3_free(azCol);
3172}
3173
3174/*
3175** Return a list of pointers to strings which are the names of all
3176** columns in table zTab.   The memory to hold the names is dynamically
3177** allocated and must be released by the caller using a subsequent call
3178** to freeColumnList().
3179**
3180** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3181** value that needs to be preserved, then azCol[0] is filled in with the
3182** name of the rowid column.
3183**
3184** The first regular column in the table is azCol[1].  The list is terminated
3185** by an entry with azCol[i]==0.
3186*/
3187static char **tableColumnList(ShellState *p, const char *zTab){
3188  char **azCol = 0;
3189  sqlite3_stmt *pStmt;
3190  char *zSql;
3191  int nCol = 0;
3192  int nAlloc = 0;
3193  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3194  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3195  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3196  int rc;
3197
3198  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3199  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3200  sqlite3_free(zSql);
3201  if( rc ) return 0;
3202  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3203    if( nCol>=nAlloc-2 ){
3204      nAlloc = nAlloc*2 + nCol + 10;
3205      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3206      if( azCol==0 ) shell_out_of_memory();
3207    }
3208    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3209    if( sqlite3_column_int(pStmt, 5) ){
3210      nPK++;
3211      if( nPK==1
3212       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3213                          "INTEGER")==0
3214      ){
3215        isIPK = 1;
3216      }else{
3217        isIPK = 0;
3218      }
3219    }
3220  }
3221  sqlite3_finalize(pStmt);
3222  if( azCol==0 ) return 0;
3223  azCol[0] = 0;
3224  azCol[nCol+1] = 0;
3225
3226  /* The decision of whether or not a rowid really needs to be preserved
3227  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3228  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3229  ** rowids on tables where the rowid is inaccessible because there are other
3230  ** columns in the table named "rowid", "_rowid_", and "oid".
3231  */
3232  if( preserveRowid && isIPK ){
3233    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3234    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3235    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3236    ** ROWID aliases.  To distinguish these cases, check to see if
3237    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3238    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3239    */
3240    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3241                           " WHERE origin='pk'", zTab);
3242    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3243    sqlite3_free(zSql);
3244    if( rc ){
3245      freeColumnList(azCol);
3246      return 0;
3247    }
3248    rc = sqlite3_step(pStmt);
3249    sqlite3_finalize(pStmt);
3250    preserveRowid = rc==SQLITE_ROW;
3251  }
3252  if( preserveRowid ){
3253    /* Only preserve the rowid if we can find a name to use for the
3254    ** rowid */
3255    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3256    int i, j;
3257    for(j=0; j<3; j++){
3258      for(i=1; i<=nCol; i++){
3259        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3260      }
3261      if( i>nCol ){
3262        /* At this point, we know that azRowid[j] is not the name of any
3263        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3264        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3265        ** tables will fail this last check */
3266        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3267        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3268        break;
3269      }
3270    }
3271  }
3272  return azCol;
3273}
3274
3275/*
3276** Toggle the reverse_unordered_selects setting.
3277*/
3278static void toggleSelectOrder(sqlite3 *db){
3279  sqlite3_stmt *pStmt = 0;
3280  int iSetting = 0;
3281  char zStmt[100];
3282  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3283  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3284    iSetting = sqlite3_column_int(pStmt, 0);
3285  }
3286  sqlite3_finalize(pStmt);
3287  sqlite3_snprintf(sizeof(zStmt), zStmt,
3288       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3289  sqlite3_exec(db, zStmt, 0, 0, 0);
3290}
3291
3292/*
3293** This is a different callback routine used for dumping the database.
3294** Each row received by this callback consists of a table name,
3295** the table type ("index" or "table") and SQL to create the table.
3296** This routine should print text sufficient to recreate the table.
3297*/
3298static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3299  int rc;
3300  const char *zTable;
3301  const char *zType;
3302  const char *zSql;
3303  ShellState *p = (ShellState *)pArg;
3304
3305  UNUSED_PARAMETER(azNotUsed);
3306  if( nArg!=3 || azArg==0 ) return 0;
3307  zTable = azArg[0];
3308  zType = azArg[1];
3309  zSql = azArg[2];
3310
3311  if( strcmp(zTable, "sqlite_sequence")==0 ){
3312    raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3313  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3314    raw_printf(p->out, "ANALYZE sqlite_master;\n");
3315  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3316    return 0;
3317  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3318    char *zIns;
3319    if( !p->writableSchema ){
3320      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3321      p->writableSchema = 1;
3322    }
3323    zIns = sqlite3_mprintf(
3324       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3325       "VALUES('table','%q','%q',0,'%q');",
3326       zTable, zTable, zSql);
3327    utf8_printf(p->out, "%s\n", zIns);
3328    sqlite3_free(zIns);
3329    return 0;
3330  }else{
3331    printSchemaLine(p->out, zSql, ";\n");
3332  }
3333
3334  if( strcmp(zType, "table")==0 ){
3335    ShellText sSelect;
3336    ShellText sTable;
3337    char **azCol;
3338    int i;
3339    char *savedDestTable;
3340    int savedMode;
3341
3342    azCol = tableColumnList(p, zTable);
3343    if( azCol==0 ){
3344      p->nErr++;
3345      return 0;
3346    }
3347
3348    /* Always quote the table name, even if it appears to be pure ascii,
3349    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3350    initText(&sTable);
3351    appendText(&sTable, zTable, quoteChar(zTable));
3352    /* If preserving the rowid, add a column list after the table name.
3353    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3354    ** instead of the usual "INSERT INTO tab VALUES(...)".
3355    */
3356    if( azCol[0] ){
3357      appendText(&sTable, "(", 0);
3358      appendText(&sTable, azCol[0], 0);
3359      for(i=1; azCol[i]; i++){
3360        appendText(&sTable, ",", 0);
3361        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3362      }
3363      appendText(&sTable, ")", 0);
3364    }
3365
3366    /* Build an appropriate SELECT statement */
3367    initText(&sSelect);
3368    appendText(&sSelect, "SELECT ", 0);
3369    if( azCol[0] ){
3370      appendText(&sSelect, azCol[0], 0);
3371      appendText(&sSelect, ",", 0);
3372    }
3373    for(i=1; azCol[i]; i++){
3374      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3375      if( azCol[i+1] ){
3376        appendText(&sSelect, ",", 0);
3377      }
3378    }
3379    freeColumnList(azCol);
3380    appendText(&sSelect, " FROM ", 0);
3381    appendText(&sSelect, zTable, quoteChar(zTable));
3382
3383    savedDestTable = p->zDestTable;
3384    savedMode = p->mode;
3385    p->zDestTable = sTable.z;
3386    p->mode = p->cMode = MODE_Insert;
3387    rc = shell_exec(p, sSelect.z, 0);
3388    if( (rc&0xff)==SQLITE_CORRUPT ){
3389      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3390      toggleSelectOrder(p->db);
3391      shell_exec(p, sSelect.z, 0);
3392      toggleSelectOrder(p->db);
3393    }
3394    p->zDestTable = savedDestTable;
3395    p->mode = savedMode;
3396    freeText(&sTable);
3397    freeText(&sSelect);
3398    if( rc ) p->nErr++;
3399  }
3400  return 0;
3401}
3402
3403/*
3404** Run zQuery.  Use dump_callback() as the callback routine so that
3405** the contents of the query are output as SQL statements.
3406**
3407** If we get a SQLITE_CORRUPT error, rerun the query after appending
3408** "ORDER BY rowid DESC" to the end.
3409*/
3410static int run_schema_dump_query(
3411  ShellState *p,
3412  const char *zQuery
3413){
3414  int rc;
3415  char *zErr = 0;
3416  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3417  if( rc==SQLITE_CORRUPT ){
3418    char *zQ2;
3419    int len = strlen30(zQuery);
3420    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3421    if( zErr ){
3422      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3423      sqlite3_free(zErr);
3424      zErr = 0;
3425    }
3426    zQ2 = malloc( len+100 );
3427    if( zQ2==0 ) return rc;
3428    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3429    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3430    if( rc ){
3431      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3432    }else{
3433      rc = SQLITE_CORRUPT;
3434    }
3435    sqlite3_free(zErr);
3436    free(zQ2);
3437  }
3438  return rc;
3439}
3440
3441/*
3442** Text of help messages.
3443**
3444** The help text for each individual command begins with a line that starts
3445** with ".".  Subsequent lines are supplimental information.
3446**
3447** There must be two or more spaces between the end of the command and the
3448** start of the description of what that command does.
3449*/
3450static const char *(azHelp[]) = {
3451#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3452  ".archive ...             Manage SQL archives",
3453  "   Each command must have exactly one of the following options:",
3454  "     -c, --create               Create a new archive",
3455  "     -u, --update               Update or add files to an existing archive",
3456  "     -t, --list                 List contents of archive",
3457  "     -x, --extract              Extract files from archive",
3458  "   Optional arguments:",
3459  "     -v, --verbose              Print each filename as it is processed",
3460  "     -f FILE, --file FILE       Operate on archive FILE (default is current db)",
3461  "     -a FILE, --append FILE     Operate on FILE opened using the apndvfs VFS",
3462  "     -C DIR, --directory DIR    Change to directory DIR to read/extract files",
3463  "     -n, --dryrun               Show the SQL that would have occurred",
3464  "   Examples:",
3465  "     .ar -cf archive.sar foo bar  # Create archive.sar from files foo and bar",
3466  "     .ar -tf archive.sar          # List members of archive.sar",
3467  "     .ar -xvf archive.sar         # Verbosely extract files from archive.sar",
3468  "   See also:",
3469  "      http://sqlite.org/cli.html#sqlar_archive_support",
3470#endif
3471#ifndef SQLITE_OMIT_AUTHORIZATION
3472  ".auth ON|OFF             Show authorizer callbacks",
3473#endif
3474  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
3475  "       --append            Use the appendvfs",
3476  "       --async             Write to FILE without a journal and without fsync()",
3477  ".bail on|off             Stop after hitting an error.  Default OFF",
3478  ".binary on|off           Turn binary output on or off.  Default OFF",
3479  ".cd DIRECTORY            Change the working directory to DIRECTORY",
3480  ".changes on|off          Show number of rows changed by SQL",
3481  ".check GLOB              Fail if output since .testcase does not match",
3482  ".clone NEWDB             Clone data into NEWDB from the existing database",
3483  ".databases               List names and files of attached databases",
3484  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
3485  ".dbinfo ?DB?             Show status information about the database",
3486  ".dump ?TABLE? ...        Render all database content as SQL",
3487  "   Options:",
3488  "     --preserve-rowids      Include ROWID values in the output",
3489  "     --newlines             Allow unescaped newline characters in output",
3490  "   TABLE is LIKE pattern for the tables to dump",
3491  ".echo on|off             Turn command echo on or off",
3492  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
3493  "   Other Modes:",
3494#ifdef SQLITE_DEBUG
3495  "      test                  Show raw EXPLAIN QUERY PLAN output",
3496  "      trace                 Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3497#endif
3498  "      trigger               Like \"full\" but also show trigger bytecode",
3499  ".excel                   Display the output of next command in a spreadsheet",
3500  ".exit ?CODE?             Exit this program with return-code CODE",
3501  ".expert                  EXPERIMENTAL. Suggest indexes for specified queries",
3502/* Because explain mode comes on automatically now, the ".explain" mode
3503** is removed from the help screen.  It is still supported for legacy, however */
3504/*".explain ?on|off|auto?   Turn EXPLAIN output mode on or off or to automatic",*/
3505  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
3506  ".headers on|off          Turn display of headers on or off",
3507  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
3508  ".import FILE TABLE       Import data from FILE into TABLE",
3509#ifndef SQLITE_OMIT_TEST_CONTROL
3510  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
3511#endif
3512  ".indexes ?TABLE?         Show names of indexes",
3513  "                           If TABLE is specified, only show indexes for",
3514  "                           tables matching TABLE using the LIKE operator.",
3515#ifdef SQLITE_ENABLE_IOTRACE
3516  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
3517#endif
3518  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
3519  ".lint OPTIONS            Report potential schema issues.",
3520  "     Options:",
3521  "        fkey-indexes     Find missing foreign key indexes",
3522#ifndef SQLITE_OMIT_LOAD_EXTENSION
3523  ".load FILE ?ENTRY?       Load an extension library",
3524#endif
3525  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
3526  ".mode MODE ?TABLE?       Set output mode",
3527  "   MODE is one of:",
3528  "     ascii    Columns/rows delimited by 0x1F and 0x1E",
3529  "     csv      Comma-separated values",
3530  "     column   Left-aligned columns.  (See .width)",
3531  "     html     HTML <table> code",
3532  "     insert   SQL insert statements for TABLE",
3533  "     line     One value per line",
3534  "     list     Values delimited by \"|\"",
3535  "     quote    Escape answers as for SQL",
3536  "     tabs     Tab-separated values",
3537  "     tcl      TCL list elements",
3538  ".nullvalue STRING        Use STRING in place of NULL values",
3539  ".once (-e|-x|FILE)       Output for the next SQL command only to FILE",
3540  "     If FILE begins with '|' then open as a pipe",
3541  "     Other options:",
3542  "       -e    Invoke system text editor",
3543  "       -x    Open in a spreadsheet",
3544  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
3545  "     Options:",
3546  "        --append        Use appendvfs to append database to the end of FILE",
3547#ifdef SQLITE_ENABLE_DESERIALIZE
3548  "        --deserialize   Load into memory useing sqlite3_deserialize()",
3549  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory database",
3550  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
3551#endif
3552  "        --new           Initialize FILE to an empty database",
3553  "        --readonly      Open FILE readonly",
3554  "        --zip           FILE is a ZIP archive",
3555  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
3556  "     If FILE begins with '|' then open it as a pipe.",
3557  ".parameter CMD ...       Manage SQL parameter bindings",
3558  "   clear                   Erase all bindings",
3559  "   init                    Initialize the TEMP table that holds bindings",
3560  "   list                    List the current parameter bindings",
3561  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
3562  "                           PARAMETER should start with '$', ':', '@', or '?'",
3563  "   unset PARAMETER         Remove PARAMETER from the binding table",
3564  ".print STRING...         Print literal STRING",
3565#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
3566  ".progress N              Invoke progress handler after every N opcodes",
3567  "   --limit N                 Interrupt after N progress callbacks",
3568  "   --once                    Do no more than one progress interrupt",
3569  "   --quiet|-q                No output except at interrupts",
3570  "   --reset                   Reset the count for each input and interrupt",
3571#endif
3572  ".prompt MAIN CONTINUE    Replace the standard prompts",
3573  ".quit                    Exit this program",
3574  ".read FILE               Read input from FILE",
3575  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
3576  ".save FILE               Write in-memory database into FILE",
3577  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
3578  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
3579  "     Options:",
3580  "         --indent            Try to pretty-print the schema",
3581  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
3582  "    Options:",
3583  "       --init               Create a new SELFTEST table",
3584  "       -v                   Verbose output",
3585  ".separator COL ?ROW?     Change the column and row separators",
3586#if defined(SQLITE_ENABLE_SESSION)
3587  ".session ?NAME? CMD ...  Create or control sessions",
3588  "   Subcommands:",
3589  "     attach TABLE             Attach TABLE",
3590  "     changeset FILE           Write a changeset into FILE",
3591  "     close                    Close one session",
3592  "     enable ?BOOLEAN?         Set or query the enable bit",
3593  "     filter GLOB...           Reject tables matching GLOBs",
3594  "     indirect ?BOOLEAN?       Mark or query the indirect status",
3595  "     isempty                  Query whether the session is empty",
3596  "     list                     List currently open session names",
3597  "     open DB NAME             Open a new session on DB",
3598  "     patchset FILE            Write a patchset into FILE",
3599  "   If ?NAME? is omitted, the first defined session is used.",
3600#endif
3601  ".sha3sum ...             Compute a SHA3 hash of database content",
3602  "    Options:",
3603  "      --schema              Also hash the sqlite_master table",
3604  "      --sha3-224            Use the sha3-224 algorithm",
3605  "      --sha3-256            Use the sha3-256 algorithm.  This is the default.",
3606  "      --sha3-384            Use the sha3-384 algorithm",
3607  "      --sha3-512            Use the sha3-512 algorithm",
3608  "    Any other argument is a LIKE pattern for tables to hash",
3609#ifndef SQLITE_NOHAVE_SYSTEM
3610  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
3611#endif
3612  ".show                    Show the current values for various settings",
3613  ".stats ?on|off?          Show stats or turn stats on or off",
3614#ifndef SQLITE_NOHAVE_SYSTEM
3615  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
3616#endif
3617  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
3618  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
3619  ".timeout MS              Try opening locked tables for MS milliseconds",
3620  ".timer on|off            Turn SQL timer on or off",
3621#ifndef SQLITE_OMIT_TRACE
3622  ".trace ?OPTIONS?         Output each SQL statement as it is run",
3623  "    FILE                    Send output to FILE",
3624  "    stdout                  Send output to stdout",
3625  "    stderr                  Send output to stderr",
3626  "    off                     Disable tracing",
3627  "    --expanded              Expand query parameters",
3628#ifdef SQLITE_ENABLE_NORMALIZE
3629  "    --normalized            Normal the SQL statements",
3630#endif
3631  "    --plain                 Show SQL as it is input",
3632  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
3633  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
3634  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
3635  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
3636#endif /* SQLITE_OMIT_TRACE */
3637  ".vfsinfo ?AUX?           Information about the top-level VFS",
3638  ".vfslist                 List all available VFSes",
3639  ".vfsname ?AUX?           Print the name of the VFS stack",
3640  ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
3641  "     Negative values right-justify",
3642};
3643
3644/*
3645** Output help text.
3646**
3647** zPattern describes the set of commands for which help text is provided.
3648** If zPattern is NULL, then show all commands, but only give a one-line
3649** description of each.
3650**
3651** Return the number of matches.
3652*/
3653static int showHelp(FILE *out, const char *zPattern){
3654  int i = 0;
3655  int j = 0;
3656  int n = 0;
3657  char *zPat;
3658  if( zPattern==0
3659   || zPattern[0]=='0'
3660   || strcmp(zPattern,"-a")==0
3661   || strcmp(zPattern,"-all")==0
3662  ){
3663    /* Show all commands, but only one line per command */
3664    if( zPattern==0 ) zPattern = "";
3665    for(i=0; i<ArraySize(azHelp); i++){
3666      if( azHelp[i][0]=='.' || zPattern[0] ){
3667        utf8_printf(out, "%s\n", azHelp[i]);
3668        n++;
3669      }
3670    }
3671  }else{
3672    /* Look for commands that for which zPattern is an exact prefix */
3673    zPat = sqlite3_mprintf(".%s*", zPattern);
3674    for(i=0; i<ArraySize(azHelp); i++){
3675      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3676        utf8_printf(out, "%s\n", azHelp[i]);
3677        j = i+1;
3678        n++;
3679      }
3680    }
3681    sqlite3_free(zPat);
3682    if( n ){
3683      if( n==1 ){
3684        /* when zPattern is a prefix of exactly one command, then include the
3685        ** details of that command, which should begin at offset j */
3686        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3687          utf8_printf(out, "%s\n", azHelp[j]);
3688          j++;
3689        }
3690      }
3691      return n;
3692    }
3693    /* Look for commands that contain zPattern anywhere.  Show the complete
3694    ** text of all commands that match. */
3695    zPat = sqlite3_mprintf("%%%s%%", zPattern);
3696    for(i=0; i<ArraySize(azHelp); i++){
3697      if( azHelp[i][0]=='.' ) j = i;
3698      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3699        utf8_printf(out, "%s\n", azHelp[j]);
3700        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3701          j++;
3702          utf8_printf(out, "%s\n", azHelp[j]);
3703        }
3704        i = j;
3705        n++;
3706      }
3707    }
3708    sqlite3_free(zPat);
3709  }
3710  return n;
3711}
3712
3713/* Forward reference */
3714static int process_input(ShellState *p);
3715
3716/*
3717** Read the content of file zName into memory obtained from sqlite3_malloc64()
3718** and return a pointer to the buffer. The caller is responsible for freeing
3719** the memory.
3720**
3721** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3722** read.
3723**
3724** For convenience, a nul-terminator byte is always appended to the data read
3725** from the file before the buffer is returned. This byte is not included in
3726** the final value of (*pnByte), if applicable.
3727**
3728** NULL is returned if any error is encountered. The final value of *pnByte
3729** is undefined in this case.
3730*/
3731static char *readFile(const char *zName, int *pnByte){
3732  FILE *in = fopen(zName, "rb");
3733  long nIn;
3734  size_t nRead;
3735  char *pBuf;
3736  if( in==0 ) return 0;
3737  fseek(in, 0, SEEK_END);
3738  nIn = ftell(in);
3739  rewind(in);
3740  pBuf = sqlite3_malloc64( nIn+1 );
3741  if( pBuf==0 ){ fclose(in); return 0; }
3742  nRead = fread(pBuf, nIn, 1, in);
3743  fclose(in);
3744  if( nRead!=1 ){
3745    sqlite3_free(pBuf);
3746    return 0;
3747  }
3748  pBuf[nIn] = 0;
3749  if( pnByte ) *pnByte = nIn;
3750  return pBuf;
3751}
3752
3753#if defined(SQLITE_ENABLE_SESSION)
3754/*
3755** Close a single OpenSession object and release all of its associated
3756** resources.
3757*/
3758static void session_close(OpenSession *pSession){
3759  int i;
3760  sqlite3session_delete(pSession->p);
3761  sqlite3_free(pSession->zName);
3762  for(i=0; i<pSession->nFilter; i++){
3763    sqlite3_free(pSession->azFilter[i]);
3764  }
3765  sqlite3_free(pSession->azFilter);
3766  memset(pSession, 0, sizeof(OpenSession));
3767}
3768#endif
3769
3770/*
3771** Close all OpenSession objects and release all associated resources.
3772*/
3773#if defined(SQLITE_ENABLE_SESSION)
3774static void session_close_all(ShellState *p){
3775  int i;
3776  for(i=0; i<p->nSession; i++){
3777    session_close(&p->aSession[i]);
3778  }
3779  p->nSession = 0;
3780}
3781#else
3782# define session_close_all(X)
3783#endif
3784
3785/*
3786** Implementation of the xFilter function for an open session.  Omit
3787** any tables named by ".session filter" but let all other table through.
3788*/
3789#if defined(SQLITE_ENABLE_SESSION)
3790static int session_filter(void *pCtx, const char *zTab){
3791  OpenSession *pSession = (OpenSession*)pCtx;
3792  int i;
3793  for(i=0; i<pSession->nFilter; i++){
3794    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3795  }
3796  return 1;
3797}
3798#endif
3799
3800/*
3801** Try to deduce the type of file for zName based on its content.  Return
3802** one of the SHELL_OPEN_* constants.
3803**
3804** If the file does not exist or is empty but its name looks like a ZIP
3805** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3806** Otherwise, assume an ordinary database regardless of the filename if
3807** the type cannot be determined from content.
3808*/
3809int deduceDatabaseType(const char *zName, int dfltZip){
3810  FILE *f = fopen(zName, "rb");
3811  size_t n;
3812  int rc = SHELL_OPEN_UNSPEC;
3813  char zBuf[100];
3814  if( f==0 ){
3815    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3816       return SHELL_OPEN_ZIPFILE;
3817    }else{
3818       return SHELL_OPEN_NORMAL;
3819    }
3820  }
3821  n = fread(zBuf, 16, 1, f);
3822  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3823    fclose(f);
3824    return SHELL_OPEN_NORMAL;
3825  }
3826  fseek(f, -25, SEEK_END);
3827  n = fread(zBuf, 25, 1, f);
3828  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3829    rc = SHELL_OPEN_APPENDVFS;
3830  }else{
3831    fseek(f, -22, SEEK_END);
3832    n = fread(zBuf, 22, 1, f);
3833    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3834       && zBuf[3]==0x06 ){
3835      rc = SHELL_OPEN_ZIPFILE;
3836    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3837      rc = SHELL_OPEN_ZIPFILE;
3838    }
3839  }
3840  fclose(f);
3841  return rc;
3842}
3843
3844#ifdef SQLITE_ENABLE_DESERIALIZE
3845/*
3846** Reconstruct an in-memory database using the output from the "dbtotxt"
3847** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
3848** is 0, then read from standard input.
3849*/
3850static unsigned char *readHexDb(ShellState *p, int *pnData){
3851  unsigned char *a = 0;
3852  int nLine;
3853  int n = 0;
3854  int pgsz = 0;
3855  int iOffset = 0;
3856  int j, k;
3857  int rc;
3858  FILE *in;
3859  unsigned char x[16];
3860  char zLine[1000];
3861  if( p->zDbFilename ){
3862    in = fopen(p->zDbFilename, "r");
3863    if( in==0 ){
3864      utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3865      return 0;
3866    }
3867    nLine = 0;
3868  }else{
3869    in = p->in;
3870    nLine = p->lineno;
3871  }
3872  *pnData = 0;
3873  nLine++;
3874  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3875  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3876  if( rc!=2 ) goto readHexDb_error;
3877  if( n<=0 ) goto readHexDb_error;
3878  a = sqlite3_malloc( n );
3879  if( a==0 ){
3880    utf8_printf(stderr, "Out of memory!\n");
3881    goto readHexDb_error;
3882  }
3883  memset(a, 0, n);
3884  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3885    utf8_printf(stderr, "invalid pagesize\n");
3886    goto readHexDb_error;
3887  }
3888  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
3889    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3890    if( rc==2 ){
3891      iOffset = k;
3892      continue;
3893    }
3894    if( strncmp(zLine, "| end ", 6)==0 ){
3895      break;
3896    }
3897    rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx"
3898                      "  %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
3899                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3900                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3901    if( rc==17 ){
3902      k = iOffset+j;
3903      if( k+16<=n ){
3904        memcpy(a+k, x, 16);
3905      }
3906    }
3907  }
3908  *pnData = n;
3909  if( in!=p->in ){
3910    fclose(in);
3911  }else{
3912    p->lineno = nLine;
3913  }
3914  return a;
3915
3916readHexDb_error:
3917  if( in!=stdin ){
3918    fclose(in);
3919  }else{
3920    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
3921      nLine++;
3922      if(strncmp(zLine, "| end ", 6)==0 ) break;
3923    }
3924    p->lineno = nLine;
3925  }
3926  sqlite3_free(a);
3927  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3928  return 0;
3929}
3930#endif /* SQLITE_ENABLE_DESERIALIZE */
3931
3932/* Flags for open_db().
3933**
3934** The default behavior of open_db() is to exit(1) if the database fails to
3935** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3936** but still returns without calling exit.
3937**
3938** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3939** ZIP archive if the file does not exist or is empty and its name matches
3940** the *.zip pattern.
3941*/
3942#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
3943#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
3944
3945/*
3946** Make sure the database is open.  If it is not, then open it.  If
3947** the database fails to open, print an error message and exit.
3948*/
3949static void open_db(ShellState *p, int openFlags){
3950  if( p->db==0 ){
3951    if( p->openMode==SHELL_OPEN_UNSPEC ){
3952      if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3953        p->openMode = SHELL_OPEN_NORMAL;
3954      }else{
3955        p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3956                             (openFlags & OPEN_DB_ZIPFILE)!=0);
3957      }
3958    }
3959    switch( p->openMode ){
3960      case SHELL_OPEN_APPENDVFS: {
3961        sqlite3_open_v2(p->zDbFilename, &p->db,
3962           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3963        break;
3964      }
3965      case SHELL_OPEN_HEXDB:
3966      case SHELL_OPEN_DESERIALIZE: {
3967        sqlite3_open(0, &p->db);
3968        break;
3969      }
3970      case SHELL_OPEN_ZIPFILE: {
3971        sqlite3_open(":memory:", &p->db);
3972        break;
3973      }
3974      case SHELL_OPEN_READONLY: {
3975        sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3976        break;
3977      }
3978      case SHELL_OPEN_UNSPEC:
3979      case SHELL_OPEN_NORMAL: {
3980        sqlite3_open(p->zDbFilename, &p->db);
3981        break;
3982      }
3983    }
3984    globalDb = p->db;
3985    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3986      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3987          p->zDbFilename, sqlite3_errmsg(p->db));
3988      if( openFlags & OPEN_DB_KEEPALIVE ){
3989        sqlite3_open(":memory:", &p->db);
3990        return;
3991      }
3992      exit(1);
3993    }
3994#ifndef SQLITE_OMIT_LOAD_EXTENSION
3995    sqlite3_enable_load_extension(p->db, 1);
3996#endif
3997    sqlite3_fileio_init(p->db, 0, 0);
3998    sqlite3_shathree_init(p->db, 0, 0);
3999    sqlite3_completion_init(p->db, 0, 0);
4000#ifdef SQLITE_HAVE_ZLIB
4001    sqlite3_zipfile_init(p->db, 0, 0);
4002    sqlite3_sqlar_init(p->db, 0, 0);
4003#endif
4004    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4005                            shellAddSchemaName, 0, 0);
4006    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4007                            shellModuleSchema, 0, 0);
4008    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4009                            shellPutsFunc, 0, 0);
4010#ifndef SQLITE_NOHAVE_SYSTEM
4011    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4012                            editFunc, 0, 0);
4013    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4014                            editFunc, 0, 0);
4015#endif
4016    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4017      char *zSql = sqlite3_mprintf(
4018         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4019      sqlite3_exec(p->db, zSql, 0, 0, 0);
4020      sqlite3_free(zSql);
4021    }
4022#ifdef SQLITE_ENABLE_DESERIALIZE
4023    else
4024    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4025      int rc;
4026      int nData = 0;
4027      unsigned char *aData;
4028      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4029        aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4030      }else{
4031        aData = readHexDb(p, &nData);
4032        if( aData==0 ){
4033          utf8_printf(stderr, "Error in hexdb input\n");
4034          return;
4035        }
4036      }
4037      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4038                   SQLITE_DESERIALIZE_RESIZEABLE |
4039                   SQLITE_DESERIALIZE_FREEONCLOSE);
4040      if( rc ){
4041        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4042      }
4043      if( p->szMax>0 ){
4044        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4045      }
4046    }
4047#endif
4048  }
4049}
4050
4051/*
4052** Attempt to close the databaes connection.  Report errors.
4053*/
4054void close_db(sqlite3 *db){
4055  int rc = sqlite3_close(db);
4056  if( rc ){
4057    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4058        rc, sqlite3_errmsg(db));
4059  }
4060}
4061
4062#if HAVE_READLINE || HAVE_EDITLINE
4063/*
4064** Readline completion callbacks
4065*/
4066static char *readline_completion_generator(const char *text, int state){
4067  static sqlite3_stmt *pStmt = 0;
4068  char *zRet;
4069  if( state==0 ){
4070    char *zSql;
4071    sqlite3_finalize(pStmt);
4072    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4073                           "  FROM completion(%Q) ORDER BY 1", text);
4074    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4075    sqlite3_free(zSql);
4076  }
4077  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4078    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4079  }else{
4080    sqlite3_finalize(pStmt);
4081    pStmt = 0;
4082    zRet = 0;
4083  }
4084  return zRet;
4085}
4086static char **readline_completion(const char *zText, int iStart, int iEnd){
4087  rl_attempted_completion_over = 1;
4088  return rl_completion_matches(zText, readline_completion_generator);
4089}
4090
4091#elif HAVE_LINENOISE
4092/*
4093** Linenoise completion callback
4094*/
4095static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4096  int nLine = strlen30(zLine);
4097  int i, iStart;
4098  sqlite3_stmt *pStmt = 0;
4099  char *zSql;
4100  char zBuf[1000];
4101
4102  if( nLine>sizeof(zBuf)-30 ) return;
4103  if( zLine[0]=='.' || zLine[0]=='#') return;
4104  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4105  if( i==nLine-1 ) return;
4106  iStart = i+1;
4107  memcpy(zBuf, zLine, iStart);
4108  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4109                         "  FROM completion(%Q,%Q) ORDER BY 1",
4110                         &zLine[iStart], zLine);
4111  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4112  sqlite3_free(zSql);
4113  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4114  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4115    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4116    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4117    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4118      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4119      linenoiseAddCompletion(lc, zBuf);
4120    }
4121  }
4122  sqlite3_finalize(pStmt);
4123}
4124#endif
4125
4126/*
4127** Do C-language style dequoting.
4128**
4129**    \a    -> alarm
4130**    \b    -> backspace
4131**    \t    -> tab
4132**    \n    -> newline
4133**    \v    -> vertical tab
4134**    \f    -> form feed
4135**    \r    -> carriage return
4136**    \s    -> space
4137**    \"    -> "
4138**    \'    -> '
4139**    \\    -> backslash
4140**    \NNN  -> ascii character NNN in octal
4141*/
4142static void resolve_backslashes(char *z){
4143  int i, j;
4144  char c;
4145  while( *z && *z!='\\' ) z++;
4146  for(i=j=0; (c = z[i])!=0; i++, j++){
4147    if( c=='\\' && z[i+1]!=0 ){
4148      c = z[++i];
4149      if( c=='a' ){
4150        c = '\a';
4151      }else if( c=='b' ){
4152        c = '\b';
4153      }else if( c=='t' ){
4154        c = '\t';
4155      }else if( c=='n' ){
4156        c = '\n';
4157      }else if( c=='v' ){
4158        c = '\v';
4159      }else if( c=='f' ){
4160        c = '\f';
4161      }else if( c=='r' ){
4162        c = '\r';
4163      }else if( c=='"' ){
4164        c = '"';
4165      }else if( c=='\'' ){
4166        c = '\'';
4167      }else if( c=='\\' ){
4168        c = '\\';
4169      }else if( c>='0' && c<='7' ){
4170        c -= '0';
4171        if( z[i+1]>='0' && z[i+1]<='7' ){
4172          i++;
4173          c = (c<<3) + z[i] - '0';
4174          if( z[i+1]>='0' && z[i+1]<='7' ){
4175            i++;
4176            c = (c<<3) + z[i] - '0';
4177          }
4178        }
4179      }
4180    }
4181    z[j] = c;
4182  }
4183  if( j<i ) z[j] = 0;
4184}
4185
4186/*
4187** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4188** for TRUE and FALSE.  Return the integer value if appropriate.
4189*/
4190static int booleanValue(const char *zArg){
4191  int i;
4192  if( zArg[0]=='0' && zArg[1]=='x' ){
4193    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4194  }else{
4195    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4196  }
4197  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4198  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4199    return 1;
4200  }
4201  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4202    return 0;
4203  }
4204  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4205          zArg);
4206  return 0;
4207}
4208
4209/*
4210** Set or clear a shell flag according to a boolean value.
4211*/
4212static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4213  if( booleanValue(zArg) ){
4214    ShellSetFlag(p, mFlag);
4215  }else{
4216    ShellClearFlag(p, mFlag);
4217  }
4218}
4219
4220/*
4221** Close an output file, assuming it is not stderr or stdout
4222*/
4223static void output_file_close(FILE *f){
4224  if( f && f!=stdout && f!=stderr ) fclose(f);
4225}
4226
4227/*
4228** Try to open an output file.   The names "stdout" and "stderr" are
4229** recognized and do the right thing.  NULL is returned if the output
4230** filename is "off".
4231*/
4232static FILE *output_file_open(const char *zFile, int bTextMode){
4233  FILE *f;
4234  if( strcmp(zFile,"stdout")==0 ){
4235    f = stdout;
4236  }else if( strcmp(zFile, "stderr")==0 ){
4237    f = stderr;
4238  }else if( strcmp(zFile, "off")==0 ){
4239    f = 0;
4240  }else{
4241    f = fopen(zFile, bTextMode ? "w" : "wb");
4242    if( f==0 ){
4243      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4244    }
4245  }
4246  return f;
4247}
4248
4249#ifndef SQLITE_OMIT_TRACE
4250/*
4251** A routine for handling output from sqlite3_trace().
4252*/
4253static int sql_trace_callback(
4254  unsigned mType,         /* The trace type */
4255  void *pArg,             /* The ShellState pointer */
4256  void *pP,               /* Usually a pointer to sqlite_stmt */
4257  void *pX                /* Auxiliary output */
4258){
4259  ShellState *p = (ShellState*)pArg;
4260  sqlite3_stmt *pStmt;
4261  const char *zSql;
4262  int nSql;
4263  if( p->traceOut==0 ) return 0;
4264  if( mType==SQLITE_TRACE_CLOSE ){
4265    utf8_printf(p->traceOut, "-- closing database connection\n");
4266    return 0;
4267  }
4268  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4269    zSql = (const char*)pX;
4270  }else{
4271    pStmt = (sqlite3_stmt*)pP;
4272    switch( p->eTraceType ){
4273      case SHELL_TRACE_EXPANDED: {
4274        zSql = sqlite3_expanded_sql(pStmt);
4275        break;
4276      }
4277#ifdef SQLITE_ENABLE_NORMALIZE
4278      case SHELL_TRACE_NORMALIZED: {
4279        zSql = sqlite3_normalized_sql(pStmt);
4280        break;
4281      }
4282#endif
4283      default: {
4284        zSql = sqlite3_sql(pStmt);
4285        break;
4286      }
4287    }
4288  }
4289  if( zSql==0 ) return 0;
4290  nSql = strlen30(zSql);
4291  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4292  switch( mType ){
4293    case SQLITE_TRACE_ROW:
4294    case SQLITE_TRACE_STMT: {
4295      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4296      break;
4297    }
4298    case SQLITE_TRACE_PROFILE: {
4299      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4300      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4301      break;
4302    }
4303  }
4304  return 0;
4305}
4306#endif
4307
4308/*
4309** A no-op routine that runs with the ".breakpoint" doc-command.  This is
4310** a useful spot to set a debugger breakpoint.
4311*/
4312static void test_breakpoint(void){
4313  static int nCall = 0;
4314  nCall++;
4315}
4316
4317/*
4318** An object used to read a CSV and other files for import.
4319*/
4320typedef struct ImportCtx ImportCtx;
4321struct ImportCtx {
4322  const char *zFile;  /* Name of the input file */
4323  FILE *in;           /* Read the CSV text from this input stream */
4324  char *z;            /* Accumulated text for a field */
4325  int n;              /* Number of bytes in z */
4326  int nAlloc;         /* Space allocated for z[] */
4327  int nLine;          /* Current line number */
4328  int bNotFirst;      /* True if one or more bytes already read */
4329  int cTerm;          /* Character that terminated the most recent field */
4330  int cColSep;        /* The column separator character.  (Usually ",") */
4331  int cRowSep;        /* The row separator character.  (Usually "\n") */
4332};
4333
4334/* Append a single byte to z[] */
4335static void import_append_char(ImportCtx *p, int c){
4336  if( p->n+1>=p->nAlloc ){
4337    p->nAlloc += p->nAlloc + 100;
4338    p->z = sqlite3_realloc64(p->z, p->nAlloc);
4339    if( p->z==0 ) shell_out_of_memory();
4340  }
4341  p->z[p->n++] = (char)c;
4342}
4343
4344/* Read a single field of CSV text.  Compatible with rfc4180 and extended
4345** with the option of having a separator other than ",".
4346**
4347**   +  Input comes from p->in.
4348**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4349**      from sqlite3_malloc64().
4350**   +  Use p->cSep as the column separator.  The default is ",".
4351**   +  Use p->rSep as the row separator.  The default is "\n".
4352**   +  Keep track of the line number in p->nLine.
4353**   +  Store the character that terminates the field in p->cTerm.  Store
4354**      EOF on end-of-file.
4355**   +  Report syntax errors on stderr
4356*/
4357static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4358  int c;
4359  int cSep = p->cColSep;
4360  int rSep = p->cRowSep;
4361  p->n = 0;
4362  c = fgetc(p->in);
4363  if( c==EOF || seenInterrupt ){
4364    p->cTerm = EOF;
4365    return 0;
4366  }
4367  if( c=='"' ){
4368    int pc, ppc;
4369    int startLine = p->nLine;
4370    int cQuote = c;
4371    pc = ppc = 0;
4372    while( 1 ){
4373      c = fgetc(p->in);
4374      if( c==rSep ) p->nLine++;
4375      if( c==cQuote ){
4376        if( pc==cQuote ){
4377          pc = 0;
4378          continue;
4379        }
4380      }
4381      if( (c==cSep && pc==cQuote)
4382       || (c==rSep && pc==cQuote)
4383       || (c==rSep && pc=='\r' && ppc==cQuote)
4384       || (c==EOF && pc==cQuote)
4385      ){
4386        do{ p->n--; }while( p->z[p->n]!=cQuote );
4387        p->cTerm = c;
4388        break;
4389      }
4390      if( pc==cQuote && c!='\r' ){
4391        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4392                p->zFile, p->nLine, cQuote);
4393      }
4394      if( c==EOF ){
4395        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4396                p->zFile, startLine, cQuote);
4397        p->cTerm = c;
4398        break;
4399      }
4400      import_append_char(p, c);
4401      ppc = pc;
4402      pc = c;
4403    }
4404  }else{
4405    /* If this is the first field being parsed and it begins with the
4406    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
4407    if( (c&0xff)==0xef && p->bNotFirst==0 ){
4408      import_append_char(p, c);
4409      c = fgetc(p->in);
4410      if( (c&0xff)==0xbb ){
4411        import_append_char(p, c);
4412        c = fgetc(p->in);
4413        if( (c&0xff)==0xbf ){
4414          p->bNotFirst = 1;
4415          p->n = 0;
4416          return csv_read_one_field(p);
4417        }
4418      }
4419    }
4420    while( c!=EOF && c!=cSep && c!=rSep ){
4421      import_append_char(p, c);
4422      c = fgetc(p->in);
4423    }
4424    if( c==rSep ){
4425      p->nLine++;
4426      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4427    }
4428    p->cTerm = c;
4429  }
4430  if( p->z ) p->z[p->n] = 0;
4431  p->bNotFirst = 1;
4432  return p->z;
4433}
4434
4435/* Read a single field of ASCII delimited text.
4436**
4437**   +  Input comes from p->in.
4438**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4439**      from sqlite3_malloc64().
4440**   +  Use p->cSep as the column separator.  The default is "\x1F".
4441**   +  Use p->rSep as the row separator.  The default is "\x1E".
4442**   +  Keep track of the row number in p->nLine.
4443**   +  Store the character that terminates the field in p->cTerm.  Store
4444**      EOF on end-of-file.
4445**   +  Report syntax errors on stderr
4446*/
4447static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4448  int c;
4449  int cSep = p->cColSep;
4450  int rSep = p->cRowSep;
4451  p->n = 0;
4452  c = fgetc(p->in);
4453  if( c==EOF || seenInterrupt ){
4454    p->cTerm = EOF;
4455    return 0;
4456  }
4457  while( c!=EOF && c!=cSep && c!=rSep ){
4458    import_append_char(p, c);
4459    c = fgetc(p->in);
4460  }
4461  if( c==rSep ){
4462    p->nLine++;
4463  }
4464  p->cTerm = c;
4465  if( p->z ) p->z[p->n] = 0;
4466  return p->z;
4467}
4468
4469/*
4470** Try to transfer data for table zTable.  If an error is seen while
4471** moving forward, try to go backwards.  The backwards movement won't
4472** work for WITHOUT ROWID tables.
4473*/
4474static void tryToCloneData(
4475  ShellState *p,
4476  sqlite3 *newDb,
4477  const char *zTable
4478){
4479  sqlite3_stmt *pQuery = 0;
4480  sqlite3_stmt *pInsert = 0;
4481  char *zQuery = 0;
4482  char *zInsert = 0;
4483  int rc;
4484  int i, j, n;
4485  int nTable = strlen30(zTable);
4486  int k = 0;
4487  int cnt = 0;
4488  const int spinRate = 10000;
4489
4490  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4491  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4492  if( rc ){
4493    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4494            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4495            zQuery);
4496    goto end_data_xfer;
4497  }
4498  n = sqlite3_column_count(pQuery);
4499  zInsert = sqlite3_malloc64(200 + nTable + n*3);
4500  if( zInsert==0 ) shell_out_of_memory();
4501  sqlite3_snprintf(200+nTable,zInsert,
4502                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4503  i = strlen30(zInsert);
4504  for(j=1; j<n; j++){
4505    memcpy(zInsert+i, ",?", 2);
4506    i += 2;
4507  }
4508  memcpy(zInsert+i, ");", 3);
4509  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4510  if( rc ){
4511    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4512            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4513            zQuery);
4514    goto end_data_xfer;
4515  }
4516  for(k=0; k<2; k++){
4517    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4518      for(i=0; i<n; i++){
4519        switch( sqlite3_column_type(pQuery, i) ){
4520          case SQLITE_NULL: {
4521            sqlite3_bind_null(pInsert, i+1);
4522            break;
4523          }
4524          case SQLITE_INTEGER: {
4525            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4526            break;
4527          }
4528          case SQLITE_FLOAT: {
4529            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4530            break;
4531          }
4532          case SQLITE_TEXT: {
4533            sqlite3_bind_text(pInsert, i+1,
4534                             (const char*)sqlite3_column_text(pQuery,i),
4535                             -1, SQLITE_STATIC);
4536            break;
4537          }
4538          case SQLITE_BLOB: {
4539            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4540                                            sqlite3_column_bytes(pQuery,i),
4541                                            SQLITE_STATIC);
4542            break;
4543          }
4544        }
4545      } /* End for */
4546      rc = sqlite3_step(pInsert);
4547      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4548        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4549                        sqlite3_errmsg(newDb));
4550      }
4551      sqlite3_reset(pInsert);
4552      cnt++;
4553      if( (cnt%spinRate)==0 ){
4554        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4555        fflush(stdout);
4556      }
4557    } /* End while */
4558    if( rc==SQLITE_DONE ) break;
4559    sqlite3_finalize(pQuery);
4560    sqlite3_free(zQuery);
4561    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4562                             zTable);
4563    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4564    if( rc ){
4565      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4566      break;
4567    }
4568  } /* End for(k=0...) */
4569
4570end_data_xfer:
4571  sqlite3_finalize(pQuery);
4572  sqlite3_finalize(pInsert);
4573  sqlite3_free(zQuery);
4574  sqlite3_free(zInsert);
4575}
4576
4577
4578/*
4579** Try to transfer all rows of the schema that match zWhere.  For
4580** each row, invoke xForEach() on the object defined by that row.
4581** If an error is encountered while moving forward through the
4582** sqlite_master table, try again moving backwards.
4583*/
4584static void tryToCloneSchema(
4585  ShellState *p,
4586  sqlite3 *newDb,
4587  const char *zWhere,
4588  void (*xForEach)(ShellState*,sqlite3*,const char*)
4589){
4590  sqlite3_stmt *pQuery = 0;
4591  char *zQuery = 0;
4592  int rc;
4593  const unsigned char *zName;
4594  const unsigned char *zSql;
4595  char *zErrMsg = 0;
4596
4597  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4598                           " WHERE %s", zWhere);
4599  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4600  if( rc ){
4601    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4602                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4603                    zQuery);
4604    goto end_schema_xfer;
4605  }
4606  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4607    zName = sqlite3_column_text(pQuery, 0);
4608    zSql = sqlite3_column_text(pQuery, 1);
4609    printf("%s... ", zName); fflush(stdout);
4610    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4611    if( zErrMsg ){
4612      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4613      sqlite3_free(zErrMsg);
4614      zErrMsg = 0;
4615    }
4616    if( xForEach ){
4617      xForEach(p, newDb, (const char*)zName);
4618    }
4619    printf("done\n");
4620  }
4621  if( rc!=SQLITE_DONE ){
4622    sqlite3_finalize(pQuery);
4623    sqlite3_free(zQuery);
4624    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4625                             " WHERE %s ORDER BY rowid DESC", zWhere);
4626    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4627    if( rc ){
4628      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4629                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4630                      zQuery);
4631      goto end_schema_xfer;
4632    }
4633    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4634      zName = sqlite3_column_text(pQuery, 0);
4635      zSql = sqlite3_column_text(pQuery, 1);
4636      printf("%s... ", zName); fflush(stdout);
4637      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4638      if( zErrMsg ){
4639        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4640        sqlite3_free(zErrMsg);
4641        zErrMsg = 0;
4642      }
4643      if( xForEach ){
4644        xForEach(p, newDb, (const char*)zName);
4645      }
4646      printf("done\n");
4647    }
4648  }
4649end_schema_xfer:
4650  sqlite3_finalize(pQuery);
4651  sqlite3_free(zQuery);
4652}
4653
4654/*
4655** Open a new database file named "zNewDb".  Try to recover as much information
4656** as possible out of the main database (which might be corrupt) and write it
4657** into zNewDb.
4658*/
4659static void tryToClone(ShellState *p, const char *zNewDb){
4660  int rc;
4661  sqlite3 *newDb = 0;
4662  if( access(zNewDb,0)==0 ){
4663    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4664    return;
4665  }
4666  rc = sqlite3_open(zNewDb, &newDb);
4667  if( rc ){
4668    utf8_printf(stderr, "Cannot create output database: %s\n",
4669            sqlite3_errmsg(newDb));
4670  }else{
4671    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4672    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4673    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4674    tryToCloneSchema(p, newDb, "type!='table'", 0);
4675    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4676    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4677  }
4678  close_db(newDb);
4679}
4680
4681/*
4682** Change the output file back to stdout.
4683**
4684** If the p->doXdgOpen flag is set, that means the output was being
4685** redirected to a temporary file named by p->zTempFile.  In that case,
4686** launch start/open/xdg-open on that temporary file.
4687*/
4688static void output_reset(ShellState *p){
4689  if( p->outfile[0]=='|' ){
4690#ifndef SQLITE_OMIT_POPEN
4691    pclose(p->out);
4692#endif
4693  }else{
4694    output_file_close(p->out);
4695#ifndef SQLITE_NOHAVE_SYSTEM
4696    if( p->doXdgOpen ){
4697      const char *zXdgOpenCmd =
4698#if defined(_WIN32)
4699      "start";
4700#elif defined(__APPLE__)
4701      "open";
4702#else
4703      "xdg-open";
4704#endif
4705      char *zCmd;
4706      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
4707      if( system(zCmd) ){
4708        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4709      }
4710      sqlite3_free(zCmd);
4711      outputModePop(p);
4712      p->doXdgOpen = 0;
4713    }
4714#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4715  }
4716  p->outfile[0] = 0;
4717  p->out = stdout;
4718}
4719
4720/*
4721** Run an SQL command and return the single integer result.
4722*/
4723static int db_int(ShellState *p, const char *zSql){
4724  sqlite3_stmt *pStmt;
4725  int res = 0;
4726  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4727  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4728    res = sqlite3_column_int(pStmt,0);
4729  }
4730  sqlite3_finalize(pStmt);
4731  return res;
4732}
4733
4734/*
4735** Convert a 2-byte or 4-byte big-endian integer into a native integer
4736*/
4737static unsigned int get2byteInt(unsigned char *a){
4738  return (a[0]<<8) + a[1];
4739}
4740static unsigned int get4byteInt(unsigned char *a){
4741  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4742}
4743
4744/*
4745** Implementation of the ".info" command.
4746**
4747** Return 1 on error, 2 to exit, and 0 otherwise.
4748*/
4749static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4750  static const struct { const char *zName; int ofst; } aField[] = {
4751     { "file change counter:",  24  },
4752     { "database page count:",  28  },
4753     { "freelist page count:",  36  },
4754     { "schema cookie:",        40  },
4755     { "schema format:",        44  },
4756     { "default cache size:",   48  },
4757     { "autovacuum top root:",  52  },
4758     { "incremental vacuum:",   64  },
4759     { "text encoding:",        56  },
4760     { "user version:",         60  },
4761     { "application id:",       68  },
4762     { "software version:",     96  },
4763  };
4764  static const struct { const char *zName; const char *zSql; } aQuery[] = {
4765     { "number of tables:",
4766       "SELECT count(*) FROM %s WHERE type='table'" },
4767     { "number of indexes:",
4768       "SELECT count(*) FROM %s WHERE type='index'" },
4769     { "number of triggers:",
4770       "SELECT count(*) FROM %s WHERE type='trigger'" },
4771     { "number of views:",
4772       "SELECT count(*) FROM %s WHERE type='view'" },
4773     { "schema size:",
4774       "SELECT total(length(sql)) FROM %s" },
4775  };
4776  int i, rc;
4777  unsigned iDataVersion;
4778  char *zSchemaTab;
4779  char *zDb = nArg>=2 ? azArg[1] : "main";
4780  sqlite3_stmt *pStmt = 0;
4781  unsigned char aHdr[100];
4782  open_db(p, 0);
4783  if( p->db==0 ) return 1;
4784  rc = sqlite3_prepare_v2(p->db,
4785             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4786             -1, &pStmt, 0);
4787  if( rc ){
4788    if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4789      utf8_printf(stderr, "the \".dbinfo\" command requires the "
4790                          "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4791    }else{
4792      utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4793    }
4794    sqlite3_finalize(pStmt);
4795    return 1;
4796  }
4797  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4798  if( sqlite3_step(pStmt)==SQLITE_ROW
4799   && sqlite3_column_bytes(pStmt,0)>100
4800  ){
4801    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4802    sqlite3_finalize(pStmt);
4803  }else{
4804    raw_printf(stderr, "unable to read database header\n");
4805    sqlite3_finalize(pStmt);
4806    return 1;
4807  }
4808  i = get2byteInt(aHdr+16);
4809  if( i==1 ) i = 65536;
4810  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4811  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4812  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4813  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4814  for(i=0; i<ArraySize(aField); i++){
4815    int ofst = aField[i].ofst;
4816    unsigned int val = get4byteInt(aHdr + ofst);
4817    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4818    switch( ofst ){
4819      case 56: {
4820        if( val==1 ) raw_printf(p->out, " (utf8)");
4821        if( val==2 ) raw_printf(p->out, " (utf16le)");
4822        if( val==3 ) raw_printf(p->out, " (utf16be)");
4823      }
4824    }
4825    raw_printf(p->out, "\n");
4826  }
4827  if( zDb==0 ){
4828    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4829  }else if( strcmp(zDb,"temp")==0 ){
4830    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4831  }else{
4832    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4833  }
4834  for(i=0; i<ArraySize(aQuery); i++){
4835    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4836    int val = db_int(p, zSql);
4837    sqlite3_free(zSql);
4838    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4839  }
4840  sqlite3_free(zSchemaTab);
4841  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4842  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
4843  return 0;
4844}
4845
4846/*
4847** Print the current sqlite3_errmsg() value to stderr and return 1.
4848*/
4849static int shellDatabaseError(sqlite3 *db){
4850  const char *zErr = sqlite3_errmsg(db);
4851  utf8_printf(stderr, "Error: %s\n", zErr);
4852  return 1;
4853}
4854
4855/*
4856** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
4857** if they match and FALSE (0) if they do not match.
4858**
4859** Globbing rules:
4860**
4861**      '*'       Matches any sequence of zero or more characters.
4862**
4863**      '?'       Matches exactly one character.
4864**
4865**     [...]      Matches one character from the enclosed list of
4866**                characters.
4867**
4868**     [^...]     Matches one character not in the enclosed list.
4869**
4870**      '#'       Matches any sequence of one or more digits with an
4871**                optional + or - sign in front
4872**
4873**      ' '       Any span of whitespace matches any other span of
4874**                whitespace.
4875**
4876** Extra whitespace at the end of z[] is ignored.
4877*/
4878static int testcase_glob(const char *zGlob, const char *z){
4879  int c, c2;
4880  int invert;
4881  int seen;
4882
4883  while( (c = (*(zGlob++)))!=0 ){
4884    if( IsSpace(c) ){
4885      if( !IsSpace(*z) ) return 0;
4886      while( IsSpace(*zGlob) ) zGlob++;
4887      while( IsSpace(*z) ) z++;
4888    }else if( c=='*' ){
4889      while( (c=(*(zGlob++))) == '*' || c=='?' ){
4890        if( c=='?' && (*(z++))==0 ) return 0;
4891      }
4892      if( c==0 ){
4893        return 1;
4894      }else if( c=='[' ){
4895        while( *z && testcase_glob(zGlob-1,z)==0 ){
4896          z++;
4897        }
4898        return (*z)!=0;
4899      }
4900      while( (c2 = (*(z++)))!=0 ){
4901        while( c2!=c ){
4902          c2 = *(z++);
4903          if( c2==0 ) return 0;
4904        }
4905        if( testcase_glob(zGlob,z) ) return 1;
4906      }
4907      return 0;
4908    }else if( c=='?' ){
4909      if( (*(z++))==0 ) return 0;
4910    }else if( c=='[' ){
4911      int prior_c = 0;
4912      seen = 0;
4913      invert = 0;
4914      c = *(z++);
4915      if( c==0 ) return 0;
4916      c2 = *(zGlob++);
4917      if( c2=='^' ){
4918        invert = 1;
4919        c2 = *(zGlob++);
4920      }
4921      if( c2==']' ){
4922        if( c==']' ) seen = 1;
4923        c2 = *(zGlob++);
4924      }
4925      while( c2 && c2!=']' ){
4926        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4927          c2 = *(zGlob++);
4928          if( c>=prior_c && c<=c2 ) seen = 1;
4929          prior_c = 0;
4930        }else{
4931          if( c==c2 ){
4932            seen = 1;
4933          }
4934          prior_c = c2;
4935        }
4936        c2 = *(zGlob++);
4937      }
4938      if( c2==0 || (seen ^ invert)==0 ) return 0;
4939    }else if( c=='#' ){
4940      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4941      if( !IsDigit(z[0]) ) return 0;
4942      z++;
4943      while( IsDigit(z[0]) ){ z++; }
4944    }else{
4945      if( c!=(*(z++)) ) return 0;
4946    }
4947  }
4948  while( IsSpace(*z) ){ z++; }
4949  return *z==0;
4950}
4951
4952
4953/*
4954** Compare the string as a command-line option with either one or two
4955** initial "-" characters.
4956*/
4957static int optionMatch(const char *zStr, const char *zOpt){
4958  if( zStr[0]!='-' ) return 0;
4959  zStr++;
4960  if( zStr[0]=='-' ) zStr++;
4961  return strcmp(zStr, zOpt)==0;
4962}
4963
4964/*
4965** Delete a file.
4966*/
4967int shellDeleteFile(const char *zFilename){
4968  int rc;
4969#ifdef _WIN32
4970  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4971  rc = _wunlink(z);
4972  sqlite3_free(z);
4973#else
4974  rc = unlink(zFilename);
4975#endif
4976  return rc;
4977}
4978
4979/*
4980** Try to delete the temporary file (if there is one) and free the
4981** memory used to hold the name of the temp file.
4982*/
4983static void clearTempFile(ShellState *p){
4984  if( p->zTempFile==0 ) return;
4985  if( p->doXdgOpen ) return;
4986  if( shellDeleteFile(p->zTempFile) ) return;
4987  sqlite3_free(p->zTempFile);
4988  p->zTempFile = 0;
4989}
4990
4991/*
4992** Create a new temp file name with the given suffix.
4993*/
4994static void newTempFile(ShellState *p, const char *zSuffix){
4995  clearTempFile(p);
4996  sqlite3_free(p->zTempFile);
4997  p->zTempFile = 0;
4998  if( p->db ){
4999    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5000  }
5001  if( p->zTempFile==0 ){
5002    sqlite3_uint64 r;
5003    sqlite3_randomness(sizeof(r), &r);
5004    p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5005  }else{
5006    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5007  }
5008  if( p->zTempFile==0 ){
5009    raw_printf(stderr, "out of memory\n");
5010    exit(1);
5011  }
5012}
5013
5014
5015/*
5016** The implementation of SQL scalar function fkey_collate_clause(), used
5017** by the ".lint fkey-indexes" command. This scalar function is always
5018** called with four arguments - the parent table name, the parent column name,
5019** the child table name and the child column name.
5020**
5021**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5022**
5023** If either of the named tables or columns do not exist, this function
5024** returns an empty string. An empty string is also returned if both tables
5025** and columns exist but have the same default collation sequence. Or,
5026** if both exist but the default collation sequences are different, this
5027** function returns the string " COLLATE <parent-collation>", where
5028** <parent-collation> is the default collation sequence of the parent column.
5029*/
5030static void shellFkeyCollateClause(
5031  sqlite3_context *pCtx,
5032  int nVal,
5033  sqlite3_value **apVal
5034){
5035  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5036  const char *zParent;
5037  const char *zParentCol;
5038  const char *zParentSeq;
5039  const char *zChild;
5040  const char *zChildCol;
5041  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5042  int rc;
5043
5044  assert( nVal==4 );
5045  zParent = (const char*)sqlite3_value_text(apVal[0]);
5046  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5047  zChild = (const char*)sqlite3_value_text(apVal[2]);
5048  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5049
5050  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5051  rc = sqlite3_table_column_metadata(
5052      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5053  );
5054  if( rc==SQLITE_OK ){
5055    rc = sqlite3_table_column_metadata(
5056        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5057    );
5058  }
5059
5060  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5061    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5062    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5063    sqlite3_free(z);
5064  }
5065}
5066
5067
5068/*
5069** The implementation of dot-command ".lint fkey-indexes".
5070*/
5071static int lintFkeyIndexes(
5072  ShellState *pState,             /* Current shell tool state */
5073  char **azArg,                   /* Array of arguments passed to dot command */
5074  int nArg                        /* Number of entries in azArg[] */
5075){
5076  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5077  FILE *out = pState->out;        /* Stream to write non-error output to */
5078  int bVerbose = 0;               /* If -verbose is present */
5079  int bGroupByParent = 0;         /* If -groupbyparent is present */
5080  int i;                          /* To iterate through azArg[] */
5081  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5082  int rc;                         /* Return code */
5083  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5084
5085  /*
5086  ** This SELECT statement returns one row for each foreign key constraint
5087  ** in the schema of the main database. The column values are:
5088  **
5089  ** 0. The text of an SQL statement similar to:
5090  **
5091  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5092  **
5093  **    This SELECT is similar to the one that the foreign keys implementation
5094  **    needs to run internally on child tables. If there is an index that can
5095  **    be used to optimize this query, then it can also be used by the FK
5096  **    implementation to optimize DELETE or UPDATE statements on the parent
5097  **    table.
5098  **
5099  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5100  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5101  **    contains an index that can be used to optimize the query.
5102  **
5103  ** 2. Human readable text that describes the child table and columns. e.g.
5104  **
5105  **       "child_table(child_key1, child_key2)"
5106  **
5107  ** 3. Human readable text that describes the parent table and columns. e.g.
5108  **
5109  **       "parent_table(parent_key1, parent_key2)"
5110  **
5111  ** 4. A full CREATE INDEX statement for an index that could be used to
5112  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5113  **
5114  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5115  **
5116  ** 5. The name of the parent table.
5117  **
5118  ** These six values are used by the C logic below to generate the report.
5119  */
5120  const char *zSql =
5121  "SELECT "
5122    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5123    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5124    "  || fkey_collate_clause("
5125    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5126    ", "
5127    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5128    "  || group_concat('*=?', ' AND ') || ')'"
5129    ", "
5130    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5131    ", "
5132    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5133    ", "
5134    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5135    "  || ' ON ' || quote(s.name) || '('"
5136    "  || group_concat(quote(f.[from]) ||"
5137    "        fkey_collate_clause("
5138    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5139    "  || ');'"
5140    ", "
5141    "     f.[table] "
5142    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5143    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5144    "GROUP BY s.name, f.id "
5145    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5146  ;
5147  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5148
5149  for(i=2; i<nArg; i++){
5150    int n = strlen30(azArg[i]);
5151    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5152      bVerbose = 1;
5153    }
5154    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5155      bGroupByParent = 1;
5156      zIndent = "    ";
5157    }
5158    else{
5159      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5160          azArg[0], azArg[1]
5161      );
5162      return SQLITE_ERROR;
5163    }
5164  }
5165
5166  /* Register the fkey_collate_clause() SQL function */
5167  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5168      0, shellFkeyCollateClause, 0, 0
5169  );
5170
5171
5172  if( rc==SQLITE_OK ){
5173    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5174  }
5175  if( rc==SQLITE_OK ){
5176    sqlite3_bind_int(pSql, 1, bGroupByParent);
5177  }
5178
5179  if( rc==SQLITE_OK ){
5180    int rc2;
5181    char *zPrev = 0;
5182    while( SQLITE_ROW==sqlite3_step(pSql) ){
5183      int res = -1;
5184      sqlite3_stmt *pExplain = 0;
5185      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5186      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5187      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5188      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5189      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5190      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5191
5192      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5193      if( rc!=SQLITE_OK ) break;
5194      if( SQLITE_ROW==sqlite3_step(pExplain) ){
5195        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5196        res = (
5197              0==sqlite3_strglob(zGlob, zPlan)
5198           || 0==sqlite3_strglob(zGlobIPK, zPlan)
5199        );
5200      }
5201      rc = sqlite3_finalize(pExplain);
5202      if( rc!=SQLITE_OK ) break;
5203
5204      if( res<0 ){
5205        raw_printf(stderr, "Error: internal error");
5206        break;
5207      }else{
5208        if( bGroupByParent
5209        && (bVerbose || res==0)
5210        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5211        ){
5212          raw_printf(out, "-- Parent table %s\n", zParent);
5213          sqlite3_free(zPrev);
5214          zPrev = sqlite3_mprintf("%s", zParent);
5215        }
5216
5217        if( res==0 ){
5218          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5219        }else if( bVerbose ){
5220          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5221              zIndent, zFrom, zTarget
5222          );
5223        }
5224      }
5225    }
5226    sqlite3_free(zPrev);
5227
5228    if( rc!=SQLITE_OK ){
5229      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5230    }
5231
5232    rc2 = sqlite3_finalize(pSql);
5233    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5234      rc = rc2;
5235      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5236    }
5237  }else{
5238    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5239  }
5240
5241  return rc;
5242}
5243
5244/*
5245** Implementation of ".lint" dot command.
5246*/
5247static int lintDotCommand(
5248  ShellState *pState,             /* Current shell tool state */
5249  char **azArg,                   /* Array of arguments passed to dot command */
5250  int nArg                        /* Number of entries in azArg[] */
5251){
5252  int n;
5253  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5254  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5255  return lintFkeyIndexes(pState, azArg, nArg);
5256
5257 usage:
5258  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5259  raw_printf(stderr, "Where sub-commands are:\n");
5260  raw_printf(stderr, "    fkey-indexes\n");
5261  return SQLITE_ERROR;
5262}
5263
5264#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5265/*********************************************************************************
5266** The ".archive" or ".ar" command.
5267*/
5268static void shellPrepare(
5269  sqlite3 *db,
5270  int *pRc,
5271  const char *zSql,
5272  sqlite3_stmt **ppStmt
5273){
5274  *ppStmt = 0;
5275  if( *pRc==SQLITE_OK ){
5276    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5277    if( rc!=SQLITE_OK ){
5278      raw_printf(stderr, "sql error: %s (%d)\n",
5279          sqlite3_errmsg(db), sqlite3_errcode(db)
5280      );
5281      *pRc = rc;
5282    }
5283  }
5284}
5285
5286static void shellPreparePrintf(
5287  sqlite3 *db,
5288  int *pRc,
5289  sqlite3_stmt **ppStmt,
5290  const char *zFmt,
5291  ...
5292){
5293  *ppStmt = 0;
5294  if( *pRc==SQLITE_OK ){
5295    va_list ap;
5296    char *z;
5297    va_start(ap, zFmt);
5298    z = sqlite3_vmprintf(zFmt, ap);
5299    va_end(ap);
5300    if( z==0 ){
5301      *pRc = SQLITE_NOMEM;
5302    }else{
5303      shellPrepare(db, pRc, z, ppStmt);
5304      sqlite3_free(z);
5305    }
5306  }
5307}
5308
5309static void shellFinalize(
5310  int *pRc,
5311  sqlite3_stmt *pStmt
5312){
5313  if( pStmt ){
5314    sqlite3 *db = sqlite3_db_handle(pStmt);
5315    int rc = sqlite3_finalize(pStmt);
5316    if( *pRc==SQLITE_OK ){
5317      if( rc!=SQLITE_OK ){
5318        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5319      }
5320      *pRc = rc;
5321    }
5322  }
5323}
5324
5325static void shellReset(
5326  int *pRc,
5327  sqlite3_stmt *pStmt
5328){
5329  int rc = sqlite3_reset(pStmt);
5330  if( *pRc==SQLITE_OK ){
5331    if( rc!=SQLITE_OK ){
5332      sqlite3 *db = sqlite3_db_handle(pStmt);
5333      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5334    }
5335    *pRc = rc;
5336  }
5337}
5338/*
5339** Structure representing a single ".ar" command.
5340*/
5341typedef struct ArCommand ArCommand;
5342struct ArCommand {
5343  u8 eCmd;                        /* An AR_CMD_* value */
5344  u8 bVerbose;                    /* True if --verbose */
5345  u8 bZip;                        /* True if the archive is a ZIP */
5346  u8 bDryRun;                     /* True if --dry-run */
5347  u8 bAppend;                     /* True if --append */
5348  u8 fromCmdLine;                 /* Run from -A instead of .archive */
5349  int nArg;                       /* Number of command arguments */
5350  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
5351  const char *zFile;              /* --file argument, or NULL */
5352  const char *zDir;               /* --directory argument, or NULL */
5353  char **azArg;                   /* Array of command arguments */
5354  ShellState *p;                  /* Shell state */
5355  sqlite3 *db;                    /* Database containing the archive */
5356};
5357
5358/*
5359** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5360*/
5361static int arUsage(FILE *f){
5362  showHelp(f,"archive");
5363  return SQLITE_ERROR;
5364}
5365
5366/*
5367** Print an error message for the .ar command to stderr and return
5368** SQLITE_ERROR.
5369*/
5370static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
5371  va_list ap;
5372  char *z;
5373  va_start(ap, zFmt);
5374  z = sqlite3_vmprintf(zFmt, ap);
5375  va_end(ap);
5376  utf8_printf(stderr, "Error: %s\n", z);
5377  if( pAr->fromCmdLine ){
5378    utf8_printf(stderr, "Use \"-A\" for more help\n");
5379  }else{
5380    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5381  }
5382  sqlite3_free(z);
5383  return SQLITE_ERROR;
5384}
5385
5386/*
5387** Values for ArCommand.eCmd.
5388*/
5389#define AR_CMD_CREATE       1
5390#define AR_CMD_EXTRACT      2
5391#define AR_CMD_LIST         3
5392#define AR_CMD_UPDATE       4
5393#define AR_CMD_HELP         5
5394
5395/*
5396** Other (non-command) switches.
5397*/
5398#define AR_SWITCH_VERBOSE     6
5399#define AR_SWITCH_FILE        7
5400#define AR_SWITCH_DIRECTORY   8
5401#define AR_SWITCH_APPEND      9
5402#define AR_SWITCH_DRYRUN     10
5403
5404static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5405  switch( eSwitch ){
5406    case AR_CMD_CREATE:
5407    case AR_CMD_EXTRACT:
5408    case AR_CMD_LIST:
5409    case AR_CMD_UPDATE:
5410    case AR_CMD_HELP:
5411      if( pAr->eCmd ){
5412        return arErrorMsg(pAr, "multiple command options");
5413      }
5414      pAr->eCmd = eSwitch;
5415      break;
5416
5417    case AR_SWITCH_DRYRUN:
5418      pAr->bDryRun = 1;
5419      break;
5420    case AR_SWITCH_VERBOSE:
5421      pAr->bVerbose = 1;
5422      break;
5423    case AR_SWITCH_APPEND:
5424      pAr->bAppend = 1;
5425      /* Fall thru into --file */
5426    case AR_SWITCH_FILE:
5427      pAr->zFile = zArg;
5428      break;
5429    case AR_SWITCH_DIRECTORY:
5430      pAr->zDir = zArg;
5431      break;
5432  }
5433
5434  return SQLITE_OK;
5435}
5436
5437/*
5438** Parse the command line for an ".ar" command. The results are written into
5439** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5440** successfully, otherwise an error message is written to stderr and
5441** SQLITE_ERROR returned.
5442*/
5443static int arParseCommand(
5444  char **azArg,                   /* Array of arguments passed to dot command */
5445  int nArg,                       /* Number of entries in azArg[] */
5446  ArCommand *pAr                  /* Populate this object */
5447){
5448  struct ArSwitch {
5449    const char *zLong;
5450    char cShort;
5451    u8 eSwitch;
5452    u8 bArg;
5453  } aSwitch[] = {
5454    { "create",    'c', AR_CMD_CREATE,       0 },
5455    { "extract",   'x', AR_CMD_EXTRACT,      0 },
5456    { "list",      't', AR_CMD_LIST,         0 },
5457    { "update",    'u', AR_CMD_UPDATE,       0 },
5458    { "help",      'h', AR_CMD_HELP,         0 },
5459    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
5460    { "file",      'f', AR_SWITCH_FILE,      1 },
5461    { "append",    'a', AR_SWITCH_APPEND,    1 },
5462    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
5463    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
5464  };
5465  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5466  struct ArSwitch *pEnd = &aSwitch[nSwitch];
5467
5468  if( nArg<=1 ){
5469    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
5470    return arUsage(stderr);
5471  }else{
5472    char *z = azArg[1];
5473    if( z[0]!='-' ){
5474      /* Traditional style [tar] invocation */
5475      int i;
5476      int iArg = 2;
5477      for(i=0; z[i]; i++){
5478        const char *zArg = 0;
5479        struct ArSwitch *pOpt;
5480        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5481          if( z[i]==pOpt->cShort ) break;
5482        }
5483        if( pOpt==pEnd ){
5484          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5485        }
5486        if( pOpt->bArg ){
5487          if( iArg>=nArg ){
5488            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5489          }
5490          zArg = azArg[iArg++];
5491        }
5492        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5493      }
5494      pAr->nArg = nArg-iArg;
5495      if( pAr->nArg>0 ){
5496        pAr->azArg = &azArg[iArg];
5497      }
5498    }else{
5499      /* Non-traditional invocation */
5500      int iArg;
5501      for(iArg=1; iArg<nArg; iArg++){
5502        int n;
5503        z = azArg[iArg];
5504        if( z[0]!='-' ){
5505          /* All remaining command line words are command arguments. */
5506          pAr->azArg = &azArg[iArg];
5507          pAr->nArg = nArg-iArg;
5508          break;
5509        }
5510        n = strlen30(z);
5511
5512        if( z[1]!='-' ){
5513          int i;
5514          /* One or more short options */
5515          for(i=1; i<n; i++){
5516            const char *zArg = 0;
5517            struct ArSwitch *pOpt;
5518            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5519              if( z[i]==pOpt->cShort ) break;
5520            }
5521            if( pOpt==pEnd ){
5522              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5523            }
5524            if( pOpt->bArg ){
5525              if( i<(n-1) ){
5526                zArg = &z[i+1];
5527                i = n;
5528              }else{
5529                if( iArg>=(nArg-1) ){
5530                  return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5531                }
5532                zArg = azArg[++iArg];
5533              }
5534            }
5535            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5536          }
5537        }else if( z[2]=='\0' ){
5538          /* A -- option, indicating that all remaining command line words
5539          ** are command arguments.  */
5540          pAr->azArg = &azArg[iArg+1];
5541          pAr->nArg = nArg-iArg-1;
5542          break;
5543        }else{
5544          /* A long option */
5545          const char *zArg = 0;             /* Argument for option, if any */
5546          struct ArSwitch *pMatch = 0;      /* Matching option */
5547          struct ArSwitch *pOpt;            /* Iterator */
5548          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5549            const char *zLong = pOpt->zLong;
5550            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
5551              if( pMatch ){
5552                return arErrorMsg(pAr, "ambiguous option: %s",z);
5553              }else{
5554                pMatch = pOpt;
5555              }
5556            }
5557          }
5558
5559          if( pMatch==0 ){
5560            return arErrorMsg(pAr, "unrecognized option: %s", z);
5561          }
5562          if( pMatch->bArg ){
5563            if( iArg>=(nArg-1) ){
5564              return arErrorMsg(pAr, "option requires an argument: %s", z);
5565            }
5566            zArg = azArg[++iArg];
5567          }
5568          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5569        }
5570      }
5571    }
5572  }
5573
5574  return SQLITE_OK;
5575}
5576
5577/*
5578** This function assumes that all arguments within the ArCommand.azArg[]
5579** array refer to archive members, as for the --extract or --list commands.
5580** It checks that each of them are present. If any specified file is not
5581** present in the archive, an error is printed to stderr and an error
5582** code returned. Otherwise, if all specified arguments are present in
5583** the archive, SQLITE_OK is returned.
5584**
5585** This function strips any trailing '/' characters from each argument.
5586** This is consistent with the way the [tar] command seems to work on
5587** Linux.
5588*/
5589static int arCheckEntries(ArCommand *pAr){
5590  int rc = SQLITE_OK;
5591  if( pAr->nArg ){
5592    int i, j;
5593    sqlite3_stmt *pTest = 0;
5594
5595    shellPreparePrintf(pAr->db, &rc, &pTest,
5596        "SELECT name FROM %s WHERE name=$name",
5597        pAr->zSrcTable
5598    );
5599    j = sqlite3_bind_parameter_index(pTest, "$name");
5600    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5601      char *z = pAr->azArg[i];
5602      int n = strlen30(z);
5603      int bOk = 0;
5604      while( n>0 && z[n-1]=='/' ) n--;
5605      z[n] = '\0';
5606      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
5607      if( SQLITE_ROW==sqlite3_step(pTest) ){
5608        bOk = 1;
5609      }
5610      shellReset(&rc, pTest);
5611      if( rc==SQLITE_OK && bOk==0 ){
5612        utf8_printf(stderr, "not found in archive: %s\n", z);
5613        rc = SQLITE_ERROR;
5614      }
5615    }
5616    shellFinalize(&rc, pTest);
5617  }
5618  return rc;
5619}
5620
5621/*
5622** Format a WHERE clause that can be used against the "sqlar" table to
5623** identify all archive members that match the command arguments held
5624** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5625** The caller is responsible for eventually calling sqlite3_free() on
5626** any non-NULL (*pzWhere) value.
5627*/
5628static void arWhereClause(
5629  int *pRc,
5630  ArCommand *pAr,
5631  char **pzWhere                  /* OUT: New WHERE clause */
5632){
5633  char *zWhere = 0;
5634  if( *pRc==SQLITE_OK ){
5635    if( pAr->nArg==0 ){
5636      zWhere = sqlite3_mprintf("1");
5637    }else{
5638      int i;
5639      const char *zSep = "";
5640      for(i=0; i<pAr->nArg; i++){
5641        const char *z = pAr->azArg[i];
5642        zWhere = sqlite3_mprintf(
5643          "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5644          zWhere, zSep, z, strlen30(z)+1, z
5645        );
5646        if( zWhere==0 ){
5647          *pRc = SQLITE_NOMEM;
5648          break;
5649        }
5650        zSep = " OR ";
5651      }
5652    }
5653  }
5654  *pzWhere = zWhere;
5655}
5656
5657/*
5658** Implementation of .ar "lisT" command.
5659*/
5660static int arListCommand(ArCommand *pAr){
5661  const char *zSql = "SELECT %s FROM %s WHERE %s";
5662  const char *azCols[] = {
5663    "name",
5664    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5665  };
5666
5667  char *zWhere = 0;
5668  sqlite3_stmt *pSql = 0;
5669  int rc;
5670
5671  rc = arCheckEntries(pAr);
5672  arWhereClause(&rc, pAr, &zWhere);
5673
5674  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5675                     pAr->zSrcTable, zWhere);
5676  if( pAr->bDryRun ){
5677    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5678  }else{
5679    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5680      if( pAr->bVerbose ){
5681        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
5682            sqlite3_column_text(pSql, 0),
5683            sqlite3_column_int(pSql, 1),
5684            sqlite3_column_text(pSql, 2),
5685            sqlite3_column_text(pSql, 3)
5686        );
5687      }else{
5688        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5689      }
5690    }
5691  }
5692  shellFinalize(&rc, pSql);
5693  sqlite3_free(zWhere);
5694  return rc;
5695}
5696
5697
5698/*
5699** Implementation of .ar "eXtract" command.
5700*/
5701static int arExtractCommand(ArCommand *pAr){
5702  const char *zSql1 =
5703    "SELECT "
5704    " ($dir || name),"
5705    " writefile(($dir || name), %s, mode, mtime) "
5706    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5707    " AND name NOT GLOB '*..[/\\]*'";
5708
5709  const char *azExtraArg[] = {
5710    "sqlar_uncompress(data, sz)",
5711    "data"
5712  };
5713
5714  sqlite3_stmt *pSql = 0;
5715  int rc = SQLITE_OK;
5716  char *zDir = 0;
5717  char *zWhere = 0;
5718  int i, j;
5719
5720  /* If arguments are specified, check that they actually exist within
5721  ** the archive before proceeding. And formulate a WHERE clause to
5722  ** match them.  */
5723  rc = arCheckEntries(pAr);
5724  arWhereClause(&rc, pAr, &zWhere);
5725
5726  if( rc==SQLITE_OK ){
5727    if( pAr->zDir ){
5728      zDir = sqlite3_mprintf("%s/", pAr->zDir);
5729    }else{
5730      zDir = sqlite3_mprintf("");
5731    }
5732    if( zDir==0 ) rc = SQLITE_NOMEM;
5733  }
5734
5735  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5736      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
5737  );
5738
5739  if( rc==SQLITE_OK ){
5740    j = sqlite3_bind_parameter_index(pSql, "$dir");
5741    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
5742
5743    /* Run the SELECT statement twice. The first time, writefile() is called
5744    ** for all archive members that should be extracted. The second time,
5745    ** only for the directories. This is because the timestamps for
5746    ** extracted directories must be reset after they are populated (as
5747    ** populating them changes the timestamp).  */
5748    for(i=0; i<2; i++){
5749      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5750      sqlite3_bind_int(pSql, j, i);
5751      if( pAr->bDryRun ){
5752        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5753      }else{
5754        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5755          if( i==0 && pAr->bVerbose ){
5756            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5757          }
5758        }
5759      }
5760      shellReset(&rc, pSql);
5761    }
5762    shellFinalize(&rc, pSql);
5763  }
5764
5765  sqlite3_free(zDir);
5766  sqlite3_free(zWhere);
5767  return rc;
5768}
5769
5770/*
5771** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
5772*/
5773static int arExecSql(ArCommand *pAr, const char *zSql){
5774  int rc;
5775  if( pAr->bDryRun ){
5776    utf8_printf(pAr->p->out, "%s\n", zSql);
5777    rc = SQLITE_OK;
5778  }else{
5779    char *zErr = 0;
5780    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5781    if( zErr ){
5782      utf8_printf(stdout, "ERROR: %s\n", zErr);
5783      sqlite3_free(zErr);
5784    }
5785  }
5786  return rc;
5787}
5788
5789
5790/*
5791** Implementation of .ar "create" and "update" commands.
5792**
5793** Create the "sqlar" table in the database if it does not already exist.
5794** Then add each file in the azFile[] array to the archive. Directories
5795** are added recursively. If argument bVerbose is non-zero, a message is
5796** printed on stdout for each file archived.
5797**
5798** The create command is the same as update, except that it drops
5799** any existing "sqlar" table before beginning.
5800*/
5801static int arCreateOrUpdateCommand(
5802  ArCommand *pAr,                 /* Command arguments and options */
5803  int bUpdate                     /* true for a --create.  false for --update */
5804){
5805  const char *zCreate =
5806      "CREATE TABLE IF NOT EXISTS sqlar(\n"
5807      "  name TEXT PRIMARY KEY,  -- name of the file\n"
5808      "  mode INT,               -- access permissions\n"
5809      "  mtime INT,              -- last modification time\n"
5810      "  sz INT,                 -- original file size\n"
5811      "  data BLOB               -- compressed content\n"
5812      ")";
5813  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
5814  const char *zInsertFmt[2] = {
5815     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5816     "  SELECT\n"
5817     "    %s,\n"
5818     "    mode,\n"
5819     "    mtime,\n"
5820     "    CASE substr(lsmode(mode),1,1)\n"
5821     "      WHEN '-' THEN length(data)\n"
5822     "      WHEN 'd' THEN 0\n"
5823     "      ELSE -1 END,\n"
5824     "    sqlar_compress(data)\n"
5825     "  FROM fsdir(%Q,%Q)\n"
5826     "  WHERE lsmode(mode) NOT LIKE '?%%';",
5827     "REPLACE INTO %s(name,mode,mtime,data)\n"
5828     "  SELECT\n"
5829     "    %s,\n"
5830     "    mode,\n"
5831     "    mtime,\n"
5832     "    data\n"
5833     "  FROM fsdir(%Q,%Q)\n"
5834     "  WHERE lsmode(mode) NOT LIKE '?%%';"
5835  };
5836  int i;                          /* For iterating through azFile[] */
5837  int rc;                         /* Return code */
5838  const char *zTab = 0;           /* SQL table into which to insert */
5839  char *zSql;
5840  char zTemp[50];
5841
5842  arExecSql(pAr, "PRAGMA page_size=512");
5843  rc = arExecSql(pAr, "SAVEPOINT ar;");
5844  if( rc!=SQLITE_OK ) return rc;
5845  zTemp[0] = 0;
5846  if( pAr->bZip ){
5847    /* Initialize the zipfile virtual table, if necessary */
5848    if( pAr->zFile ){
5849      sqlite3_uint64 r;
5850      sqlite3_randomness(sizeof(r),&r);
5851      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5852      zTab = zTemp;
5853      zSql = sqlite3_mprintf(
5854         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5855         zTab, pAr->zFile
5856      );
5857      rc = arExecSql(pAr, zSql);
5858      sqlite3_free(zSql);
5859    }else{
5860      zTab = "zip";
5861    }
5862  }else{
5863    /* Initialize the table for an SQLAR */
5864    zTab = "sqlar";
5865    if( bUpdate==0 ){
5866      rc = arExecSql(pAr, zDrop);
5867      if( rc!=SQLITE_OK ) goto end_ar_transaction;
5868    }
5869    rc = arExecSql(pAr, zCreate);
5870  }
5871  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5872    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
5873        pAr->bVerbose ? "shell_putsnl(name)" : "name",
5874        pAr->azArg[i], pAr->zDir);
5875    rc = arExecSql(pAr, zSql2);
5876    sqlite3_free(zSql2);
5877  }
5878end_ar_transaction:
5879  if( rc!=SQLITE_OK ){
5880    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
5881  }else{
5882    rc = arExecSql(pAr, "RELEASE ar;");
5883    if( pAr->bZip && pAr->zFile ){
5884      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5885      arExecSql(pAr, zSql);
5886      sqlite3_free(zSql);
5887    }
5888  }
5889  return rc;
5890}
5891
5892/*
5893** Implementation of ".ar" dot command.
5894*/
5895static int arDotCommand(
5896  ShellState *pState,             /* Current shell tool state */
5897  int fromCmdLine,                /* True if -A command-line option, not .ar cmd */
5898  char **azArg,                   /* Array of arguments passed to dot command */
5899  int nArg                        /* Number of entries in azArg[] */
5900){
5901  ArCommand cmd;
5902  int rc;
5903  memset(&cmd, 0, sizeof(cmd));
5904  cmd.fromCmdLine = fromCmdLine;
5905  rc = arParseCommand(azArg, nArg, &cmd);
5906  if( rc==SQLITE_OK ){
5907    int eDbType = SHELL_OPEN_UNSPEC;
5908    cmd.p = pState;
5909    cmd.db = pState->db;
5910    if( cmd.zFile ){
5911      eDbType = deduceDatabaseType(cmd.zFile, 1);
5912    }else{
5913      eDbType = pState->openMode;
5914    }
5915    if( eDbType==SHELL_OPEN_ZIPFILE ){
5916      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5917        if( cmd.zFile==0 ){
5918          cmd.zSrcTable = sqlite3_mprintf("zip");
5919        }else{
5920          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5921        }
5922      }
5923      cmd.bZip = 1;
5924    }else if( cmd.zFile ){
5925      int flags;
5926      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
5927      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5928        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5929      }else{
5930        flags = SQLITE_OPEN_READONLY;
5931      }
5932      cmd.db = 0;
5933      if( cmd.bDryRun ){
5934        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5935             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5936      }
5937      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5938             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
5939      if( rc!=SQLITE_OK ){
5940        utf8_printf(stderr, "cannot open file: %s (%s)\n",
5941            cmd.zFile, sqlite3_errmsg(cmd.db)
5942        );
5943        goto end_ar_command;
5944      }
5945      sqlite3_fileio_init(cmd.db, 0, 0);
5946      sqlite3_sqlar_init(cmd.db, 0, 0);
5947      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5948                              shellPutsFunc, 0, 0);
5949
5950    }
5951    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
5952      if( cmd.eCmd!=AR_CMD_CREATE
5953       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5954      ){
5955        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5956        rc = SQLITE_ERROR;
5957        goto end_ar_command;
5958      }
5959      cmd.zSrcTable = sqlite3_mprintf("sqlar");
5960    }
5961
5962    switch( cmd.eCmd ){
5963      case AR_CMD_CREATE:
5964        rc = arCreateOrUpdateCommand(&cmd, 0);
5965        break;
5966
5967      case AR_CMD_EXTRACT:
5968        rc = arExtractCommand(&cmd);
5969        break;
5970
5971      case AR_CMD_LIST:
5972        rc = arListCommand(&cmd);
5973        break;
5974
5975      case AR_CMD_HELP:
5976        arUsage(pState->out);
5977        break;
5978
5979      default:
5980        assert( cmd.eCmd==AR_CMD_UPDATE );
5981        rc = arCreateOrUpdateCommand(&cmd, 1);
5982        break;
5983    }
5984  }
5985end_ar_command:
5986  if( cmd.db!=pState->db ){
5987    close_db(cmd.db);
5988  }
5989  sqlite3_free(cmd.zSrcTable);
5990
5991  return rc;
5992}
5993/* End of the ".archive" or ".ar" command logic
5994**********************************************************************************/
5995#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5996
5997
5998/*
5999** If an input line begins with "." then invoke this routine to
6000** process that line.
6001**
6002** Return 1 on error, 2 to exit, and 0 otherwise.
6003*/
6004static int do_meta_command(char *zLine, ShellState *p){
6005  int h = 1;
6006  int nArg = 0;
6007  int n, c;
6008  int rc = 0;
6009  char *azArg[50];
6010
6011#ifndef SQLITE_OMIT_VIRTUALTABLE
6012  if( p->expert.pExpert ){
6013    expertFinish(p, 1, 0);
6014  }
6015#endif
6016
6017  /* Parse the input line into tokens.
6018  */
6019  while( zLine[h] && nArg<ArraySize(azArg) ){
6020    while( IsSpace(zLine[h]) ){ h++; }
6021    if( zLine[h]==0 ) break;
6022    if( zLine[h]=='\'' || zLine[h]=='"' ){
6023      int delim = zLine[h++];
6024      azArg[nArg++] = &zLine[h];
6025      while( zLine[h] && zLine[h]!=delim ){
6026        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6027        h++;
6028      }
6029      if( zLine[h]==delim ){
6030        zLine[h++] = 0;
6031      }
6032      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6033    }else{
6034      azArg[nArg++] = &zLine[h];
6035      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6036      if( zLine[h] ) zLine[h++] = 0;
6037      resolve_backslashes(azArg[nArg-1]);
6038    }
6039  }
6040
6041  /* Process the input line.
6042  */
6043  if( nArg==0 ) return 0; /* no tokens, no error */
6044  n = strlen30(azArg[0]);
6045  c = azArg[0][0];
6046  clearTempFile(p);
6047
6048#ifndef SQLITE_OMIT_AUTHORIZATION
6049  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6050    if( nArg!=2 ){
6051      raw_printf(stderr, "Usage: .auth ON|OFF\n");
6052      rc = 1;
6053      goto meta_command_exit;
6054    }
6055    open_db(p, 0);
6056    if( booleanValue(azArg[1]) ){
6057      sqlite3_set_authorizer(p->db, shellAuth, p);
6058    }else{
6059      sqlite3_set_authorizer(p->db, 0, 0);
6060    }
6061  }else
6062#endif
6063
6064#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6065  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
6066    open_db(p, 0);
6067    rc = arDotCommand(p, 0, azArg, nArg);
6068  }else
6069#endif
6070
6071  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6072   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6073  ){
6074    const char *zDestFile = 0;
6075    const char *zDb = 0;
6076    sqlite3 *pDest;
6077    sqlite3_backup *pBackup;
6078    int j;
6079    int bAsync = 0;
6080    const char *zVfs = 0;
6081    for(j=1; j<nArg; j++){
6082      const char *z = azArg[j];
6083      if( z[0]=='-' ){
6084        if( z[1]=='-' ) z++;
6085        if( strcmp(z, "-append")==0 ){
6086          zVfs = "apndvfs";
6087        }else
6088        if( strcmp(z, "-async")==0 ){
6089          bAsync = 1;
6090        }else
6091        {
6092          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6093          return 1;
6094        }
6095      }else if( zDestFile==0 ){
6096        zDestFile = azArg[j];
6097      }else if( zDb==0 ){
6098        zDb = zDestFile;
6099        zDestFile = azArg[j];
6100      }else{
6101        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
6102        return 1;
6103      }
6104    }
6105    if( zDestFile==0 ){
6106      raw_printf(stderr, "missing FILENAME argument on .backup\n");
6107      return 1;
6108    }
6109    if( zDb==0 ) zDb = "main";
6110    rc = sqlite3_open_v2(zDestFile, &pDest,
6111                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
6112    if( rc!=SQLITE_OK ){
6113      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
6114      close_db(pDest);
6115      return 1;
6116    }
6117    if( bAsync ){
6118      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6119                   0, 0, 0);
6120    }
6121    open_db(p, 0);
6122    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6123    if( pBackup==0 ){
6124      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6125      close_db(pDest);
6126      return 1;
6127    }
6128    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6129    sqlite3_backup_finish(pBackup);
6130    if( rc==SQLITE_DONE ){
6131      rc = 0;
6132    }else{
6133      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6134      rc = 1;
6135    }
6136    close_db(pDest);
6137  }else
6138
6139  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6140    if( nArg==2 ){
6141      bail_on_error = booleanValue(azArg[1]);
6142    }else{
6143      raw_printf(stderr, "Usage: .bail on|off\n");
6144      rc = 1;
6145    }
6146  }else
6147
6148  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6149    if( nArg==2 ){
6150      if( booleanValue(azArg[1]) ){
6151        setBinaryMode(p->out, 1);
6152      }else{
6153        setTextMode(p->out, 1);
6154      }
6155    }else{
6156      raw_printf(stderr, "Usage: .binary on|off\n");
6157      rc = 1;
6158    }
6159  }else
6160
6161  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6162    if( nArg==2 ){
6163#if defined(_WIN32) || defined(WIN32)
6164      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6165      rc = !SetCurrentDirectoryW(z);
6166      sqlite3_free(z);
6167#else
6168      rc = chdir(azArg[1]);
6169#endif
6170      if( rc ){
6171        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6172        rc = 1;
6173      }
6174    }else{
6175      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6176      rc = 1;
6177    }
6178  }else
6179
6180  /* The undocumented ".breakpoint" command causes a call to the no-op
6181  ** routine named test_breakpoint().
6182  */
6183  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6184    test_breakpoint();
6185  }else
6186
6187  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6188    if( nArg==2 ){
6189      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6190    }else{
6191      raw_printf(stderr, "Usage: .changes on|off\n");
6192      rc = 1;
6193    }
6194  }else
6195
6196  /* Cancel output redirection, if it is currently set (by .testcase)
6197  ** Then read the content of the testcase-out.txt file and compare against
6198  ** azArg[1].  If there are differences, report an error and exit.
6199  */
6200  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6201    char *zRes = 0;
6202    output_reset(p);
6203    if( nArg!=2 ){
6204      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6205      rc = 2;
6206    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6207      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6208      rc = 2;
6209    }else if( testcase_glob(azArg[1],zRes)==0 ){
6210      utf8_printf(stderr,
6211                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
6212                 p->zTestcase, azArg[1], zRes);
6213      rc = 1;
6214    }else{
6215      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6216      p->nCheck++;
6217    }
6218    sqlite3_free(zRes);
6219  }else
6220
6221  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6222    if( nArg==2 ){
6223      tryToClone(p, azArg[1]);
6224    }else{
6225      raw_printf(stderr, "Usage: .clone FILENAME\n");
6226      rc = 1;
6227    }
6228  }else
6229
6230  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6231    ShellState data;
6232    char *zErrMsg = 0;
6233    open_db(p, 0);
6234    memcpy(&data, p, sizeof(data));
6235    data.showHeader = 0;
6236    data.cMode = data.mode = MODE_List;
6237    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
6238    data.cnt = 0;
6239    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
6240                 callback, &data, &zErrMsg);
6241    if( zErrMsg ){
6242      utf8_printf(stderr,"Error: %s\n", zErrMsg);
6243      sqlite3_free(zErrMsg);
6244      rc = 1;
6245    }
6246  }else
6247
6248  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
6249    static const struct DbConfigChoices {
6250      const char *zName;
6251      int op;
6252    } aDbConfig[] = {
6253        { "enable_fkey",      SQLITE_DBCONFIG_ENABLE_FKEY            },
6254        { "enable_trigger",   SQLITE_DBCONFIG_ENABLE_TRIGGER         },
6255        { "fts3_tokenizer",   SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER  },
6256        { "load_extension",   SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION  },
6257        { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE       },
6258        { "enable_qpsg",      SQLITE_DBCONFIG_ENABLE_QPSG            },
6259        { "trigger_eqp",      SQLITE_DBCONFIG_TRIGGER_EQP            },
6260        { "reset_database",   SQLITE_DBCONFIG_RESET_DATABASE         },
6261        { "defensive",        SQLITE_DBCONFIG_DEFENSIVE              },
6262    };
6263    int ii, v;
6264    open_db(p, 0);
6265    for(ii=0; ii<ArraySize(aDbConfig); ii++){
6266      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
6267      if( nArg>=3 ){
6268        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
6269      }
6270      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
6271      utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
6272      if( nArg>1 ) break;
6273    }
6274    if( nArg>1 && ii==ArraySize(aDbConfig) ){
6275      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
6276      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
6277    }
6278  }else
6279
6280  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
6281    rc = shell_dbinfo_command(p, nArg, azArg);
6282  }else
6283
6284  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
6285    const char *zLike = 0;
6286    int i;
6287    int savedShowHeader = p->showHeader;
6288    int savedShellFlags = p->shellFlgs;
6289    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
6290    for(i=1; i<nArg; i++){
6291      if( azArg[i][0]=='-' ){
6292        const char *z = azArg[i]+1;
6293        if( z[0]=='-' ) z++;
6294        if( strcmp(z,"preserve-rowids")==0 ){
6295#ifdef SQLITE_OMIT_VIRTUALTABLE
6296          raw_printf(stderr, "The --preserve-rowids option is not compatible"
6297                             " with SQLITE_OMIT_VIRTUALTABLE\n");
6298          rc = 1;
6299          goto meta_command_exit;
6300#else
6301          ShellSetFlag(p, SHFLG_PreserveRowid);
6302#endif
6303        }else
6304        if( strcmp(z,"newlines")==0 ){
6305          ShellSetFlag(p, SHFLG_Newlines);
6306        }else
6307        {
6308          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
6309          rc = 1;
6310          goto meta_command_exit;
6311        }
6312      }else if( zLike ){
6313        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
6314                           "?--newlines? ?LIKE-PATTERN?\n");
6315        rc = 1;
6316        goto meta_command_exit;
6317      }else{
6318        zLike = azArg[i];
6319      }
6320    }
6321    open_db(p, 0);
6322    /* When playing back a "dump", the content might appear in an order
6323    ** which causes immediate foreign key constraints to be violated.
6324    ** So disable foreign-key constraint enforcement to prevent problems. */
6325    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
6326    raw_printf(p->out, "BEGIN TRANSACTION;\n");
6327    p->writableSchema = 0;
6328    p->showHeader = 0;
6329    /* Set writable_schema=ON since doing so forces SQLite to initialize
6330    ** as much of the schema as it can even if the sqlite_master table is
6331    ** corrupt. */
6332    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6333    p->nErr = 0;
6334    if( zLike==0 ){
6335      run_schema_dump_query(p,
6336        "SELECT name, type, sql FROM sqlite_master "
6337        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6338      );
6339      run_schema_dump_query(p,
6340        "SELECT name, type, sql FROM sqlite_master "
6341        "WHERE name=='sqlite_sequence'"
6342      );
6343      run_table_dump_query(p,
6344        "SELECT sql FROM sqlite_master "
6345        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6346      );
6347    }else{
6348      char *zSql;
6349      zSql = sqlite3_mprintf(
6350        "SELECT name, type, sql FROM sqlite_master "
6351        "WHERE tbl_name LIKE %Q AND type=='table'"
6352        "  AND sql NOT NULL", zLike);
6353      run_schema_dump_query(p,zSql);
6354      sqlite3_free(zSql);
6355      zSql = sqlite3_mprintf(
6356        "SELECT sql FROM sqlite_master "
6357        "WHERE sql NOT NULL"
6358        "  AND type IN ('index','trigger','view')"
6359        "  AND tbl_name LIKE %Q", zLike);
6360      run_table_dump_query(p, zSql, 0);
6361      sqlite3_free(zSql);
6362    }
6363    if( p->writableSchema ){
6364      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6365      p->writableSchema = 0;
6366    }
6367    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6368    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
6369    raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6370    p->showHeader = savedShowHeader;
6371    p->shellFlgs = savedShellFlags;
6372  }else
6373
6374  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6375    if( nArg==2 ){
6376      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6377    }else{
6378      raw_printf(stderr, "Usage: .echo on|off\n");
6379      rc = 1;
6380    }
6381  }else
6382
6383  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6384    if( nArg==2 ){
6385      p->autoEQPtest = 0;
6386      if( p->autoEQPtrace ){
6387        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
6388        p->autoEQPtrace = 0;
6389      }
6390      if( strcmp(azArg[1],"full")==0 ){
6391        p->autoEQP = AUTOEQP_full;
6392      }else if( strcmp(azArg[1],"trigger")==0 ){
6393        p->autoEQP = AUTOEQP_trigger;
6394#ifdef SQLITE_DEBUG
6395      }else if( strcmp(azArg[1],"test")==0 ){
6396        p->autoEQP = AUTOEQP_on;
6397        p->autoEQPtest = 1;
6398      }else if( strcmp(azArg[1],"trace")==0 ){
6399        p->autoEQP = AUTOEQP_full;
6400        p->autoEQPtrace = 1;
6401        open_db(p, 0);
6402        sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
6403        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
6404#endif
6405      }else{
6406        p->autoEQP = (u8)booleanValue(azArg[1]);
6407      }
6408    }else{
6409      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
6410      rc = 1;
6411    }
6412  }else
6413
6414  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6415    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6416    rc = 2;
6417  }else
6418
6419  /* The ".explain" command is automatic now.  It is largely pointless.  It
6420  ** retained purely for backwards compatibility */
6421  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6422    int val = 1;
6423    if( nArg>=2 ){
6424      if( strcmp(azArg[1],"auto")==0 ){
6425        val = 99;
6426      }else{
6427        val =  booleanValue(azArg[1]);
6428      }
6429    }
6430    if( val==1 && p->mode!=MODE_Explain ){
6431      p->normalMode = p->mode;
6432      p->mode = MODE_Explain;
6433      p->autoExplain = 0;
6434    }else if( val==0 ){
6435      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6436      p->autoExplain = 0;
6437    }else if( val==99 ){
6438      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6439      p->autoExplain = 1;
6440    }
6441  }else
6442
6443#ifndef SQLITE_OMIT_VIRTUALTABLE
6444  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6445    open_db(p, 0);
6446    expertDotCommand(p, azArg, nArg);
6447  }else
6448#endif
6449
6450  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6451    ShellState data;
6452    char *zErrMsg = 0;
6453    int doStats = 0;
6454    memcpy(&data, p, sizeof(data));
6455    data.showHeader = 0;
6456    data.cMode = data.mode = MODE_Semi;
6457    if( nArg==2 && optionMatch(azArg[1], "indent") ){
6458      data.cMode = data.mode = MODE_Pretty;
6459      nArg = 1;
6460    }
6461    if( nArg!=1 ){
6462      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6463      rc = 1;
6464      goto meta_command_exit;
6465    }
6466    open_db(p, 0);
6467    rc = sqlite3_exec(p->db,
6468       "SELECT sql FROM"
6469       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6470       "     FROM sqlite_master UNION ALL"
6471       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6472       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6473       "ORDER BY rowid",
6474       callback, &data, &zErrMsg
6475    );
6476    if( rc==SQLITE_OK ){
6477      sqlite3_stmt *pStmt;
6478      rc = sqlite3_prepare_v2(p->db,
6479               "SELECT rowid FROM sqlite_master"
6480               " WHERE name GLOB 'sqlite_stat[134]'",
6481               -1, &pStmt, 0);
6482      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6483      sqlite3_finalize(pStmt);
6484    }
6485    if( doStats==0 ){
6486      raw_printf(p->out, "/* No STAT tables available */\n");
6487    }else{
6488      raw_printf(p->out, "ANALYZE sqlite_master;\n");
6489      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6490                   callback, &data, &zErrMsg);
6491      data.cMode = data.mode = MODE_Insert;
6492      data.zDestTable = "sqlite_stat1";
6493      shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
6494      data.zDestTable = "sqlite_stat3";
6495      shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
6496      data.zDestTable = "sqlite_stat4";
6497      shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
6498      raw_printf(p->out, "ANALYZE sqlite_master;\n");
6499    }
6500  }else
6501
6502  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6503    if( nArg==2 ){
6504      p->showHeader = booleanValue(azArg[1]);
6505    }else{
6506      raw_printf(stderr, "Usage: .headers on|off\n");
6507      rc = 1;
6508    }
6509  }else
6510
6511  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
6512    if( nArg>=2 ){
6513      n = showHelp(p->out, azArg[1]);
6514      if( n==0 ){
6515        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
6516      }
6517    }else{
6518      showHelp(p->out, 0);
6519    }
6520  }else
6521
6522  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6523    char *zTable;               /* Insert data into this table */
6524    char *zFile;                /* Name of file to extra content from */
6525    sqlite3_stmt *pStmt = NULL; /* A statement */
6526    int nCol;                   /* Number of columns in the table */
6527    int nByte;                  /* Number of bytes in an SQL string */
6528    int i, j;                   /* Loop counters */
6529    int needCommit;             /* True to COMMIT or ROLLBACK at end */
6530    int nSep;                   /* Number of bytes in p->colSeparator[] */
6531    char *zSql;                 /* An SQL statement */
6532    ImportCtx sCtx;             /* Reader context */
6533    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6534    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
6535
6536    if( nArg!=3 ){
6537      raw_printf(stderr, "Usage: .import FILE TABLE\n");
6538      goto meta_command_exit;
6539    }
6540    zFile = azArg[1];
6541    zTable = azArg[2];
6542    seenInterrupt = 0;
6543    memset(&sCtx, 0, sizeof(sCtx));
6544    open_db(p, 0);
6545    nSep = strlen30(p->colSeparator);
6546    if( nSep==0 ){
6547      raw_printf(stderr,
6548                 "Error: non-null column separator required for import\n");
6549      return 1;
6550    }
6551    if( nSep>1 ){
6552      raw_printf(stderr, "Error: multi-character column separators not allowed"
6553                      " for import\n");
6554      return 1;
6555    }
6556    nSep = strlen30(p->rowSeparator);
6557    if( nSep==0 ){
6558      raw_printf(stderr, "Error: non-null row separator required for import\n");
6559      return 1;
6560    }
6561    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6562      /* When importing CSV (only), if the row separator is set to the
6563      ** default output row separator, change it to the default input
6564      ** row separator.  This avoids having to maintain different input
6565      ** and output row separators. */
6566      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6567      nSep = strlen30(p->rowSeparator);
6568    }
6569    if( nSep>1 ){
6570      raw_printf(stderr, "Error: multi-character row separators not allowed"
6571                      " for import\n");
6572      return 1;
6573    }
6574    sCtx.zFile = zFile;
6575    sCtx.nLine = 1;
6576    if( sCtx.zFile[0]=='|' ){
6577#ifdef SQLITE_OMIT_POPEN
6578      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6579      return 1;
6580#else
6581      sCtx.in = popen(sCtx.zFile+1, "r");
6582      sCtx.zFile = "<pipe>";
6583      xCloser = pclose;
6584#endif
6585    }else{
6586      sCtx.in = fopen(sCtx.zFile, "rb");
6587      xCloser = fclose;
6588    }
6589    if( p->mode==MODE_Ascii ){
6590      xRead = ascii_read_one_field;
6591    }else{
6592      xRead = csv_read_one_field;
6593    }
6594    if( sCtx.in==0 ){
6595      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6596      return 1;
6597    }
6598    sCtx.cColSep = p->colSeparator[0];
6599    sCtx.cRowSep = p->rowSeparator[0];
6600    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6601    if( zSql==0 ){
6602      xCloser(sCtx.in);
6603      shell_out_of_memory();
6604    }
6605    nByte = strlen30(zSql);
6606    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6607    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
6608    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6609      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6610      char cSep = '(';
6611      while( xRead(&sCtx) ){
6612        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
6613        cSep = ',';
6614        if( sCtx.cTerm!=sCtx.cColSep ) break;
6615      }
6616      if( cSep=='(' ){
6617        sqlite3_free(zCreate);
6618        sqlite3_free(sCtx.z);
6619        xCloser(sCtx.in);
6620        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6621        return 1;
6622      }
6623      zCreate = sqlite3_mprintf("%z\n)", zCreate);
6624      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6625      sqlite3_free(zCreate);
6626      if( rc ){
6627        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6628                sqlite3_errmsg(p->db));
6629        sqlite3_free(sCtx.z);
6630        xCloser(sCtx.in);
6631        return 1;
6632      }
6633      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6634    }
6635    sqlite3_free(zSql);
6636    if( rc ){
6637      if (pStmt) sqlite3_finalize(pStmt);
6638      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6639      xCloser(sCtx.in);
6640      return 1;
6641    }
6642    nCol = sqlite3_column_count(pStmt);
6643    sqlite3_finalize(pStmt);
6644    pStmt = 0;
6645    if( nCol==0 ) return 0; /* no columns, no error */
6646    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6647    if( zSql==0 ){
6648      xCloser(sCtx.in);
6649      shell_out_of_memory();
6650    }
6651    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6652    j = strlen30(zSql);
6653    for(i=1; i<nCol; i++){
6654      zSql[j++] = ',';
6655      zSql[j++] = '?';
6656    }
6657    zSql[j++] = ')';
6658    zSql[j] = 0;
6659    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6660    sqlite3_free(zSql);
6661    if( rc ){
6662      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6663      if (pStmt) sqlite3_finalize(pStmt);
6664      xCloser(sCtx.in);
6665      return 1;
6666    }
6667    needCommit = sqlite3_get_autocommit(p->db);
6668    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6669    do{
6670      int startLine = sCtx.nLine;
6671      for(i=0; i<nCol; i++){
6672        char *z = xRead(&sCtx);
6673        /*
6674        ** Did we reach end-of-file before finding any columns?
6675        ** If so, stop instead of NULL filling the remaining columns.
6676        */
6677        if( z==0 && i==0 ) break;
6678        /*
6679        ** Did we reach end-of-file OR end-of-line before finding any
6680        ** columns in ASCII mode?  If so, stop instead of NULL filling
6681        ** the remaining columns.
6682        */
6683        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6684        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6685        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6686          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6687                          "filling the rest with NULL\n",
6688                          sCtx.zFile, startLine, nCol, i+1);
6689          i += 2;
6690          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6691        }
6692      }
6693      if( sCtx.cTerm==sCtx.cColSep ){
6694        do{
6695          xRead(&sCtx);
6696          i++;
6697        }while( sCtx.cTerm==sCtx.cColSep );
6698        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6699                        "extras ignored\n",
6700                        sCtx.zFile, startLine, nCol, i);
6701      }
6702      if( i>=nCol ){
6703        sqlite3_step(pStmt);
6704        rc = sqlite3_reset(pStmt);
6705        if( rc!=SQLITE_OK ){
6706          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6707                      startLine, sqlite3_errmsg(p->db));
6708        }
6709      }
6710    }while( sCtx.cTerm!=EOF );
6711
6712    xCloser(sCtx.in);
6713    sqlite3_free(sCtx.z);
6714    sqlite3_finalize(pStmt);
6715    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6716  }else
6717
6718#ifndef SQLITE_UNTESTABLE
6719  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6720    char *zSql;
6721    char *zCollist = 0;
6722    sqlite3_stmt *pStmt;
6723    int tnum = 0;
6724    int i;
6725    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6726      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6727                          "       .imposter off\n");
6728      rc = 1;
6729      goto meta_command_exit;
6730    }
6731    open_db(p, 0);
6732    if( nArg==2 ){
6733      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6734      goto meta_command_exit;
6735    }
6736    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6737                           " WHERE name='%q' AND type='index'", azArg[1]);
6738    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6739    sqlite3_free(zSql);
6740    if( sqlite3_step(pStmt)==SQLITE_ROW ){
6741      tnum = sqlite3_column_int(pStmt, 0);
6742    }
6743    sqlite3_finalize(pStmt);
6744    if( tnum==0 ){
6745      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6746      rc = 1;
6747      goto meta_command_exit;
6748    }
6749    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6750    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6751    sqlite3_free(zSql);
6752    i = 0;
6753    while( sqlite3_step(pStmt)==SQLITE_ROW ){
6754      char zLabel[20];
6755      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6756      i++;
6757      if( zCol==0 ){
6758        if( sqlite3_column_int(pStmt,1)==-1 ){
6759          zCol = "_ROWID_";
6760        }else{
6761          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6762          zCol = zLabel;
6763        }
6764      }
6765      if( zCollist==0 ){
6766        zCollist = sqlite3_mprintf("\"%w\"", zCol);
6767      }else{
6768        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6769      }
6770    }
6771    sqlite3_finalize(pStmt);
6772    zSql = sqlite3_mprintf(
6773          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6774          azArg[2], zCollist, zCollist);
6775    sqlite3_free(zCollist);
6776    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6777    if( rc==SQLITE_OK ){
6778      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6779      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6780      if( rc ){
6781        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6782      }else{
6783        utf8_printf(stdout, "%s;\n", zSql);
6784        raw_printf(stdout,
6785           "WARNING: writing to an imposter table will corrupt the index!\n"
6786        );
6787      }
6788    }else{
6789      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6790      rc = 1;
6791    }
6792    sqlite3_free(zSql);
6793  }else
6794#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6795
6796#ifdef SQLITE_ENABLE_IOTRACE
6797  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6798    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6799    if( iotrace && iotrace!=stdout ) fclose(iotrace);
6800    iotrace = 0;
6801    if( nArg<2 ){
6802      sqlite3IoTrace = 0;
6803    }else if( strcmp(azArg[1], "-")==0 ){
6804      sqlite3IoTrace = iotracePrintf;
6805      iotrace = stdout;
6806    }else{
6807      iotrace = fopen(azArg[1], "w");
6808      if( iotrace==0 ){
6809        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6810        sqlite3IoTrace = 0;
6811        rc = 1;
6812      }else{
6813        sqlite3IoTrace = iotracePrintf;
6814      }
6815    }
6816  }else
6817#endif
6818
6819  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6820    static const struct {
6821       const char *zLimitName;   /* Name of a limit */
6822       int limitCode;            /* Integer code for that limit */
6823    } aLimit[] = {
6824      { "length",                SQLITE_LIMIT_LENGTH                    },
6825      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
6826      { "column",                SQLITE_LIMIT_COLUMN                    },
6827      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
6828      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
6829      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
6830      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
6831      { "attached",              SQLITE_LIMIT_ATTACHED                  },
6832      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
6833      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
6834      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
6835      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
6836    };
6837    int i, n2;
6838    open_db(p, 0);
6839    if( nArg==1 ){
6840      for(i=0; i<ArraySize(aLimit); i++){
6841        printf("%20s %d\n", aLimit[i].zLimitName,
6842               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6843      }
6844    }else if( nArg>3 ){
6845      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6846      rc = 1;
6847      goto meta_command_exit;
6848    }else{
6849      int iLimit = -1;
6850      n2 = strlen30(azArg[1]);
6851      for(i=0; i<ArraySize(aLimit); i++){
6852        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6853          if( iLimit<0 ){
6854            iLimit = i;
6855          }else{
6856            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6857            rc = 1;
6858            goto meta_command_exit;
6859          }
6860        }
6861      }
6862      if( iLimit<0 ){
6863        utf8_printf(stderr, "unknown limit: \"%s\"\n"
6864                        "enter \".limits\" with no arguments for a list.\n",
6865                         azArg[1]);
6866        rc = 1;
6867        goto meta_command_exit;
6868      }
6869      if( nArg==3 ){
6870        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6871                      (int)integerValue(azArg[2]));
6872      }
6873      printf("%20s %d\n", aLimit[iLimit].zLimitName,
6874             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6875    }
6876  }else
6877
6878  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6879    open_db(p, 0);
6880    lintDotCommand(p, azArg, nArg);
6881  }else
6882
6883#ifndef SQLITE_OMIT_LOAD_EXTENSION
6884  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6885    const char *zFile, *zProc;
6886    char *zErrMsg = 0;
6887    if( nArg<2 ){
6888      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6889      rc = 1;
6890      goto meta_command_exit;
6891    }
6892    zFile = azArg[1];
6893    zProc = nArg>=3 ? azArg[2] : 0;
6894    open_db(p, 0);
6895    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6896    if( rc!=SQLITE_OK ){
6897      utf8_printf(stderr, "Error: %s\n", zErrMsg);
6898      sqlite3_free(zErrMsg);
6899      rc = 1;
6900    }
6901  }else
6902#endif
6903
6904  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6905    if( nArg!=2 ){
6906      raw_printf(stderr, "Usage: .log FILENAME\n");
6907      rc = 1;
6908    }else{
6909      const char *zFile = azArg[1];
6910      output_file_close(p->pLog);
6911      p->pLog = output_file_open(zFile, 0);
6912    }
6913  }else
6914
6915  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6916    const char *zMode = nArg>=2 ? azArg[1] : "";
6917    int n2 = strlen30(zMode);
6918    int c2 = zMode[0];
6919    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6920      p->mode = MODE_Line;
6921      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6922    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6923      p->mode = MODE_Column;
6924      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6925    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6926      p->mode = MODE_List;
6927      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6928      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6929    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6930      p->mode = MODE_Html;
6931    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6932      p->mode = MODE_Tcl;
6933      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6934      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6935    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6936      p->mode = MODE_Csv;
6937      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6938      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6939    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6940      p->mode = MODE_List;
6941      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6942    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6943      p->mode = MODE_Insert;
6944      set_table_name(p, nArg>=3 ? azArg[2] : "table");
6945    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6946      p->mode = MODE_Quote;
6947    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6948      p->mode = MODE_Ascii;
6949      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6950      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6951    }else if( nArg==1 ){
6952      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6953    }else{
6954      raw_printf(stderr, "Error: mode should be one of: "
6955         "ascii column csv html insert line list quote tabs tcl\n");
6956      rc = 1;
6957    }
6958    p->cMode = p->mode;
6959  }else
6960
6961  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6962    if( nArg==2 ){
6963      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6964                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6965    }else{
6966      raw_printf(stderr, "Usage: .nullvalue STRING\n");
6967      rc = 1;
6968    }
6969  }else
6970
6971  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6972    char *zNewFilename;  /* Name of the database file to open */
6973    int iName = 1;       /* Index in azArg[] of the filename */
6974    int newFlag = 0;     /* True to delete file before opening */
6975    /* Close the existing database */
6976    session_close_all(p);
6977    close_db(p->db);
6978    p->db = 0;
6979    p->zDbFilename = 0;
6980    sqlite3_free(p->zFreeOnClose);
6981    p->zFreeOnClose = 0;
6982    p->openMode = SHELL_OPEN_UNSPEC;
6983    p->szMax = 0;
6984    /* Check for command-line arguments */
6985    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6986      const char *z = azArg[iName];
6987      if( optionMatch(z,"new") ){
6988        newFlag = 1;
6989#ifdef SQLITE_HAVE_ZLIB
6990      }else if( optionMatch(z, "zip") ){
6991        p->openMode = SHELL_OPEN_ZIPFILE;
6992#endif
6993      }else if( optionMatch(z, "append") ){
6994        p->openMode = SHELL_OPEN_APPENDVFS;
6995      }else if( optionMatch(z, "readonly") ){
6996        p->openMode = SHELL_OPEN_READONLY;
6997#ifdef SQLITE_ENABLE_DESERIALIZE
6998      }else if( optionMatch(z, "deserialize") ){
6999        p->openMode = SHELL_OPEN_DESERIALIZE;
7000      }else if( optionMatch(z, "hexdb") ){
7001        p->openMode = SHELL_OPEN_HEXDB;
7002      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7003        p->szMax = integerValue(azArg[++iName]);
7004#endif /* SQLITE_ENABLE_DESERIALIZE */
7005      }else if( z[0]=='-' ){
7006        utf8_printf(stderr, "unknown option: %s\n", z);
7007        rc = 1;
7008        goto meta_command_exit;
7009      }
7010    }
7011    /* If a filename is specified, try to open it first */
7012    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
7013    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
7014      if( newFlag ) shellDeleteFile(zNewFilename);
7015      p->zDbFilename = zNewFilename;
7016      open_db(p, OPEN_DB_KEEPALIVE);
7017      if( p->db==0 ){
7018        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
7019        sqlite3_free(zNewFilename);
7020      }else{
7021        p->zFreeOnClose = zNewFilename;
7022      }
7023    }
7024    if( p->db==0 ){
7025      /* As a fall-back open a TEMP database */
7026      p->zDbFilename = 0;
7027      open_db(p, 0);
7028    }
7029  }else
7030
7031  if( (c=='o'
7032        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
7033   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
7034  ){
7035    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
7036    int bTxtMode = 0;
7037    if( azArg[0][0]=='e' ){
7038      /* Transform the ".excel" command into ".once -x" */
7039      nArg = 2;
7040      azArg[0] = "once";
7041      zFile = azArg[1] = "-x";
7042      n = 4;
7043    }
7044    if( nArg>2 ){
7045      utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
7046      rc = 1;
7047      goto meta_command_exit;
7048    }
7049    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
7050      if( nArg<2 ){
7051        raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
7052        rc = 1;
7053        goto meta_command_exit;
7054      }
7055      p->outCount = 2;
7056    }else{
7057      p->outCount = 0;
7058    }
7059    output_reset(p);
7060    if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
7061#ifndef SQLITE_NOHAVE_SYSTEM
7062    if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
7063      p->doXdgOpen = 1;
7064      outputModePush(p);
7065      if( zFile[1]=='x' ){
7066        newTempFile(p, "csv");
7067        p->mode = MODE_Csv;
7068        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7069        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7070      }else{
7071        newTempFile(p, "txt");
7072        bTxtMode = 1;
7073      }
7074      zFile = p->zTempFile;
7075    }
7076#endif /* SQLITE_NOHAVE_SYSTEM */
7077    if( zFile[0]=='|' ){
7078#ifdef SQLITE_OMIT_POPEN
7079      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7080      rc = 1;
7081      p->out = stdout;
7082#else
7083      p->out = popen(zFile + 1, "w");
7084      if( p->out==0 ){
7085        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7086        p->out = stdout;
7087        rc = 1;
7088      }else{
7089        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7090      }
7091#endif
7092    }else{
7093      p->out = output_file_open(zFile, bTxtMode);
7094      if( p->out==0 ){
7095        if( strcmp(zFile,"off")!=0 ){
7096          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7097        }
7098        p->out = stdout;
7099        rc = 1;
7100      } else {
7101        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7102      }
7103    }
7104  }else
7105
7106  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
7107    open_db(p,0);
7108    if( nArg<=1 ) goto parameter_syntax_error;
7109
7110    /* .parameter clear
7111    ** Clear all bind parameters by dropping the TEMP table that holds them.
7112    */
7113    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
7114      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.[" BIND_PARAM_TABLE "];",
7115                   0, 0, 0);
7116    }else
7117
7118    /* .parameter list
7119    ** List all bind parameters.
7120    */
7121    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
7122      sqlite3_stmt *pStmt = 0;
7123      int rx;
7124      int len = 0;
7125      rx = sqlite3_prepare_v2(p->db,
7126             "SELECT max(length(key)) "
7127             "FROM temp.[" BIND_PARAM_TABLE "];", -1, &pStmt, 0);
7128      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7129        len = sqlite3_column_int(pStmt, 0);
7130        if( len>40 ) len = 40;
7131      }
7132      sqlite3_finalize(pStmt);
7133      pStmt = 0;
7134      if( len ){
7135        rx = sqlite3_prepare_v2(p->db,
7136             "SELECT key, quote(value) "
7137             "FROM temp.[" BIND_PARAM_TABLE "];", -1, &pStmt, 0);
7138        while( sqlite3_step(pStmt)==SQLITE_ROW ){
7139          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
7140                      sqlite3_column_text(pStmt,1));
7141        }
7142        sqlite3_finalize(pStmt);
7143      }
7144    }else
7145
7146    /* .parameter init
7147    ** Make sure the TEMP table used to hold bind parameters exists.
7148    ** Create it if necessary.
7149    */
7150    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
7151      bind_table_init(p);
7152    }else
7153
7154    /* .parameter set NAME VALUE
7155    ** Set or reset a bind parameter.  NAME should be the full parameter
7156    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
7157    ** VALUE can be in either SQL literal notation, or if not it will be
7158    ** understood to be a text string.
7159    */
7160    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
7161      int rx;
7162      char *zSql;
7163      sqlite3_stmt *pStmt;
7164      const char *zKey = azArg[2];
7165      const char *zValue = azArg[3];
7166      bind_table_init(p);
7167      zSql = sqlite3_mprintf(
7168                  "REPLACE INTO temp.[" BIND_PARAM_TABLE "](key,value)"
7169                  "VALUES(%Q,%s);", zKey, zValue);
7170      if( zSql==0 ) shell_out_of_memory();
7171      pStmt = 0;
7172      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7173      sqlite3_free(zSql);
7174      if( rx!=SQLITE_OK ){
7175        sqlite3_finalize(pStmt);
7176        pStmt = 0;
7177        zSql = sqlite3_mprintf(
7178                   "REPLACE INTO temp.[" BIND_PARAM_TABLE "](key,value)"
7179                   "VALUES(%Q,%Q);", zKey, zValue);
7180        if( zSql==0 ) shell_out_of_memory();
7181        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7182        sqlite3_free(zSql);
7183        if( rx!=SQLITE_OK ){
7184          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
7185          sqlite3_finalize(pStmt);
7186          pStmt = 0;
7187          rc = 1;
7188        }
7189      }
7190      sqlite3_step(pStmt);
7191      sqlite3_finalize(pStmt);
7192    }else
7193
7194    /* .parameter unset NAME
7195    ** Remove the NAME binding from the parameter binding table, if it
7196    ** exists.
7197    */
7198    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
7199      char *zSql = sqlite3_mprintf(
7200          "DELETE FROM temp.[" BIND_PARAM_TABLE "] WHERE key=%Q", azArg[2]);
7201      if( zSql==0 ) shell_out_of_memory();
7202      sqlite3_exec(p->db, zSql, 0, 0, 0);
7203      sqlite3_free(zSql);
7204    }else
7205    /* If no command name matches, show a syntax error */
7206    parameter_syntax_error:
7207    showHelp(p->out, "parameter");
7208  }else
7209
7210  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7211    int i;
7212    for(i=1; i<nArg; i++){
7213      if( i>1 ) raw_printf(p->out, " ");
7214      utf8_printf(p->out, "%s", azArg[i]);
7215    }
7216    raw_printf(p->out, "\n");
7217  }else
7218
7219#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
7220  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7221    int i;
7222    int nn = 0;
7223    p->flgProgress = 0;
7224    p->mxProgress = 0;
7225    p->nProgress = 0;
7226    for(i=1; i<nArg; i++){
7227      const char *z = azArg[i];
7228      if( z[0]=='-' ){
7229        z++;
7230        if( z[0]=='-' ) z++;
7231        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
7232          p->flgProgress |= SHELL_PROGRESS_QUIET;
7233          continue;
7234        }
7235        if( strcmp(z,"reset")==0 ){
7236          p->flgProgress |= SHELL_PROGRESS_RESET;
7237          continue;
7238        }
7239        if( strcmp(z,"once")==0 ){
7240          p->flgProgress |= SHELL_PROGRESS_ONCE;
7241          continue;
7242        }
7243        if( strcmp(z,"limit")==0 ){
7244          if( i+1>=nArg ){
7245            utf8_printf(stderr, "Error: missing argument on --limit\n");
7246            rc = 1;
7247            goto meta_command_exit;
7248          }else{
7249            p->mxProgress = (int)integerValue(azArg[++i]);
7250          }
7251          continue;
7252        }
7253        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
7254        rc = 1;
7255        goto meta_command_exit;
7256      }else{
7257        nn = (int)integerValue(z);
7258      }
7259    }
7260    open_db(p, 0);
7261    sqlite3_progress_handler(p->db, nn, progress_handler, p);
7262  }else
7263#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
7264
7265  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
7266    if( nArg >= 2) {
7267      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
7268    }
7269    if( nArg >= 3) {
7270      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
7271    }
7272  }else
7273
7274  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
7275    rc = 2;
7276  }else
7277
7278  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
7279    FILE *inSaved = p->in;
7280    int savedLineno = p->lineno;
7281    if( nArg!=2 ){
7282      raw_printf(stderr, "Usage: .read FILE\n");
7283      rc = 1;
7284      goto meta_command_exit;
7285    }
7286    p->in = fopen(azArg[1], "rb");
7287    if( p->in==0 ){
7288      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
7289      rc = 1;
7290    }else{
7291      rc = process_input(p);
7292      fclose(p->in);
7293    }
7294    p->in = inSaved;
7295    p->lineno = savedLineno;
7296  }else
7297
7298  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
7299    const char *zSrcFile;
7300    const char *zDb;
7301    sqlite3 *pSrc;
7302    sqlite3_backup *pBackup;
7303    int nTimeout = 0;
7304
7305    if( nArg==2 ){
7306      zSrcFile = azArg[1];
7307      zDb = "main";
7308    }else if( nArg==3 ){
7309      zSrcFile = azArg[2];
7310      zDb = azArg[1];
7311    }else{
7312      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
7313      rc = 1;
7314      goto meta_command_exit;
7315    }
7316    rc = sqlite3_open(zSrcFile, &pSrc);
7317    if( rc!=SQLITE_OK ){
7318      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
7319      close_db(pSrc);
7320      return 1;
7321    }
7322    open_db(p, 0);
7323    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
7324    if( pBackup==0 ){
7325      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7326      close_db(pSrc);
7327      return 1;
7328    }
7329    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
7330          || rc==SQLITE_BUSY  ){
7331      if( rc==SQLITE_BUSY ){
7332        if( nTimeout++ >= 3 ) break;
7333        sqlite3_sleep(100);
7334      }
7335    }
7336    sqlite3_backup_finish(pBackup);
7337    if( rc==SQLITE_DONE ){
7338      rc = 0;
7339    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
7340      raw_printf(stderr, "Error: source database is busy\n");
7341      rc = 1;
7342    }else{
7343      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7344      rc = 1;
7345    }
7346    close_db(pSrc);
7347  }else
7348
7349  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
7350    if( nArg==2 ){
7351      p->scanstatsOn = (u8)booleanValue(azArg[1]);
7352#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
7353      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
7354#endif
7355    }else{
7356      raw_printf(stderr, "Usage: .scanstats on|off\n");
7357      rc = 1;
7358    }
7359  }else
7360
7361  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
7362    ShellText sSelect;
7363    ShellState data;
7364    char *zErrMsg = 0;
7365    const char *zDiv = "(";
7366    const char *zName = 0;
7367    int iSchema = 0;
7368    int bDebug = 0;
7369    int ii;
7370
7371    open_db(p, 0);
7372    memcpy(&data, p, sizeof(data));
7373    data.showHeader = 0;
7374    data.cMode = data.mode = MODE_Semi;
7375    initText(&sSelect);
7376    for(ii=1; ii<nArg; ii++){
7377      if( optionMatch(azArg[ii],"indent") ){
7378        data.cMode = data.mode = MODE_Pretty;
7379      }else if( optionMatch(azArg[ii],"debug") ){
7380        bDebug = 1;
7381      }else if( zName==0 ){
7382        zName = azArg[ii];
7383      }else{
7384        raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
7385        rc = 1;
7386        goto meta_command_exit;
7387      }
7388    }
7389    if( zName!=0 ){
7390      int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
7391      if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
7392        char *new_argv[2], *new_colv[2];
7393        new_argv[0] = sqlite3_mprintf(
7394                      "CREATE TABLE %s (\n"
7395                      "  type text,\n"
7396                      "  name text,\n"
7397                      "  tbl_name text,\n"
7398                      "  rootpage integer,\n"
7399                      "  sql text\n"
7400                      ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
7401        new_argv[1] = 0;
7402        new_colv[0] = "sql";
7403        new_colv[1] = 0;
7404        callback(&data, 1, new_argv, new_colv);
7405        sqlite3_free(new_argv[0]);
7406      }
7407    }
7408    if( zDiv ){
7409      sqlite3_stmt *pStmt = 0;
7410      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
7411                              -1, &pStmt, 0);
7412      if( rc ){
7413        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7414        sqlite3_finalize(pStmt);
7415        rc = 1;
7416        goto meta_command_exit;
7417      }
7418      appendText(&sSelect, "SELECT sql FROM", 0);
7419      iSchema = 0;
7420      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7421        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
7422        char zScNum[30];
7423        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
7424        appendText(&sSelect, zDiv, 0);
7425        zDiv = " UNION ALL ";
7426        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
7427        if( sqlite3_stricmp(zDb, "main")!=0 ){
7428          appendText(&sSelect, zDb, '"');
7429        }else{
7430          appendText(&sSelect, "NULL", 0);
7431        }
7432        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
7433        appendText(&sSelect, zScNum, 0);
7434        appendText(&sSelect, " AS snum, ", 0);
7435        appendText(&sSelect, zDb, '\'');
7436        appendText(&sSelect, " AS sname FROM ", 0);
7437        appendText(&sSelect, zDb, '"');
7438        appendText(&sSelect, ".sqlite_master", 0);
7439      }
7440      sqlite3_finalize(pStmt);
7441#ifdef SQLITE_INTROSPECTION_PRAGMAS
7442      if( zName ){
7443        appendText(&sSelect,
7444           " UNION ALL SELECT shell_module_schema(name),"
7445           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
7446      }
7447#endif
7448      appendText(&sSelect, ") WHERE ", 0);
7449      if( zName ){
7450        char *zQarg = sqlite3_mprintf("%Q", zName);
7451        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
7452                    strchr(zName, '[') != 0;
7453        if( strchr(zName, '.') ){
7454          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
7455        }else{
7456          appendText(&sSelect, "lower(tbl_name)", 0);
7457        }
7458        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
7459        appendText(&sSelect, zQarg, 0);
7460        if( !bGlob ){
7461          appendText(&sSelect, " ESCAPE '\\' ", 0);
7462        }
7463        appendText(&sSelect, " AND ", 0);
7464        sqlite3_free(zQarg);
7465      }
7466      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
7467                           " ORDER BY snum, rowid", 0);
7468      if( bDebug ){
7469        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
7470      }else{
7471        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
7472      }
7473      freeText(&sSelect);
7474    }
7475    if( zErrMsg ){
7476      utf8_printf(stderr,"Error: %s\n", zErrMsg);
7477      sqlite3_free(zErrMsg);
7478      rc = 1;
7479    }else if( rc != SQLITE_OK ){
7480      raw_printf(stderr,"Error: querying schema information\n");
7481      rc = 1;
7482    }else{
7483      rc = 0;
7484    }
7485  }else
7486
7487#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
7488  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
7489    sqlite3SelectTrace = (int)integerValue(azArg[1]);
7490  }else
7491#endif
7492
7493#if defined(SQLITE_ENABLE_SESSION)
7494  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
7495    OpenSession *pSession = &p->aSession[0];
7496    char **azCmd = &azArg[1];
7497    int iSes = 0;
7498    int nCmd = nArg - 1;
7499    int i;
7500    if( nArg<=1 ) goto session_syntax_error;
7501    open_db(p, 0);
7502    if( nArg>=3 ){
7503      for(iSes=0; iSes<p->nSession; iSes++){
7504        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
7505      }
7506      if( iSes<p->nSession ){
7507        pSession = &p->aSession[iSes];
7508        azCmd++;
7509        nCmd--;
7510      }else{
7511        pSession = &p->aSession[0];
7512        iSes = 0;
7513      }
7514    }
7515
7516    /* .session attach TABLE
7517    ** Invoke the sqlite3session_attach() interface to attach a particular
7518    ** table so that it is never filtered.
7519    */
7520    if( strcmp(azCmd[0],"attach")==0 ){
7521      if( nCmd!=2 ) goto session_syntax_error;
7522      if( pSession->p==0 ){
7523        session_not_open:
7524        raw_printf(stderr, "ERROR: No sessions are open\n");
7525      }else{
7526        rc = sqlite3session_attach(pSession->p, azCmd[1]);
7527        if( rc ){
7528          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
7529          rc = 0;
7530        }
7531      }
7532    }else
7533
7534    /* .session changeset FILE
7535    ** .session patchset FILE
7536    ** Write a changeset or patchset into a file.  The file is overwritten.
7537    */
7538    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
7539      FILE *out = 0;
7540      if( nCmd!=2 ) goto session_syntax_error;
7541      if( pSession->p==0 ) goto session_not_open;
7542      out = fopen(azCmd[1], "wb");
7543      if( out==0 ){
7544        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
7545      }else{
7546        int szChng;
7547        void *pChng;
7548        if( azCmd[0][0]=='c' ){
7549          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
7550        }else{
7551          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
7552        }
7553        if( rc ){
7554          printf("Error: error code %d\n", rc);
7555          rc = 0;
7556        }
7557        if( pChng
7558          && fwrite(pChng, szChng, 1, out)!=1 ){
7559          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
7560                  szChng);
7561        }
7562        sqlite3_free(pChng);
7563        fclose(out);
7564      }
7565    }else
7566
7567    /* .session close
7568    ** Close the identified session
7569    */
7570    if( strcmp(azCmd[0], "close")==0 ){
7571      if( nCmd!=1 ) goto session_syntax_error;
7572      if( p->nSession ){
7573        session_close(pSession);
7574        p->aSession[iSes] = p->aSession[--p->nSession];
7575      }
7576    }else
7577
7578    /* .session enable ?BOOLEAN?
7579    ** Query or set the enable flag
7580    */
7581    if( strcmp(azCmd[0], "enable")==0 ){
7582      int ii;
7583      if( nCmd>2 ) goto session_syntax_error;
7584      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7585      if( p->nSession ){
7586        ii = sqlite3session_enable(pSession->p, ii);
7587        utf8_printf(p->out, "session %s enable flag = %d\n",
7588                    pSession->zName, ii);
7589      }
7590    }else
7591
7592    /* .session filter GLOB ....
7593    ** Set a list of GLOB patterns of table names to be excluded.
7594    */
7595    if( strcmp(azCmd[0], "filter")==0 ){
7596      int ii, nByte;
7597      if( nCmd<2 ) goto session_syntax_error;
7598      if( p->nSession ){
7599        for(ii=0; ii<pSession->nFilter; ii++){
7600          sqlite3_free(pSession->azFilter[ii]);
7601        }
7602        sqlite3_free(pSession->azFilter);
7603        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
7604        pSession->azFilter = sqlite3_malloc( nByte );
7605        if( pSession->azFilter==0 ){
7606          raw_printf(stderr, "Error: out or memory\n");
7607          exit(1);
7608        }
7609        for(ii=1; ii<nCmd; ii++){
7610          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7611        }
7612        pSession->nFilter = ii-1;
7613      }
7614    }else
7615
7616    /* .session indirect ?BOOLEAN?
7617    ** Query or set the indirect flag
7618    */
7619    if( strcmp(azCmd[0], "indirect")==0 ){
7620      int ii;
7621      if( nCmd>2 ) goto session_syntax_error;
7622      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7623      if( p->nSession ){
7624        ii = sqlite3session_indirect(pSession->p, ii);
7625        utf8_printf(p->out, "session %s indirect flag = %d\n",
7626                    pSession->zName, ii);
7627      }
7628    }else
7629
7630    /* .session isempty
7631    ** Determine if the session is empty
7632    */
7633    if( strcmp(azCmd[0], "isempty")==0 ){
7634      int ii;
7635      if( nCmd!=1 ) goto session_syntax_error;
7636      if( p->nSession ){
7637        ii = sqlite3session_isempty(pSession->p);
7638        utf8_printf(p->out, "session %s isempty flag = %d\n",
7639                    pSession->zName, ii);
7640      }
7641    }else
7642
7643    /* .session list
7644    ** List all currently open sessions
7645    */
7646    if( strcmp(azCmd[0],"list")==0 ){
7647      for(i=0; i<p->nSession; i++){
7648        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7649      }
7650    }else
7651
7652    /* .session open DB NAME
7653    ** Open a new session called NAME on the attached database DB.
7654    ** DB is normally "main".
7655    */
7656    if( strcmp(azCmd[0],"open")==0 ){
7657      char *zName;
7658      if( nCmd!=3 ) goto session_syntax_error;
7659      zName = azCmd[2];
7660      if( zName[0]==0 ) goto session_syntax_error;
7661      for(i=0; i<p->nSession; i++){
7662        if( strcmp(p->aSession[i].zName,zName)==0 ){
7663          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7664          goto meta_command_exit;
7665        }
7666      }
7667      if( p->nSession>=ArraySize(p->aSession) ){
7668        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7669        goto meta_command_exit;
7670      }
7671      pSession = &p->aSession[p->nSession];
7672      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7673      if( rc ){
7674        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7675        rc = 0;
7676        goto meta_command_exit;
7677      }
7678      pSession->nFilter = 0;
7679      sqlite3session_table_filter(pSession->p, session_filter, pSession);
7680      p->nSession++;
7681      pSession->zName = sqlite3_mprintf("%s", zName);
7682    }else
7683    /* If no command name matches, show a syntax error */
7684    session_syntax_error:
7685    showHelp(p->out, "session");
7686  }else
7687#endif
7688
7689#ifdef SQLITE_DEBUG
7690  /* Undocumented commands for internal testing.  Subject to change
7691  ** without notice. */
7692  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7693    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7694      int i, v;
7695      for(i=1; i<nArg; i++){
7696        v = booleanValue(azArg[i]);
7697        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7698      }
7699    }
7700    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7701      int i; sqlite3_int64 v;
7702      for(i=1; i<nArg; i++){
7703        char zBuf[200];
7704        v = integerValue(azArg[i]);
7705        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7706        utf8_printf(p->out, "%s", zBuf);
7707      }
7708    }
7709  }else
7710#endif
7711
7712  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7713    int bIsInit = 0;         /* True to initialize the SELFTEST table */
7714    int bVerbose = 0;        /* Verbose output */
7715    int bSelftestExists;     /* True if SELFTEST already exists */
7716    int i, k;                /* Loop counters */
7717    int nTest = 0;           /* Number of tests runs */
7718    int nErr = 0;            /* Number of errors seen */
7719    ShellText str;           /* Answer for a query */
7720    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7721
7722    open_db(p,0);
7723    for(i=1; i<nArg; i++){
7724      const char *z = azArg[i];
7725      if( z[0]=='-' && z[1]=='-' ) z++;
7726      if( strcmp(z,"-init")==0 ){
7727        bIsInit = 1;
7728      }else
7729      if( strcmp(z,"-v")==0 ){
7730        bVerbose++;
7731      }else
7732      {
7733        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7734                    azArg[i], azArg[0]);
7735        raw_printf(stderr, "Should be one of: --init -v\n");
7736        rc = 1;
7737        goto meta_command_exit;
7738      }
7739    }
7740    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7741           != SQLITE_OK ){
7742      bSelftestExists = 0;
7743    }else{
7744      bSelftestExists = 1;
7745    }
7746    if( bIsInit ){
7747      createSelftestTable(p);
7748      bSelftestExists = 1;
7749    }
7750    initText(&str);
7751    appendText(&str, "x", 0);
7752    for(k=bSelftestExists; k>=0; k--){
7753      if( k==1 ){
7754        rc = sqlite3_prepare_v2(p->db,
7755            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7756            -1, &pStmt, 0);
7757      }else{
7758        rc = sqlite3_prepare_v2(p->db,
7759          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7760          "      (1,'run','PRAGMA integrity_check','ok')",
7761          -1, &pStmt, 0);
7762      }
7763      if( rc ){
7764        raw_printf(stderr, "Error querying the selftest table\n");
7765        rc = 1;
7766        sqlite3_finalize(pStmt);
7767        goto meta_command_exit;
7768      }
7769      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7770        int tno = sqlite3_column_int(pStmt, 0);
7771        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7772        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7773        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7774
7775        k = 0;
7776        if( bVerbose>0 ){
7777          char *zQuote = sqlite3_mprintf("%q", zSql);
7778          printf("%d: %s %s\n", tno, zOp, zSql);
7779          sqlite3_free(zQuote);
7780        }
7781        if( strcmp(zOp,"memo")==0 ){
7782          utf8_printf(p->out, "%s\n", zSql);
7783        }else
7784        if( strcmp(zOp,"run")==0 ){
7785          char *zErrMsg = 0;
7786          str.n = 0;
7787          str.z[0] = 0;
7788          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7789          nTest++;
7790          if( bVerbose ){
7791            utf8_printf(p->out, "Result: %s\n", str.z);
7792          }
7793          if( rc || zErrMsg ){
7794            nErr++;
7795            rc = 1;
7796            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7797            sqlite3_free(zErrMsg);
7798          }else if( strcmp(zAns,str.z)!=0 ){
7799            nErr++;
7800            rc = 1;
7801            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7802            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
7803          }
7804        }else
7805        {
7806          utf8_printf(stderr,
7807            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7808          rc = 1;
7809          break;
7810        }
7811      } /* End loop over rows of content from SELFTEST */
7812      sqlite3_finalize(pStmt);
7813    } /* End loop over k */
7814    freeText(&str);
7815    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7816  }else
7817
7818  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7819    if( nArg<2 || nArg>3 ){
7820      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7821      rc = 1;
7822    }
7823    if( nArg>=2 ){
7824      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7825                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7826    }
7827    if( nArg>=3 ){
7828      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7829                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7830    }
7831  }else
7832
7833  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7834    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
7835    int i;                   /* Loop counter */
7836    int bSchema = 0;         /* Also hash the schema */
7837    int bSeparate = 0;       /* Hash each table separately */
7838    int iSize = 224;         /* Hash algorithm to use */
7839    int bDebug = 0;          /* Only show the query that would have run */
7840    sqlite3_stmt *pStmt;     /* For querying tables names */
7841    char *zSql;              /* SQL to be run */
7842    char *zSep;              /* Separator */
7843    ShellText sSql;          /* Complete SQL for the query to run the hash */
7844    ShellText sQuery;        /* Set of queries used to read all content */
7845    open_db(p, 0);
7846    for(i=1; i<nArg; i++){
7847      const char *z = azArg[i];
7848      if( z[0]=='-' ){
7849        z++;
7850        if( z[0]=='-' ) z++;
7851        if( strcmp(z,"schema")==0 ){
7852          bSchema = 1;
7853        }else
7854        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7855         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7856        ){
7857          iSize = atoi(&z[5]);
7858        }else
7859        if( strcmp(z,"debug")==0 ){
7860          bDebug = 1;
7861        }else
7862        {
7863          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7864                      azArg[i], azArg[0]);
7865          raw_printf(stderr, "Should be one of: --schema"
7866                             " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
7867          rc = 1;
7868          goto meta_command_exit;
7869        }
7870      }else if( zLike ){
7871        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7872        rc = 1;
7873        goto meta_command_exit;
7874      }else{
7875        zLike = z;
7876        bSeparate = 1;
7877        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
7878      }
7879    }
7880    if( bSchema ){
7881      zSql = "SELECT lower(name) FROM sqlite_master"
7882             " WHERE type='table' AND coalesce(rootpage,0)>1"
7883             " UNION ALL SELECT 'sqlite_master'"
7884             " ORDER BY 1 collate nocase";
7885    }else{
7886      zSql = "SELECT lower(name) FROM sqlite_master"
7887             " WHERE type='table' AND coalesce(rootpage,0)>1"
7888             " AND name NOT LIKE 'sqlite_%'"
7889             " ORDER BY 1 collate nocase";
7890    }
7891    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7892    initText(&sQuery);
7893    initText(&sSql);
7894    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7895    zSep = "VALUES(";
7896    while( SQLITE_ROW==sqlite3_step(pStmt) ){
7897      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7898      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7899      if( strncmp(zTab, "sqlite_",7)!=0 ){
7900        appendText(&sQuery,"SELECT * FROM ", 0);
7901        appendText(&sQuery,zTab,'"');
7902        appendText(&sQuery," NOT INDEXED;", 0);
7903      }else if( strcmp(zTab, "sqlite_master")==0 ){
7904        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7905                           " ORDER BY name;", 0);
7906      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7907        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7908                           " ORDER BY name;", 0);
7909      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7910        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7911                           " ORDER BY tbl,idx;", 0);
7912      }else if( strcmp(zTab, "sqlite_stat3")==0
7913             || strcmp(zTab, "sqlite_stat4")==0 ){
7914        appendText(&sQuery, "SELECT * FROM ", 0);
7915        appendText(&sQuery, zTab, 0);
7916        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7917      }
7918      appendText(&sSql, zSep, 0);
7919      appendText(&sSql, sQuery.z, '\'');
7920      sQuery.n = 0;
7921      appendText(&sSql, ",", 0);
7922      appendText(&sSql, zTab, '\'');
7923      zSep = "),(";
7924    }
7925    sqlite3_finalize(pStmt);
7926    if( bSeparate ){
7927      zSql = sqlite3_mprintf(
7928          "%s))"
7929          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7930          "   FROM [sha3sum$query]",
7931          sSql.z, iSize);
7932    }else{
7933      zSql = sqlite3_mprintf(
7934          "%s))"
7935          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7936          "   FROM [sha3sum$query]",
7937          sSql.z, iSize);
7938    }
7939    freeText(&sQuery);
7940    freeText(&sSql);
7941    if( bDebug ){
7942      utf8_printf(p->out, "%s\n", zSql);
7943    }else{
7944      shell_exec(p, zSql, 0);
7945    }
7946    sqlite3_free(zSql);
7947  }else
7948
7949#ifndef SQLITE_NOHAVE_SYSTEM
7950  if( c=='s'
7951   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7952  ){
7953    char *zCmd;
7954    int i, x;
7955    if( nArg<2 ){
7956      raw_printf(stderr, "Usage: .system COMMAND\n");
7957      rc = 1;
7958      goto meta_command_exit;
7959    }
7960    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7961    for(i=2; i<nArg; i++){
7962      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7963                             zCmd, azArg[i]);
7964    }
7965    x = system(zCmd);
7966    sqlite3_free(zCmd);
7967    if( x ) raw_printf(stderr, "System command returns %d\n", x);
7968  }else
7969#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7970
7971  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
7972    static const char *azBool[] = { "off", "on", "trigger", "full"};
7973    int i;
7974    if( nArg!=1 ){
7975      raw_printf(stderr, "Usage: .show\n");
7976      rc = 1;
7977      goto meta_command_exit;
7978    }
7979    utf8_printf(p->out, "%12.12s: %s\n","echo",
7980                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
7981    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7982    utf8_printf(p->out, "%12.12s: %s\n","explain",
7983         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7984    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7985    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7986    utf8_printf(p->out, "%12.12s: ", "nullvalue");
7987      output_c_string(p->out, p->nullValue);
7988      raw_printf(p->out, "\n");
7989    utf8_printf(p->out,"%12.12s: %s\n","output",
7990            strlen30(p->outfile) ? p->outfile : "stdout");
7991    utf8_printf(p->out,"%12.12s: ", "colseparator");
7992      output_c_string(p->out, p->colSeparator);
7993      raw_printf(p->out, "\n");
7994    utf8_printf(p->out,"%12.12s: ", "rowseparator");
7995      output_c_string(p->out, p->rowSeparator);
7996      raw_printf(p->out, "\n");
7997    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7998    utf8_printf(p->out, "%12.12s: ", "width");
7999    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8000      raw_printf(p->out, "%d ", p->colWidth[i]);
8001    }
8002    raw_printf(p->out, "\n");
8003    utf8_printf(p->out, "%12.12s: %s\n", "filename",
8004                p->zDbFilename ? p->zDbFilename : "");
8005  }else
8006
8007  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
8008    if( nArg==2 ){
8009      p->statsOn = (u8)booleanValue(azArg[1]);
8010    }else if( nArg==1 ){
8011      display_stats(p->db, p, 0);
8012    }else{
8013      raw_printf(stderr, "Usage: .stats ?on|off?\n");
8014      rc = 1;
8015    }
8016  }else
8017
8018  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
8019   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
8020                 || strncmp(azArg[0], "indexes", n)==0) )
8021  ){
8022    sqlite3_stmt *pStmt;
8023    char **azResult;
8024    int nRow, nAlloc;
8025    int ii;
8026    ShellText s;
8027    initText(&s);
8028    open_db(p, 0);
8029    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8030    if( rc ){
8031      sqlite3_finalize(pStmt);
8032      return shellDatabaseError(p->db);
8033    }
8034
8035    if( nArg>2 && c=='i' ){
8036      /* It is an historical accident that the .indexes command shows an error
8037      ** when called with the wrong number of arguments whereas the .tables
8038      ** command does not. */
8039      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
8040      rc = 1;
8041      sqlite3_finalize(pStmt);
8042      goto meta_command_exit;
8043    }
8044    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
8045      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
8046      if( zDbName==0 ) continue;
8047      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
8048      if( sqlite3_stricmp(zDbName, "main")==0 ){
8049        appendText(&s, "SELECT name FROM ", 0);
8050      }else{
8051        appendText(&s, "SELECT ", 0);
8052        appendText(&s, zDbName, '\'');
8053        appendText(&s, "||'.'||name FROM ", 0);
8054      }
8055      appendText(&s, zDbName, '"');
8056      appendText(&s, ".sqlite_master ", 0);
8057      if( c=='t' ){
8058        appendText(&s," WHERE type IN ('table','view')"
8059                      "   AND name NOT LIKE 'sqlite_%'"
8060                      "   AND name LIKE ?1", 0);
8061      }else{
8062        appendText(&s," WHERE type='index'"
8063                      "   AND tbl_name LIKE ?1", 0);
8064      }
8065    }
8066    rc = sqlite3_finalize(pStmt);
8067    appendText(&s, " ORDER BY 1", 0);
8068    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
8069    freeText(&s);
8070    if( rc ) return shellDatabaseError(p->db);
8071
8072    /* Run the SQL statement prepared by the above block. Store the results
8073    ** as an array of nul-terminated strings in azResult[].  */
8074    nRow = nAlloc = 0;
8075    azResult = 0;
8076    if( nArg>1 ){
8077      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
8078    }else{
8079      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
8080    }
8081    while( sqlite3_step(pStmt)==SQLITE_ROW ){
8082      if( nRow>=nAlloc ){
8083        char **azNew;
8084        int n2 = nAlloc*2 + 10;
8085        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
8086        if( azNew==0 ) shell_out_of_memory();
8087        nAlloc = n2;
8088        azResult = azNew;
8089      }
8090      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8091      if( 0==azResult[nRow] ) shell_out_of_memory();
8092      nRow++;
8093    }
8094    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
8095      rc = shellDatabaseError(p->db);
8096    }
8097
8098    /* Pretty-print the contents of array azResult[] to the output */
8099    if( rc==0 && nRow>0 ){
8100      int len, maxlen = 0;
8101      int i, j;
8102      int nPrintCol, nPrintRow;
8103      for(i=0; i<nRow; i++){
8104        len = strlen30(azResult[i]);
8105        if( len>maxlen ) maxlen = len;
8106      }
8107      nPrintCol = 80/(maxlen+2);
8108      if( nPrintCol<1 ) nPrintCol = 1;
8109      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
8110      for(i=0; i<nPrintRow; i++){
8111        for(j=i; j<nRow; j+=nPrintRow){
8112          char *zSp = j<nPrintRow ? "" : "  ";
8113          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
8114                      azResult[j] ? azResult[j]:"");
8115        }
8116        raw_printf(p->out, "\n");
8117      }
8118    }
8119
8120    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
8121    sqlite3_free(azResult);
8122  }else
8123
8124  /* Begin redirecting output to the file "testcase-out.txt" */
8125  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
8126    output_reset(p);
8127    p->out = output_file_open("testcase-out.txt", 0);
8128    if( p->out==0 ){
8129      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
8130    }
8131    if( nArg>=2 ){
8132      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
8133    }else{
8134      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
8135    }
8136  }else
8137
8138#ifndef SQLITE_UNTESTABLE
8139  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
8140    static const struct {
8141       const char *zCtrlName;   /* Name of a test-control option */
8142       int ctrlCode;            /* Integer code for that option */
8143       const char *zUsage;      /* Usage notes */
8144    } aCtrl[] = {
8145      { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
8146      { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
8147    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
8148    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
8149      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
8150    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
8151      { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
8152      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN"       },
8153      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
8154      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
8155      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
8156#ifdef YYCOVERAGE
8157      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
8158#endif
8159      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
8160      { "prng_reset",         SQLITE_TESTCTRL_PRNG_RESET,    ""                   },
8161      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""                   },
8162      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""                   },
8163      { "reserve",            SQLITE_TESTCTRL_RESERVE,       "BYTES-OF-RESERVE"   },
8164    };
8165    int testctrl = -1;
8166    int iCtrl = -1;
8167    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
8168    int isOk = 0;
8169    int i, n2;
8170    const char *zCmd = 0;
8171
8172    open_db(p, 0);
8173    zCmd = nArg>=2 ? azArg[1] : "help";
8174
8175    /* The argument can optionally begin with "-" or "--" */
8176    if( zCmd[0]=='-' && zCmd[1] ){
8177      zCmd++;
8178      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8179    }
8180
8181    /* --help lists all test-controls */
8182    if( strcmp(zCmd,"help")==0 ){
8183      utf8_printf(p->out, "Available test-controls:\n");
8184      for(i=0; i<ArraySize(aCtrl); i++){
8185        utf8_printf(p->out, "  .testctrl %s %s\n",
8186                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8187      }
8188      rc = 1;
8189      goto meta_command_exit;
8190    }
8191
8192    /* convert testctrl text option to value. allow any unique prefix
8193    ** of the option name, or a numerical value. */
8194    n2 = strlen30(zCmd);
8195    for(i=0; i<ArraySize(aCtrl); i++){
8196      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8197        if( testctrl<0 ){
8198          testctrl = aCtrl[i].ctrlCode;
8199          iCtrl = i;
8200        }else{
8201          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8202                              "Use \".testctrl --help\" for help\n", zCmd);
8203          rc = 1;
8204          goto meta_command_exit;
8205        }
8206      }
8207    }
8208    if( testctrl<0 ){
8209      utf8_printf(stderr,"Error: unknown test-control: %s\n"
8210                         "Use \".testctrl --help\" for help\n", zCmd);
8211    }else{
8212      switch(testctrl){
8213
8214        /* sqlite3_test_control(int, db, int) */
8215        case SQLITE_TESTCTRL_OPTIMIZATIONS:
8216        case SQLITE_TESTCTRL_RESERVE:
8217          if( nArg==3 ){
8218            int opt = (int)strtol(azArg[2], 0, 0);
8219            rc2 = sqlite3_test_control(testctrl, p->db, opt);
8220            isOk = 3;
8221          }
8222          break;
8223
8224        /* sqlite3_test_control(int) */
8225        case SQLITE_TESTCTRL_PRNG_SAVE:
8226        case SQLITE_TESTCTRL_PRNG_RESTORE:
8227        case SQLITE_TESTCTRL_PRNG_RESET:
8228        case SQLITE_TESTCTRL_BYTEORDER:
8229          if( nArg==2 ){
8230            rc2 = sqlite3_test_control(testctrl);
8231            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
8232          }
8233          break;
8234
8235        /* sqlite3_test_control(int, uint) */
8236        case SQLITE_TESTCTRL_PENDING_BYTE:
8237          if( nArg==3 ){
8238            unsigned int opt = (unsigned int)integerValue(azArg[2]);
8239            rc2 = sqlite3_test_control(testctrl, opt);
8240            isOk = 3;
8241          }
8242          break;
8243
8244        /* sqlite3_test_control(int, int) */
8245        case SQLITE_TESTCTRL_ASSERT:
8246        case SQLITE_TESTCTRL_ALWAYS:
8247        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
8248          if( nArg==3 ){
8249            int opt = booleanValue(azArg[2]);
8250            rc2 = sqlite3_test_control(testctrl, opt);
8251            isOk = 1;
8252          }
8253          break;
8254
8255        /* sqlite3_test_control(int, int) */
8256        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
8257        case SQLITE_TESTCTRL_NEVER_CORRUPT:
8258          if( nArg==3 ){
8259            int opt = booleanValue(azArg[2]);
8260            rc2 = sqlite3_test_control(testctrl, opt);
8261            isOk = 3;
8262          }
8263          break;
8264
8265        case SQLITE_TESTCTRL_IMPOSTER:
8266          if( nArg==5 ){
8267            rc2 = sqlite3_test_control(testctrl, p->db,
8268                          azArg[2],
8269                          integerValue(azArg[3]),
8270                          integerValue(azArg[4]));
8271            isOk = 3;
8272          }
8273          break;
8274
8275#ifdef YYCOVERAGE
8276        case SQLITE_TESTCTRL_PARSER_COVERAGE:
8277          if( nArg==2 ){
8278            sqlite3_test_control(testctrl, p->out);
8279            isOk = 3;
8280          }
8281#endif
8282      }
8283    }
8284    if( isOk==0 && iCtrl>=0 ){
8285      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
8286      rc = 1;
8287    }else if( isOk==1 ){
8288      raw_printf(p->out, "%d\n", rc2);
8289    }else if( isOk==2 ){
8290      raw_printf(p->out, "0x%08x\n", rc2);
8291    }
8292  }else
8293#endif /* !defined(SQLITE_UNTESTABLE) */
8294
8295  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
8296    open_db(p, 0);
8297    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
8298  }else
8299
8300  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
8301    if( nArg==2 ){
8302      enableTimer = booleanValue(azArg[1]);
8303      if( enableTimer && !HAS_TIMER ){
8304        raw_printf(stderr, "Error: timer not available on this system.\n");
8305        enableTimer = 0;
8306      }
8307    }else{
8308      raw_printf(stderr, "Usage: .timer on|off\n");
8309      rc = 1;
8310    }
8311  }else
8312
8313#ifndef SQLITE_OMIT_TRACE
8314  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
8315    int mType = 0;
8316    int jj;
8317    open_db(p, 0);
8318    for(jj=1; jj<nArg; jj++){
8319      const char *z = azArg[jj];
8320      if( z[0]=='-' ){
8321        if( optionMatch(z, "expanded") ){
8322          p->eTraceType = SHELL_TRACE_EXPANDED;
8323        }
8324#ifdef SQLITE_ENABLE_NORMALIZE
8325        else if( optionMatch(z, "normalized") ){
8326          p->eTraceType = SHELL_TRACE_NORMALIZED;
8327        }
8328#endif
8329        else if( optionMatch(z, "plain") ){
8330          p->eTraceType = SHELL_TRACE_PLAIN;
8331        }
8332        else if( optionMatch(z, "profile") ){
8333          mType |= SQLITE_TRACE_PROFILE;
8334        }
8335        else if( optionMatch(z, "row") ){
8336          mType |= SQLITE_TRACE_ROW;
8337        }
8338        else if( optionMatch(z, "stmt") ){
8339          mType |= SQLITE_TRACE_STMT;
8340        }
8341        else if( optionMatch(z, "close") ){
8342          mType |= SQLITE_TRACE_CLOSE;
8343        }
8344        else {
8345          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
8346          rc = 1;
8347          goto meta_command_exit;
8348        }
8349      }else{
8350        output_file_close(p->traceOut);
8351        p->traceOut = output_file_open(azArg[1], 0);
8352      }
8353    }
8354    if( p->traceOut==0 ){
8355      sqlite3_trace_v2(p->db, 0, 0, 0);
8356    }else{
8357      if( mType==0 ) mType = SQLITE_TRACE_STMT;
8358      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
8359    }
8360  }else
8361#endif /* !defined(SQLITE_OMIT_TRACE) */
8362
8363#if SQLITE_USER_AUTHENTICATION
8364  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
8365    if( nArg<2 ){
8366      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
8367      rc = 1;
8368      goto meta_command_exit;
8369    }
8370    open_db(p, 0);
8371    if( strcmp(azArg[1],"login")==0 ){
8372      if( nArg!=4 ){
8373        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
8374        rc = 1;
8375        goto meta_command_exit;
8376      }
8377      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
8378      if( rc ){
8379        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
8380        rc = 1;
8381      }
8382    }else if( strcmp(azArg[1],"add")==0 ){
8383      if( nArg!=5 ){
8384        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
8385        rc = 1;
8386        goto meta_command_exit;
8387      }
8388      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
8389                            booleanValue(azArg[4]));
8390      if( rc ){
8391        raw_printf(stderr, "User-Add failed: %d\n", rc);
8392        rc = 1;
8393      }
8394    }else if( strcmp(azArg[1],"edit")==0 ){
8395      if( nArg!=5 ){
8396        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
8397        rc = 1;
8398        goto meta_command_exit;
8399      }
8400      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
8401                              booleanValue(azArg[4]));
8402      if( rc ){
8403        raw_printf(stderr, "User-Edit failed: %d\n", rc);
8404        rc = 1;
8405      }
8406    }else if( strcmp(azArg[1],"delete")==0 ){
8407      if( nArg!=3 ){
8408        raw_printf(stderr, "Usage: .user delete USER\n");
8409        rc = 1;
8410        goto meta_command_exit;
8411      }
8412      rc = sqlite3_user_delete(p->db, azArg[2]);
8413      if( rc ){
8414        raw_printf(stderr, "User-Delete failed: %d\n", rc);
8415        rc = 1;
8416      }
8417    }else{
8418      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
8419      rc = 1;
8420      goto meta_command_exit;
8421    }
8422  }else
8423#endif /* SQLITE_USER_AUTHENTICATION */
8424
8425  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
8426    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
8427        sqlite3_libversion(), sqlite3_sourceid());
8428#if SQLITE_HAVE_ZLIB
8429    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
8430#endif
8431#define CTIMEOPT_VAL_(opt) #opt
8432#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
8433#if defined(__clang__) && defined(__clang_major__)
8434    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
8435                    CTIMEOPT_VAL(__clang_minor__) "."
8436                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
8437#elif defined(_MSC_VER)
8438    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
8439#elif defined(__GNUC__) && defined(__VERSION__)
8440    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
8441#endif
8442  }else
8443
8444  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
8445    const char *zDbName = nArg==2 ? azArg[1] : "main";
8446    sqlite3_vfs *pVfs = 0;
8447    if( p->db ){
8448      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
8449      if( pVfs ){
8450        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
8451        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
8452        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
8453        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8454      }
8455    }
8456  }else
8457
8458  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
8459    sqlite3_vfs *pVfs;
8460    sqlite3_vfs *pCurrent = 0;
8461    if( p->db ){
8462      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
8463    }
8464    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
8465      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
8466           pVfs==pCurrent ? "  <--- CURRENT" : "");
8467      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
8468      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
8469      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8470      if( pVfs->pNext ){
8471        raw_printf(p->out, "-----------------------------------\n");
8472      }
8473    }
8474  }else
8475
8476  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
8477    const char *zDbName = nArg==2 ? azArg[1] : "main";
8478    char *zVfsName = 0;
8479    if( p->db ){
8480      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
8481      if( zVfsName ){
8482        utf8_printf(p->out, "%s\n", zVfsName);
8483        sqlite3_free(zVfsName);
8484      }
8485    }
8486  }else
8487
8488#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
8489  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
8490    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
8491  }else
8492#endif
8493
8494  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
8495    int j;
8496    assert( nArg<=ArraySize(azArg) );
8497    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
8498      p->colWidth[j-1] = (int)integerValue(azArg[j]);
8499    }
8500  }else
8501
8502  {
8503    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
8504      " \"%s\". Enter \".help\" for help\n", azArg[0]);
8505    rc = 1;
8506  }
8507
8508meta_command_exit:
8509  if( p->outCount ){
8510    p->outCount--;
8511    if( p->outCount==0 ) output_reset(p);
8512  }
8513  return rc;
8514}
8515
8516/*
8517** Return TRUE if a semicolon occurs anywhere in the first N characters
8518** of string z[].
8519*/
8520static int line_contains_semicolon(const char *z, int N){
8521  int i;
8522  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
8523  return 0;
8524}
8525
8526/*
8527** Test to see if a line consists entirely of whitespace.
8528*/
8529static int _all_whitespace(const char *z){
8530  for(; *z; z++){
8531    if( IsSpace(z[0]) ) continue;
8532    if( *z=='/' && z[1]=='*' ){
8533      z += 2;
8534      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
8535      if( *z==0 ) return 0;
8536      z++;
8537      continue;
8538    }
8539    if( *z=='-' && z[1]=='-' ){
8540      z += 2;
8541      while( *z && *z!='\n' ){ z++; }
8542      if( *z==0 ) return 1;
8543      continue;
8544    }
8545    return 0;
8546  }
8547  return 1;
8548}
8549
8550/*
8551** Return TRUE if the line typed in is an SQL command terminator other
8552** than a semi-colon.  The SQL Server style "go" command is understood
8553** as is the Oracle "/".
8554*/
8555static int line_is_command_terminator(const char *zLine){
8556  while( IsSpace(zLine[0]) ){ zLine++; };
8557  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
8558    return 1;  /* Oracle */
8559  }
8560  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
8561         && _all_whitespace(&zLine[2]) ){
8562    return 1;  /* SQL Server */
8563  }
8564  return 0;
8565}
8566
8567/*
8568** We need a default sqlite3_complete() implementation to use in case
8569** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
8570** any arbitrary text is a complete SQL statement.  This is not very
8571** user-friendly, but it does seem to work.
8572*/
8573#ifdef SQLITE_OMIT_COMPLETE
8574#define sqlite3_complete(x) 1
8575#endif
8576
8577/*
8578** Return true if zSql is a complete SQL statement.  Return false if it
8579** ends in the middle of a string literal or C-style comment.
8580*/
8581static int line_is_complete(char *zSql, int nSql){
8582  int rc;
8583  if( zSql==0 ) return 1;
8584  zSql[nSql] = ';';
8585  zSql[nSql+1] = 0;
8586  rc = sqlite3_complete(zSql);
8587  zSql[nSql] = 0;
8588  return rc;
8589}
8590
8591/*
8592** Run a single line of SQL.  Return the number of errors.
8593*/
8594static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
8595  int rc;
8596  char *zErrMsg = 0;
8597
8598  open_db(p, 0);
8599  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
8600  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
8601  BEGIN_TIMER;
8602  rc = shell_exec(p, zSql, &zErrMsg);
8603  END_TIMER;
8604  if( rc || zErrMsg ){
8605    char zPrefix[100];
8606    if( in!=0 || !stdin_is_interactive ){
8607      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
8608                       "Error: near line %d:", startline);
8609    }else{
8610      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
8611    }
8612    if( zErrMsg!=0 ){
8613      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
8614      sqlite3_free(zErrMsg);
8615      zErrMsg = 0;
8616    }else{
8617      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
8618    }
8619    return 1;
8620  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
8621    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
8622            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
8623  }
8624  return 0;
8625}
8626
8627
8628/*
8629** Read input from *in and process it.  If *in==0 then input
8630** is interactive - the user is typing it it.  Otherwise, input
8631** is coming from a file or device.  A prompt is issued and history
8632** is saved only if input is interactive.  An interrupt signal will
8633** cause this routine to exit immediately, unless input is interactive.
8634**
8635** Return the number of errors.
8636*/
8637static int process_input(ShellState *p){
8638  char *zLine = 0;          /* A single input line */
8639  char *zSql = 0;           /* Accumulated SQL text */
8640  int nLine;                /* Length of current line */
8641  int nSql = 0;             /* Bytes of zSql[] used */
8642  int nAlloc = 0;           /* Allocated zSql[] space */
8643  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
8644  int rc;                   /* Error code */
8645  int errCnt = 0;           /* Number of errors seen */
8646  int startline = 0;        /* Line number for start of current input */
8647
8648  p->lineno = 0;
8649  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
8650    fflush(p->out);
8651    zLine = one_input_line(p->in, zLine, nSql>0);
8652    if( zLine==0 ){
8653      /* End of input */
8654      if( p->in==0 && stdin_is_interactive ) printf("\n");
8655      break;
8656    }
8657    if( seenInterrupt ){
8658      if( p->in!=0 ) break;
8659      seenInterrupt = 0;
8660    }
8661    p->lineno++;
8662    if( nSql==0 && _all_whitespace(zLine) ){
8663      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8664      continue;
8665    }
8666    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
8667      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8668      if( zLine[0]=='.' ){
8669        rc = do_meta_command(zLine, p);
8670        if( rc==2 ){ /* exit requested */
8671          break;
8672        }else if( rc ){
8673          errCnt++;
8674        }
8675      }
8676      continue;
8677    }
8678    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8679      memcpy(zLine,";",2);
8680    }
8681    nLine = strlen30(zLine);
8682    if( nSql+nLine+2>=nAlloc ){
8683      nAlloc = nSql+nLine+100;
8684      zSql = realloc(zSql, nAlloc);
8685      if( zSql==0 ) shell_out_of_memory();
8686    }
8687    nSqlPrior = nSql;
8688    if( nSql==0 ){
8689      int i;
8690      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8691      assert( nAlloc>0 && zSql!=0 );
8692      memcpy(zSql, zLine+i, nLine+1-i);
8693      startline = p->lineno;
8694      nSql = nLine-i;
8695    }else{
8696      zSql[nSql++] = '\n';
8697      memcpy(zSql+nSql, zLine, nLine+1);
8698      nSql += nLine;
8699    }
8700    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8701                && sqlite3_complete(zSql) ){
8702      errCnt += runOneSqlLine(p, zSql, p->in, startline);
8703      nSql = 0;
8704      if( p->outCount ){
8705        output_reset(p);
8706        p->outCount = 0;
8707      }else{
8708        clearTempFile(p);
8709      }
8710    }else if( nSql && _all_whitespace(zSql) ){
8711      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8712      nSql = 0;
8713    }
8714  }
8715  if( nSql && !_all_whitespace(zSql) ){
8716    errCnt += runOneSqlLine(p, zSql, p->in, startline);
8717  }
8718  free(zSql);
8719  free(zLine);
8720  return errCnt>0;
8721}
8722
8723/*
8724** Return a pathname which is the user's home directory.  A
8725** 0 return indicates an error of some kind.
8726*/
8727static char *find_home_dir(int clearFlag){
8728  static char *home_dir = NULL;
8729  if( clearFlag ){
8730    free(home_dir);
8731    home_dir = 0;
8732    return 0;
8733  }
8734  if( home_dir ) return home_dir;
8735
8736#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8737     && !defined(__RTP__) && !defined(_WRS_KERNEL)
8738  {
8739    struct passwd *pwent;
8740    uid_t uid = getuid();
8741    if( (pwent=getpwuid(uid)) != NULL) {
8742      home_dir = pwent->pw_dir;
8743    }
8744  }
8745#endif
8746
8747#if defined(_WIN32_WCE)
8748  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8749   */
8750  home_dir = "/";
8751#else
8752
8753#if defined(_WIN32) || defined(WIN32)
8754  if (!home_dir) {
8755    home_dir = getenv("USERPROFILE");
8756  }
8757#endif
8758
8759  if (!home_dir) {
8760    home_dir = getenv("HOME");
8761  }
8762
8763#if defined(_WIN32) || defined(WIN32)
8764  if (!home_dir) {
8765    char *zDrive, *zPath;
8766    int n;
8767    zDrive = getenv("HOMEDRIVE");
8768    zPath = getenv("HOMEPATH");
8769    if( zDrive && zPath ){
8770      n = strlen30(zDrive) + strlen30(zPath) + 1;
8771      home_dir = malloc( n );
8772      if( home_dir==0 ) return 0;
8773      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8774      return home_dir;
8775    }
8776    home_dir = "c:\\";
8777  }
8778#endif
8779
8780#endif /* !_WIN32_WCE */
8781
8782  if( home_dir ){
8783    int n = strlen30(home_dir) + 1;
8784    char *z = malloc( n );
8785    if( z ) memcpy(z, home_dir, n);
8786    home_dir = z;
8787  }
8788
8789  return home_dir;
8790}
8791
8792/*
8793** Read input from the file given by sqliterc_override.  Or if that
8794** parameter is NULL, take input from ~/.sqliterc
8795**
8796** Returns the number of errors.
8797*/
8798static void process_sqliterc(
8799  ShellState *p,                  /* Configuration data */
8800  const char *sqliterc_override   /* Name of config file. NULL to use default */
8801){
8802  char *home_dir = NULL;
8803  const char *sqliterc = sqliterc_override;
8804  char *zBuf = 0;
8805  FILE *inSaved = p->in;
8806  int savedLineno = p->lineno;
8807
8808  if (sqliterc == NULL) {
8809    home_dir = find_home_dir(0);
8810    if( home_dir==0 ){
8811      raw_printf(stderr, "-- warning: cannot find home directory;"
8812                      " cannot read ~/.sqliterc\n");
8813      return;
8814    }
8815    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8816    sqliterc = zBuf;
8817  }
8818  p->in = fopen(sqliterc,"rb");
8819  if( p->in ){
8820    if( stdin_is_interactive ){
8821      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8822    }
8823    process_input(p);
8824    fclose(p->in);
8825  }
8826  p->in = inSaved;
8827  p->lineno = savedLineno;
8828  sqlite3_free(zBuf);
8829}
8830
8831/*
8832** Show available command line options
8833*/
8834static const char zOptions[] =
8835#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
8836  "   -A ARGS...           run \".archive ARGS\" and exit\n"
8837#endif
8838  "   -append              append the database to the end of the file\n"
8839  "   -ascii               set output mode to 'ascii'\n"
8840  "   -bail                stop after hitting an error\n"
8841  "   -batch               force batch I/O\n"
8842  "   -column              set output mode to 'column'\n"
8843  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
8844  "   -csv                 set output mode to 'csv'\n"
8845#if defined(SQLITE_ENABLE_DESERIALIZE)
8846  "   -deserialize         open the database using sqlite3_deserialize()\n"
8847#endif
8848  "   -echo                print commands before execution\n"
8849  "   -init FILENAME       read/process named file\n"
8850  "   -[no]header          turn headers on or off\n"
8851#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8852  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
8853#endif
8854  "   -help                show this message\n"
8855  "   -html                set output mode to HTML\n"
8856  "   -interactive         force interactive I/O\n"
8857  "   -line                set output mode to 'line'\n"
8858  "   -list                set output mode to 'list'\n"
8859  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
8860#if defined(SQLITE_ENABLE_DESERIALIZE)
8861  "   -maxsize N           maximum size for a --deserialize database\n"
8862#endif
8863  "   -memtrace            trace all memory allocations and deallocations\n"
8864  "   -mmap N              default mmap size set to N\n"
8865#ifdef SQLITE_ENABLE_MULTIPLEX
8866  "   -multiplex           enable the multiplexor VFS\n"
8867#endif
8868  "   -newline SEP         set output row separator. Default: '\\n'\n"
8869  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
8870  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
8871  "   -quote               set output mode to 'quote'\n"
8872  "   -readonly            open the database read-only\n"
8873  "   -separator SEP       set output column separator. Default: '|'\n"
8874#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8875  "   -sorterref SIZE      sorter references threshold size\n"
8876#endif
8877  "   -stats               print memory stats before each finalize\n"
8878  "   -version             show SQLite version\n"
8879  "   -vfs NAME            use NAME as the default VFS\n"
8880#ifdef SQLITE_ENABLE_VFSTRACE
8881  "   -vfstrace            enable tracing of all VFS calls\n"
8882#endif
8883#ifdef SQLITE_HAVE_ZLIB
8884  "   -zip                 open the file as a ZIP Archive\n"
8885#endif
8886;
8887static void usage(int showDetail){
8888  utf8_printf(stderr,
8889      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8890      "FILENAME is the name of an SQLite database. A new database is created\n"
8891      "if the file does not previously exist.\n", Argv0);
8892  if( showDetail ){
8893    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8894  }else{
8895    raw_printf(stderr, "Use the -help option for additional information\n");
8896  }
8897  exit(1);
8898}
8899
8900/*
8901** Internal check:  Verify that the SQLite is uninitialized.  Print a
8902** error message if it is initialized.
8903*/
8904static void verify_uninitialized(void){
8905  if( sqlite3_config(-1)==SQLITE_MISUSE ){
8906    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
8907                        " initialization.\n");
8908  }
8909}
8910
8911/*
8912** Initialize the state information in data
8913*/
8914static void main_init(ShellState *data) {
8915  memset(data, 0, sizeof(*data));
8916  data->normalMode = data->cMode = data->mode = MODE_List;
8917  data->autoExplain = 1;
8918  memcpy(data->colSeparator,SEP_Column, 2);
8919  memcpy(data->rowSeparator,SEP_Row, 2);
8920  data->showHeader = 0;
8921  data->shellFlgs = SHFLG_Lookaside;
8922  verify_uninitialized();
8923  sqlite3_config(SQLITE_CONFIG_URI, 1);
8924  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8925  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8926  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8927  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
8928}
8929
8930/*
8931** Output text to the console in a font that attracts extra attention.
8932*/
8933#ifdef _WIN32
8934static void printBold(const char *zText){
8935  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8936  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8937  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8938  SetConsoleTextAttribute(out,
8939         FOREGROUND_RED|FOREGROUND_INTENSITY
8940  );
8941  printf("%s", zText);
8942  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8943}
8944#else
8945static void printBold(const char *zText){
8946  printf("\033[1m%s\033[0m", zText);
8947}
8948#endif
8949
8950/*
8951** Get the argument to an --option.  Throw an error and die if no argument
8952** is available.
8953*/
8954static char *cmdline_option_value(int argc, char **argv, int i){
8955  if( i==argc ){
8956    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8957            argv[0], argv[argc-1]);
8958    exit(1);
8959  }
8960  return argv[i];
8961}
8962
8963#ifndef SQLITE_SHELL_IS_UTF8
8964#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8965#    define SQLITE_SHELL_IS_UTF8          (0)
8966#  else
8967#    define SQLITE_SHELL_IS_UTF8          (1)
8968#  endif
8969#endif
8970
8971#if SQLITE_SHELL_IS_UTF8
8972int SQLITE_CDECL main(int argc, char **argv){
8973#else
8974int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8975  char **argv;
8976#endif
8977  char *zErrMsg = 0;
8978  ShellState data;
8979  const char *zInitFile = 0;
8980  int i;
8981  int rc = 0;
8982  int warnInmemoryDb = 0;
8983  int readStdin = 1;
8984  int nCmd = 0;
8985  char **azCmd = 0;
8986  const char *zVfs = 0;           /* Value of -vfs command-line option */
8987#if !SQLITE_SHELL_IS_UTF8
8988  char **argvToFree = 0;
8989  int argcToFree = 0;
8990#endif
8991
8992  setBinaryMode(stdin, 0);
8993  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8994  stdin_is_interactive = isatty(0);
8995  stdout_is_console = isatty(1);
8996
8997#if !defined(_WIN32_WCE)
8998  if( getenv("SQLITE_DEBUG_BREAK") ){
8999    if( isatty(0) && isatty(2) ){
9000      fprintf(stderr,
9001          "attach debugger to process %d and press any key to continue.\n",
9002          GETPID());
9003      fgetc(stdin);
9004    }else{
9005#if defined(_WIN32) || defined(WIN32)
9006      DebugBreak();
9007#elif defined(SIGTRAP)
9008      raise(SIGTRAP);
9009#endif
9010    }
9011  }
9012#endif
9013
9014#if USE_SYSTEM_SQLITE+0!=1
9015  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
9016    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
9017            sqlite3_sourceid(), SQLITE_SOURCE_ID);
9018    exit(1);
9019  }
9020#endif
9021  main_init(&data);
9022
9023  /* On Windows, we must translate command-line arguments into UTF-8.
9024  ** The SQLite memory allocator subsystem has to be enabled in order to
9025  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
9026  ** subsequent sqlite3_config() calls will work.  So copy all results into
9027  ** memory that does not come from the SQLite memory allocator.
9028  */
9029#if !SQLITE_SHELL_IS_UTF8
9030  sqlite3_initialize();
9031  argvToFree = malloc(sizeof(argv[0])*argc*2);
9032  argcToFree = argc;
9033  argv = argvToFree + argc;
9034  if( argv==0 ) shell_out_of_memory();
9035  for(i=0; i<argc; i++){
9036    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
9037    int n;
9038    if( z==0 ) shell_out_of_memory();
9039    n = (int)strlen(z);
9040    argv[i] = malloc( n+1 );
9041    if( argv[i]==0 ) shell_out_of_memory();
9042    memcpy(argv[i], z, n+1);
9043    argvToFree[i] = argv[i];
9044    sqlite3_free(z);
9045  }
9046  sqlite3_shutdown();
9047#endif
9048
9049  assert( argc>=1 && argv && argv[0] );
9050  Argv0 = argv[0];
9051
9052  /* Make sure we have a valid signal handler early, before anything
9053  ** else is done.
9054  */
9055#ifdef SIGINT
9056  signal(SIGINT, interrupt_handler);
9057#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9058  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
9059#endif
9060
9061#ifdef SQLITE_SHELL_DBNAME_PROC
9062  {
9063    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
9064    ** of a C-function that will provide the name of the database file.  Use
9065    ** this compile-time option to embed this shell program in larger
9066    ** applications. */
9067    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
9068    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
9069    warnInmemoryDb = 0;
9070  }
9071#endif
9072
9073  /* Do an initial pass through the command-line argument to locate
9074  ** the name of the database file, the name of the initialization file,
9075  ** the size of the alternative malloc heap,
9076  ** and the first command to execute.
9077  */
9078  verify_uninitialized();
9079  for(i=1; i<argc; i++){
9080    char *z;
9081    z = argv[i];
9082    if( z[0]!='-' ){
9083      if( data.zDbFilename==0 ){
9084        data.zDbFilename = z;
9085      }else{
9086        /* Excesss arguments are interpreted as SQL (or dot-commands) and
9087        ** mean that nothing is read from stdin */
9088        readStdin = 0;
9089        nCmd++;
9090        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
9091        if( azCmd==0 ) shell_out_of_memory();
9092        azCmd[nCmd-1] = z;
9093      }
9094    }
9095    if( z[1]=='-' ) z++;
9096    if( strcmp(z,"-separator")==0
9097     || strcmp(z,"-nullvalue")==0
9098     || strcmp(z,"-newline")==0
9099     || strcmp(z,"-cmd")==0
9100    ){
9101      (void)cmdline_option_value(argc, argv, ++i);
9102    }else if( strcmp(z,"-init")==0 ){
9103      zInitFile = cmdline_option_value(argc, argv, ++i);
9104    }else if( strcmp(z,"-batch")==0 ){
9105      /* Need to check for batch mode here to so we can avoid printing
9106      ** informational messages (like from process_sqliterc) before
9107      ** we do the actual processing of arguments later in a second pass.
9108      */
9109      stdin_is_interactive = 0;
9110    }else if( strcmp(z,"-heap")==0 ){
9111#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9112      const char *zSize;
9113      sqlite3_int64 szHeap;
9114
9115      zSize = cmdline_option_value(argc, argv, ++i);
9116      szHeap = integerValue(zSize);
9117      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
9118      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
9119#else
9120      (void)cmdline_option_value(argc, argv, ++i);
9121#endif
9122    }else if( strcmp(z,"-pagecache")==0 ){
9123      int n, sz;
9124      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9125      if( sz>70000 ) sz = 70000;
9126      if( sz<0 ) sz = 0;
9127      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9128      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
9129                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
9130      data.shellFlgs |= SHFLG_Pagecache;
9131    }else if( strcmp(z,"-lookaside")==0 ){
9132      int n, sz;
9133      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9134      if( sz<0 ) sz = 0;
9135      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9136      if( n<0 ) n = 0;
9137      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
9138      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
9139#ifdef SQLITE_ENABLE_VFSTRACE
9140    }else if( strcmp(z,"-vfstrace")==0 ){
9141      extern int vfstrace_register(
9142         const char *zTraceName,
9143         const char *zOldVfsName,
9144         int (*xOut)(const char*,void*),
9145         void *pOutArg,
9146         int makeDefault
9147      );
9148      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
9149#endif
9150#ifdef SQLITE_ENABLE_MULTIPLEX
9151    }else if( strcmp(z,"-multiplex")==0 ){
9152      extern int sqlite3_multiple_initialize(const char*,int);
9153      sqlite3_multiplex_initialize(0, 1);
9154#endif
9155    }else if( strcmp(z,"-mmap")==0 ){
9156      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9157      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
9158#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9159    }else if( strcmp(z,"-sorterref")==0 ){
9160      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9161      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
9162#endif
9163    }else if( strcmp(z,"-vfs")==0 ){
9164      zVfs = cmdline_option_value(argc, argv, ++i);
9165#ifdef SQLITE_HAVE_ZLIB
9166    }else if( strcmp(z,"-zip")==0 ){
9167      data.openMode = SHELL_OPEN_ZIPFILE;
9168#endif
9169    }else if( strcmp(z,"-append")==0 ){
9170      data.openMode = SHELL_OPEN_APPENDVFS;
9171#ifdef SQLITE_ENABLE_DESERIALIZE
9172    }else if( strcmp(z,"-deserialize")==0 ){
9173      data.openMode = SHELL_OPEN_DESERIALIZE;
9174    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9175      data.szMax = integerValue(argv[++i]);
9176#endif
9177    }else if( strcmp(z,"-readonly")==0 ){
9178      data.openMode = SHELL_OPEN_READONLY;
9179#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
9180    }else if( strncmp(z, "-A",2)==0 ){
9181      /* All remaining command-line arguments are passed to the ".archive"
9182      ** command, so ignore them */
9183      break;
9184#endif
9185    }else if( strcmp(z, "-memtrace")==0 ){
9186      sqlite3MemTraceActivate(stderr);
9187    }
9188  }
9189  verify_uninitialized();
9190
9191
9192#ifdef SQLITE_SHELL_INIT_PROC
9193  {
9194    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9195    ** of a C-function that will perform initialization actions on SQLite that
9196    ** occur just before or after sqlite3_initialize(). Use this compile-time
9197    ** option to embed this shell program in larger applications. */
9198    extern void SQLITE_SHELL_INIT_PROC(void);
9199    SQLITE_SHELL_INIT_PROC();
9200  }
9201#else
9202  /* All the sqlite3_config() calls have now been made. So it is safe
9203  ** to call sqlite3_initialize() and process any command line -vfs option. */
9204  sqlite3_initialize();
9205#endif
9206
9207  if( zVfs ){
9208    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9209    if( pVfs ){
9210      sqlite3_vfs_register(pVfs, 1);
9211    }else{
9212      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9213      exit(1);
9214    }
9215  }
9216
9217  if( data.zDbFilename==0 ){
9218#ifndef SQLITE_OMIT_MEMORYDB
9219    data.zDbFilename = ":memory:";
9220    warnInmemoryDb = argc==1;
9221#else
9222    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9223    return 1;
9224#endif
9225  }
9226  data.out = stdout;
9227  sqlite3_appendvfs_init(0,0,0);
9228
9229  /* Go ahead and open the database file if it already exists.  If the
9230  ** file does not exist, delay opening it.  This prevents empty database
9231  ** files from being created if a user mistypes the database name argument
9232  ** to the sqlite command-line tool.
9233  */
9234  if( access(data.zDbFilename, 0)==0 ){
9235    open_db(&data, 0);
9236  }
9237
9238  /* Process the initialization file if there is one.  If no -init option
9239  ** is given on the command line, look for a file named ~/.sqliterc and
9240  ** try to process it.
9241  */
9242  process_sqliterc(&data,zInitFile);
9243
9244  /* Make a second pass through the command-line argument and set
9245  ** options.  This second pass is delayed until after the initialization
9246  ** file is processed so that the command-line arguments will override
9247  ** settings in the initialization file.
9248  */
9249  for(i=1; i<argc; i++){
9250    char *z = argv[i];
9251    if( z[0]!='-' ) continue;
9252    if( z[1]=='-' ){ z++; }
9253    if( strcmp(z,"-init")==0 ){
9254      i++;
9255    }else if( strcmp(z,"-html")==0 ){
9256      data.mode = MODE_Html;
9257    }else if( strcmp(z,"-list")==0 ){
9258      data.mode = MODE_List;
9259    }else if( strcmp(z,"-quote")==0 ){
9260      data.mode = MODE_Quote;
9261    }else if( strcmp(z,"-line")==0 ){
9262      data.mode = MODE_Line;
9263    }else if( strcmp(z,"-column")==0 ){
9264      data.mode = MODE_Column;
9265    }else if( strcmp(z,"-csv")==0 ){
9266      data.mode = MODE_Csv;
9267      memcpy(data.colSeparator,",",2);
9268#ifdef SQLITE_HAVE_ZLIB
9269    }else if( strcmp(z,"-zip")==0 ){
9270      data.openMode = SHELL_OPEN_ZIPFILE;
9271#endif
9272    }else if( strcmp(z,"-append")==0 ){
9273      data.openMode = SHELL_OPEN_APPENDVFS;
9274#ifdef SQLITE_ENABLE_DESERIALIZE
9275    }else if( strcmp(z,"-deserialize")==0 ){
9276      data.openMode = SHELL_OPEN_DESERIALIZE;
9277    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9278      data.szMax = integerValue(argv[++i]);
9279#endif
9280    }else if( strcmp(z,"-readonly")==0 ){
9281      data.openMode = SHELL_OPEN_READONLY;
9282    }else if( strcmp(z,"-ascii")==0 ){
9283      data.mode = MODE_Ascii;
9284      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9285                       SEP_Unit);
9286      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9287                       SEP_Record);
9288    }else if( strcmp(z,"-separator")==0 ){
9289      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9290                       "%s",cmdline_option_value(argc,argv,++i));
9291    }else if( strcmp(z,"-newline")==0 ){
9292      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9293                       "%s",cmdline_option_value(argc,argv,++i));
9294    }else if( strcmp(z,"-nullvalue")==0 ){
9295      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
9296                       "%s",cmdline_option_value(argc,argv,++i));
9297    }else if( strcmp(z,"-header")==0 ){
9298      data.showHeader = 1;
9299    }else if( strcmp(z,"-noheader")==0 ){
9300      data.showHeader = 0;
9301    }else if( strcmp(z,"-echo")==0 ){
9302      ShellSetFlag(&data, SHFLG_Echo);
9303    }else if( strcmp(z,"-eqp")==0 ){
9304      data.autoEQP = AUTOEQP_on;
9305    }else if( strcmp(z,"-eqpfull")==0 ){
9306      data.autoEQP = AUTOEQP_full;
9307    }else if( strcmp(z,"-stats")==0 ){
9308      data.statsOn = 1;
9309    }else if( strcmp(z,"-scanstats")==0 ){
9310      data.scanstatsOn = 1;
9311    }else if( strcmp(z,"-backslash")==0 ){
9312      /* Undocumented command-line option: -backslash
9313      ** Causes C-style backslash escapes to be evaluated in SQL statements
9314      ** prior to sending the SQL into SQLite.  Useful for injecting
9315      ** crazy bytes in the middle of SQL statements for testing and debugging.
9316      */
9317      ShellSetFlag(&data, SHFLG_Backslash);
9318    }else if( strcmp(z,"-bail")==0 ){
9319      bail_on_error = 1;
9320    }else if( strcmp(z,"-version")==0 ){
9321      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
9322      return 0;
9323    }else if( strcmp(z,"-interactive")==0 ){
9324      stdin_is_interactive = 1;
9325    }else if( strcmp(z,"-batch")==0 ){
9326      stdin_is_interactive = 0;
9327    }else if( strcmp(z,"-heap")==0 ){
9328      i++;
9329    }else if( strcmp(z,"-pagecache")==0 ){
9330      i+=2;
9331    }else if( strcmp(z,"-lookaside")==0 ){
9332      i+=2;
9333    }else if( strcmp(z,"-mmap")==0 ){
9334      i++;
9335    }else if( strcmp(z,"-memtrace")==0 ){
9336      i++;
9337#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9338    }else if( strcmp(z,"-sorterref")==0 ){
9339      i++;
9340#endif
9341    }else if( strcmp(z,"-vfs")==0 ){
9342      i++;
9343#ifdef SQLITE_ENABLE_VFSTRACE
9344    }else if( strcmp(z,"-vfstrace")==0 ){
9345      i++;
9346#endif
9347#ifdef SQLITE_ENABLE_MULTIPLEX
9348    }else if( strcmp(z,"-multiplex")==0 ){
9349      i++;
9350#endif
9351    }else if( strcmp(z,"-help")==0 ){
9352      usage(1);
9353    }else if( strcmp(z,"-cmd")==0 ){
9354      /* Run commands that follow -cmd first and separately from commands
9355      ** that simply appear on the command-line.  This seems goofy.  It would
9356      ** be better if all commands ran in the order that they appear.  But
9357      ** we retain the goofy behavior for historical compatibility. */
9358      if( i==argc-1 ) break;
9359      z = cmdline_option_value(argc,argv,++i);
9360      if( z[0]=='.' ){
9361        rc = do_meta_command(z, &data);
9362        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
9363      }else{
9364        open_db(&data, 0);
9365        rc = shell_exec(&data, z, &zErrMsg);
9366        if( zErrMsg!=0 ){
9367          utf8_printf(stderr,"Error: %s\n", zErrMsg);
9368          if( bail_on_error ) return rc!=0 ? rc : 1;
9369        }else if( rc!=0 ){
9370          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
9371          if( bail_on_error ) return rc;
9372        }
9373      }
9374#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
9375    }else if( strncmp(z, "-A", 2)==0 ){
9376      if( nCmd>0 ){
9377        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
9378                            " with \"%s\"\n", z);
9379        return 1;
9380      }
9381      open_db(&data, OPEN_DB_ZIPFILE);
9382      if( z[2] ){
9383        argv[i] = &z[2];
9384        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
9385      }else{
9386        arDotCommand(&data, 1, argv+i, argc-i);
9387      }
9388      readStdin = 0;
9389      break;
9390#endif
9391    }else{
9392      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
9393      raw_printf(stderr,"Use -help for a list of options.\n");
9394      return 1;
9395    }
9396    data.cMode = data.mode;
9397  }
9398
9399  if( !readStdin ){
9400    /* Run all arguments that do not begin with '-' as if they were separate
9401    ** command-line inputs, except for the argToSkip argument which contains
9402    ** the database filename.
9403    */
9404    for(i=0; i<nCmd; i++){
9405      if( azCmd[i][0]=='.' ){
9406        rc = do_meta_command(azCmd[i], &data);
9407        if( rc ) return rc==2 ? 0 : rc;
9408      }else{
9409        open_db(&data, 0);
9410        rc = shell_exec(&data, azCmd[i], &zErrMsg);
9411        if( zErrMsg!=0 ){
9412          utf8_printf(stderr,"Error: %s\n", zErrMsg);
9413          return rc!=0 ? rc : 1;
9414        }else if( rc!=0 ){
9415          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
9416          return rc;
9417        }
9418      }
9419    }
9420    free(azCmd);
9421  }else{
9422    /* Run commands received from standard input
9423    */
9424    if( stdin_is_interactive ){
9425      char *zHome;
9426      char *zHistory;
9427      int nHistory;
9428      printf(
9429        "SQLite version %s %.19s\n" /*extra-version-info*/
9430        "Enter \".help\" for usage hints.\n",
9431        sqlite3_libversion(), sqlite3_sourceid()
9432      );
9433      if( warnInmemoryDb ){
9434        printf("Connected to a ");
9435        printBold("transient in-memory database");
9436        printf(".\nUse \".open FILENAME\" to reopen on a "
9437               "persistent database.\n");
9438      }
9439      zHistory = getenv("SQLITE_HISTORY");
9440      if( zHistory ){
9441        zHistory = strdup(zHistory);
9442      }else if( (zHome = find_home_dir(0))!=0 ){
9443        nHistory = strlen30(zHome) + 20;
9444        if( (zHistory = malloc(nHistory))!=0 ){
9445          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
9446        }
9447      }
9448      if( zHistory ){ shell_read_history(zHistory); }
9449#if HAVE_READLINE || HAVE_EDITLINE
9450      rl_attempted_completion_function = readline_completion;
9451#elif HAVE_LINENOISE
9452      linenoiseSetCompletionCallback(linenoise_completion);
9453#endif
9454      data.in = 0;
9455      rc = process_input(&data);
9456      if( zHistory ){
9457        shell_stifle_history(2000);
9458        shell_write_history(zHistory);
9459        free(zHistory);
9460      }
9461    }else{
9462      data.in = stdin;
9463      rc = process_input(&data);
9464    }
9465  }
9466  set_table_name(&data, 0);
9467  if( data.db ){
9468    session_close_all(&data);
9469    close_db(data.db);
9470  }
9471  sqlite3_free(data.zFreeOnClose);
9472  find_home_dir(1);
9473  output_reset(&data);
9474  data.doXdgOpen = 0;
9475  clearTempFile(&data);
9476#if !SQLITE_SHELL_IS_UTF8
9477  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
9478  free(argvToFree);
9479#endif
9480  /* Clear the global data structure so that valgrind will detect memory
9481  ** leaks */
9482  memset(&data, 0, sizeof(data));
9483  return rc;
9484}
9485