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