xref: /sqlite-3.40.0/src/shell.c.in (revision f71a243a)
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  ".vfsinfo ?AUX?           Information about the top-level VFS",
3653  ".vfslist                 List all available VFSes",
3654  ".vfsname ?AUX?           Print the name of the VFS stack",
3655  ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
3656  "     Negative values right-justify",
3657};
3658
3659/*
3660** Output help text.
3661**
3662** zPattern describes the set of commands for which help text is provided.
3663** If zPattern is NULL, then show all commands, but only give a one-line
3664** description of each.
3665**
3666** Return the number of matches.
3667*/
3668static int showHelp(FILE *out, const char *zPattern){
3669  int i = 0;
3670  int j = 0;
3671  int n = 0;
3672  char *zPat;
3673  if( zPattern==0
3674   || zPattern[0]=='0'
3675   || strcmp(zPattern,"-a")==0
3676   || strcmp(zPattern,"-all")==0
3677  ){
3678    /* Show all commands, but only one line per command */
3679    if( zPattern==0 ) zPattern = "";
3680    for(i=0; i<ArraySize(azHelp); i++){
3681      if( azHelp[i][0]=='.' || zPattern[0] ){
3682        utf8_printf(out, "%s\n", azHelp[i]);
3683        n++;
3684      }
3685    }
3686  }else{
3687    /* Look for commands that for which zPattern is an exact prefix */
3688    zPat = sqlite3_mprintf(".%s*", zPattern);
3689    for(i=0; i<ArraySize(azHelp); i++){
3690      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3691        utf8_printf(out, "%s\n", azHelp[i]);
3692        j = i+1;
3693        n++;
3694      }
3695    }
3696    sqlite3_free(zPat);
3697    if( n ){
3698      if( n==1 ){
3699        /* when zPattern is a prefix of exactly one command, then include the
3700        ** details of that command, which should begin at offset j */
3701        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3702          utf8_printf(out, "%s\n", azHelp[j]);
3703          j++;
3704        }
3705      }
3706      return n;
3707    }
3708    /* Look for commands that contain zPattern anywhere.  Show the complete
3709    ** text of all commands that match. */
3710    zPat = sqlite3_mprintf("%%%s%%", zPattern);
3711    for(i=0; i<ArraySize(azHelp); i++){
3712      if( azHelp[i][0]=='.' ) j = i;
3713      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3714        utf8_printf(out, "%s\n", azHelp[j]);
3715        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3716          j++;
3717          utf8_printf(out, "%s\n", azHelp[j]);
3718        }
3719        i = j;
3720        n++;
3721      }
3722    }
3723    sqlite3_free(zPat);
3724  }
3725  return n;
3726}
3727
3728/* Forward reference */
3729static int process_input(ShellState *p);
3730
3731/*
3732** Read the content of file zName into memory obtained from sqlite3_malloc64()
3733** and return a pointer to the buffer. The caller is responsible for freeing
3734** the memory.
3735**
3736** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3737** read.
3738**
3739** For convenience, a nul-terminator byte is always appended to the data read
3740** from the file before the buffer is returned. This byte is not included in
3741** the final value of (*pnByte), if applicable.
3742**
3743** NULL is returned if any error is encountered. The final value of *pnByte
3744** is undefined in this case.
3745*/
3746static char *readFile(const char *zName, int *pnByte){
3747  FILE *in = fopen(zName, "rb");
3748  long nIn;
3749  size_t nRead;
3750  char *pBuf;
3751  if( in==0 ) return 0;
3752  fseek(in, 0, SEEK_END);
3753  nIn = ftell(in);
3754  rewind(in);
3755  pBuf = sqlite3_malloc64( nIn+1 );
3756  if( pBuf==0 ){ fclose(in); return 0; }
3757  nRead = fread(pBuf, nIn, 1, in);
3758  fclose(in);
3759  if( nRead!=1 ){
3760    sqlite3_free(pBuf);
3761    return 0;
3762  }
3763  pBuf[nIn] = 0;
3764  if( pnByte ) *pnByte = nIn;
3765  return pBuf;
3766}
3767
3768#if defined(SQLITE_ENABLE_SESSION)
3769/*
3770** Close a single OpenSession object and release all of its associated
3771** resources.
3772*/
3773static void session_close(OpenSession *pSession){
3774  int i;
3775  sqlite3session_delete(pSession->p);
3776  sqlite3_free(pSession->zName);
3777  for(i=0; i<pSession->nFilter; i++){
3778    sqlite3_free(pSession->azFilter[i]);
3779  }
3780  sqlite3_free(pSession->azFilter);
3781  memset(pSession, 0, sizeof(OpenSession));
3782}
3783#endif
3784
3785/*
3786** Close all OpenSession objects and release all associated resources.
3787*/
3788#if defined(SQLITE_ENABLE_SESSION)
3789static void session_close_all(ShellState *p){
3790  int i;
3791  for(i=0; i<p->nSession; i++){
3792    session_close(&p->aSession[i]);
3793  }
3794  p->nSession = 0;
3795}
3796#else
3797# define session_close_all(X)
3798#endif
3799
3800/*
3801** Implementation of the xFilter function for an open session.  Omit
3802** any tables named by ".session filter" but let all other table through.
3803*/
3804#if defined(SQLITE_ENABLE_SESSION)
3805static int session_filter(void *pCtx, const char *zTab){
3806  OpenSession *pSession = (OpenSession*)pCtx;
3807  int i;
3808  for(i=0; i<pSession->nFilter; i++){
3809    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3810  }
3811  return 1;
3812}
3813#endif
3814
3815/*
3816** Try to deduce the type of file for zName based on its content.  Return
3817** one of the SHELL_OPEN_* constants.
3818**
3819** If the file does not exist or is empty but its name looks like a ZIP
3820** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3821** Otherwise, assume an ordinary database regardless of the filename if
3822** the type cannot be determined from content.
3823*/
3824int deduceDatabaseType(const char *zName, int dfltZip){
3825  FILE *f = fopen(zName, "rb");
3826  size_t n;
3827  int rc = SHELL_OPEN_UNSPEC;
3828  char zBuf[100];
3829  if( f==0 ){
3830    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3831       return SHELL_OPEN_ZIPFILE;
3832    }else{
3833       return SHELL_OPEN_NORMAL;
3834    }
3835  }
3836  n = fread(zBuf, 16, 1, f);
3837  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3838    fclose(f);
3839    return SHELL_OPEN_NORMAL;
3840  }
3841  fseek(f, -25, SEEK_END);
3842  n = fread(zBuf, 25, 1, f);
3843  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3844    rc = SHELL_OPEN_APPENDVFS;
3845  }else{
3846    fseek(f, -22, SEEK_END);
3847    n = fread(zBuf, 22, 1, f);
3848    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3849       && zBuf[3]==0x06 ){
3850      rc = SHELL_OPEN_ZIPFILE;
3851    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3852      rc = SHELL_OPEN_ZIPFILE;
3853    }
3854  }
3855  fclose(f);
3856  return rc;
3857}
3858
3859#ifdef SQLITE_ENABLE_DESERIALIZE
3860/*
3861** Reconstruct an in-memory database using the output from the "dbtotxt"
3862** program.  Read content from the file in p->zDbFilename.  If p->zDbFilename
3863** is 0, then read from standard input.
3864*/
3865static unsigned char *readHexDb(ShellState *p, int *pnData){
3866  unsigned char *a = 0;
3867  int nLine;
3868  int n = 0;
3869  int pgsz = 0;
3870  int iOffset = 0;
3871  int j, k;
3872  int rc;
3873  FILE *in;
3874  unsigned int x[16];
3875  char zLine[1000];
3876  if( p->zDbFilename ){
3877    in = fopen(p->zDbFilename, "r");
3878    if( in==0 ){
3879      utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3880      return 0;
3881    }
3882    nLine = 0;
3883  }else{
3884    in = p->in;
3885    nLine = p->lineno;
3886    if( in==0 ) in = stdin;
3887  }
3888  *pnData = 0;
3889  nLine++;
3890  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3891  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3892  if( rc!=2 ) goto readHexDb_error;
3893  if( n<0 ) goto readHexDb_error;
3894  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
3895  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
3896  a = sqlite3_malloc( n ? n : 1 );
3897  if( a==0 ){
3898    utf8_printf(stderr, "Out of memory!\n");
3899    goto readHexDb_error;
3900  }
3901  memset(a, 0, n);
3902  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3903    utf8_printf(stderr, "invalid pagesize\n");
3904    goto readHexDb_error;
3905  }
3906  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
3907    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3908    if( rc==2 ){
3909      iOffset = k;
3910      continue;
3911    }
3912    if( strncmp(zLine, "| end ", 6)==0 ){
3913      break;
3914    }
3915    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
3916                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3917                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3918    if( rc==17 ){
3919      k = iOffset+j;
3920      if( k+16<=n ){
3921        int ii;
3922        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
3923      }
3924    }
3925  }
3926  *pnData = n;
3927  if( in!=p->in ){
3928    fclose(in);
3929  }else{
3930    p->lineno = nLine;
3931  }
3932  return a;
3933
3934readHexDb_error:
3935  if( in!=p->in ){
3936    fclose(in);
3937  }else{
3938    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
3939      nLine++;
3940      if(strncmp(zLine, "| end ", 6)==0 ) break;
3941    }
3942    p->lineno = nLine;
3943  }
3944  sqlite3_free(a);
3945  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3946  return 0;
3947}
3948#endif /* SQLITE_ENABLE_DESERIALIZE */
3949
3950/*
3951** Scalar function "shell_int32". The first argument to this function
3952** must be a blob. The second a non-negative integer. This function
3953** reads and returns a 32-bit big-endian integer from byte
3954** offset (4*<arg2>) of the blob.
3955*/
3956static void shellInt32(
3957  sqlite3_context *context,
3958  int argc,
3959  sqlite3_value **argv
3960){
3961  const unsigned char *pBlob;
3962  int nBlob;
3963  int iInt;
3964
3965  UNUSED_PARAMETER(argc);
3966  nBlob = sqlite3_value_bytes(argv[0]);
3967  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
3968  iInt = sqlite3_value_int(argv[1]);
3969
3970  if( iInt>=0 && (iInt+1)*4<=nBlob ){
3971    const unsigned char *a = &pBlob[iInt*4];
3972    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
3973                       + ((sqlite3_int64)a[1]<<16)
3974                       + ((sqlite3_int64)a[2]<< 8)
3975                       + ((sqlite3_int64)a[3]<< 0);
3976    sqlite3_result_int64(context, iVal);
3977  }
3978}
3979
3980/*
3981** Scalar function "shell_escape_crnl" used by the .recover command.
3982** The argument passed to this function is the output of built-in
3983** function quote(). If the first character of the input is "'",
3984** indicating that the value passed to quote() was a text value,
3985** then this function searches the input for "\n" and "\r" characters
3986** and adds a wrapper similar to the following:
3987**
3988**   replace(replace(<input>, '\n', char(10), '\r', char(13));
3989**
3990** Or, if the first character of the input is not "'", then a copy
3991** of the input is returned.
3992*/
3993static void shellEscapeCrnl(
3994  sqlite3_context *context,
3995  int argc,
3996  sqlite3_value **argv
3997){
3998  const char *zText = (const char*)sqlite3_value_text(argv[0]);
3999  UNUSED_PARAMETER(argc);
4000  if( zText[0]=='\'' ){
4001    int nText = sqlite3_value_bytes(argv[0]);
4002    int i;
4003    char zBuf1[20];
4004    char zBuf2[20];
4005    const char *zNL = 0;
4006    const char *zCR = 0;
4007    int nCR = 0;
4008    int nNL = 0;
4009
4010    for(i=0; zText[i]; i++){
4011      if( zNL==0 && zText[i]=='\n' ){
4012        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4013        nNL = (int)strlen(zNL);
4014      }
4015      if( zCR==0 && zText[i]=='\r' ){
4016        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4017        nCR = (int)strlen(zCR);
4018      }
4019    }
4020
4021    if( zNL || zCR ){
4022      int iOut = 0;
4023      i64 nMax = (nNL > nCR) ? nNL : nCR;
4024      i64 nAlloc = nMax * nText + (nMax+64)*2;
4025      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4026      if( zOut==0 ){
4027        sqlite3_result_error_nomem(context);
4028        return;
4029      }
4030
4031      if( zNL && zCR ){
4032        memcpy(&zOut[iOut], "replace(replace(", 16);
4033        iOut += 16;
4034      }else{
4035        memcpy(&zOut[iOut], "replace(", 8);
4036        iOut += 8;
4037      }
4038      for(i=0; zText[i]; i++){
4039        if( zText[i]=='\n' ){
4040          memcpy(&zOut[iOut], zNL, nNL);
4041          iOut += nNL;
4042        }else if( zText[i]=='\r' ){
4043          memcpy(&zOut[iOut], zCR, nCR);
4044          iOut += nCR;
4045        }else{
4046          zOut[iOut] = zText[i];
4047          iOut++;
4048        }
4049      }
4050
4051      if( zNL ){
4052        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4053        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4054        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4055      }
4056      if( zCR ){
4057        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4058        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4059        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4060      }
4061
4062      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4063      sqlite3_free(zOut);
4064      return;
4065    }
4066  }
4067
4068  sqlite3_result_value(context, argv[0]);
4069}
4070
4071/* Flags for open_db().
4072**
4073** The default behavior of open_db() is to exit(1) if the database fails to
4074** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4075** but still returns without calling exit.
4076**
4077** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4078** ZIP archive if the file does not exist or is empty and its name matches
4079** the *.zip pattern.
4080*/
4081#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4082#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4083
4084/*
4085** Make sure the database is open.  If it is not, then open it.  If
4086** the database fails to open, print an error message and exit.
4087*/
4088static void open_db(ShellState *p, int openFlags){
4089  if( p->db==0 ){
4090    if( p->openMode==SHELL_OPEN_UNSPEC ){
4091      if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4092        p->openMode = SHELL_OPEN_NORMAL;
4093      }else{
4094        p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4095                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4096      }
4097    }
4098    switch( p->openMode ){
4099      case SHELL_OPEN_APPENDVFS: {
4100        sqlite3_open_v2(p->zDbFilename, &p->db,
4101           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
4102        break;
4103      }
4104      case SHELL_OPEN_HEXDB:
4105      case SHELL_OPEN_DESERIALIZE: {
4106        sqlite3_open(0, &p->db);
4107        break;
4108      }
4109      case SHELL_OPEN_ZIPFILE: {
4110        sqlite3_open(":memory:", &p->db);
4111        break;
4112      }
4113      case SHELL_OPEN_READONLY: {
4114        sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
4115        break;
4116      }
4117      case SHELL_OPEN_UNSPEC:
4118      case SHELL_OPEN_NORMAL: {
4119        sqlite3_open(p->zDbFilename, &p->db);
4120        break;
4121      }
4122    }
4123    globalDb = p->db;
4124    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4125      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4126          p->zDbFilename, sqlite3_errmsg(p->db));
4127      if( openFlags & OPEN_DB_KEEPALIVE ){
4128        sqlite3_open(":memory:", &p->db);
4129        return;
4130      }
4131      exit(1);
4132    }
4133#ifndef SQLITE_OMIT_LOAD_EXTENSION
4134    sqlite3_enable_load_extension(p->db, 1);
4135#endif
4136    sqlite3_fileio_init(p->db, 0, 0);
4137    sqlite3_shathree_init(p->db, 0, 0);
4138    sqlite3_completion_init(p->db, 0, 0);
4139#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4140    sqlite3_dbdata_init(p->db, 0, 0);
4141#endif
4142#ifdef SQLITE_HAVE_ZLIB
4143    sqlite3_zipfile_init(p->db, 0, 0);
4144    sqlite3_sqlar_init(p->db, 0, 0);
4145#endif
4146    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4147                            shellAddSchemaName, 0, 0);
4148    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4149                            shellModuleSchema, 0, 0);
4150    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4151                            shellPutsFunc, 0, 0);
4152    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4153                            shellEscapeCrnl, 0, 0);
4154    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4155                            shellInt32, 0, 0);
4156#ifndef SQLITE_NOHAVE_SYSTEM
4157    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4158                            editFunc, 0, 0);
4159    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4160                            editFunc, 0, 0);
4161#endif
4162    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4163      char *zSql = sqlite3_mprintf(
4164         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4165      sqlite3_exec(p->db, zSql, 0, 0, 0);
4166      sqlite3_free(zSql);
4167    }
4168#ifdef SQLITE_ENABLE_DESERIALIZE
4169    else
4170    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4171      int rc;
4172      int nData = 0;
4173      unsigned char *aData;
4174      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4175        aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4176      }else{
4177        aData = readHexDb(p, &nData);
4178        if( aData==0 ){
4179          return;
4180        }
4181      }
4182      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4183                   SQLITE_DESERIALIZE_RESIZEABLE |
4184                   SQLITE_DESERIALIZE_FREEONCLOSE);
4185      if( rc ){
4186        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4187      }
4188      if( p->szMax>0 ){
4189        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4190      }
4191    }
4192#endif
4193  }
4194}
4195
4196/*
4197** Attempt to close the databaes connection.  Report errors.
4198*/
4199void close_db(sqlite3 *db){
4200  int rc = sqlite3_close(db);
4201  if( rc ){
4202    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4203        rc, sqlite3_errmsg(db));
4204  }
4205}
4206
4207#if HAVE_READLINE || HAVE_EDITLINE
4208/*
4209** Readline completion callbacks
4210*/
4211static char *readline_completion_generator(const char *text, int state){
4212  static sqlite3_stmt *pStmt = 0;
4213  char *zRet;
4214  if( state==0 ){
4215    char *zSql;
4216    sqlite3_finalize(pStmt);
4217    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4218                           "  FROM completion(%Q) ORDER BY 1", text);
4219    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4220    sqlite3_free(zSql);
4221  }
4222  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4223    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4224  }else{
4225    sqlite3_finalize(pStmt);
4226    pStmt = 0;
4227    zRet = 0;
4228  }
4229  return zRet;
4230}
4231static char **readline_completion(const char *zText, int iStart, int iEnd){
4232  rl_attempted_completion_over = 1;
4233  return rl_completion_matches(zText, readline_completion_generator);
4234}
4235
4236#elif HAVE_LINENOISE
4237/*
4238** Linenoise completion callback
4239*/
4240static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4241  int nLine = strlen30(zLine);
4242  int i, iStart;
4243  sqlite3_stmt *pStmt = 0;
4244  char *zSql;
4245  char zBuf[1000];
4246
4247  if( nLine>sizeof(zBuf)-30 ) return;
4248  if( zLine[0]=='.' || zLine[0]=='#') return;
4249  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4250  if( i==nLine-1 ) return;
4251  iStart = i+1;
4252  memcpy(zBuf, zLine, iStart);
4253  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4254                         "  FROM completion(%Q,%Q) ORDER BY 1",
4255                         &zLine[iStart], zLine);
4256  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4257  sqlite3_free(zSql);
4258  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4259  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4260    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4261    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4262    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4263      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4264      linenoiseAddCompletion(lc, zBuf);
4265    }
4266  }
4267  sqlite3_finalize(pStmt);
4268}
4269#endif
4270
4271/*
4272** Do C-language style dequoting.
4273**
4274**    \a    -> alarm
4275**    \b    -> backspace
4276**    \t    -> tab
4277**    \n    -> newline
4278**    \v    -> vertical tab
4279**    \f    -> form feed
4280**    \r    -> carriage return
4281**    \s    -> space
4282**    \"    -> "
4283**    \'    -> '
4284**    \\    -> backslash
4285**    \NNN  -> ascii character NNN in octal
4286*/
4287static void resolve_backslashes(char *z){
4288  int i, j;
4289  char c;
4290  while( *z && *z!='\\' ) z++;
4291  for(i=j=0; (c = z[i])!=0; i++, j++){
4292    if( c=='\\' && z[i+1]!=0 ){
4293      c = z[++i];
4294      if( c=='a' ){
4295        c = '\a';
4296      }else if( c=='b' ){
4297        c = '\b';
4298      }else if( c=='t' ){
4299        c = '\t';
4300      }else if( c=='n' ){
4301        c = '\n';
4302      }else if( c=='v' ){
4303        c = '\v';
4304      }else if( c=='f' ){
4305        c = '\f';
4306      }else if( c=='r' ){
4307        c = '\r';
4308      }else if( c=='"' ){
4309        c = '"';
4310      }else if( c=='\'' ){
4311        c = '\'';
4312      }else if( c=='\\' ){
4313        c = '\\';
4314      }else if( c>='0' && c<='7' ){
4315        c -= '0';
4316        if( z[i+1]>='0' && z[i+1]<='7' ){
4317          i++;
4318          c = (c<<3) + z[i] - '0';
4319          if( z[i+1]>='0' && z[i+1]<='7' ){
4320            i++;
4321            c = (c<<3) + z[i] - '0';
4322          }
4323        }
4324      }
4325    }
4326    z[j] = c;
4327  }
4328  if( j<i ) z[j] = 0;
4329}
4330
4331/*
4332** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4333** for TRUE and FALSE.  Return the integer value if appropriate.
4334*/
4335static int booleanValue(const char *zArg){
4336  int i;
4337  if( zArg[0]=='0' && zArg[1]=='x' ){
4338    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4339  }else{
4340    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4341  }
4342  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4343  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4344    return 1;
4345  }
4346  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4347    return 0;
4348  }
4349  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4350          zArg);
4351  return 0;
4352}
4353
4354/*
4355** Set or clear a shell flag according to a boolean value.
4356*/
4357static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4358  if( booleanValue(zArg) ){
4359    ShellSetFlag(p, mFlag);
4360  }else{
4361    ShellClearFlag(p, mFlag);
4362  }
4363}
4364
4365/*
4366** Close an output file, assuming it is not stderr or stdout
4367*/
4368static void output_file_close(FILE *f){
4369  if( f && f!=stdout && f!=stderr ) fclose(f);
4370}
4371
4372/*
4373** Try to open an output file.   The names "stdout" and "stderr" are
4374** recognized and do the right thing.  NULL is returned if the output
4375** filename is "off".
4376*/
4377static FILE *output_file_open(const char *zFile, int bTextMode){
4378  FILE *f;
4379  if( strcmp(zFile,"stdout")==0 ){
4380    f = stdout;
4381  }else if( strcmp(zFile, "stderr")==0 ){
4382    f = stderr;
4383  }else if( strcmp(zFile, "off")==0 ){
4384    f = 0;
4385  }else{
4386    f = fopen(zFile, bTextMode ? "w" : "wb");
4387    if( f==0 ){
4388      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4389    }
4390  }
4391  return f;
4392}
4393
4394#ifndef SQLITE_OMIT_TRACE
4395/*
4396** A routine for handling output from sqlite3_trace().
4397*/
4398static int sql_trace_callback(
4399  unsigned mType,         /* The trace type */
4400  void *pArg,             /* The ShellState pointer */
4401  void *pP,               /* Usually a pointer to sqlite_stmt */
4402  void *pX                /* Auxiliary output */
4403){
4404  ShellState *p = (ShellState*)pArg;
4405  sqlite3_stmt *pStmt;
4406  const char *zSql;
4407  int nSql;
4408  if( p->traceOut==0 ) return 0;
4409  if( mType==SQLITE_TRACE_CLOSE ){
4410    utf8_printf(p->traceOut, "-- closing database connection\n");
4411    return 0;
4412  }
4413  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4414    zSql = (const char*)pX;
4415  }else{
4416    pStmt = (sqlite3_stmt*)pP;
4417    switch( p->eTraceType ){
4418      case SHELL_TRACE_EXPANDED: {
4419        zSql = sqlite3_expanded_sql(pStmt);
4420        break;
4421      }
4422#ifdef SQLITE_ENABLE_NORMALIZE
4423      case SHELL_TRACE_NORMALIZED: {
4424        zSql = sqlite3_normalized_sql(pStmt);
4425        break;
4426      }
4427#endif
4428      default: {
4429        zSql = sqlite3_sql(pStmt);
4430        break;
4431      }
4432    }
4433  }
4434  if( zSql==0 ) return 0;
4435  nSql = strlen30(zSql);
4436  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4437  switch( mType ){
4438    case SQLITE_TRACE_ROW:
4439    case SQLITE_TRACE_STMT: {
4440      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4441      break;
4442    }
4443    case SQLITE_TRACE_PROFILE: {
4444      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4445      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4446      break;
4447    }
4448  }
4449  return 0;
4450}
4451#endif
4452
4453/*
4454** A no-op routine that runs with the ".breakpoint" doc-command.  This is
4455** a useful spot to set a debugger breakpoint.
4456*/
4457static void test_breakpoint(void){
4458  static int nCall = 0;
4459  nCall++;
4460}
4461
4462/*
4463** An object used to read a CSV and other files for import.
4464*/
4465typedef struct ImportCtx ImportCtx;
4466struct ImportCtx {
4467  const char *zFile;  /* Name of the input file */
4468  FILE *in;           /* Read the CSV text from this input stream */
4469  char *z;            /* Accumulated text for a field */
4470  int n;              /* Number of bytes in z */
4471  int nAlloc;         /* Space allocated for z[] */
4472  int nLine;          /* Current line number */
4473  int bNotFirst;      /* True if one or more bytes already read */
4474  int cTerm;          /* Character that terminated the most recent field */
4475  int cColSep;        /* The column separator character.  (Usually ",") */
4476  int cRowSep;        /* The row separator character.  (Usually "\n") */
4477};
4478
4479/* Append a single byte to z[] */
4480static void import_append_char(ImportCtx *p, int c){
4481  if( p->n+1>=p->nAlloc ){
4482    p->nAlloc += p->nAlloc + 100;
4483    p->z = sqlite3_realloc64(p->z, p->nAlloc);
4484    if( p->z==0 ) shell_out_of_memory();
4485  }
4486  p->z[p->n++] = (char)c;
4487}
4488
4489/* Read a single field of CSV text.  Compatible with rfc4180 and extended
4490** with the option of having a separator other than ",".
4491**
4492**   +  Input comes from p->in.
4493**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4494**      from sqlite3_malloc64().
4495**   +  Use p->cSep as the column separator.  The default is ",".
4496**   +  Use p->rSep as the row separator.  The default is "\n".
4497**   +  Keep track of the line number in p->nLine.
4498**   +  Store the character that terminates the field in p->cTerm.  Store
4499**      EOF on end-of-file.
4500**   +  Report syntax errors on stderr
4501*/
4502static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4503  int c;
4504  int cSep = p->cColSep;
4505  int rSep = p->cRowSep;
4506  p->n = 0;
4507  c = fgetc(p->in);
4508  if( c==EOF || seenInterrupt ){
4509    p->cTerm = EOF;
4510    return 0;
4511  }
4512  if( c=='"' ){
4513    int pc, ppc;
4514    int startLine = p->nLine;
4515    int cQuote = c;
4516    pc = ppc = 0;
4517    while( 1 ){
4518      c = fgetc(p->in);
4519      if( c==rSep ) p->nLine++;
4520      if( c==cQuote ){
4521        if( pc==cQuote ){
4522          pc = 0;
4523          continue;
4524        }
4525      }
4526      if( (c==cSep && pc==cQuote)
4527       || (c==rSep && pc==cQuote)
4528       || (c==rSep && pc=='\r' && ppc==cQuote)
4529       || (c==EOF && pc==cQuote)
4530      ){
4531        do{ p->n--; }while( p->z[p->n]!=cQuote );
4532        p->cTerm = c;
4533        break;
4534      }
4535      if( pc==cQuote && c!='\r' ){
4536        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4537                p->zFile, p->nLine, cQuote);
4538      }
4539      if( c==EOF ){
4540        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4541                p->zFile, startLine, cQuote);
4542        p->cTerm = c;
4543        break;
4544      }
4545      import_append_char(p, c);
4546      ppc = pc;
4547      pc = c;
4548    }
4549  }else{
4550    /* If this is the first field being parsed and it begins with the
4551    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
4552    if( (c&0xff)==0xef && p->bNotFirst==0 ){
4553      import_append_char(p, c);
4554      c = fgetc(p->in);
4555      if( (c&0xff)==0xbb ){
4556        import_append_char(p, c);
4557        c = fgetc(p->in);
4558        if( (c&0xff)==0xbf ){
4559          p->bNotFirst = 1;
4560          p->n = 0;
4561          return csv_read_one_field(p);
4562        }
4563      }
4564    }
4565    while( c!=EOF && c!=cSep && c!=rSep ){
4566      import_append_char(p, c);
4567      c = fgetc(p->in);
4568    }
4569    if( c==rSep ){
4570      p->nLine++;
4571      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4572    }
4573    p->cTerm = c;
4574  }
4575  if( p->z ) p->z[p->n] = 0;
4576  p->bNotFirst = 1;
4577  return p->z;
4578}
4579
4580/* Read a single field of ASCII delimited text.
4581**
4582**   +  Input comes from p->in.
4583**   +  Store results in p->z of length p->n.  Space to hold p->z comes
4584**      from sqlite3_malloc64().
4585**   +  Use p->cSep as the column separator.  The default is "\x1F".
4586**   +  Use p->rSep as the row separator.  The default is "\x1E".
4587**   +  Keep track of the row number in p->nLine.
4588**   +  Store the character that terminates the field in p->cTerm.  Store
4589**      EOF on end-of-file.
4590**   +  Report syntax errors on stderr
4591*/
4592static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4593  int c;
4594  int cSep = p->cColSep;
4595  int rSep = p->cRowSep;
4596  p->n = 0;
4597  c = fgetc(p->in);
4598  if( c==EOF || seenInterrupt ){
4599    p->cTerm = EOF;
4600    return 0;
4601  }
4602  while( c!=EOF && c!=cSep && c!=rSep ){
4603    import_append_char(p, c);
4604    c = fgetc(p->in);
4605  }
4606  if( c==rSep ){
4607    p->nLine++;
4608  }
4609  p->cTerm = c;
4610  if( p->z ) p->z[p->n] = 0;
4611  return p->z;
4612}
4613
4614/*
4615** Try to transfer data for table zTable.  If an error is seen while
4616** moving forward, try to go backwards.  The backwards movement won't
4617** work for WITHOUT ROWID tables.
4618*/
4619static void tryToCloneData(
4620  ShellState *p,
4621  sqlite3 *newDb,
4622  const char *zTable
4623){
4624  sqlite3_stmt *pQuery = 0;
4625  sqlite3_stmt *pInsert = 0;
4626  char *zQuery = 0;
4627  char *zInsert = 0;
4628  int rc;
4629  int i, j, n;
4630  int nTable = strlen30(zTable);
4631  int k = 0;
4632  int cnt = 0;
4633  const int spinRate = 10000;
4634
4635  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4636  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4637  if( rc ){
4638    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4639            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4640            zQuery);
4641    goto end_data_xfer;
4642  }
4643  n = sqlite3_column_count(pQuery);
4644  zInsert = sqlite3_malloc64(200 + nTable + n*3);
4645  if( zInsert==0 ) shell_out_of_memory();
4646  sqlite3_snprintf(200+nTable,zInsert,
4647                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4648  i = strlen30(zInsert);
4649  for(j=1; j<n; j++){
4650    memcpy(zInsert+i, ",?", 2);
4651    i += 2;
4652  }
4653  memcpy(zInsert+i, ");", 3);
4654  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4655  if( rc ){
4656    utf8_printf(stderr, "Error %d: %s on [%s]\n",
4657            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4658            zQuery);
4659    goto end_data_xfer;
4660  }
4661  for(k=0; k<2; k++){
4662    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4663      for(i=0; i<n; i++){
4664        switch( sqlite3_column_type(pQuery, i) ){
4665          case SQLITE_NULL: {
4666            sqlite3_bind_null(pInsert, i+1);
4667            break;
4668          }
4669          case SQLITE_INTEGER: {
4670            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4671            break;
4672          }
4673          case SQLITE_FLOAT: {
4674            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4675            break;
4676          }
4677          case SQLITE_TEXT: {
4678            sqlite3_bind_text(pInsert, i+1,
4679                             (const char*)sqlite3_column_text(pQuery,i),
4680                             -1, SQLITE_STATIC);
4681            break;
4682          }
4683          case SQLITE_BLOB: {
4684            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4685                                            sqlite3_column_bytes(pQuery,i),
4686                                            SQLITE_STATIC);
4687            break;
4688          }
4689        }
4690      } /* End for */
4691      rc = sqlite3_step(pInsert);
4692      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4693        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4694                        sqlite3_errmsg(newDb));
4695      }
4696      sqlite3_reset(pInsert);
4697      cnt++;
4698      if( (cnt%spinRate)==0 ){
4699        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4700        fflush(stdout);
4701      }
4702    } /* End while */
4703    if( rc==SQLITE_DONE ) break;
4704    sqlite3_finalize(pQuery);
4705    sqlite3_free(zQuery);
4706    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4707                             zTable);
4708    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4709    if( rc ){
4710      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4711      break;
4712    }
4713  } /* End for(k=0...) */
4714
4715end_data_xfer:
4716  sqlite3_finalize(pQuery);
4717  sqlite3_finalize(pInsert);
4718  sqlite3_free(zQuery);
4719  sqlite3_free(zInsert);
4720}
4721
4722
4723/*
4724** Try to transfer all rows of the schema that match zWhere.  For
4725** each row, invoke xForEach() on the object defined by that row.
4726** If an error is encountered while moving forward through the
4727** sqlite_master table, try again moving backwards.
4728*/
4729static void tryToCloneSchema(
4730  ShellState *p,
4731  sqlite3 *newDb,
4732  const char *zWhere,
4733  void (*xForEach)(ShellState*,sqlite3*,const char*)
4734){
4735  sqlite3_stmt *pQuery = 0;
4736  char *zQuery = 0;
4737  int rc;
4738  const unsigned char *zName;
4739  const unsigned char *zSql;
4740  char *zErrMsg = 0;
4741
4742  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4743                           " WHERE %s", zWhere);
4744  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4745  if( rc ){
4746    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4747                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4748                    zQuery);
4749    goto end_schema_xfer;
4750  }
4751  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4752    zName = sqlite3_column_text(pQuery, 0);
4753    zSql = sqlite3_column_text(pQuery, 1);
4754    printf("%s... ", zName); fflush(stdout);
4755    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4756    if( zErrMsg ){
4757      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4758      sqlite3_free(zErrMsg);
4759      zErrMsg = 0;
4760    }
4761    if( xForEach ){
4762      xForEach(p, newDb, (const char*)zName);
4763    }
4764    printf("done\n");
4765  }
4766  if( rc!=SQLITE_DONE ){
4767    sqlite3_finalize(pQuery);
4768    sqlite3_free(zQuery);
4769    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4770                             " WHERE %s ORDER BY rowid DESC", zWhere);
4771    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4772    if( rc ){
4773      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4774                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4775                      zQuery);
4776      goto end_schema_xfer;
4777    }
4778    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4779      zName = sqlite3_column_text(pQuery, 0);
4780      zSql = sqlite3_column_text(pQuery, 1);
4781      printf("%s... ", zName); fflush(stdout);
4782      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4783      if( zErrMsg ){
4784        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4785        sqlite3_free(zErrMsg);
4786        zErrMsg = 0;
4787      }
4788      if( xForEach ){
4789        xForEach(p, newDb, (const char*)zName);
4790      }
4791      printf("done\n");
4792    }
4793  }
4794end_schema_xfer:
4795  sqlite3_finalize(pQuery);
4796  sqlite3_free(zQuery);
4797}
4798
4799/*
4800** Open a new database file named "zNewDb".  Try to recover as much information
4801** as possible out of the main database (which might be corrupt) and write it
4802** into zNewDb.
4803*/
4804static void tryToClone(ShellState *p, const char *zNewDb){
4805  int rc;
4806  sqlite3 *newDb = 0;
4807  if( access(zNewDb,0)==0 ){
4808    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4809    return;
4810  }
4811  rc = sqlite3_open(zNewDb, &newDb);
4812  if( rc ){
4813    utf8_printf(stderr, "Cannot create output database: %s\n",
4814            sqlite3_errmsg(newDb));
4815  }else{
4816    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4817    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4818    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4819    tryToCloneSchema(p, newDb, "type!='table'", 0);
4820    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4821    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4822  }
4823  close_db(newDb);
4824}
4825
4826/*
4827** Change the output file back to stdout.
4828**
4829** If the p->doXdgOpen flag is set, that means the output was being
4830** redirected to a temporary file named by p->zTempFile.  In that case,
4831** launch start/open/xdg-open on that temporary file.
4832*/
4833static void output_reset(ShellState *p){
4834  if( p->outfile[0]=='|' ){
4835#ifndef SQLITE_OMIT_POPEN
4836    pclose(p->out);
4837#endif
4838  }else{
4839    output_file_close(p->out);
4840#ifndef SQLITE_NOHAVE_SYSTEM
4841    if( p->doXdgOpen ){
4842      const char *zXdgOpenCmd =
4843#if defined(_WIN32)
4844      "start";
4845#elif defined(__APPLE__)
4846      "open";
4847#else
4848      "xdg-open";
4849#endif
4850      char *zCmd;
4851      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
4852      if( system(zCmd) ){
4853        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4854      }
4855      sqlite3_free(zCmd);
4856      outputModePop(p);
4857      p->doXdgOpen = 0;
4858      sqlite3_sleep(100);
4859    }
4860#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4861  }
4862  p->outfile[0] = 0;
4863  p->out = stdout;
4864}
4865
4866/*
4867** Run an SQL command and return the single integer result.
4868*/
4869static int db_int(ShellState *p, const char *zSql){
4870  sqlite3_stmt *pStmt;
4871  int res = 0;
4872  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4873  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4874    res = sqlite3_column_int(pStmt,0);
4875  }
4876  sqlite3_finalize(pStmt);
4877  return res;
4878}
4879
4880/*
4881** Convert a 2-byte or 4-byte big-endian integer into a native integer
4882*/
4883static unsigned int get2byteInt(unsigned char *a){
4884  return (a[0]<<8) + a[1];
4885}
4886static unsigned int get4byteInt(unsigned char *a){
4887  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4888}
4889
4890/*
4891** Implementation of the ".info" command.
4892**
4893** Return 1 on error, 2 to exit, and 0 otherwise.
4894*/
4895static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4896  static const struct { const char *zName; int ofst; } aField[] = {
4897     { "file change counter:",  24  },
4898     { "database page count:",  28  },
4899     { "freelist page count:",  36  },
4900     { "schema cookie:",        40  },
4901     { "schema format:",        44  },
4902     { "default cache size:",   48  },
4903     { "autovacuum top root:",  52  },
4904     { "incremental vacuum:",   64  },
4905     { "text encoding:",        56  },
4906     { "user version:",         60  },
4907     { "application id:",       68  },
4908     { "software version:",     96  },
4909  };
4910  static const struct { const char *zName; const char *zSql; } aQuery[] = {
4911     { "number of tables:",
4912       "SELECT count(*) FROM %s WHERE type='table'" },
4913     { "number of indexes:",
4914       "SELECT count(*) FROM %s WHERE type='index'" },
4915     { "number of triggers:",
4916       "SELECT count(*) FROM %s WHERE type='trigger'" },
4917     { "number of views:",
4918       "SELECT count(*) FROM %s WHERE type='view'" },
4919     { "schema size:",
4920       "SELECT total(length(sql)) FROM %s" },
4921  };
4922  int i, rc;
4923  unsigned iDataVersion;
4924  char *zSchemaTab;
4925  char *zDb = nArg>=2 ? azArg[1] : "main";
4926  sqlite3_stmt *pStmt = 0;
4927  unsigned char aHdr[100];
4928  open_db(p, 0);
4929  if( p->db==0 ) return 1;
4930  rc = sqlite3_prepare_v2(p->db,
4931             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4932             -1, &pStmt, 0);
4933  if( rc ){
4934    if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4935      utf8_printf(stderr, "the \".dbinfo\" command requires the "
4936                          "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4937    }else{
4938      utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4939    }
4940    sqlite3_finalize(pStmt);
4941    return 1;
4942  }
4943  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4944  if( sqlite3_step(pStmt)==SQLITE_ROW
4945   && sqlite3_column_bytes(pStmt,0)>100
4946  ){
4947    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4948    sqlite3_finalize(pStmt);
4949  }else{
4950    raw_printf(stderr, "unable to read database header\n");
4951    sqlite3_finalize(pStmt);
4952    return 1;
4953  }
4954  i = get2byteInt(aHdr+16);
4955  if( i==1 ) i = 65536;
4956  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4957  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4958  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4959  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4960  for(i=0; i<ArraySize(aField); i++){
4961    int ofst = aField[i].ofst;
4962    unsigned int val = get4byteInt(aHdr + ofst);
4963    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4964    switch( ofst ){
4965      case 56: {
4966        if( val==1 ) raw_printf(p->out, " (utf8)");
4967        if( val==2 ) raw_printf(p->out, " (utf16le)");
4968        if( val==3 ) raw_printf(p->out, " (utf16be)");
4969      }
4970    }
4971    raw_printf(p->out, "\n");
4972  }
4973  if( zDb==0 ){
4974    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4975  }else if( strcmp(zDb,"temp")==0 ){
4976    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4977  }else{
4978    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4979  }
4980  for(i=0; i<ArraySize(aQuery); i++){
4981    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4982    int val = db_int(p, zSql);
4983    sqlite3_free(zSql);
4984    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4985  }
4986  sqlite3_free(zSchemaTab);
4987  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4988  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
4989  return 0;
4990}
4991
4992/*
4993** Print the current sqlite3_errmsg() value to stderr and return 1.
4994*/
4995static int shellDatabaseError(sqlite3 *db){
4996  const char *zErr = sqlite3_errmsg(db);
4997  utf8_printf(stderr, "Error: %s\n", zErr);
4998  return 1;
4999}
5000
5001/*
5002** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5003** if they match and FALSE (0) if they do not match.
5004**
5005** Globbing rules:
5006**
5007**      '*'       Matches any sequence of zero or more characters.
5008**
5009**      '?'       Matches exactly one character.
5010**
5011**     [...]      Matches one character from the enclosed list of
5012**                characters.
5013**
5014**     [^...]     Matches one character not in the enclosed list.
5015**
5016**      '#'       Matches any sequence of one or more digits with an
5017**                optional + or - sign in front
5018**
5019**      ' '       Any span of whitespace matches any other span of
5020**                whitespace.
5021**
5022** Extra whitespace at the end of z[] is ignored.
5023*/
5024static int testcase_glob(const char *zGlob, const char *z){
5025  int c, c2;
5026  int invert;
5027  int seen;
5028
5029  while( (c = (*(zGlob++)))!=0 ){
5030    if( IsSpace(c) ){
5031      if( !IsSpace(*z) ) return 0;
5032      while( IsSpace(*zGlob) ) zGlob++;
5033      while( IsSpace(*z) ) z++;
5034    }else if( c=='*' ){
5035      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5036        if( c=='?' && (*(z++))==0 ) return 0;
5037      }
5038      if( c==0 ){
5039        return 1;
5040      }else if( c=='[' ){
5041        while( *z && testcase_glob(zGlob-1,z)==0 ){
5042          z++;
5043        }
5044        return (*z)!=0;
5045      }
5046      while( (c2 = (*(z++)))!=0 ){
5047        while( c2!=c ){
5048          c2 = *(z++);
5049          if( c2==0 ) return 0;
5050        }
5051        if( testcase_glob(zGlob,z) ) return 1;
5052      }
5053      return 0;
5054    }else if( c=='?' ){
5055      if( (*(z++))==0 ) return 0;
5056    }else if( c=='[' ){
5057      int prior_c = 0;
5058      seen = 0;
5059      invert = 0;
5060      c = *(z++);
5061      if( c==0 ) return 0;
5062      c2 = *(zGlob++);
5063      if( c2=='^' ){
5064        invert = 1;
5065        c2 = *(zGlob++);
5066      }
5067      if( c2==']' ){
5068        if( c==']' ) seen = 1;
5069        c2 = *(zGlob++);
5070      }
5071      while( c2 && c2!=']' ){
5072        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5073          c2 = *(zGlob++);
5074          if( c>=prior_c && c<=c2 ) seen = 1;
5075          prior_c = 0;
5076        }else{
5077          if( c==c2 ){
5078            seen = 1;
5079          }
5080          prior_c = c2;
5081        }
5082        c2 = *(zGlob++);
5083      }
5084      if( c2==0 || (seen ^ invert)==0 ) return 0;
5085    }else if( c=='#' ){
5086      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5087      if( !IsDigit(z[0]) ) return 0;
5088      z++;
5089      while( IsDigit(z[0]) ){ z++; }
5090    }else{
5091      if( c!=(*(z++)) ) return 0;
5092    }
5093  }
5094  while( IsSpace(*z) ){ z++; }
5095  return *z==0;
5096}
5097
5098
5099/*
5100** Compare the string as a command-line option with either one or two
5101** initial "-" characters.
5102*/
5103static int optionMatch(const char *zStr, const char *zOpt){
5104  if( zStr[0]!='-' ) return 0;
5105  zStr++;
5106  if( zStr[0]=='-' ) zStr++;
5107  return strcmp(zStr, zOpt)==0;
5108}
5109
5110/*
5111** Delete a file.
5112*/
5113int shellDeleteFile(const char *zFilename){
5114  int rc;
5115#ifdef _WIN32
5116  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5117  rc = _wunlink(z);
5118  sqlite3_free(z);
5119#else
5120  rc = unlink(zFilename);
5121#endif
5122  return rc;
5123}
5124
5125/*
5126** Try to delete the temporary file (if there is one) and free the
5127** memory used to hold the name of the temp file.
5128*/
5129static void clearTempFile(ShellState *p){
5130  if( p->zTempFile==0 ) return;
5131  if( p->doXdgOpen ) return;
5132  if( shellDeleteFile(p->zTempFile) ) return;
5133  sqlite3_free(p->zTempFile);
5134  p->zTempFile = 0;
5135}
5136
5137/*
5138** Create a new temp file name with the given suffix.
5139*/
5140static void newTempFile(ShellState *p, const char *zSuffix){
5141  clearTempFile(p);
5142  sqlite3_free(p->zTempFile);
5143  p->zTempFile = 0;
5144  if( p->db ){
5145    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5146  }
5147  if( p->zTempFile==0 ){
5148    sqlite3_uint64 r;
5149    sqlite3_randomness(sizeof(r), &r);
5150    p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5151  }else{
5152    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5153  }
5154  if( p->zTempFile==0 ){
5155    raw_printf(stderr, "out of memory\n");
5156    exit(1);
5157  }
5158}
5159
5160
5161/*
5162** The implementation of SQL scalar function fkey_collate_clause(), used
5163** by the ".lint fkey-indexes" command. This scalar function is always
5164** called with four arguments - the parent table name, the parent column name,
5165** the child table name and the child column name.
5166**
5167**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5168**
5169** If either of the named tables or columns do not exist, this function
5170** returns an empty string. An empty string is also returned if both tables
5171** and columns exist but have the same default collation sequence. Or,
5172** if both exist but the default collation sequences are different, this
5173** function returns the string " COLLATE <parent-collation>", where
5174** <parent-collation> is the default collation sequence of the parent column.
5175*/
5176static void shellFkeyCollateClause(
5177  sqlite3_context *pCtx,
5178  int nVal,
5179  sqlite3_value **apVal
5180){
5181  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5182  const char *zParent;
5183  const char *zParentCol;
5184  const char *zParentSeq;
5185  const char *zChild;
5186  const char *zChildCol;
5187  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5188  int rc;
5189
5190  assert( nVal==4 );
5191  zParent = (const char*)sqlite3_value_text(apVal[0]);
5192  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5193  zChild = (const char*)sqlite3_value_text(apVal[2]);
5194  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5195
5196  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5197  rc = sqlite3_table_column_metadata(
5198      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5199  );
5200  if( rc==SQLITE_OK ){
5201    rc = sqlite3_table_column_metadata(
5202        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5203    );
5204  }
5205
5206  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5207    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5208    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5209    sqlite3_free(z);
5210  }
5211}
5212
5213
5214/*
5215** The implementation of dot-command ".lint fkey-indexes".
5216*/
5217static int lintFkeyIndexes(
5218  ShellState *pState,             /* Current shell tool state */
5219  char **azArg,                   /* Array of arguments passed to dot command */
5220  int nArg                        /* Number of entries in azArg[] */
5221){
5222  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5223  FILE *out = pState->out;        /* Stream to write non-error output to */
5224  int bVerbose = 0;               /* If -verbose is present */
5225  int bGroupByParent = 0;         /* If -groupbyparent is present */
5226  int i;                          /* To iterate through azArg[] */
5227  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5228  int rc;                         /* Return code */
5229  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5230
5231  /*
5232  ** This SELECT statement returns one row for each foreign key constraint
5233  ** in the schema of the main database. The column values are:
5234  **
5235  ** 0. The text of an SQL statement similar to:
5236  **
5237  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5238  **
5239  **    This SELECT is similar to the one that the foreign keys implementation
5240  **    needs to run internally on child tables. If there is an index that can
5241  **    be used to optimize this query, then it can also be used by the FK
5242  **    implementation to optimize DELETE or UPDATE statements on the parent
5243  **    table.
5244  **
5245  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5246  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5247  **    contains an index that can be used to optimize the query.
5248  **
5249  ** 2. Human readable text that describes the child table and columns. e.g.
5250  **
5251  **       "child_table(child_key1, child_key2)"
5252  **
5253  ** 3. Human readable text that describes the parent table and columns. e.g.
5254  **
5255  **       "parent_table(parent_key1, parent_key2)"
5256  **
5257  ** 4. A full CREATE INDEX statement for an index that could be used to
5258  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5259  **
5260  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5261  **
5262  ** 5. The name of the parent table.
5263  **
5264  ** These six values are used by the C logic below to generate the report.
5265  */
5266  const char *zSql =
5267  "SELECT "
5268    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5269    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5270    "  || fkey_collate_clause("
5271    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5272    ", "
5273    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5274    "  || group_concat('*=?', ' AND ') || ')'"
5275    ", "
5276    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5277    ", "
5278    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5279    ", "
5280    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5281    "  || ' ON ' || quote(s.name) || '('"
5282    "  || group_concat(quote(f.[from]) ||"
5283    "        fkey_collate_clause("
5284    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5285    "  || ');'"
5286    ", "
5287    "     f.[table] "
5288    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5289    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5290    "GROUP BY s.name, f.id "
5291    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5292  ;
5293  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5294
5295  for(i=2; i<nArg; i++){
5296    int n = strlen30(azArg[i]);
5297    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5298      bVerbose = 1;
5299    }
5300    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5301      bGroupByParent = 1;
5302      zIndent = "    ";
5303    }
5304    else{
5305      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5306          azArg[0], azArg[1]
5307      );
5308      return SQLITE_ERROR;
5309    }
5310  }
5311
5312  /* Register the fkey_collate_clause() SQL function */
5313  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5314      0, shellFkeyCollateClause, 0, 0
5315  );
5316
5317
5318  if( rc==SQLITE_OK ){
5319    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5320  }
5321  if( rc==SQLITE_OK ){
5322    sqlite3_bind_int(pSql, 1, bGroupByParent);
5323  }
5324
5325  if( rc==SQLITE_OK ){
5326    int rc2;
5327    char *zPrev = 0;
5328    while( SQLITE_ROW==sqlite3_step(pSql) ){
5329      int res = -1;
5330      sqlite3_stmt *pExplain = 0;
5331      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5332      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5333      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5334      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5335      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5336      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5337
5338      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5339      if( rc!=SQLITE_OK ) break;
5340      if( SQLITE_ROW==sqlite3_step(pExplain) ){
5341        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5342        res = (
5343              0==sqlite3_strglob(zGlob, zPlan)
5344           || 0==sqlite3_strglob(zGlobIPK, zPlan)
5345        );
5346      }
5347      rc = sqlite3_finalize(pExplain);
5348      if( rc!=SQLITE_OK ) break;
5349
5350      if( res<0 ){
5351        raw_printf(stderr, "Error: internal error");
5352        break;
5353      }else{
5354        if( bGroupByParent
5355        && (bVerbose || res==0)
5356        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5357        ){
5358          raw_printf(out, "-- Parent table %s\n", zParent);
5359          sqlite3_free(zPrev);
5360          zPrev = sqlite3_mprintf("%s", zParent);
5361        }
5362
5363        if( res==0 ){
5364          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5365        }else if( bVerbose ){
5366          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5367              zIndent, zFrom, zTarget
5368          );
5369        }
5370      }
5371    }
5372    sqlite3_free(zPrev);
5373
5374    if( rc!=SQLITE_OK ){
5375      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5376    }
5377
5378    rc2 = sqlite3_finalize(pSql);
5379    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5380      rc = rc2;
5381      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5382    }
5383  }else{
5384    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5385  }
5386
5387  return rc;
5388}
5389
5390/*
5391** Implementation of ".lint" dot command.
5392*/
5393static int lintDotCommand(
5394  ShellState *pState,             /* Current shell tool state */
5395  char **azArg,                   /* Array of arguments passed to dot command */
5396  int nArg                        /* Number of entries in azArg[] */
5397){
5398  int n;
5399  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5400  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5401  return lintFkeyIndexes(pState, azArg, nArg);
5402
5403 usage:
5404  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5405  raw_printf(stderr, "Where sub-commands are:\n");
5406  raw_printf(stderr, "    fkey-indexes\n");
5407  return SQLITE_ERROR;
5408}
5409
5410#if !defined SQLITE_OMIT_VIRTUALTABLE
5411static void shellPrepare(
5412  sqlite3 *db,
5413  int *pRc,
5414  const char *zSql,
5415  sqlite3_stmt **ppStmt
5416){
5417  *ppStmt = 0;
5418  if( *pRc==SQLITE_OK ){
5419    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5420    if( rc!=SQLITE_OK ){
5421      raw_printf(stderr, "sql error: %s (%d)\n",
5422          sqlite3_errmsg(db), sqlite3_errcode(db)
5423      );
5424      *pRc = rc;
5425    }
5426  }
5427}
5428
5429/*
5430** Create a prepared statement using printf-style arguments for the SQL.
5431**
5432** This routine is could be marked "static".  But it is not always used,
5433** depending on compile-time options.  By omitting the "static", we avoid
5434** nuisance compiler warnings about "defined but not used".
5435*/
5436void shellPreparePrintf(
5437  sqlite3 *db,
5438  int *pRc,
5439  sqlite3_stmt **ppStmt,
5440  const char *zFmt,
5441  ...
5442){
5443  *ppStmt = 0;
5444  if( *pRc==SQLITE_OK ){
5445    va_list ap;
5446    char *z;
5447    va_start(ap, zFmt);
5448    z = sqlite3_vmprintf(zFmt, ap);
5449    va_end(ap);
5450    if( z==0 ){
5451      *pRc = SQLITE_NOMEM;
5452    }else{
5453      shellPrepare(db, pRc, z, ppStmt);
5454      sqlite3_free(z);
5455    }
5456  }
5457}
5458
5459/* Finalize the prepared statement created using shellPreparePrintf().
5460**
5461** This routine is could be marked "static".  But it is not always used,
5462** depending on compile-time options.  By omitting the "static", we avoid
5463** nuisance compiler warnings about "defined but not used".
5464*/
5465void shellFinalize(
5466  int *pRc,
5467  sqlite3_stmt *pStmt
5468){
5469  if( pStmt ){
5470    sqlite3 *db = sqlite3_db_handle(pStmt);
5471    int rc = sqlite3_finalize(pStmt);
5472    if( *pRc==SQLITE_OK ){
5473      if( rc!=SQLITE_OK ){
5474        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5475      }
5476      *pRc = rc;
5477    }
5478  }
5479}
5480
5481/* Reset the prepared statement created using shellPreparePrintf().
5482**
5483** This routine is could be marked "static".  But it is not always used,
5484** depending on compile-time options.  By omitting the "static", we avoid
5485** nuisance compiler warnings about "defined but not used".
5486*/
5487void shellReset(
5488  int *pRc,
5489  sqlite3_stmt *pStmt
5490){
5491  int rc = sqlite3_reset(pStmt);
5492  if( *pRc==SQLITE_OK ){
5493    if( rc!=SQLITE_OK ){
5494      sqlite3 *db = sqlite3_db_handle(pStmt);
5495      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5496    }
5497    *pRc = rc;
5498  }
5499}
5500#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
5501
5502#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5503/*********************************************************************************
5504** The ".archive" or ".ar" command.
5505*/
5506/*
5507** Structure representing a single ".ar" command.
5508*/
5509typedef struct ArCommand ArCommand;
5510struct ArCommand {
5511  u8 eCmd;                        /* An AR_CMD_* value */
5512  u8 bVerbose;                    /* True if --verbose */
5513  u8 bZip;                        /* True if the archive is a ZIP */
5514  u8 bDryRun;                     /* True if --dry-run */
5515  u8 bAppend;                     /* True if --append */
5516  u8 fromCmdLine;                 /* Run from -A instead of .archive */
5517  int nArg;                       /* Number of command arguments */
5518  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
5519  const char *zFile;              /* --file argument, or NULL */
5520  const char *zDir;               /* --directory argument, or NULL */
5521  char **azArg;                   /* Array of command arguments */
5522  ShellState *p;                  /* Shell state */
5523  sqlite3 *db;                    /* Database containing the archive */
5524};
5525
5526/*
5527** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5528*/
5529static int arUsage(FILE *f){
5530  showHelp(f,"archive");
5531  return SQLITE_ERROR;
5532}
5533
5534/*
5535** Print an error message for the .ar command to stderr and return
5536** SQLITE_ERROR.
5537*/
5538static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
5539  va_list ap;
5540  char *z;
5541  va_start(ap, zFmt);
5542  z = sqlite3_vmprintf(zFmt, ap);
5543  va_end(ap);
5544  utf8_printf(stderr, "Error: %s\n", z);
5545  if( pAr->fromCmdLine ){
5546    utf8_printf(stderr, "Use \"-A\" for more help\n");
5547  }else{
5548    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5549  }
5550  sqlite3_free(z);
5551  return SQLITE_ERROR;
5552}
5553
5554/*
5555** Values for ArCommand.eCmd.
5556*/
5557#define AR_CMD_CREATE       1
5558#define AR_CMD_UPDATE       2
5559#define AR_CMD_INSERT       3
5560#define AR_CMD_EXTRACT      4
5561#define AR_CMD_LIST         5
5562#define AR_CMD_HELP         6
5563
5564/*
5565** Other (non-command) switches.
5566*/
5567#define AR_SWITCH_VERBOSE     7
5568#define AR_SWITCH_FILE        8
5569#define AR_SWITCH_DIRECTORY   9
5570#define AR_SWITCH_APPEND     10
5571#define AR_SWITCH_DRYRUN     11
5572
5573static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5574  switch( eSwitch ){
5575    case AR_CMD_CREATE:
5576    case AR_CMD_EXTRACT:
5577    case AR_CMD_LIST:
5578    case AR_CMD_UPDATE:
5579    case AR_CMD_INSERT:
5580    case AR_CMD_HELP:
5581      if( pAr->eCmd ){
5582        return arErrorMsg(pAr, "multiple command options");
5583      }
5584      pAr->eCmd = eSwitch;
5585      break;
5586
5587    case AR_SWITCH_DRYRUN:
5588      pAr->bDryRun = 1;
5589      break;
5590    case AR_SWITCH_VERBOSE:
5591      pAr->bVerbose = 1;
5592      break;
5593    case AR_SWITCH_APPEND:
5594      pAr->bAppend = 1;
5595      /* Fall thru into --file */
5596    case AR_SWITCH_FILE:
5597      pAr->zFile = zArg;
5598      break;
5599    case AR_SWITCH_DIRECTORY:
5600      pAr->zDir = zArg;
5601      break;
5602  }
5603
5604  return SQLITE_OK;
5605}
5606
5607/*
5608** Parse the command line for an ".ar" command. The results are written into
5609** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5610** successfully, otherwise an error message is written to stderr and
5611** SQLITE_ERROR returned.
5612*/
5613static int arParseCommand(
5614  char **azArg,                   /* Array of arguments passed to dot command */
5615  int nArg,                       /* Number of entries in azArg[] */
5616  ArCommand *pAr                  /* Populate this object */
5617){
5618  struct ArSwitch {
5619    const char *zLong;
5620    char cShort;
5621    u8 eSwitch;
5622    u8 bArg;
5623  } aSwitch[] = {
5624    { "create",    'c', AR_CMD_CREATE,       0 },
5625    { "extract",   'x', AR_CMD_EXTRACT,      0 },
5626    { "insert",    'i', AR_CMD_INSERT,       0 },
5627    { "list",      't', AR_CMD_LIST,         0 },
5628    { "update",    'u', AR_CMD_UPDATE,       0 },
5629    { "help",      'h', AR_CMD_HELP,         0 },
5630    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
5631    { "file",      'f', AR_SWITCH_FILE,      1 },
5632    { "append",    'a', AR_SWITCH_APPEND,    1 },
5633    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
5634    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
5635  };
5636  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5637  struct ArSwitch *pEnd = &aSwitch[nSwitch];
5638
5639  if( nArg<=1 ){
5640    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
5641    return arUsage(stderr);
5642  }else{
5643    char *z = azArg[1];
5644    if( z[0]!='-' ){
5645      /* Traditional style [tar] invocation */
5646      int i;
5647      int iArg = 2;
5648      for(i=0; z[i]; i++){
5649        const char *zArg = 0;
5650        struct ArSwitch *pOpt;
5651        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5652          if( z[i]==pOpt->cShort ) break;
5653        }
5654        if( pOpt==pEnd ){
5655          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5656        }
5657        if( pOpt->bArg ){
5658          if( iArg>=nArg ){
5659            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5660          }
5661          zArg = azArg[iArg++];
5662        }
5663        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5664      }
5665      pAr->nArg = nArg-iArg;
5666      if( pAr->nArg>0 ){
5667        pAr->azArg = &azArg[iArg];
5668      }
5669    }else{
5670      /* Non-traditional invocation */
5671      int iArg;
5672      for(iArg=1; iArg<nArg; iArg++){
5673        int n;
5674        z = azArg[iArg];
5675        if( z[0]!='-' ){
5676          /* All remaining command line words are command arguments. */
5677          pAr->azArg = &azArg[iArg];
5678          pAr->nArg = nArg-iArg;
5679          break;
5680        }
5681        n = strlen30(z);
5682
5683        if( z[1]!='-' ){
5684          int i;
5685          /* One or more short options */
5686          for(i=1; i<n; i++){
5687            const char *zArg = 0;
5688            struct ArSwitch *pOpt;
5689            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5690              if( z[i]==pOpt->cShort ) break;
5691            }
5692            if( pOpt==pEnd ){
5693              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
5694            }
5695            if( pOpt->bArg ){
5696              if( i<(n-1) ){
5697                zArg = &z[i+1];
5698                i = n;
5699              }else{
5700                if( iArg>=(nArg-1) ){
5701                  return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
5702                }
5703                zArg = azArg[++iArg];
5704              }
5705            }
5706            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5707          }
5708        }else if( z[2]=='\0' ){
5709          /* A -- option, indicating that all remaining command line words
5710          ** are command arguments.  */
5711          pAr->azArg = &azArg[iArg+1];
5712          pAr->nArg = nArg-iArg-1;
5713          break;
5714        }else{
5715          /* A long option */
5716          const char *zArg = 0;             /* Argument for option, if any */
5717          struct ArSwitch *pMatch = 0;      /* Matching option */
5718          struct ArSwitch *pOpt;            /* Iterator */
5719          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5720            const char *zLong = pOpt->zLong;
5721            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
5722              if( pMatch ){
5723                return arErrorMsg(pAr, "ambiguous option: %s",z);
5724              }else{
5725                pMatch = pOpt;
5726              }
5727            }
5728          }
5729
5730          if( pMatch==0 ){
5731            return arErrorMsg(pAr, "unrecognized option: %s", z);
5732          }
5733          if( pMatch->bArg ){
5734            if( iArg>=(nArg-1) ){
5735              return arErrorMsg(pAr, "option requires an argument: %s", z);
5736            }
5737            zArg = azArg[++iArg];
5738          }
5739          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5740        }
5741      }
5742    }
5743  }
5744
5745  return SQLITE_OK;
5746}
5747
5748/*
5749** This function assumes that all arguments within the ArCommand.azArg[]
5750** array refer to archive members, as for the --extract or --list commands.
5751** It checks that each of them are present. If any specified file is not
5752** present in the archive, an error is printed to stderr and an error
5753** code returned. Otherwise, if all specified arguments are present in
5754** the archive, SQLITE_OK is returned.
5755**
5756** This function strips any trailing '/' characters from each argument.
5757** This is consistent with the way the [tar] command seems to work on
5758** Linux.
5759*/
5760static int arCheckEntries(ArCommand *pAr){
5761  int rc = SQLITE_OK;
5762  if( pAr->nArg ){
5763    int i, j;
5764    sqlite3_stmt *pTest = 0;
5765
5766    shellPreparePrintf(pAr->db, &rc, &pTest,
5767        "SELECT name FROM %s WHERE name=$name",
5768        pAr->zSrcTable
5769    );
5770    j = sqlite3_bind_parameter_index(pTest, "$name");
5771    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5772      char *z = pAr->azArg[i];
5773      int n = strlen30(z);
5774      int bOk = 0;
5775      while( n>0 && z[n-1]=='/' ) n--;
5776      z[n] = '\0';
5777      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
5778      if( SQLITE_ROW==sqlite3_step(pTest) ){
5779        bOk = 1;
5780      }
5781      shellReset(&rc, pTest);
5782      if( rc==SQLITE_OK && bOk==0 ){
5783        utf8_printf(stderr, "not found in archive: %s\n", z);
5784        rc = SQLITE_ERROR;
5785      }
5786    }
5787    shellFinalize(&rc, pTest);
5788  }
5789  return rc;
5790}
5791
5792/*
5793** Format a WHERE clause that can be used against the "sqlar" table to
5794** identify all archive members that match the command arguments held
5795** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5796** The caller is responsible for eventually calling sqlite3_free() on
5797** any non-NULL (*pzWhere) value.
5798*/
5799static void arWhereClause(
5800  int *pRc,
5801  ArCommand *pAr,
5802  char **pzWhere                  /* OUT: New WHERE clause */
5803){
5804  char *zWhere = 0;
5805  if( *pRc==SQLITE_OK ){
5806    if( pAr->nArg==0 ){
5807      zWhere = sqlite3_mprintf("1");
5808    }else{
5809      int i;
5810      const char *zSep = "";
5811      for(i=0; i<pAr->nArg; i++){
5812        const char *z = pAr->azArg[i];
5813        zWhere = sqlite3_mprintf(
5814          "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5815          zWhere, zSep, z, strlen30(z)+1, z
5816        );
5817        if( zWhere==0 ){
5818          *pRc = SQLITE_NOMEM;
5819          break;
5820        }
5821        zSep = " OR ";
5822      }
5823    }
5824  }
5825  *pzWhere = zWhere;
5826}
5827
5828/*
5829** Implementation of .ar "lisT" command.
5830*/
5831static int arListCommand(ArCommand *pAr){
5832  const char *zSql = "SELECT %s FROM %s WHERE %s";
5833  const char *azCols[] = {
5834    "name",
5835    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5836  };
5837
5838  char *zWhere = 0;
5839  sqlite3_stmt *pSql = 0;
5840  int rc;
5841
5842  rc = arCheckEntries(pAr);
5843  arWhereClause(&rc, pAr, &zWhere);
5844
5845  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5846                     pAr->zSrcTable, zWhere);
5847  if( pAr->bDryRun ){
5848    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5849  }else{
5850    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5851      if( pAr->bVerbose ){
5852        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
5853            sqlite3_column_text(pSql, 0),
5854            sqlite3_column_int(pSql, 1),
5855            sqlite3_column_text(pSql, 2),
5856            sqlite3_column_text(pSql, 3)
5857        );
5858      }else{
5859        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5860      }
5861    }
5862  }
5863  shellFinalize(&rc, pSql);
5864  sqlite3_free(zWhere);
5865  return rc;
5866}
5867
5868
5869/*
5870** Implementation of .ar "eXtract" command.
5871*/
5872static int arExtractCommand(ArCommand *pAr){
5873  const char *zSql1 =
5874    "SELECT "
5875    " ($dir || name),"
5876    " writefile(($dir || name), %s, mode, mtime) "
5877    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5878    " AND name NOT GLOB '*..[/\\]*'";
5879
5880  const char *azExtraArg[] = {
5881    "sqlar_uncompress(data, sz)",
5882    "data"
5883  };
5884
5885  sqlite3_stmt *pSql = 0;
5886  int rc = SQLITE_OK;
5887  char *zDir = 0;
5888  char *zWhere = 0;
5889  int i, j;
5890
5891  /* If arguments are specified, check that they actually exist within
5892  ** the archive before proceeding. And formulate a WHERE clause to
5893  ** match them.  */
5894  rc = arCheckEntries(pAr);
5895  arWhereClause(&rc, pAr, &zWhere);
5896
5897  if( rc==SQLITE_OK ){
5898    if( pAr->zDir ){
5899      zDir = sqlite3_mprintf("%s/", pAr->zDir);
5900    }else{
5901      zDir = sqlite3_mprintf("");
5902    }
5903    if( zDir==0 ) rc = SQLITE_NOMEM;
5904  }
5905
5906  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5907      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
5908  );
5909
5910  if( rc==SQLITE_OK ){
5911    j = sqlite3_bind_parameter_index(pSql, "$dir");
5912    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
5913
5914    /* Run the SELECT statement twice. The first time, writefile() is called
5915    ** for all archive members that should be extracted. The second time,
5916    ** only for the directories. This is because the timestamps for
5917    ** extracted directories must be reset after they are populated (as
5918    ** populating them changes the timestamp).  */
5919    for(i=0; i<2; i++){
5920      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5921      sqlite3_bind_int(pSql, j, i);
5922      if( pAr->bDryRun ){
5923        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5924      }else{
5925        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5926          if( i==0 && pAr->bVerbose ){
5927            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5928          }
5929        }
5930      }
5931      shellReset(&rc, pSql);
5932    }
5933    shellFinalize(&rc, pSql);
5934  }
5935
5936  sqlite3_free(zDir);
5937  sqlite3_free(zWhere);
5938  return rc;
5939}
5940
5941/*
5942** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
5943*/
5944static int arExecSql(ArCommand *pAr, const char *zSql){
5945  int rc;
5946  if( pAr->bDryRun ){
5947    utf8_printf(pAr->p->out, "%s\n", zSql);
5948    rc = SQLITE_OK;
5949  }else{
5950    char *zErr = 0;
5951    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5952    if( zErr ){
5953      utf8_printf(stdout, "ERROR: %s\n", zErr);
5954      sqlite3_free(zErr);
5955    }
5956  }
5957  return rc;
5958}
5959
5960
5961/*
5962** Implementation of .ar "create", "insert", and "update" commands.
5963**
5964**     create    ->     Create a new SQL archive
5965**     insert    ->     Insert or reinsert all files listed
5966**     update    ->     Insert files that have changed or that were not
5967**                      previously in the archive
5968**
5969** Create the "sqlar" table in the database if it does not already exist.
5970** Then add each file in the azFile[] array to the archive. Directories
5971** are added recursively. If argument bVerbose is non-zero, a message is
5972** printed on stdout for each file archived.
5973**
5974** The create command is the same as update, except that it drops
5975** any existing "sqlar" table before beginning.  The "insert" command
5976** always overwrites every file named on the command-line, where as
5977** "update" only overwrites if the size or mtime or mode has changed.
5978*/
5979static int arCreateOrUpdateCommand(
5980  ArCommand *pAr,                 /* Command arguments and options */
5981  int bUpdate,                    /* true for a --create. */
5982  int bOnlyIfChanged              /* Only update if file has changed */
5983){
5984  const char *zCreate =
5985      "CREATE TABLE IF NOT EXISTS sqlar(\n"
5986      "  name TEXT PRIMARY KEY,  -- name of the file\n"
5987      "  mode INT,               -- access permissions\n"
5988      "  mtime INT,              -- last modification time\n"
5989      "  sz INT,                 -- original file size\n"
5990      "  data BLOB               -- compressed content\n"
5991      ")";
5992  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
5993  const char *zInsertFmt[2] = {
5994     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5995     "  SELECT\n"
5996     "    %s,\n"
5997     "    mode,\n"
5998     "    mtime,\n"
5999     "    CASE substr(lsmode(mode),1,1)\n"
6000     "      WHEN '-' THEN length(data)\n"
6001     "      WHEN 'd' THEN 0\n"
6002     "      ELSE -1 END,\n"
6003     "    sqlar_compress(data)\n"
6004     "  FROM fsdir(%Q,%Q) AS disk\n"
6005     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6006     ,
6007     "REPLACE INTO %s(name,mode,mtime,data)\n"
6008     "  SELECT\n"
6009     "    %s,\n"
6010     "    mode,\n"
6011     "    mtime,\n"
6012     "    data\n"
6013     "  FROM fsdir(%Q,%Q) AS disk\n"
6014     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6015  };
6016  int i;                          /* For iterating through azFile[] */
6017  int rc;                         /* Return code */
6018  const char *zTab = 0;           /* SQL table into which to insert */
6019  char *zSql;
6020  char zTemp[50];
6021  char *zExists = 0;
6022
6023  arExecSql(pAr, "PRAGMA page_size=512");
6024  rc = arExecSql(pAr, "SAVEPOINT ar;");
6025  if( rc!=SQLITE_OK ) return rc;
6026  zTemp[0] = 0;
6027  if( pAr->bZip ){
6028    /* Initialize the zipfile virtual table, if necessary */
6029    if( pAr->zFile ){
6030      sqlite3_uint64 r;
6031      sqlite3_randomness(sizeof(r),&r);
6032      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6033      zTab = zTemp;
6034      zSql = sqlite3_mprintf(
6035         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6036         zTab, pAr->zFile
6037      );
6038      rc = arExecSql(pAr, zSql);
6039      sqlite3_free(zSql);
6040    }else{
6041      zTab = "zip";
6042    }
6043  }else{
6044    /* Initialize the table for an SQLAR */
6045    zTab = "sqlar";
6046    if( bUpdate==0 ){
6047      rc = arExecSql(pAr, zDrop);
6048      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6049    }
6050    rc = arExecSql(pAr, zCreate);
6051  }
6052  if( bOnlyIfChanged ){
6053    zExists = sqlite3_mprintf(
6054      " AND NOT EXISTS("
6055          "SELECT 1 FROM %s AS mem"
6056          " WHERE mem.name=disk.name"
6057          " AND mem.mtime=disk.mtime"
6058          " AND mem.mode=disk.mode)", zTab);
6059  }else{
6060    zExists = sqlite3_mprintf("");
6061  }
6062  if( zExists==0 ) rc = SQLITE_NOMEM;
6063  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6064    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6065        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6066        pAr->azArg[i], pAr->zDir, zExists);
6067    rc = arExecSql(pAr, zSql2);
6068    sqlite3_free(zSql2);
6069  }
6070end_ar_transaction:
6071  if( rc!=SQLITE_OK ){
6072    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6073  }else{
6074    rc = arExecSql(pAr, "RELEASE ar;");
6075    if( pAr->bZip && pAr->zFile ){
6076      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6077      arExecSql(pAr, zSql);
6078      sqlite3_free(zSql);
6079    }
6080  }
6081  sqlite3_free(zExists);
6082  return rc;
6083}
6084
6085/*
6086** Implementation of ".ar" dot command.
6087*/
6088static int arDotCommand(
6089  ShellState *pState,             /* Current shell tool state */
6090  int fromCmdLine,                /* True if -A command-line option, not .ar cmd */
6091  char **azArg,                   /* Array of arguments passed to dot command */
6092  int nArg                        /* Number of entries in azArg[] */
6093){
6094  ArCommand cmd;
6095  int rc;
6096  memset(&cmd, 0, sizeof(cmd));
6097  cmd.fromCmdLine = fromCmdLine;
6098  rc = arParseCommand(azArg, nArg, &cmd);
6099  if( rc==SQLITE_OK ){
6100    int eDbType = SHELL_OPEN_UNSPEC;
6101    cmd.p = pState;
6102    cmd.db = pState->db;
6103    if( cmd.zFile ){
6104      eDbType = deduceDatabaseType(cmd.zFile, 1);
6105    }else{
6106      eDbType = pState->openMode;
6107    }
6108    if( eDbType==SHELL_OPEN_ZIPFILE ){
6109      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6110        if( cmd.zFile==0 ){
6111          cmd.zSrcTable = sqlite3_mprintf("zip");
6112        }else{
6113          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6114        }
6115      }
6116      cmd.bZip = 1;
6117    }else if( cmd.zFile ){
6118      int flags;
6119      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6120      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6121           || cmd.eCmd==AR_CMD_UPDATE ){
6122        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6123      }else{
6124        flags = SQLITE_OPEN_READONLY;
6125      }
6126      cmd.db = 0;
6127      if( cmd.bDryRun ){
6128        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6129             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6130      }
6131      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6132             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6133      if( rc!=SQLITE_OK ){
6134        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6135            cmd.zFile, sqlite3_errmsg(cmd.db)
6136        );
6137        goto end_ar_command;
6138      }
6139      sqlite3_fileio_init(cmd.db, 0, 0);
6140      sqlite3_sqlar_init(cmd.db, 0, 0);
6141      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6142                              shellPutsFunc, 0, 0);
6143
6144    }
6145    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6146      if( cmd.eCmd!=AR_CMD_CREATE
6147       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6148      ){
6149        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6150        rc = SQLITE_ERROR;
6151        goto end_ar_command;
6152      }
6153      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6154    }
6155
6156    switch( cmd.eCmd ){
6157      case AR_CMD_CREATE:
6158        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6159        break;
6160
6161      case AR_CMD_EXTRACT:
6162        rc = arExtractCommand(&cmd);
6163        break;
6164
6165      case AR_CMD_LIST:
6166        rc = arListCommand(&cmd);
6167        break;
6168
6169      case AR_CMD_HELP:
6170        arUsage(pState->out);
6171        break;
6172
6173      case AR_CMD_INSERT:
6174        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6175        break;
6176
6177      default:
6178        assert( cmd.eCmd==AR_CMD_UPDATE );
6179        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6180        break;
6181    }
6182  }
6183end_ar_command:
6184  if( cmd.db!=pState->db ){
6185    close_db(cmd.db);
6186  }
6187  sqlite3_free(cmd.zSrcTable);
6188
6189  return rc;
6190}
6191/* End of the ".archive" or ".ar" command logic
6192**********************************************************************************/
6193#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6194
6195#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6196/*
6197** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6198** Otherwise, the SQL statement or statements in zSql are executed using
6199** database connection db and the error code written to *pRc before
6200** this function returns.
6201*/
6202static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6203  int rc = *pRc;
6204  if( rc==SQLITE_OK ){
6205    char *zErr = 0;
6206    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6207    if( rc!=SQLITE_OK ){
6208      raw_printf(stderr, "SQL error: %s\n", zErr);
6209    }
6210    *pRc = rc;
6211  }
6212}
6213
6214/*
6215** Like shellExec(), except that zFmt is a printf() style format string.
6216*/
6217static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6218  char *z = 0;
6219  if( *pRc==SQLITE_OK ){
6220    va_list ap;
6221    va_start(ap, zFmt);
6222    z = sqlite3_vmprintf(zFmt, ap);
6223    va_end(ap);
6224    if( z==0 ){
6225      *pRc = SQLITE_NOMEM;
6226    }else{
6227      shellExec(db, pRc, z);
6228    }
6229    sqlite3_free(z);
6230  }
6231}
6232
6233/*
6234** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6235** Otherwise, an attempt is made to allocate, zero and return a pointer
6236** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6237** to SQLITE_NOMEM and NULL returned.
6238*/
6239static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6240  void *pRet = 0;
6241  if( *pRc==SQLITE_OK ){
6242    pRet = sqlite3_malloc64(nByte);
6243    if( pRet==0 ){
6244      *pRc = SQLITE_NOMEM;
6245    }else{
6246      memset(pRet, 0, nByte);
6247    }
6248  }
6249  return pRet;
6250}
6251
6252/*
6253** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6254** Otherwise, zFmt is treated as a printf() style string. The result of
6255** formatting it along with any trailing arguments is written into a
6256** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6257** It is the responsibility of the caller to eventually free this buffer
6258** using a call to sqlite3_free().
6259**
6260** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6261** pointer returned.
6262*/
6263static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6264  char *z = 0;
6265  if( *pRc==SQLITE_OK ){
6266    va_list ap;
6267    va_start(ap, zFmt);
6268    z = sqlite3_vmprintf(zFmt, ap);
6269    va_end(ap);
6270    if( z==0 ){
6271      *pRc = SQLITE_NOMEM;
6272    }
6273  }
6274  return z;
6275}
6276
6277/*
6278** When running the ".recover" command, each output table, and the special
6279** orphaned row table if it is required, is represented by an instance
6280** of the following struct.
6281*/
6282typedef struct RecoverTable RecoverTable;
6283struct RecoverTable {
6284  char *zQuoted;                  /* Quoted version of table name */
6285  int nCol;                       /* Number of columns in table */
6286  char **azlCol;                  /* Array of column lists */
6287  int iPk;                        /* Index of IPK column */
6288};
6289
6290/*
6291** Free a RecoverTable object allocated by recoverFindTable() or
6292** recoverOrphanTable().
6293*/
6294static void recoverFreeTable(RecoverTable *pTab){
6295  if( pTab ){
6296    sqlite3_free(pTab->zQuoted);
6297    if( pTab->azlCol ){
6298      int i;
6299      for(i=0; i<=pTab->nCol; i++){
6300        sqlite3_free(pTab->azlCol[i]);
6301      }
6302      sqlite3_free(pTab->azlCol);
6303    }
6304    sqlite3_free(pTab);
6305  }
6306}
6307
6308/*
6309** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6310** Otherwise, it allocates and returns a RecoverTable object based on the
6311** final four arguments passed to this function. It is the responsibility
6312** of the caller to eventually free the returned object using
6313** recoverFreeTable().
6314*/
6315static RecoverTable *recoverNewTable(
6316  int *pRc,                       /* IN/OUT: Error code */
6317  const char *zName,              /* Name of table */
6318  const char *zSql,               /* CREATE TABLE statement */
6319  int bIntkey,
6320  int nCol
6321){
6322  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
6323  int rc = *pRc;
6324  RecoverTable *pTab = 0;
6325
6326  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
6327  if( rc==SQLITE_OK ){
6328    int nSqlCol = 0;
6329    int bSqlIntkey = 0;
6330    sqlite3_stmt *pStmt = 0;
6331
6332    rc = sqlite3_open("", &dbtmp);
6333    if( rc==SQLITE_OK ){
6334      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6335    }
6336    if( rc==SQLITE_OK ){
6337      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6338      if( rc==SQLITE_ERROR ){
6339        rc = SQLITE_OK;
6340        goto finished;
6341      }
6342    }
6343    shellPreparePrintf(dbtmp, &rc, &pStmt,
6344        "SELECT count(*) FROM pragma_table_info(%Q)", zName
6345    );
6346    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6347      nSqlCol = sqlite3_column_int(pStmt, 0);
6348    }
6349    shellFinalize(&rc, pStmt);
6350
6351    if( rc!=SQLITE_OK || nSqlCol<nCol ){
6352      goto finished;
6353    }
6354
6355    shellPreparePrintf(dbtmp, &rc, &pStmt,
6356      "SELECT ("
6357      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6358      ") FROM sqlite_master WHERE name = %Q", zName
6359    );
6360    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6361      bSqlIntkey = sqlite3_column_int(pStmt, 0);
6362    }
6363    shellFinalize(&rc, pStmt);
6364
6365    if( bIntkey==bSqlIntkey ){
6366      int i;
6367      const char *zPk = "_rowid_";
6368      sqlite3_stmt *pPkFinder = 0;
6369
6370      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6371      ** set zPk to the name of the PK column, and pTab->iPk to the index
6372      ** of the column, where columns are 0-numbered from left to right.
6373      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6374      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
6375      pTab->iPk = -2;
6376      if( bIntkey ){
6377        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6378          "SELECT cid, name FROM pragma_table_info(%Q) "
6379          "  WHERE pk=1 AND type='integer' COLLATE nocase"
6380          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6381          , zName, zName
6382        );
6383        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6384          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6385          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6386        }
6387      }
6388
6389      pTab->zQuoted = shellMPrintf(&rc, "%Q", zName);
6390      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
6391      pTab->nCol = nSqlCol;
6392
6393      if( bIntkey ){
6394        pTab->azlCol[0] = shellMPrintf(&rc, "%Q", zPk);
6395      }else{
6396        pTab->azlCol[0] = shellMPrintf(&rc, "");
6397      }
6398      i = 1;
6399      shellPreparePrintf(dbtmp, &rc, &pStmt,
6400          "SELECT %Q || group_concat(quote(name), ', ') "
6401          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
6402          "FROM pragma_table_info(%Q)",
6403          bIntkey ? ", " : "", pTab->iPk,
6404          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6405          zName
6406      );
6407      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6408        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6409        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6410        i++;
6411      }
6412      shellFinalize(&rc, pStmt);
6413
6414      shellFinalize(&rc, pPkFinder);
6415    }
6416  }
6417
6418 finished:
6419  sqlite3_close(dbtmp);
6420  *pRc = rc;
6421  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
6422    recoverFreeTable(pTab);
6423    pTab = 0;
6424  }
6425  return pTab;
6426}
6427
6428/*
6429** This function is called to search the schema recovered from the
6430** sqlite_master table of the (possibly) corrupt database as part
6431** of a ".recover" command. Specifically, for a table with root page
6432** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6433** table must be a WITHOUT ROWID table, or if non-zero, not one of
6434** those.
6435**
6436** If a table is found, a (RecoverTable*) object is returned. Or, if
6437** no such table is found, but bIntkey is false and iRoot is the
6438** root page of an index in the recovered schema, then (*pbNoop) is
6439** set to true and NULL returned. Or, if there is no such table or
6440** index, NULL is returned and (*pbNoop) set to 0, indicating that
6441** the caller should write data to the orphans table.
6442*/
6443static RecoverTable *recoverFindTable(
6444  ShellState *pState,             /* Shell state object */
6445  int *pRc,                       /* IN/OUT: Error code */
6446  int iRoot,                      /* Root page of table */
6447  int bIntkey,                    /* True for an intkey table */
6448  int nCol,                       /* Number of columns in table */
6449  int *pbNoop                     /* OUT: True if iRoot is root of index */
6450){
6451  sqlite3_stmt *pStmt = 0;
6452  RecoverTable *pRet = 0;
6453  int bNoop = 0;
6454  const char *zSql = 0;
6455  const char *zName = 0;
6456
6457  /* Search the recovered schema for an object with root page iRoot. */
6458  shellPreparePrintf(pState->db, pRc, &pStmt,
6459      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6460  );
6461  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6462    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6463    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6464      bNoop = 1;
6465      break;
6466    }
6467    if( sqlite3_stricmp(zType, "table")==0 ){
6468      zName = (const char*)sqlite3_column_text(pStmt, 1);
6469      zSql = (const char*)sqlite3_column_text(pStmt, 2);
6470      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
6471      break;
6472    }
6473  }
6474
6475  shellFinalize(pRc, pStmt);
6476  *pbNoop = bNoop;
6477  return pRet;
6478}
6479
6480/*
6481** Return a RecoverTable object representing the orphans table.
6482*/
6483static RecoverTable *recoverOrphanTable(
6484  ShellState *pState,             /* Shell state object */
6485  int *pRc,                       /* IN/OUT: Error code */
6486  const char *zLostAndFound,      /* Base name for orphans table */
6487  int nCol                        /* Number of user data columns */
6488){
6489  RecoverTable *pTab = 0;
6490  if( nCol>=0 && *pRc==SQLITE_OK ){
6491    int i;
6492
6493    /* This block determines the name of the orphan table. The prefered
6494    ** name is zLostAndFound. But if that clashes with another name
6495    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
6496    ** and so on until a non-clashing name is found.  */
6497    int iTab = 0;
6498    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
6499    sqlite3_stmt *pTest = 0;
6500    shellPrepare(pState->db, pRc,
6501        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
6502    );
6503    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6504    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
6505      shellReset(pRc, pTest);
6506      sqlite3_free(zTab);
6507      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
6508      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6509    }
6510    shellFinalize(pRc, pTest);
6511
6512    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
6513    if( pTab ){
6514      pTab->zQuoted = shellMPrintf(pRc, "%Q", zTab);
6515      pTab->nCol = nCol;
6516      pTab->iPk = -2;
6517      if( nCol>0 ){
6518        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
6519        if( pTab->azlCol ){
6520          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
6521          for(i=nCol-1; i>=0; i--){
6522            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
6523          }
6524        }
6525      }
6526
6527      if( *pRc!=SQLITE_OK ){
6528        recoverFreeTable(pTab);
6529        pTab = 0;
6530      }else{
6531        raw_printf(pState->out,
6532            "CREATE TABLE %s(rootpgno INTEGER, "
6533            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
6534        );
6535        for(i=0; i<nCol; i++){
6536          raw_printf(pState->out, ", c%d", i);
6537        }
6538        raw_printf(pState->out, ");\n");
6539      }
6540    }
6541    sqlite3_free(zTab);
6542  }
6543  return pTab;
6544}
6545
6546/*
6547** This function is called to recover data from the database. A script
6548** to construct a new database containing all recovered data is output
6549** on stream pState->out.
6550*/
6551static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
6552  int rc = SQLITE_OK;
6553  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
6554  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
6555  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
6556  const char *zRecoveryDb = "";   /* Name of "recovery" database */
6557  const char *zLostAndFound = "lost_and_found";
6558  int i;
6559  int nOrphan = -1;
6560  RecoverTable *pOrphan = 0;
6561
6562  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
6563  for(i=1; i<nArg; i++){
6564    char *z = azArg[i];
6565    int n;
6566    if( z[0]=='-' && z[1]=='-' ) z++;
6567    n = strlen30(z);
6568    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
6569      bFreelist = 0;
6570    }else
6571    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
6572      i++;
6573      zRecoveryDb = azArg[i];
6574    }else
6575    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
6576      i++;
6577      zLostAndFound = azArg[i];
6578    }
6579    else{
6580      raw_printf(stderr, "unexpected option: %s\n", azArg[i]);
6581      raw_printf(stderr, "options are:\n");
6582      raw_printf(stderr, "    --freelist-corrupt\n");
6583      raw_printf(stderr, "    --recovery-db DATABASE\n");
6584      raw_printf(stderr, "    --lost-and-found TABLE-NAME\n");
6585      return 1;
6586    }
6587  }
6588
6589  shellExecPrintf(pState->db, &rc,
6590    /* Attach an in-memory database named 'recovery'. Create an indexed
6591    ** cache of the sqlite_dbptr virtual table. */
6592    "PRAGMA writable_schema = on;"
6593    "ATTACH %Q AS recovery;"
6594    "DROP TABLE IF EXISTS recovery.dbptr;"
6595    "DROP TABLE IF EXISTS recovery.freelist;"
6596    "DROP TABLE IF EXISTS recovery.map;"
6597    "DROP TABLE IF EXISTS recovery.schema;"
6598    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
6599  );
6600
6601  if( bFreelist ){
6602    shellExec(pState->db, &rc,
6603      "WITH trunk(pgno) AS ("
6604      "  SELECT shell_int32("
6605      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
6606      "      WHERE x>0"
6607      "    UNION"
6608      "  SELECT shell_int32("
6609      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
6610      "      FROM trunk WHERE x>0"
6611      "),"
6612      "freelist(data, n, freepgno) AS ("
6613      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
6614      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
6615      "    UNION ALL"
6616      "  SELECT data, n-1, shell_int32(data, 2+n) "
6617      "      FROM freelist WHERE n>=0"
6618      ")"
6619      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
6620    );
6621  }
6622
6623  /* If this is an auto-vacuum database, add all pointer-map pages to
6624  ** the freelist table. Do this regardless of whether or not
6625  ** --freelist-corrupt was specified.  */
6626  shellExec(pState->db, &rc,
6627    "WITH ptrmap(pgno) AS ("
6628    "  SELECT 2 WHERE shell_int32("
6629    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
6630    "  )"
6631    "    UNION ALL "
6632    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
6633    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
6634    ")"
6635    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
6636  );
6637
6638  shellExec(pState->db, &rc,
6639    "CREATE TABLE recovery.dbptr("
6640    "      pgno, child, PRIMARY KEY(child, pgno)"
6641    ") WITHOUT ROWID;"
6642    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
6643    "    SELECT * FROM sqlite_dbptr"
6644    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
6645
6646    /* Delete any pointer to page 1. This ensures that page 1 is considered
6647    ** a root page, regardless of how corrupt the db is. */
6648    "DELETE FROM recovery.dbptr WHERE child = 1;"
6649
6650    /* Delete all pointers to any pages that have more than one pointer
6651    ** to them. Such pages will be treated as root pages when recovering
6652    ** data.  */
6653    "DELETE FROM recovery.dbptr WHERE child IN ("
6654    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6655    ");"
6656
6657    /* Create the "map" table that will (eventually) contain instructions
6658    ** for dealing with each page in the db that contains one or more
6659    ** records. */
6660    "CREATE TABLE recovery.map("
6661      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6662    ");"
6663
6664    /* Populate table [map]. If there are circular loops of pages in the
6665    ** database, the following adds all pages in such a loop to the map
6666    ** as individual root pages. This could be handled better.  */
6667    "WITH pages(i, maxlen) AS ("
6668    "  SELECT page_count, ("
6669    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
6670    "  ) FROM pragma_page_count WHERE page_count>0"
6671    "    UNION ALL"
6672    "  SELECT i-1, ("
6673    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6674    "  ) FROM pages WHERE i>=2"
6675    ")"
6676    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6677    "  SELECT i, maxlen, NULL, ("
6678    "    WITH p(orig, pgno, parent) AS ("
6679    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
6680    "        UNION "
6681    "      SELECT i, p.parent, "
6682    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6683    "    )"
6684    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6685    ") "
6686    "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;"
6687    "UPDATE recovery.map AS o SET intkey = ("
6688    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6689    ");"
6690
6691    /* Extract data from page 1 and any linked pages into table
6692    ** recovery.schema. With the same schema as an sqlite_master table.  */
6693    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6694    "INSERT INTO recovery.schema SELECT "
6695    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
6696    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
6697    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
6698    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
6699    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
6700    "FROM sqlite_dbdata WHERE pgno IN ("
6701    "  SELECT pgno FROM recovery.map WHERE root=1"
6702    ")"
6703    "GROUP BY pgno, cell;"
6704    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
6705  );
6706
6707  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6708  ** CREATE TABLE statements that extracted from the existing schema.  */
6709  if( rc==SQLITE_OK ){
6710    sqlite3_stmt *pStmt = 0;
6711    raw_printf(pState->out, "BEGIN;\n");
6712    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6713    shellPrepare(pState->db, &rc,
6714        "SELECT sql FROM recovery.schema "
6715        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
6716    );
6717    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6718      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
6719      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6720          &zCreateTable[12]
6721      );
6722    }
6723    shellFinalize(&rc, pStmt);
6724  }
6725
6726  /* Figure out if an orphan table will be required. And if so, how many
6727  ** user columns it should contain */
6728  shellPrepare(pState->db, &rc,
6729      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
6730      , &pLoop
6731  );
6732  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6733    nOrphan = sqlite3_column_int(pLoop, 0);
6734  }
6735  shellFinalize(&rc, pLoop);
6736  pLoop = 0;
6737
6738  shellPrepare(pState->db, &rc,
6739      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6740  );
6741  shellPrepare(pState->db, &rc,
6742      "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')"
6743      ", min(field) "
6744      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6745      "GROUP BY cell", &pCells
6746  );
6747
6748  /* Loop through each root page. */
6749  shellPrepare(pState->db, &rc,
6750      "SELECT root, intkey, max(maxlen) FROM recovery.map"
6751      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6752      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6753      ")", &pLoop
6754  );
6755  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6756    int iRoot = sqlite3_column_int(pLoop, 0);
6757    int bIntkey = sqlite3_column_int(pLoop, 1);
6758    int nCol = sqlite3_column_int(pLoop, 2);
6759    int bNoop = 0;
6760    RecoverTable *pTab;
6761
6762    assert( bIntkey==0 || bIntkey==1 );
6763    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
6764    if( bNoop || rc ) continue;
6765    if( pTab==0 ){
6766      if( pOrphan==0 ){
6767        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6768      }
6769      pTab = pOrphan;
6770      if( pTab==0 ) break;
6771    }
6772
6773    if( 0==sqlite3_stricmp(pTab->zQuoted, "'sqlite_sequence'") ){
6774      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6775    }
6776    sqlite3_bind_int(pPages, 1, iRoot);
6777    sqlite3_bind_int(pCells, 2, pTab->iPk);
6778
6779    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6780      int iPgno = sqlite3_column_int(pPages, 0);
6781      sqlite3_bind_int(pCells, 1, iPgno);
6782      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6783        int nField = sqlite3_column_int(pCells, 0);
6784        int iMin = sqlite3_column_int(pCells, 2);
6785        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6786
6787        RecoverTable *pTab2 = pTab;
6788        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
6789          if( pOrphan==0 ){
6790            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6791          }
6792          pTab2 = pOrphan;
6793          if( pTab2==0 ) break;
6794        }
6795
6796        nField = nField+1;
6797        if( pTab2==pOrphan ){
6798          raw_printf(pState->out,
6799              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
6800              pTab2->zQuoted, iRoot, iPgno, nField,
6801              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
6802          );
6803        }else{
6804          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
6805              pTab2->zQuoted, pTab2->azlCol[nField], zVal
6806          );
6807        }
6808      }
6809      shellReset(&rc, pCells);
6810    }
6811    shellReset(&rc, pPages);
6812    if( pTab!=pOrphan ) recoverFreeTable(pTab);
6813  }
6814  shellFinalize(&rc, pLoop);
6815  shellFinalize(&rc, pPages);
6816  shellFinalize(&rc, pCells);
6817  recoverFreeTable(pOrphan);
6818
6819  /* The rest of the schema */
6820  if( rc==SQLITE_OK ){
6821    sqlite3_stmt *pStmt = 0;
6822    shellPrepare(pState->db, &rc,
6823        "SELECT sql, name FROM recovery.schema "
6824        "WHERE sql NOT LIKE 'create table%'", &pStmt
6825    );
6826    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6827      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6828      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6829        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6830        char *zPrint = shellMPrintf(&rc,
6831          "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6832          zName, zName, zSql
6833        );
6834        raw_printf(pState->out, "%s;\n", zPrint);
6835        sqlite3_free(zPrint);
6836      }else{
6837        raw_printf(pState->out, "%s;\n", zSql);
6838      }
6839    }
6840    shellFinalize(&rc, pStmt);
6841  }
6842
6843  if( rc==SQLITE_OK ){
6844    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
6845    raw_printf(pState->out, "COMMIT;\n");
6846  }
6847  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6848  return rc;
6849}
6850#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
6851
6852
6853/*
6854** If an input line begins with "." then invoke this routine to
6855** process that line.
6856**
6857** Return 1 on error, 2 to exit, and 0 otherwise.
6858*/
6859static int do_meta_command(char *zLine, ShellState *p){
6860  int h = 1;
6861  int nArg = 0;
6862  int n, c;
6863  int rc = 0;
6864  char *azArg[50];
6865
6866#ifndef SQLITE_OMIT_VIRTUALTABLE
6867  if( p->expert.pExpert ){
6868    expertFinish(p, 1, 0);
6869  }
6870#endif
6871
6872  /* Parse the input line into tokens.
6873  */
6874  while( zLine[h] && nArg<ArraySize(azArg) ){
6875    while( IsSpace(zLine[h]) ){ h++; }
6876    if( zLine[h]==0 ) break;
6877    if( zLine[h]=='\'' || zLine[h]=='"' ){
6878      int delim = zLine[h++];
6879      azArg[nArg++] = &zLine[h];
6880      while( zLine[h] && zLine[h]!=delim ){
6881        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6882        h++;
6883      }
6884      if( zLine[h]==delim ){
6885        zLine[h++] = 0;
6886      }
6887      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6888    }else{
6889      azArg[nArg++] = &zLine[h];
6890      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6891      if( zLine[h] ) zLine[h++] = 0;
6892      resolve_backslashes(azArg[nArg-1]);
6893    }
6894  }
6895
6896  /* Process the input line.
6897  */
6898  if( nArg==0 ) return 0; /* no tokens, no error */
6899  n = strlen30(azArg[0]);
6900  c = azArg[0][0];
6901  clearTempFile(p);
6902
6903#ifndef SQLITE_OMIT_AUTHORIZATION
6904  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6905    if( nArg!=2 ){
6906      raw_printf(stderr, "Usage: .auth ON|OFF\n");
6907      rc = 1;
6908      goto meta_command_exit;
6909    }
6910    open_db(p, 0);
6911    if( booleanValue(azArg[1]) ){
6912      sqlite3_set_authorizer(p->db, shellAuth, p);
6913    }else{
6914      sqlite3_set_authorizer(p->db, 0, 0);
6915    }
6916  }else
6917#endif
6918
6919#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6920  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
6921    open_db(p, 0);
6922    rc = arDotCommand(p, 0, azArg, nArg);
6923  }else
6924#endif
6925
6926  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6927   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6928  ){
6929    const char *zDestFile = 0;
6930    const char *zDb = 0;
6931    sqlite3 *pDest;
6932    sqlite3_backup *pBackup;
6933    int j;
6934    int bAsync = 0;
6935    const char *zVfs = 0;
6936    for(j=1; j<nArg; j++){
6937      const char *z = azArg[j];
6938      if( z[0]=='-' ){
6939        if( z[1]=='-' ) z++;
6940        if( strcmp(z, "-append")==0 ){
6941          zVfs = "apndvfs";
6942        }else
6943        if( strcmp(z, "-async")==0 ){
6944          bAsync = 1;
6945        }else
6946        {
6947          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6948          return 1;
6949        }
6950      }else if( zDestFile==0 ){
6951        zDestFile = azArg[j];
6952      }else if( zDb==0 ){
6953        zDb = zDestFile;
6954        zDestFile = azArg[j];
6955      }else{
6956        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
6957        return 1;
6958      }
6959    }
6960    if( zDestFile==0 ){
6961      raw_printf(stderr, "missing FILENAME argument on .backup\n");
6962      return 1;
6963    }
6964    if( zDb==0 ) zDb = "main";
6965    rc = sqlite3_open_v2(zDestFile, &pDest,
6966                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
6967    if( rc!=SQLITE_OK ){
6968      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
6969      close_db(pDest);
6970      return 1;
6971    }
6972    if( bAsync ){
6973      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6974                   0, 0, 0);
6975    }
6976    open_db(p, 0);
6977    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6978    if( pBackup==0 ){
6979      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6980      close_db(pDest);
6981      return 1;
6982    }
6983    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6984    sqlite3_backup_finish(pBackup);
6985    if( rc==SQLITE_DONE ){
6986      rc = 0;
6987    }else{
6988      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6989      rc = 1;
6990    }
6991    close_db(pDest);
6992  }else
6993
6994  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6995    if( nArg==2 ){
6996      bail_on_error = booleanValue(azArg[1]);
6997    }else{
6998      raw_printf(stderr, "Usage: .bail on|off\n");
6999      rc = 1;
7000    }
7001  }else
7002
7003  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7004    if( nArg==2 ){
7005      if( booleanValue(azArg[1]) ){
7006        setBinaryMode(p->out, 1);
7007      }else{
7008        setTextMode(p->out, 1);
7009      }
7010    }else{
7011      raw_printf(stderr, "Usage: .binary on|off\n");
7012      rc = 1;
7013    }
7014  }else
7015
7016  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7017    if( nArg==2 ){
7018#if defined(_WIN32) || defined(WIN32)
7019      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7020      rc = !SetCurrentDirectoryW(z);
7021      sqlite3_free(z);
7022#else
7023      rc = chdir(azArg[1]);
7024#endif
7025      if( rc ){
7026        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7027        rc = 1;
7028      }
7029    }else{
7030      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7031      rc = 1;
7032    }
7033  }else
7034
7035  /* The undocumented ".breakpoint" command causes a call to the no-op
7036  ** routine named test_breakpoint().
7037  */
7038  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7039    test_breakpoint();
7040  }else
7041
7042  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7043    if( nArg==2 ){
7044      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7045    }else{
7046      raw_printf(stderr, "Usage: .changes on|off\n");
7047      rc = 1;
7048    }
7049  }else
7050
7051  /* Cancel output redirection, if it is currently set (by .testcase)
7052  ** Then read the content of the testcase-out.txt file and compare against
7053  ** azArg[1].  If there are differences, report an error and exit.
7054  */
7055  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7056    char *zRes = 0;
7057    output_reset(p);
7058    if( nArg!=2 ){
7059      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7060      rc = 2;
7061    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7062      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7063      rc = 2;
7064    }else if( testcase_glob(azArg[1],zRes)==0 ){
7065      utf8_printf(stderr,
7066                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7067                 p->zTestcase, azArg[1], zRes);
7068      rc = 1;
7069    }else{
7070      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7071      p->nCheck++;
7072    }
7073    sqlite3_free(zRes);
7074  }else
7075
7076  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7077    if( nArg==2 ){
7078      tryToClone(p, azArg[1]);
7079    }else{
7080      raw_printf(stderr, "Usage: .clone FILENAME\n");
7081      rc = 1;
7082    }
7083  }else
7084
7085  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7086    ShellState data;
7087    char *zErrMsg = 0;
7088    open_db(p, 0);
7089    memcpy(&data, p, sizeof(data));
7090    data.showHeader = 0;
7091    data.cMode = data.mode = MODE_List;
7092    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
7093    data.cnt = 0;
7094    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
7095                 callback, &data, &zErrMsg);
7096    if( zErrMsg ){
7097      utf8_printf(stderr,"Error: %s\n", zErrMsg);
7098      sqlite3_free(zErrMsg);
7099      rc = 1;
7100    }
7101  }else
7102
7103  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7104    static const struct DbConfigChoices {
7105      const char *zName;
7106      int op;
7107    } aDbConfig[] = {
7108        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7109        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7110        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7111        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7112        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7113        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7114        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7115        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7116        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7117        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7118        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7119        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7120        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7121    };
7122    int ii, v;
7123    open_db(p, 0);
7124    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7125      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7126      if( nArg>=3 ){
7127        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7128      }
7129      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7130      utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7131      if( nArg>1 ) break;
7132    }
7133    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7134      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7135      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7136    }
7137  }else
7138
7139  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7140    rc = shell_dbinfo_command(p, nArg, azArg);
7141  }else
7142
7143#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7144  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7145    open_db(p, 0);
7146    rc = recoverDatabaseCmd(p, nArg, azArg);
7147  }else
7148#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7149
7150  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7151    const char *zLike = 0;
7152    int i;
7153    int savedShowHeader = p->showHeader;
7154    int savedShellFlags = p->shellFlgs;
7155    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
7156    for(i=1; i<nArg; i++){
7157      if( azArg[i][0]=='-' ){
7158        const char *z = azArg[i]+1;
7159        if( z[0]=='-' ) z++;
7160        if( strcmp(z,"preserve-rowids")==0 ){
7161#ifdef SQLITE_OMIT_VIRTUALTABLE
7162          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7163                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7164          rc = 1;
7165          goto meta_command_exit;
7166#else
7167          ShellSetFlag(p, SHFLG_PreserveRowid);
7168#endif
7169        }else
7170        if( strcmp(z,"newlines")==0 ){
7171          ShellSetFlag(p, SHFLG_Newlines);
7172        }else
7173        {
7174          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7175          rc = 1;
7176          goto meta_command_exit;
7177        }
7178      }else if( zLike ){
7179        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
7180                           "?--newlines? ?LIKE-PATTERN?\n");
7181        rc = 1;
7182        goto meta_command_exit;
7183      }else{
7184        zLike = azArg[i];
7185      }
7186    }
7187
7188    open_db(p, 0);
7189
7190    /* When playing back a "dump", the content might appear in an order
7191    ** which causes immediate foreign key constraints to be violated.
7192    ** So disable foreign-key constraint enforcement to prevent problems. */
7193    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7194    raw_printf(p->out, "BEGIN TRANSACTION;\n");
7195    p->writableSchema = 0;
7196    p->showHeader = 0;
7197    /* Set writable_schema=ON since doing so forces SQLite to initialize
7198    ** as much of the schema as it can even if the sqlite_master table is
7199    ** corrupt. */
7200    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7201    p->nErr = 0;
7202    if( zLike==0 ){
7203      run_schema_dump_query(p,
7204        "SELECT name, type, sql FROM sqlite_master "
7205        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
7206      );
7207      run_schema_dump_query(p,
7208        "SELECT name, type, sql FROM sqlite_master "
7209        "WHERE name=='sqlite_sequence'"
7210      );
7211      run_table_dump_query(p,
7212        "SELECT sql FROM sqlite_master "
7213        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
7214      );
7215    }else{
7216      char *zSql;
7217      zSql = sqlite3_mprintf(
7218        "SELECT name, type, sql FROM sqlite_master "
7219        "WHERE tbl_name LIKE %Q AND type=='table'"
7220        "  AND sql NOT NULL", zLike);
7221      run_schema_dump_query(p,zSql);
7222      sqlite3_free(zSql);
7223      zSql = sqlite3_mprintf(
7224        "SELECT sql FROM sqlite_master "
7225        "WHERE sql NOT NULL"
7226        "  AND type IN ('index','trigger','view')"
7227        "  AND tbl_name LIKE %Q", zLike);
7228      run_table_dump_query(p, zSql, 0);
7229      sqlite3_free(zSql);
7230    }
7231    if( p->writableSchema ){
7232      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7233      p->writableSchema = 0;
7234    }
7235    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7236    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
7237    raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
7238    p->showHeader = savedShowHeader;
7239    p->shellFlgs = savedShellFlags;
7240  }else
7241
7242  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7243    if( nArg==2 ){
7244      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7245    }else{
7246      raw_printf(stderr, "Usage: .echo on|off\n");
7247      rc = 1;
7248    }
7249  }else
7250
7251  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7252    if( nArg==2 ){
7253      p->autoEQPtest = 0;
7254      if( p->autoEQPtrace ){
7255        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7256        p->autoEQPtrace = 0;
7257      }
7258      if( strcmp(azArg[1],"full")==0 ){
7259        p->autoEQP = AUTOEQP_full;
7260      }else if( strcmp(azArg[1],"trigger")==0 ){
7261        p->autoEQP = AUTOEQP_trigger;
7262#ifdef SQLITE_DEBUG
7263      }else if( strcmp(azArg[1],"test")==0 ){
7264        p->autoEQP = AUTOEQP_on;
7265        p->autoEQPtest = 1;
7266      }else if( strcmp(azArg[1],"trace")==0 ){
7267        p->autoEQP = AUTOEQP_full;
7268        p->autoEQPtrace = 1;
7269        open_db(p, 0);
7270        sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
7271        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7272#endif
7273      }else{
7274        p->autoEQP = (u8)booleanValue(azArg[1]);
7275      }
7276    }else{
7277      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
7278      rc = 1;
7279    }
7280  }else
7281
7282  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7283    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7284    rc = 2;
7285  }else
7286
7287  /* The ".explain" command is automatic now.  It is largely pointless.  It
7288  ** retained purely for backwards compatibility */
7289  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7290    int val = 1;
7291    if( nArg>=2 ){
7292      if( strcmp(azArg[1],"auto")==0 ){
7293        val = 99;
7294      }else{
7295        val =  booleanValue(azArg[1]);
7296      }
7297    }
7298    if( val==1 && p->mode!=MODE_Explain ){
7299      p->normalMode = p->mode;
7300      p->mode = MODE_Explain;
7301      p->autoExplain = 0;
7302    }else if( val==0 ){
7303      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7304      p->autoExplain = 0;
7305    }else if( val==99 ){
7306      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7307      p->autoExplain = 1;
7308    }
7309  }else
7310
7311#ifndef SQLITE_OMIT_VIRTUALTABLE
7312  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7313    open_db(p, 0);
7314    expertDotCommand(p, azArg, nArg);
7315  }else
7316#endif
7317
7318  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7319    static const struct {
7320       const char *zCtrlName;   /* Name of a test-control option */
7321       int ctrlCode;            /* Integer code for that option */
7322       const char *zUsage;      /* Usage notes */
7323    } aCtrl[] = {
7324      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
7325      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
7326   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
7327      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
7328      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
7329   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
7330      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
7331      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
7332      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
7333    };
7334    int filectrl = -1;
7335    int iCtrl = -1;
7336    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
7337    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
7338    int n2, i;
7339    const char *zCmd = 0;
7340
7341    open_db(p, 0);
7342    zCmd = nArg>=2 ? azArg[1] : "help";
7343
7344    /* The argument can optionally begin with "-" or "--" */
7345    if( zCmd[0]=='-' && zCmd[1] ){
7346      zCmd++;
7347      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7348    }
7349
7350    /* --help lists all file-controls */
7351    if( strcmp(zCmd,"help")==0 ){
7352      utf8_printf(p->out, "Available file-controls:\n");
7353      for(i=0; i<ArraySize(aCtrl); i++){
7354        utf8_printf(p->out, "  .filectrl %s %s\n",
7355                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7356      }
7357      rc = 1;
7358      goto meta_command_exit;
7359    }
7360
7361    /* convert filectrl text option to value. allow any unique prefix
7362    ** of the option name, or a numerical value. */
7363    n2 = strlen30(zCmd);
7364    for(i=0; i<ArraySize(aCtrl); i++){
7365      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7366        if( filectrl<0 ){
7367          filectrl = aCtrl[i].ctrlCode;
7368          iCtrl = i;
7369        }else{
7370          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
7371                              "Use \".filectrl --help\" for help\n", zCmd);
7372          rc = 1;
7373          goto meta_command_exit;
7374        }
7375      }
7376    }
7377    if( filectrl<0 ){
7378      utf8_printf(stderr,"Error: unknown file-control: %s\n"
7379                         "Use \".filectrl --help\" for help\n", zCmd);
7380    }else{
7381      switch(filectrl){
7382        case SQLITE_FCNTL_SIZE_LIMIT: {
7383          if( nArg!=2 && nArg!=3 ) break;
7384          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
7385          sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
7386          isOk = 1;
7387          break;
7388        }
7389        case SQLITE_FCNTL_LOCK_TIMEOUT:
7390        case SQLITE_FCNTL_CHUNK_SIZE: {
7391          int x;
7392          if( nArg!=3 ) break;
7393          x = (int)integerValue(azArg[2]);
7394          sqlite3_file_control(p->db, 0, filectrl, &x);
7395          isOk = 2;
7396          break;
7397        }
7398        case SQLITE_FCNTL_PERSIST_WAL:
7399        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
7400          int x;
7401          if( nArg!=2 && nArg!=3 ) break;
7402          x = nArg==3 ? booleanValue(azArg[2]) : -1;
7403          sqlite3_file_control(p->db, 0, filectrl, &x);
7404          iRes = x;
7405          isOk = 1;
7406          break;
7407        }
7408        case SQLITE_FCNTL_HAS_MOVED: {
7409          int x;
7410          if( nArg!=2 ) break;
7411          sqlite3_file_control(p->db, 0, filectrl, &x);
7412          iRes = x;
7413          isOk = 1;
7414          break;
7415        }
7416        case SQLITE_FCNTL_TEMPFILENAME: {
7417          char *z = 0;
7418          if( nArg!=2 ) break;
7419          sqlite3_file_control(p->db, 0, filectrl, &z);
7420          if( z ){
7421            utf8_printf(p->out, "%s\n", z);
7422            sqlite3_free(z);
7423          }
7424          isOk = 2;
7425          break;
7426        }
7427      }
7428    }
7429    if( isOk==0 && iCtrl>=0 ){
7430      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
7431      rc = 1;
7432    }else if( isOk==1 ){
7433      char zBuf[100];
7434      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
7435      raw_printf(p->out, "%s\n", zBuf);
7436    }
7437  }else
7438
7439  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7440    ShellState data;
7441    char *zErrMsg = 0;
7442    int doStats = 0;
7443    memcpy(&data, p, sizeof(data));
7444    data.showHeader = 0;
7445    data.cMode = data.mode = MODE_Semi;
7446    if( nArg==2 && optionMatch(azArg[1], "indent") ){
7447      data.cMode = data.mode = MODE_Pretty;
7448      nArg = 1;
7449    }
7450    if( nArg!=1 ){
7451      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7452      rc = 1;
7453      goto meta_command_exit;
7454    }
7455    open_db(p, 0);
7456    rc = sqlite3_exec(p->db,
7457       "SELECT sql FROM"
7458       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7459       "     FROM sqlite_master UNION ALL"
7460       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7461       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7462       "ORDER BY rowid",
7463       callback, &data, &zErrMsg
7464    );
7465    if( rc==SQLITE_OK ){
7466      sqlite3_stmt *pStmt;
7467      rc = sqlite3_prepare_v2(p->db,
7468               "SELECT rowid FROM sqlite_master"
7469               " WHERE name GLOB 'sqlite_stat[134]'",
7470               -1, &pStmt, 0);
7471      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7472      sqlite3_finalize(pStmt);
7473    }
7474    if( doStats==0 ){
7475      raw_printf(p->out, "/* No STAT tables available */\n");
7476    }else{
7477      raw_printf(p->out, "ANALYZE sqlite_master;\n");
7478      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7479                   callback, &data, &zErrMsg);
7480      data.cMode = data.mode = MODE_Insert;
7481      data.zDestTable = "sqlite_stat1";
7482      shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
7483      data.zDestTable = "sqlite_stat3";
7484      shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
7485      data.zDestTable = "sqlite_stat4";
7486      shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
7487      raw_printf(p->out, "ANALYZE sqlite_master;\n");
7488    }
7489  }else
7490
7491  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7492    if( nArg==2 ){
7493      p->showHeader = booleanValue(azArg[1]);
7494    }else{
7495      raw_printf(stderr, "Usage: .headers on|off\n");
7496      rc = 1;
7497    }
7498  }else
7499
7500  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
7501    if( nArg>=2 ){
7502      n = showHelp(p->out, azArg[1]);
7503      if( n==0 ){
7504        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7505      }
7506    }else{
7507      showHelp(p->out, 0);
7508    }
7509  }else
7510
7511  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7512    char *zTable;               /* Insert data into this table */
7513    char *zFile;                /* Name of file to extra content from */
7514    sqlite3_stmt *pStmt = NULL; /* A statement */
7515    int nCol;                   /* Number of columns in the table */
7516    int nByte;                  /* Number of bytes in an SQL string */
7517    int i, j;                   /* Loop counters */
7518    int needCommit;             /* True to COMMIT or ROLLBACK at end */
7519    int nSep;                   /* Number of bytes in p->colSeparator[] */
7520    char *zSql;                 /* An SQL statement */
7521    ImportCtx sCtx;             /* Reader context */
7522    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7523    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
7524
7525    if( nArg!=3 ){
7526      raw_printf(stderr, "Usage: .import FILE TABLE\n");
7527      goto meta_command_exit;
7528    }
7529    zFile = azArg[1];
7530    zTable = azArg[2];
7531    seenInterrupt = 0;
7532    memset(&sCtx, 0, sizeof(sCtx));
7533    open_db(p, 0);
7534    nSep = strlen30(p->colSeparator);
7535    if( nSep==0 ){
7536      raw_printf(stderr,
7537                 "Error: non-null column separator required for import\n");
7538      return 1;
7539    }
7540    if( nSep>1 ){
7541      raw_printf(stderr, "Error: multi-character column separators not allowed"
7542                      " for import\n");
7543      return 1;
7544    }
7545    nSep = strlen30(p->rowSeparator);
7546    if( nSep==0 ){
7547      raw_printf(stderr, "Error: non-null row separator required for import\n");
7548      return 1;
7549    }
7550    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7551      /* When importing CSV (only), if the row separator is set to the
7552      ** default output row separator, change it to the default input
7553      ** row separator.  This avoids having to maintain different input
7554      ** and output row separators. */
7555      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7556      nSep = strlen30(p->rowSeparator);
7557    }
7558    if( nSep>1 ){
7559      raw_printf(stderr, "Error: multi-character row separators not allowed"
7560                      " for import\n");
7561      return 1;
7562    }
7563    sCtx.zFile = zFile;
7564    sCtx.nLine = 1;
7565    if( sCtx.zFile[0]=='|' ){
7566#ifdef SQLITE_OMIT_POPEN
7567      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7568      return 1;
7569#else
7570      sCtx.in = popen(sCtx.zFile+1, "r");
7571      sCtx.zFile = "<pipe>";
7572      xCloser = pclose;
7573#endif
7574    }else{
7575      sCtx.in = fopen(sCtx.zFile, "rb");
7576      xCloser = fclose;
7577    }
7578    if( p->mode==MODE_Ascii ){
7579      xRead = ascii_read_one_field;
7580    }else{
7581      xRead = csv_read_one_field;
7582    }
7583    if( sCtx.in==0 ){
7584      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7585      return 1;
7586    }
7587    sCtx.cColSep = p->colSeparator[0];
7588    sCtx.cRowSep = p->rowSeparator[0];
7589    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7590    if( zSql==0 ){
7591      xCloser(sCtx.in);
7592      shell_out_of_memory();
7593    }
7594    nByte = strlen30(zSql);
7595    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7596    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
7597    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7598      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7599      char cSep = '(';
7600      while( xRead(&sCtx) ){
7601        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
7602        cSep = ',';
7603        if( sCtx.cTerm!=sCtx.cColSep ) break;
7604      }
7605      if( cSep=='(' ){
7606        sqlite3_free(zCreate);
7607        sqlite3_free(sCtx.z);
7608        xCloser(sCtx.in);
7609        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7610        return 1;
7611      }
7612      zCreate = sqlite3_mprintf("%z\n)", zCreate);
7613      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7614      sqlite3_free(zCreate);
7615      if( rc ){
7616        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7617                sqlite3_errmsg(p->db));
7618        sqlite3_free(sCtx.z);
7619        xCloser(sCtx.in);
7620        return 1;
7621      }
7622      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7623    }
7624    sqlite3_free(zSql);
7625    if( rc ){
7626      if (pStmt) sqlite3_finalize(pStmt);
7627      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7628      xCloser(sCtx.in);
7629      return 1;
7630    }
7631    nCol = sqlite3_column_count(pStmt);
7632    sqlite3_finalize(pStmt);
7633    pStmt = 0;
7634    if( nCol==0 ) return 0; /* no columns, no error */
7635    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7636    if( zSql==0 ){
7637      xCloser(sCtx.in);
7638      shell_out_of_memory();
7639    }
7640    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7641    j = strlen30(zSql);
7642    for(i=1; i<nCol; i++){
7643      zSql[j++] = ',';
7644      zSql[j++] = '?';
7645    }
7646    zSql[j++] = ')';
7647    zSql[j] = 0;
7648    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7649    sqlite3_free(zSql);
7650    if( rc ){
7651      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7652      if (pStmt) sqlite3_finalize(pStmt);
7653      xCloser(sCtx.in);
7654      return 1;
7655    }
7656    needCommit = sqlite3_get_autocommit(p->db);
7657    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7658    do{
7659      int startLine = sCtx.nLine;
7660      for(i=0; i<nCol; i++){
7661        char *z = xRead(&sCtx);
7662        /*
7663        ** Did we reach end-of-file before finding any columns?
7664        ** If so, stop instead of NULL filling the remaining columns.
7665        */
7666        if( z==0 && i==0 ) break;
7667        /*
7668        ** Did we reach end-of-file OR end-of-line before finding any
7669        ** columns in ASCII mode?  If so, stop instead of NULL filling
7670        ** the remaining columns.
7671        */
7672        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7673        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7674        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7675          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7676                          "filling the rest with NULL\n",
7677                          sCtx.zFile, startLine, nCol, i+1);
7678          i += 2;
7679          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7680        }
7681      }
7682      if( sCtx.cTerm==sCtx.cColSep ){
7683        do{
7684          xRead(&sCtx);
7685          i++;
7686        }while( sCtx.cTerm==sCtx.cColSep );
7687        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7688                        "extras ignored\n",
7689                        sCtx.zFile, startLine, nCol, i);
7690      }
7691      if( i>=nCol ){
7692        sqlite3_step(pStmt);
7693        rc = sqlite3_reset(pStmt);
7694        if( rc!=SQLITE_OK ){
7695          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7696                      startLine, sqlite3_errmsg(p->db));
7697        }
7698      }
7699    }while( sCtx.cTerm!=EOF );
7700
7701    xCloser(sCtx.in);
7702    sqlite3_free(sCtx.z);
7703    sqlite3_finalize(pStmt);
7704    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7705  }else
7706
7707#ifndef SQLITE_UNTESTABLE
7708  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7709    char *zSql;
7710    char *zCollist = 0;
7711    sqlite3_stmt *pStmt;
7712    int tnum = 0;
7713    int i;
7714    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7715      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7716                          "       .imposter off\n");
7717      rc = 1;
7718      goto meta_command_exit;
7719    }
7720    open_db(p, 0);
7721    if( nArg==2 ){
7722      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7723      goto meta_command_exit;
7724    }
7725    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
7726                           " WHERE name='%q' AND type='index'", azArg[1]);
7727    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7728    sqlite3_free(zSql);
7729    if( sqlite3_step(pStmt)==SQLITE_ROW ){
7730      tnum = sqlite3_column_int(pStmt, 0);
7731    }
7732    sqlite3_finalize(pStmt);
7733    if( tnum==0 ){
7734      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7735      rc = 1;
7736      goto meta_command_exit;
7737    }
7738    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7739    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7740    sqlite3_free(zSql);
7741    i = 0;
7742    while( sqlite3_step(pStmt)==SQLITE_ROW ){
7743      char zLabel[20];
7744      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7745      i++;
7746      if( zCol==0 ){
7747        if( sqlite3_column_int(pStmt,1)==-1 ){
7748          zCol = "_ROWID_";
7749        }else{
7750          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7751          zCol = zLabel;
7752        }
7753      }
7754      if( zCollist==0 ){
7755        zCollist = sqlite3_mprintf("\"%w\"", zCol);
7756      }else{
7757        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7758      }
7759    }
7760    sqlite3_finalize(pStmt);
7761    zSql = sqlite3_mprintf(
7762          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
7763          azArg[2], zCollist, zCollist);
7764    sqlite3_free(zCollist);
7765    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7766    if( rc==SQLITE_OK ){
7767      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7768      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7769      if( rc ){
7770        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7771      }else{
7772        utf8_printf(stdout, "%s;\n", zSql);
7773        raw_printf(stdout,
7774           "WARNING: writing to an imposter table will corrupt the index!\n"
7775        );
7776      }
7777    }else{
7778      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7779      rc = 1;
7780    }
7781    sqlite3_free(zSql);
7782  }else
7783#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7784
7785#ifdef SQLITE_ENABLE_IOTRACE
7786  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7787    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7788    if( iotrace && iotrace!=stdout ) fclose(iotrace);
7789    iotrace = 0;
7790    if( nArg<2 ){
7791      sqlite3IoTrace = 0;
7792    }else if( strcmp(azArg[1], "-")==0 ){
7793      sqlite3IoTrace = iotracePrintf;
7794      iotrace = stdout;
7795    }else{
7796      iotrace = fopen(azArg[1], "w");
7797      if( iotrace==0 ){
7798        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7799        sqlite3IoTrace = 0;
7800        rc = 1;
7801      }else{
7802        sqlite3IoTrace = iotracePrintf;
7803      }
7804    }
7805  }else
7806#endif
7807
7808  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7809    static const struct {
7810       const char *zLimitName;   /* Name of a limit */
7811       int limitCode;            /* Integer code for that limit */
7812    } aLimit[] = {
7813      { "length",                SQLITE_LIMIT_LENGTH                    },
7814      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
7815      { "column",                SQLITE_LIMIT_COLUMN                    },
7816      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
7817      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
7818      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
7819      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
7820      { "attached",              SQLITE_LIMIT_ATTACHED                  },
7821      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
7822      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
7823      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
7824      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
7825    };
7826    int i, n2;
7827    open_db(p, 0);
7828    if( nArg==1 ){
7829      for(i=0; i<ArraySize(aLimit); i++){
7830        printf("%20s %d\n", aLimit[i].zLimitName,
7831               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7832      }
7833    }else if( nArg>3 ){
7834      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7835      rc = 1;
7836      goto meta_command_exit;
7837    }else{
7838      int iLimit = -1;
7839      n2 = strlen30(azArg[1]);
7840      for(i=0; i<ArraySize(aLimit); i++){
7841        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7842          if( iLimit<0 ){
7843            iLimit = i;
7844          }else{
7845            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7846            rc = 1;
7847            goto meta_command_exit;
7848          }
7849        }
7850      }
7851      if( iLimit<0 ){
7852        utf8_printf(stderr, "unknown limit: \"%s\"\n"
7853                        "enter \".limits\" with no arguments for a list.\n",
7854                         azArg[1]);
7855        rc = 1;
7856        goto meta_command_exit;
7857      }
7858      if( nArg==3 ){
7859        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7860                      (int)integerValue(azArg[2]));
7861      }
7862      printf("%20s %d\n", aLimit[iLimit].zLimitName,
7863             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
7864    }
7865  }else
7866
7867  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
7868    open_db(p, 0);
7869    lintDotCommand(p, azArg, nArg);
7870  }else
7871
7872#ifndef SQLITE_OMIT_LOAD_EXTENSION
7873  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
7874    const char *zFile, *zProc;
7875    char *zErrMsg = 0;
7876    if( nArg<2 ){
7877      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
7878      rc = 1;
7879      goto meta_command_exit;
7880    }
7881    zFile = azArg[1];
7882    zProc = nArg>=3 ? azArg[2] : 0;
7883    open_db(p, 0);
7884    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
7885    if( rc!=SQLITE_OK ){
7886      utf8_printf(stderr, "Error: %s\n", zErrMsg);
7887      sqlite3_free(zErrMsg);
7888      rc = 1;
7889    }
7890  }else
7891#endif
7892
7893  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
7894    if( nArg!=2 ){
7895      raw_printf(stderr, "Usage: .log FILENAME\n");
7896      rc = 1;
7897    }else{
7898      const char *zFile = azArg[1];
7899      output_file_close(p->pLog);
7900      p->pLog = output_file_open(zFile, 0);
7901    }
7902  }else
7903
7904  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
7905    const char *zMode = nArg>=2 ? azArg[1] : "";
7906    int n2 = strlen30(zMode);
7907    int c2 = zMode[0];
7908    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
7909      p->mode = MODE_Line;
7910      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7911    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
7912      p->mode = MODE_Column;
7913      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7914    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
7915      p->mode = MODE_List;
7916      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
7917      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7918    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
7919      p->mode = MODE_Html;
7920    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
7921      p->mode = MODE_Tcl;
7922      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
7923      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7924    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
7925      p->mode = MODE_Csv;
7926      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7927      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7928    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
7929      p->mode = MODE_List;
7930      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
7931    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
7932      p->mode = MODE_Insert;
7933      set_table_name(p, nArg>=3 ? azArg[2] : "table");
7934    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
7935      p->mode = MODE_Quote;
7936    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
7937      p->mode = MODE_Ascii;
7938      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
7939      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
7940    }else if( nArg==1 ){
7941      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
7942    }else{
7943      raw_printf(stderr, "Error: mode should be one of: "
7944         "ascii column csv html insert line list quote tabs tcl\n");
7945      rc = 1;
7946    }
7947    p->cMode = p->mode;
7948  }else
7949
7950  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
7951    if( nArg==2 ){
7952      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
7953                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
7954    }else{
7955      raw_printf(stderr, "Usage: .nullvalue STRING\n");
7956      rc = 1;
7957    }
7958  }else
7959
7960  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
7961    char *zNewFilename;  /* Name of the database file to open */
7962    int iName = 1;       /* Index in azArg[] of the filename */
7963    int newFlag = 0;     /* True to delete file before opening */
7964    /* Close the existing database */
7965    session_close_all(p);
7966    close_db(p->db);
7967    p->db = 0;
7968    p->zDbFilename = 0;
7969    sqlite3_free(p->zFreeOnClose);
7970    p->zFreeOnClose = 0;
7971    p->openMode = SHELL_OPEN_UNSPEC;
7972    p->szMax = 0;
7973    /* Check for command-line arguments */
7974    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
7975      const char *z = azArg[iName];
7976      if( optionMatch(z,"new") ){
7977        newFlag = 1;
7978#ifdef SQLITE_HAVE_ZLIB
7979      }else if( optionMatch(z, "zip") ){
7980        p->openMode = SHELL_OPEN_ZIPFILE;
7981#endif
7982      }else if( optionMatch(z, "append") ){
7983        p->openMode = SHELL_OPEN_APPENDVFS;
7984      }else if( optionMatch(z, "readonly") ){
7985        p->openMode = SHELL_OPEN_READONLY;
7986#ifdef SQLITE_ENABLE_DESERIALIZE
7987      }else if( optionMatch(z, "deserialize") ){
7988        p->openMode = SHELL_OPEN_DESERIALIZE;
7989      }else if( optionMatch(z, "hexdb") ){
7990        p->openMode = SHELL_OPEN_HEXDB;
7991      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7992        p->szMax = integerValue(azArg[++iName]);
7993#endif /* SQLITE_ENABLE_DESERIALIZE */
7994      }else if( z[0]=='-' ){
7995        utf8_printf(stderr, "unknown option: %s\n", z);
7996        rc = 1;
7997        goto meta_command_exit;
7998      }
7999    }
8000    /* If a filename is specified, try to open it first */
8001    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
8002    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8003      if( newFlag ) shellDeleteFile(zNewFilename);
8004      p->zDbFilename = zNewFilename;
8005      open_db(p, OPEN_DB_KEEPALIVE);
8006      if( p->db==0 ){
8007        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8008        sqlite3_free(zNewFilename);
8009      }else{
8010        p->zFreeOnClose = zNewFilename;
8011      }
8012    }
8013    if( p->db==0 ){
8014      /* As a fall-back open a TEMP database */
8015      p->zDbFilename = 0;
8016      open_db(p, 0);
8017    }
8018  }else
8019
8020  if( (c=='o'
8021        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8022   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
8023  ){
8024    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
8025    int bTxtMode = 0;
8026    if( azArg[0][0]=='e' ){
8027      /* Transform the ".excel" command into ".once -x" */
8028      nArg = 2;
8029      azArg[0] = "once";
8030      zFile = azArg[1] = "-x";
8031      n = 4;
8032    }
8033    if( nArg>2 ){
8034      utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
8035      rc = 1;
8036      goto meta_command_exit;
8037    }
8038    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
8039      if( nArg<2 ){
8040        raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
8041        rc = 1;
8042        goto meta_command_exit;
8043      }
8044      p->outCount = 2;
8045    }else{
8046      p->outCount = 0;
8047    }
8048    output_reset(p);
8049    if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
8050#ifndef SQLITE_NOHAVE_SYSTEM
8051    if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
8052      p->doXdgOpen = 1;
8053      outputModePush(p);
8054      if( zFile[1]=='x' ){
8055        newTempFile(p, "csv");
8056        p->mode = MODE_Csv;
8057        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8058        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8059      }else{
8060        newTempFile(p, "txt");
8061        bTxtMode = 1;
8062      }
8063      zFile = p->zTempFile;
8064    }
8065#endif /* SQLITE_NOHAVE_SYSTEM */
8066    if( zFile[0]=='|' ){
8067#ifdef SQLITE_OMIT_POPEN
8068      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8069      rc = 1;
8070      p->out = stdout;
8071#else
8072      p->out = popen(zFile + 1, "w");
8073      if( p->out==0 ){
8074        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8075        p->out = stdout;
8076        rc = 1;
8077      }else{
8078        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8079      }
8080#endif
8081    }else{
8082      p->out = output_file_open(zFile, bTxtMode);
8083      if( p->out==0 ){
8084        if( strcmp(zFile,"off")!=0 ){
8085          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8086        }
8087        p->out = stdout;
8088        rc = 1;
8089      } else {
8090        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8091      }
8092    }
8093  }else
8094
8095  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8096    open_db(p,0);
8097    if( nArg<=1 ) goto parameter_syntax_error;
8098
8099    /* .parameter clear
8100    ** Clear all bind parameters by dropping the TEMP table that holds them.
8101    */
8102    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
8103      int wrSchema = 0;
8104      sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
8105      sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
8106      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
8107                   0, 0, 0);
8108      sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
8109    }else
8110
8111    /* .parameter list
8112    ** List all bind parameters.
8113    */
8114    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8115      sqlite3_stmt *pStmt = 0;
8116      int rx;
8117      int len = 0;
8118      rx = sqlite3_prepare_v2(p->db,
8119             "SELECT max(length(key)) "
8120             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8121      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8122        len = sqlite3_column_int(pStmt, 0);
8123        if( len>40 ) len = 40;
8124      }
8125      sqlite3_finalize(pStmt);
8126      pStmt = 0;
8127      if( len ){
8128        rx = sqlite3_prepare_v2(p->db,
8129             "SELECT key, quote(value) "
8130             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8131        while( sqlite3_step(pStmt)==SQLITE_ROW ){
8132          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8133                      sqlite3_column_text(pStmt,1));
8134        }
8135        sqlite3_finalize(pStmt);
8136      }
8137    }else
8138
8139    /* .parameter init
8140    ** Make sure the TEMP table used to hold bind parameters exists.
8141    ** Create it if necessary.
8142    */
8143    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8144      bind_table_init(p);
8145    }else
8146
8147    /* .parameter set NAME VALUE
8148    ** Set or reset a bind parameter.  NAME should be the full parameter
8149    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
8150    ** VALUE can be in either SQL literal notation, or if not it will be
8151    ** understood to be a text string.
8152    */
8153    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8154      int rx;
8155      char *zSql;
8156      sqlite3_stmt *pStmt;
8157      const char *zKey = azArg[2];
8158      const char *zValue = azArg[3];
8159      bind_table_init(p);
8160      zSql = sqlite3_mprintf(
8161                  "REPLACE INTO temp.sqlite_parameters(key,value)"
8162                  "VALUES(%Q,%s);", zKey, zValue);
8163      if( zSql==0 ) shell_out_of_memory();
8164      pStmt = 0;
8165      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8166      sqlite3_free(zSql);
8167      if( rx!=SQLITE_OK ){
8168        sqlite3_finalize(pStmt);
8169        pStmt = 0;
8170        zSql = sqlite3_mprintf(
8171                   "REPLACE INTO temp.sqlite_parameters(key,value)"
8172                   "VALUES(%Q,%Q);", zKey, zValue);
8173        if( zSql==0 ) shell_out_of_memory();
8174        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8175        sqlite3_free(zSql);
8176        if( rx!=SQLITE_OK ){
8177          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
8178          sqlite3_finalize(pStmt);
8179          pStmt = 0;
8180          rc = 1;
8181        }
8182      }
8183      sqlite3_step(pStmt);
8184      sqlite3_finalize(pStmt);
8185    }else
8186
8187    /* .parameter unset NAME
8188    ** Remove the NAME binding from the parameter binding table, if it
8189    ** exists.
8190    */
8191    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
8192      char *zSql = sqlite3_mprintf(
8193          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
8194      if( zSql==0 ) shell_out_of_memory();
8195      sqlite3_exec(p->db, zSql, 0, 0, 0);
8196      sqlite3_free(zSql);
8197    }else
8198    /* If no command name matches, show a syntax error */
8199    parameter_syntax_error:
8200    showHelp(p->out, "parameter");
8201  }else
8202
8203  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
8204    int i;
8205    for(i=1; i<nArg; i++){
8206      if( i>1 ) raw_printf(p->out, " ");
8207      utf8_printf(p->out, "%s", azArg[i]);
8208    }
8209    raw_printf(p->out, "\n");
8210  }else
8211
8212#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8213  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
8214    int i;
8215    int nn = 0;
8216    p->flgProgress = 0;
8217    p->mxProgress = 0;
8218    p->nProgress = 0;
8219    for(i=1; i<nArg; i++){
8220      const char *z = azArg[i];
8221      if( z[0]=='-' ){
8222        z++;
8223        if( z[0]=='-' ) z++;
8224        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
8225          p->flgProgress |= SHELL_PROGRESS_QUIET;
8226          continue;
8227        }
8228        if( strcmp(z,"reset")==0 ){
8229          p->flgProgress |= SHELL_PROGRESS_RESET;
8230          continue;
8231        }
8232        if( strcmp(z,"once")==0 ){
8233          p->flgProgress |= SHELL_PROGRESS_ONCE;
8234          continue;
8235        }
8236        if( strcmp(z,"limit")==0 ){
8237          if( i+1>=nArg ){
8238            utf8_printf(stderr, "Error: missing argument on --limit\n");
8239            rc = 1;
8240            goto meta_command_exit;
8241          }else{
8242            p->mxProgress = (int)integerValue(azArg[++i]);
8243          }
8244          continue;
8245        }
8246        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
8247        rc = 1;
8248        goto meta_command_exit;
8249      }else{
8250        nn = (int)integerValue(z);
8251      }
8252    }
8253    open_db(p, 0);
8254    sqlite3_progress_handler(p->db, nn, progress_handler, p);
8255  }else
8256#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
8257
8258  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
8259    if( nArg >= 2) {
8260      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
8261    }
8262    if( nArg >= 3) {
8263      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
8264    }
8265  }else
8266
8267  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
8268    rc = 2;
8269  }else
8270
8271  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
8272    FILE *inSaved = p->in;
8273    int savedLineno = p->lineno;
8274    if( nArg!=2 ){
8275      raw_printf(stderr, "Usage: .read FILE\n");
8276      rc = 1;
8277      goto meta_command_exit;
8278    }
8279    p->in = fopen(azArg[1], "rb");
8280    if( p->in==0 ){
8281      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8282      rc = 1;
8283    }else{
8284      rc = process_input(p);
8285      fclose(p->in);
8286    }
8287    p->in = inSaved;
8288    p->lineno = savedLineno;
8289  }else
8290
8291  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8292    const char *zSrcFile;
8293    const char *zDb;
8294    sqlite3 *pSrc;
8295    sqlite3_backup *pBackup;
8296    int nTimeout = 0;
8297
8298    if( nArg==2 ){
8299      zSrcFile = azArg[1];
8300      zDb = "main";
8301    }else if( nArg==3 ){
8302      zSrcFile = azArg[2];
8303      zDb = azArg[1];
8304    }else{
8305      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
8306      rc = 1;
8307      goto meta_command_exit;
8308    }
8309    rc = sqlite3_open(zSrcFile, &pSrc);
8310    if( rc!=SQLITE_OK ){
8311      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
8312      close_db(pSrc);
8313      return 1;
8314    }
8315    open_db(p, 0);
8316    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
8317    if( pBackup==0 ){
8318      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8319      close_db(pSrc);
8320      return 1;
8321    }
8322    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
8323          || rc==SQLITE_BUSY  ){
8324      if( rc==SQLITE_BUSY ){
8325        if( nTimeout++ >= 3 ) break;
8326        sqlite3_sleep(100);
8327      }
8328    }
8329    sqlite3_backup_finish(pBackup);
8330    if( rc==SQLITE_DONE ){
8331      rc = 0;
8332    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
8333      raw_printf(stderr, "Error: source database is busy\n");
8334      rc = 1;
8335    }else{
8336      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8337      rc = 1;
8338    }
8339    close_db(pSrc);
8340  }else
8341
8342  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
8343    if( nArg==2 ){
8344      p->scanstatsOn = (u8)booleanValue(azArg[1]);
8345#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
8346      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
8347#endif
8348    }else{
8349      raw_printf(stderr, "Usage: .scanstats on|off\n");
8350      rc = 1;
8351    }
8352  }else
8353
8354  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
8355    ShellText sSelect;
8356    ShellState data;
8357    char *zErrMsg = 0;
8358    const char *zDiv = "(";
8359    const char *zName = 0;
8360    int iSchema = 0;
8361    int bDebug = 0;
8362    int ii;
8363
8364    open_db(p, 0);
8365    memcpy(&data, p, sizeof(data));
8366    data.showHeader = 0;
8367    data.cMode = data.mode = MODE_Semi;
8368    initText(&sSelect);
8369    for(ii=1; ii<nArg; ii++){
8370      if( optionMatch(azArg[ii],"indent") ){
8371        data.cMode = data.mode = MODE_Pretty;
8372      }else if( optionMatch(azArg[ii],"debug") ){
8373        bDebug = 1;
8374      }else if( zName==0 ){
8375        zName = azArg[ii];
8376      }else{
8377        raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
8378        rc = 1;
8379        goto meta_command_exit;
8380      }
8381    }
8382    if( zName!=0 ){
8383      int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
8384      if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
8385        char *new_argv[2], *new_colv[2];
8386        new_argv[0] = sqlite3_mprintf(
8387                      "CREATE TABLE %s (\n"
8388                      "  type text,\n"
8389                      "  name text,\n"
8390                      "  tbl_name text,\n"
8391                      "  rootpage integer,\n"
8392                      "  sql text\n"
8393                      ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
8394        new_argv[1] = 0;
8395        new_colv[0] = "sql";
8396        new_colv[1] = 0;
8397        callback(&data, 1, new_argv, new_colv);
8398        sqlite3_free(new_argv[0]);
8399      }
8400    }
8401    if( zDiv ){
8402      sqlite3_stmt *pStmt = 0;
8403      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
8404                              -1, &pStmt, 0);
8405      if( rc ){
8406        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8407        sqlite3_finalize(pStmt);
8408        rc = 1;
8409        goto meta_command_exit;
8410      }
8411      appendText(&sSelect, "SELECT sql FROM", 0);
8412      iSchema = 0;
8413      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8414        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
8415        char zScNum[30];
8416        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
8417        appendText(&sSelect, zDiv, 0);
8418        zDiv = " UNION ALL ";
8419        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
8420        if( sqlite3_stricmp(zDb, "main")!=0 ){
8421          appendText(&sSelect, zDb, '\'');
8422        }else{
8423          appendText(&sSelect, "NULL", 0);
8424        }
8425        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
8426        appendText(&sSelect, zScNum, 0);
8427        appendText(&sSelect, " AS snum, ", 0);
8428        appendText(&sSelect, zDb, '\'');
8429        appendText(&sSelect, " AS sname FROM ", 0);
8430        appendText(&sSelect, zDb, quoteChar(zDb));
8431        appendText(&sSelect, ".sqlite_master", 0);
8432      }
8433      sqlite3_finalize(pStmt);
8434#ifdef SQLITE_INTROSPECTION_PRAGMAS
8435      if( zName ){
8436        appendText(&sSelect,
8437           " UNION ALL SELECT shell_module_schema(name),"
8438           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
8439      }
8440#endif
8441      appendText(&sSelect, ") WHERE ", 0);
8442      if( zName ){
8443        char *zQarg = sqlite3_mprintf("%Q", zName);
8444        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8445                    strchr(zName, '[') != 0;
8446        if( strchr(zName, '.') ){
8447          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8448        }else{
8449          appendText(&sSelect, "lower(tbl_name)", 0);
8450        }
8451        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
8452        appendText(&sSelect, zQarg, 0);
8453        if( !bGlob ){
8454          appendText(&sSelect, " ESCAPE '\\' ", 0);
8455        }
8456        appendText(&sSelect, " AND ", 0);
8457        sqlite3_free(zQarg);
8458      }
8459      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8460                           " ORDER BY snum, rowid", 0);
8461      if( bDebug ){
8462        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8463      }else{
8464        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8465      }
8466      freeText(&sSelect);
8467    }
8468    if( zErrMsg ){
8469      utf8_printf(stderr,"Error: %s\n", zErrMsg);
8470      sqlite3_free(zErrMsg);
8471      rc = 1;
8472    }else if( rc != SQLITE_OK ){
8473      raw_printf(stderr,"Error: querying schema information\n");
8474      rc = 1;
8475    }else{
8476      rc = 0;
8477    }
8478  }else
8479
8480#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8481  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8482    sqlite3SelectTrace = (int)integerValue(azArg[1]);
8483  }else
8484#endif
8485
8486#if defined(SQLITE_ENABLE_SESSION)
8487  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8488    OpenSession *pSession = &p->aSession[0];
8489    char **azCmd = &azArg[1];
8490    int iSes = 0;
8491    int nCmd = nArg - 1;
8492    int i;
8493    if( nArg<=1 ) goto session_syntax_error;
8494    open_db(p, 0);
8495    if( nArg>=3 ){
8496      for(iSes=0; iSes<p->nSession; iSes++){
8497        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8498      }
8499      if( iSes<p->nSession ){
8500        pSession = &p->aSession[iSes];
8501        azCmd++;
8502        nCmd--;
8503      }else{
8504        pSession = &p->aSession[0];
8505        iSes = 0;
8506      }
8507    }
8508
8509    /* .session attach TABLE
8510    ** Invoke the sqlite3session_attach() interface to attach a particular
8511    ** table so that it is never filtered.
8512    */
8513    if( strcmp(azCmd[0],"attach")==0 ){
8514      if( nCmd!=2 ) goto session_syntax_error;
8515      if( pSession->p==0 ){
8516        session_not_open:
8517        raw_printf(stderr, "ERROR: No sessions are open\n");
8518      }else{
8519        rc = sqlite3session_attach(pSession->p, azCmd[1]);
8520        if( rc ){
8521          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8522          rc = 0;
8523        }
8524      }
8525    }else
8526
8527    /* .session changeset FILE
8528    ** .session patchset FILE
8529    ** Write a changeset or patchset into a file.  The file is overwritten.
8530    */
8531    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8532      FILE *out = 0;
8533      if( nCmd!=2 ) goto session_syntax_error;
8534      if( pSession->p==0 ) goto session_not_open;
8535      out = fopen(azCmd[1], "wb");
8536      if( out==0 ){
8537        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
8538      }else{
8539        int szChng;
8540        void *pChng;
8541        if( azCmd[0][0]=='c' ){
8542          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8543        }else{
8544          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8545        }
8546        if( rc ){
8547          printf("Error: error code %d\n", rc);
8548          rc = 0;
8549        }
8550        if( pChng
8551          && fwrite(pChng, szChng, 1, out)!=1 ){
8552          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8553                  szChng);
8554        }
8555        sqlite3_free(pChng);
8556        fclose(out);
8557      }
8558    }else
8559
8560    /* .session close
8561    ** Close the identified session
8562    */
8563    if( strcmp(azCmd[0], "close")==0 ){
8564      if( nCmd!=1 ) goto session_syntax_error;
8565      if( p->nSession ){
8566        session_close(pSession);
8567        p->aSession[iSes] = p->aSession[--p->nSession];
8568      }
8569    }else
8570
8571    /* .session enable ?BOOLEAN?
8572    ** Query or set the enable flag
8573    */
8574    if( strcmp(azCmd[0], "enable")==0 ){
8575      int ii;
8576      if( nCmd>2 ) goto session_syntax_error;
8577      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8578      if( p->nSession ){
8579        ii = sqlite3session_enable(pSession->p, ii);
8580        utf8_printf(p->out, "session %s enable flag = %d\n",
8581                    pSession->zName, ii);
8582      }
8583    }else
8584
8585    /* .session filter GLOB ....
8586    ** Set a list of GLOB patterns of table names to be excluded.
8587    */
8588    if( strcmp(azCmd[0], "filter")==0 ){
8589      int ii, nByte;
8590      if( nCmd<2 ) goto session_syntax_error;
8591      if( p->nSession ){
8592        for(ii=0; ii<pSession->nFilter; ii++){
8593          sqlite3_free(pSession->azFilter[ii]);
8594        }
8595        sqlite3_free(pSession->azFilter);
8596        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8597        pSession->azFilter = sqlite3_malloc( nByte );
8598        if( pSession->azFilter==0 ){
8599          raw_printf(stderr, "Error: out or memory\n");
8600          exit(1);
8601        }
8602        for(ii=1; ii<nCmd; ii++){
8603          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8604        }
8605        pSession->nFilter = ii-1;
8606      }
8607    }else
8608
8609    /* .session indirect ?BOOLEAN?
8610    ** Query or set the indirect flag
8611    */
8612    if( strcmp(azCmd[0], "indirect")==0 ){
8613      int ii;
8614      if( nCmd>2 ) goto session_syntax_error;
8615      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8616      if( p->nSession ){
8617        ii = sqlite3session_indirect(pSession->p, ii);
8618        utf8_printf(p->out, "session %s indirect flag = %d\n",
8619                    pSession->zName, ii);
8620      }
8621    }else
8622
8623    /* .session isempty
8624    ** Determine if the session is empty
8625    */
8626    if( strcmp(azCmd[0], "isempty")==0 ){
8627      int ii;
8628      if( nCmd!=1 ) goto session_syntax_error;
8629      if( p->nSession ){
8630        ii = sqlite3session_isempty(pSession->p);
8631        utf8_printf(p->out, "session %s isempty flag = %d\n",
8632                    pSession->zName, ii);
8633      }
8634    }else
8635
8636    /* .session list
8637    ** List all currently open sessions
8638    */
8639    if( strcmp(azCmd[0],"list")==0 ){
8640      for(i=0; i<p->nSession; i++){
8641        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8642      }
8643    }else
8644
8645    /* .session open DB NAME
8646    ** Open a new session called NAME on the attached database DB.
8647    ** DB is normally "main".
8648    */
8649    if( strcmp(azCmd[0],"open")==0 ){
8650      char *zName;
8651      if( nCmd!=3 ) goto session_syntax_error;
8652      zName = azCmd[2];
8653      if( zName[0]==0 ) goto session_syntax_error;
8654      for(i=0; i<p->nSession; i++){
8655        if( strcmp(p->aSession[i].zName,zName)==0 ){
8656          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8657          goto meta_command_exit;
8658        }
8659      }
8660      if( p->nSession>=ArraySize(p->aSession) ){
8661        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8662        goto meta_command_exit;
8663      }
8664      pSession = &p->aSession[p->nSession];
8665      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8666      if( rc ){
8667        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8668        rc = 0;
8669        goto meta_command_exit;
8670      }
8671      pSession->nFilter = 0;
8672      sqlite3session_table_filter(pSession->p, session_filter, pSession);
8673      p->nSession++;
8674      pSession->zName = sqlite3_mprintf("%s", zName);
8675    }else
8676    /* If no command name matches, show a syntax error */
8677    session_syntax_error:
8678    showHelp(p->out, "session");
8679  }else
8680#endif
8681
8682#ifdef SQLITE_DEBUG
8683  /* Undocumented commands for internal testing.  Subject to change
8684  ** without notice. */
8685  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8686    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8687      int i, v;
8688      for(i=1; i<nArg; i++){
8689        v = booleanValue(azArg[i]);
8690        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8691      }
8692    }
8693    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8694      int i; sqlite3_int64 v;
8695      for(i=1; i<nArg; i++){
8696        char zBuf[200];
8697        v = integerValue(azArg[i]);
8698        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8699        utf8_printf(p->out, "%s", zBuf);
8700      }
8701    }
8702  }else
8703#endif
8704
8705  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8706    int bIsInit = 0;         /* True to initialize the SELFTEST table */
8707    int bVerbose = 0;        /* Verbose output */
8708    int bSelftestExists;     /* True if SELFTEST already exists */
8709    int i, k;                /* Loop counters */
8710    int nTest = 0;           /* Number of tests runs */
8711    int nErr = 0;            /* Number of errors seen */
8712    ShellText str;           /* Answer for a query */
8713    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8714
8715    open_db(p,0);
8716    for(i=1; i<nArg; i++){
8717      const char *z = azArg[i];
8718      if( z[0]=='-' && z[1]=='-' ) z++;
8719      if( strcmp(z,"-init")==0 ){
8720        bIsInit = 1;
8721      }else
8722      if( strcmp(z,"-v")==0 ){
8723        bVerbose++;
8724      }else
8725      {
8726        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8727                    azArg[i], azArg[0]);
8728        raw_printf(stderr, "Should be one of: --init -v\n");
8729        rc = 1;
8730        goto meta_command_exit;
8731      }
8732    }
8733    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8734           != SQLITE_OK ){
8735      bSelftestExists = 0;
8736    }else{
8737      bSelftestExists = 1;
8738    }
8739    if( bIsInit ){
8740      createSelftestTable(p);
8741      bSelftestExists = 1;
8742    }
8743    initText(&str);
8744    appendText(&str, "x", 0);
8745    for(k=bSelftestExists; k>=0; k--){
8746      if( k==1 ){
8747        rc = sqlite3_prepare_v2(p->db,
8748            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8749            -1, &pStmt, 0);
8750      }else{
8751        rc = sqlite3_prepare_v2(p->db,
8752          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8753          "      (1,'run','PRAGMA integrity_check','ok')",
8754          -1, &pStmt, 0);
8755      }
8756      if( rc ){
8757        raw_printf(stderr, "Error querying the selftest table\n");
8758        rc = 1;
8759        sqlite3_finalize(pStmt);
8760        goto meta_command_exit;
8761      }
8762      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8763        int tno = sqlite3_column_int(pStmt, 0);
8764        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8765        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8766        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8767
8768        k = 0;
8769        if( bVerbose>0 ){
8770          char *zQuote = sqlite3_mprintf("%q", zSql);
8771          printf("%d: %s %s\n", tno, zOp, zSql);
8772          sqlite3_free(zQuote);
8773        }
8774        if( strcmp(zOp,"memo")==0 ){
8775          utf8_printf(p->out, "%s\n", zSql);
8776        }else
8777        if( strcmp(zOp,"run")==0 ){
8778          char *zErrMsg = 0;
8779          str.n = 0;
8780          str.z[0] = 0;
8781          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8782          nTest++;
8783          if( bVerbose ){
8784            utf8_printf(p->out, "Result: %s\n", str.z);
8785          }
8786          if( rc || zErrMsg ){
8787            nErr++;
8788            rc = 1;
8789            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8790            sqlite3_free(zErrMsg);
8791          }else if( strcmp(zAns,str.z)!=0 ){
8792            nErr++;
8793            rc = 1;
8794            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8795            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
8796          }
8797        }else
8798        {
8799          utf8_printf(stderr,
8800            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8801          rc = 1;
8802          break;
8803        }
8804      } /* End loop over rows of content from SELFTEST */
8805      sqlite3_finalize(pStmt);
8806    } /* End loop over k */
8807    freeText(&str);
8808    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8809  }else
8810
8811  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8812    if( nArg<2 || nArg>3 ){
8813      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8814      rc = 1;
8815    }
8816    if( nArg>=2 ){
8817      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8818                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8819    }
8820    if( nArg>=3 ){
8821      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8822                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8823    }
8824  }else
8825
8826  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8827    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
8828    int i;                   /* Loop counter */
8829    int bSchema = 0;         /* Also hash the schema */
8830    int bSeparate = 0;       /* Hash each table separately */
8831    int iSize = 224;         /* Hash algorithm to use */
8832    int bDebug = 0;          /* Only show the query that would have run */
8833    sqlite3_stmt *pStmt;     /* For querying tables names */
8834    char *zSql;              /* SQL to be run */
8835    char *zSep;              /* Separator */
8836    ShellText sSql;          /* Complete SQL for the query to run the hash */
8837    ShellText sQuery;        /* Set of queries used to read all content */
8838    open_db(p, 0);
8839    for(i=1; i<nArg; i++){
8840      const char *z = azArg[i];
8841      if( z[0]=='-' ){
8842        z++;
8843        if( z[0]=='-' ) z++;
8844        if( strcmp(z,"schema")==0 ){
8845          bSchema = 1;
8846        }else
8847        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
8848         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
8849        ){
8850          iSize = atoi(&z[5]);
8851        }else
8852        if( strcmp(z,"debug")==0 ){
8853          bDebug = 1;
8854        }else
8855        {
8856          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8857                      azArg[i], azArg[0]);
8858          raw_printf(stderr, "Should be one of: --schema"
8859                             " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
8860          rc = 1;
8861          goto meta_command_exit;
8862        }
8863      }else if( zLike ){
8864        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
8865        rc = 1;
8866        goto meta_command_exit;
8867      }else{
8868        zLike = z;
8869        bSeparate = 1;
8870        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
8871      }
8872    }
8873    if( bSchema ){
8874      zSql = "SELECT lower(name) FROM sqlite_master"
8875             " WHERE type='table' AND coalesce(rootpage,0)>1"
8876             " UNION ALL SELECT 'sqlite_master'"
8877             " ORDER BY 1 collate nocase";
8878    }else{
8879      zSql = "SELECT lower(name) FROM sqlite_master"
8880             " WHERE type='table' AND coalesce(rootpage,0)>1"
8881             " AND name NOT LIKE 'sqlite_%'"
8882             " ORDER BY 1 collate nocase";
8883    }
8884    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8885    initText(&sQuery);
8886    initText(&sSql);
8887    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
8888    zSep = "VALUES(";
8889    while( SQLITE_ROW==sqlite3_step(pStmt) ){
8890      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
8891      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
8892      if( strncmp(zTab, "sqlite_",7)!=0 ){
8893        appendText(&sQuery,"SELECT * FROM ", 0);
8894        appendText(&sQuery,zTab,'"');
8895        appendText(&sQuery," NOT INDEXED;", 0);
8896      }else if( strcmp(zTab, "sqlite_master")==0 ){
8897        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
8898                           " ORDER BY name;", 0);
8899      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
8900        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
8901                           " ORDER BY name;", 0);
8902      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
8903        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
8904                           " ORDER BY tbl,idx;", 0);
8905      }else if( strcmp(zTab, "sqlite_stat3")==0
8906             || strcmp(zTab, "sqlite_stat4")==0 ){
8907        appendText(&sQuery, "SELECT * FROM ", 0);
8908        appendText(&sQuery, zTab, 0);
8909        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
8910      }
8911      appendText(&sSql, zSep, 0);
8912      appendText(&sSql, sQuery.z, '\'');
8913      sQuery.n = 0;
8914      appendText(&sSql, ",", 0);
8915      appendText(&sSql, zTab, '\'');
8916      zSep = "),(";
8917    }
8918    sqlite3_finalize(pStmt);
8919    if( bSeparate ){
8920      zSql = sqlite3_mprintf(
8921          "%s))"
8922          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
8923          "   FROM [sha3sum$query]",
8924          sSql.z, iSize);
8925    }else{
8926      zSql = sqlite3_mprintf(
8927          "%s))"
8928          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
8929          "   FROM [sha3sum$query]",
8930          sSql.z, iSize);
8931    }
8932    freeText(&sQuery);
8933    freeText(&sSql);
8934    if( bDebug ){
8935      utf8_printf(p->out, "%s\n", zSql);
8936    }else{
8937      shell_exec(p, zSql, 0);
8938    }
8939    sqlite3_free(zSql);
8940  }else
8941
8942#ifndef SQLITE_NOHAVE_SYSTEM
8943  if( c=='s'
8944   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
8945  ){
8946    char *zCmd;
8947    int i, x;
8948    if( nArg<2 ){
8949      raw_printf(stderr, "Usage: .system COMMAND\n");
8950      rc = 1;
8951      goto meta_command_exit;
8952    }
8953    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
8954    for(i=2; i<nArg; i++){
8955      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
8956                             zCmd, azArg[i]);
8957    }
8958    x = system(zCmd);
8959    sqlite3_free(zCmd);
8960    if( x ) raw_printf(stderr, "System command returns %d\n", x);
8961  }else
8962#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
8963
8964  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
8965    static const char *azBool[] = { "off", "on", "trigger", "full"};
8966    int i;
8967    if( nArg!=1 ){
8968      raw_printf(stderr, "Usage: .show\n");
8969      rc = 1;
8970      goto meta_command_exit;
8971    }
8972    utf8_printf(p->out, "%12.12s: %s\n","echo",
8973                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
8974    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
8975    utf8_printf(p->out, "%12.12s: %s\n","explain",
8976         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
8977    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
8978    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
8979    utf8_printf(p->out, "%12.12s: ", "nullvalue");
8980      output_c_string(p->out, p->nullValue);
8981      raw_printf(p->out, "\n");
8982    utf8_printf(p->out,"%12.12s: %s\n","output",
8983            strlen30(p->outfile) ? p->outfile : "stdout");
8984    utf8_printf(p->out,"%12.12s: ", "colseparator");
8985      output_c_string(p->out, p->colSeparator);
8986      raw_printf(p->out, "\n");
8987    utf8_printf(p->out,"%12.12s: ", "rowseparator");
8988      output_c_string(p->out, p->rowSeparator);
8989      raw_printf(p->out, "\n");
8990    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
8991    utf8_printf(p->out, "%12.12s: ", "width");
8992    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8993      raw_printf(p->out, "%d ", p->colWidth[i]);
8994    }
8995    raw_printf(p->out, "\n");
8996    utf8_printf(p->out, "%12.12s: %s\n", "filename",
8997                p->zDbFilename ? p->zDbFilename : "");
8998  }else
8999
9000  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9001    if( nArg==2 ){
9002      p->statsOn = (u8)booleanValue(azArg[1]);
9003    }else if( nArg==1 ){
9004      display_stats(p->db, p, 0);
9005    }else{
9006      raw_printf(stderr, "Usage: .stats ?on|off?\n");
9007      rc = 1;
9008    }
9009  }else
9010
9011  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9012   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9013                 || strncmp(azArg[0], "indexes", n)==0) )
9014  ){
9015    sqlite3_stmt *pStmt;
9016    char **azResult;
9017    int nRow, nAlloc;
9018    int ii;
9019    ShellText s;
9020    initText(&s);
9021    open_db(p, 0);
9022    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
9023    if( rc ){
9024      sqlite3_finalize(pStmt);
9025      return shellDatabaseError(p->db);
9026    }
9027
9028    if( nArg>2 && c=='i' ){
9029      /* It is an historical accident that the .indexes command shows an error
9030      ** when called with the wrong number of arguments whereas the .tables
9031      ** command does not. */
9032      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9033      rc = 1;
9034      sqlite3_finalize(pStmt);
9035      goto meta_command_exit;
9036    }
9037    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9038      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9039      if( zDbName==0 ) continue;
9040      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9041      if( sqlite3_stricmp(zDbName, "main")==0 ){
9042        appendText(&s, "SELECT name FROM ", 0);
9043      }else{
9044        appendText(&s, "SELECT ", 0);
9045        appendText(&s, zDbName, '\'');
9046        appendText(&s, "||'.'||name FROM ", 0);
9047      }
9048      appendText(&s, zDbName, '"');
9049      appendText(&s, ".sqlite_master ", 0);
9050      if( c=='t' ){
9051        appendText(&s," WHERE type IN ('table','view')"
9052                      "   AND name NOT LIKE 'sqlite_%'"
9053                      "   AND name LIKE ?1", 0);
9054      }else{
9055        appendText(&s," WHERE type='index'"
9056                      "   AND tbl_name LIKE ?1", 0);
9057      }
9058    }
9059    rc = sqlite3_finalize(pStmt);
9060    appendText(&s, " ORDER BY 1", 0);
9061    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9062    freeText(&s);
9063    if( rc ) return shellDatabaseError(p->db);
9064
9065    /* Run the SQL statement prepared by the above block. Store the results
9066    ** as an array of nul-terminated strings in azResult[].  */
9067    nRow = nAlloc = 0;
9068    azResult = 0;
9069    if( nArg>1 ){
9070      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9071    }else{
9072      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9073    }
9074    while( sqlite3_step(pStmt)==SQLITE_ROW ){
9075      if( nRow>=nAlloc ){
9076        char **azNew;
9077        int n2 = nAlloc*2 + 10;
9078        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
9079        if( azNew==0 ) shell_out_of_memory();
9080        nAlloc = n2;
9081        azResult = azNew;
9082      }
9083      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
9084      if( 0==azResult[nRow] ) shell_out_of_memory();
9085      nRow++;
9086    }
9087    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9088      rc = shellDatabaseError(p->db);
9089    }
9090
9091    /* Pretty-print the contents of array azResult[] to the output */
9092    if( rc==0 && nRow>0 ){
9093      int len, maxlen = 0;
9094      int i, j;
9095      int nPrintCol, nPrintRow;
9096      for(i=0; i<nRow; i++){
9097        len = strlen30(azResult[i]);
9098        if( len>maxlen ) maxlen = len;
9099      }
9100      nPrintCol = 80/(maxlen+2);
9101      if( nPrintCol<1 ) nPrintCol = 1;
9102      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9103      for(i=0; i<nPrintRow; i++){
9104        for(j=i; j<nRow; j+=nPrintRow){
9105          char *zSp = j<nPrintRow ? "" : "  ";
9106          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9107                      azResult[j] ? azResult[j]:"");
9108        }
9109        raw_printf(p->out, "\n");
9110      }
9111    }
9112
9113    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9114    sqlite3_free(azResult);
9115  }else
9116
9117  /* Begin redirecting output to the file "testcase-out.txt" */
9118  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
9119    output_reset(p);
9120    p->out = output_file_open("testcase-out.txt", 0);
9121    if( p->out==0 ){
9122      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
9123    }
9124    if( nArg>=2 ){
9125      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
9126    }else{
9127      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
9128    }
9129  }else
9130
9131#ifndef SQLITE_UNTESTABLE
9132  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
9133    static const struct {
9134       const char *zCtrlName;   /* Name of a test-control option */
9135       int ctrlCode;            /* Integer code for that option */
9136       const char *zUsage;      /* Usage notes */
9137    } aCtrl[] = {
9138      { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"            },
9139      { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"            },
9140    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""          },*/
9141    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""                },*/
9142      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""                   },
9143    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""                }, */
9144      { "imposter",           SQLITE_TESTCTRL_IMPOSTER,   "SCHEMA ON/OFF ROOTPAGE"},
9145      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN"       },
9146      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"           },
9147      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"            },
9148      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"       },
9149#ifdef YYCOVERAGE
9150      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""                 },
9151#endif
9152      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "           },
9153      { "prng_reset",         SQLITE_TESTCTRL_PRNG_RESET,    ""                   },
9154      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""                   },
9155      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""                   },
9156      { "reserve",            SQLITE_TESTCTRL_RESERVE,       "BYTES-OF-RESERVE"   },
9157    };
9158    int testctrl = -1;
9159    int iCtrl = -1;
9160    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
9161    int isOk = 0;
9162    int i, n2;
9163    const char *zCmd = 0;
9164
9165    open_db(p, 0);
9166    zCmd = nArg>=2 ? azArg[1] : "help";
9167
9168    /* The argument can optionally begin with "-" or "--" */
9169    if( zCmd[0]=='-' && zCmd[1] ){
9170      zCmd++;
9171      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
9172    }
9173
9174    /* --help lists all test-controls */
9175    if( strcmp(zCmd,"help")==0 ){
9176      utf8_printf(p->out, "Available test-controls:\n");
9177      for(i=0; i<ArraySize(aCtrl); i++){
9178        utf8_printf(p->out, "  .testctrl %s %s\n",
9179                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
9180      }
9181      rc = 1;
9182      goto meta_command_exit;
9183    }
9184
9185    /* convert testctrl text option to value. allow any unique prefix
9186    ** of the option name, or a numerical value. */
9187    n2 = strlen30(zCmd);
9188    for(i=0; i<ArraySize(aCtrl); i++){
9189      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
9190        if( testctrl<0 ){
9191          testctrl = aCtrl[i].ctrlCode;
9192          iCtrl = i;
9193        }else{
9194          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
9195                              "Use \".testctrl --help\" for help\n", zCmd);
9196          rc = 1;
9197          goto meta_command_exit;
9198        }
9199      }
9200    }
9201    if( testctrl<0 ){
9202      utf8_printf(stderr,"Error: unknown test-control: %s\n"
9203                         "Use \".testctrl --help\" for help\n", zCmd);
9204    }else{
9205      switch(testctrl){
9206
9207        /* sqlite3_test_control(int, db, int) */
9208        case SQLITE_TESTCTRL_OPTIMIZATIONS:
9209        case SQLITE_TESTCTRL_RESERVE:
9210          if( nArg==3 ){
9211            int opt = (int)strtol(azArg[2], 0, 0);
9212            rc2 = sqlite3_test_control(testctrl, p->db, opt);
9213            isOk = 3;
9214          }
9215          break;
9216
9217        /* sqlite3_test_control(int) */
9218        case SQLITE_TESTCTRL_PRNG_SAVE:
9219        case SQLITE_TESTCTRL_PRNG_RESTORE:
9220        case SQLITE_TESTCTRL_PRNG_RESET:
9221        case SQLITE_TESTCTRL_BYTEORDER:
9222          if( nArg==2 ){
9223            rc2 = sqlite3_test_control(testctrl);
9224            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
9225          }
9226          break;
9227
9228        /* sqlite3_test_control(int, uint) */
9229        case SQLITE_TESTCTRL_PENDING_BYTE:
9230          if( nArg==3 ){
9231            unsigned int opt = (unsigned int)integerValue(azArg[2]);
9232            rc2 = sqlite3_test_control(testctrl, opt);
9233            isOk = 3;
9234          }
9235          break;
9236
9237        /* sqlite3_test_control(int, int) */
9238        case SQLITE_TESTCTRL_ASSERT:
9239        case SQLITE_TESTCTRL_ALWAYS:
9240        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
9241          if( nArg==3 ){
9242            int opt = booleanValue(azArg[2]);
9243            rc2 = sqlite3_test_control(testctrl, opt);
9244            isOk = 1;
9245          }
9246          break;
9247
9248        /* sqlite3_test_control(int, int) */
9249        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
9250        case SQLITE_TESTCTRL_NEVER_CORRUPT:
9251          if( nArg==3 ){
9252            int opt = booleanValue(azArg[2]);
9253            rc2 = sqlite3_test_control(testctrl, opt);
9254            isOk = 3;
9255          }
9256          break;
9257
9258        case SQLITE_TESTCTRL_IMPOSTER:
9259          if( nArg==5 ){
9260            rc2 = sqlite3_test_control(testctrl, p->db,
9261                          azArg[2],
9262                          integerValue(azArg[3]),
9263                          integerValue(azArg[4]));
9264            isOk = 3;
9265          }
9266          break;
9267
9268#ifdef YYCOVERAGE
9269        case SQLITE_TESTCTRL_PARSER_COVERAGE:
9270          if( nArg==2 ){
9271            sqlite3_test_control(testctrl, p->out);
9272            isOk = 3;
9273          }
9274#endif
9275      }
9276    }
9277    if( isOk==0 && iCtrl>=0 ){
9278      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
9279      rc = 1;
9280    }else if( isOk==1 ){
9281      raw_printf(p->out, "%d\n", rc2);
9282    }else if( isOk==2 ){
9283      raw_printf(p->out, "0x%08x\n", rc2);
9284    }
9285  }else
9286#endif /* !defined(SQLITE_UNTESTABLE) */
9287
9288  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
9289    open_db(p, 0);
9290    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
9291  }else
9292
9293  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
9294    if( nArg==2 ){
9295      enableTimer = booleanValue(azArg[1]);
9296      if( enableTimer && !HAS_TIMER ){
9297        raw_printf(stderr, "Error: timer not available on this system.\n");
9298        enableTimer = 0;
9299      }
9300    }else{
9301      raw_printf(stderr, "Usage: .timer on|off\n");
9302      rc = 1;
9303    }
9304  }else
9305
9306#ifndef SQLITE_OMIT_TRACE
9307  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
9308    int mType = 0;
9309    int jj;
9310    open_db(p, 0);
9311    for(jj=1; jj<nArg; jj++){
9312      const char *z = azArg[jj];
9313      if( z[0]=='-' ){
9314        if( optionMatch(z, "expanded") ){
9315          p->eTraceType = SHELL_TRACE_EXPANDED;
9316        }
9317#ifdef SQLITE_ENABLE_NORMALIZE
9318        else if( optionMatch(z, "normalized") ){
9319          p->eTraceType = SHELL_TRACE_NORMALIZED;
9320        }
9321#endif
9322        else if( optionMatch(z, "plain") ){
9323          p->eTraceType = SHELL_TRACE_PLAIN;
9324        }
9325        else if( optionMatch(z, "profile") ){
9326          mType |= SQLITE_TRACE_PROFILE;
9327        }
9328        else if( optionMatch(z, "row") ){
9329          mType |= SQLITE_TRACE_ROW;
9330        }
9331        else if( optionMatch(z, "stmt") ){
9332          mType |= SQLITE_TRACE_STMT;
9333        }
9334        else if( optionMatch(z, "close") ){
9335          mType |= SQLITE_TRACE_CLOSE;
9336        }
9337        else {
9338          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
9339          rc = 1;
9340          goto meta_command_exit;
9341        }
9342      }else{
9343        output_file_close(p->traceOut);
9344        p->traceOut = output_file_open(azArg[1], 0);
9345      }
9346    }
9347    if( p->traceOut==0 ){
9348      sqlite3_trace_v2(p->db, 0, 0, 0);
9349    }else{
9350      if( mType==0 ) mType = SQLITE_TRACE_STMT;
9351      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
9352    }
9353  }else
9354#endif /* !defined(SQLITE_OMIT_TRACE) */
9355
9356#if SQLITE_USER_AUTHENTICATION
9357  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
9358    if( nArg<2 ){
9359      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
9360      rc = 1;
9361      goto meta_command_exit;
9362    }
9363    open_db(p, 0);
9364    if( strcmp(azArg[1],"login")==0 ){
9365      if( nArg!=4 ){
9366        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
9367        rc = 1;
9368        goto meta_command_exit;
9369      }
9370      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
9371      if( rc ){
9372        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
9373        rc = 1;
9374      }
9375    }else if( strcmp(azArg[1],"add")==0 ){
9376      if( nArg!=5 ){
9377        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
9378        rc = 1;
9379        goto meta_command_exit;
9380      }
9381      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
9382                            booleanValue(azArg[4]));
9383      if( rc ){
9384        raw_printf(stderr, "User-Add failed: %d\n", rc);
9385        rc = 1;
9386      }
9387    }else if( strcmp(azArg[1],"edit")==0 ){
9388      if( nArg!=5 ){
9389        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
9390        rc = 1;
9391        goto meta_command_exit;
9392      }
9393      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
9394                              booleanValue(azArg[4]));
9395      if( rc ){
9396        raw_printf(stderr, "User-Edit failed: %d\n", rc);
9397        rc = 1;
9398      }
9399    }else if( strcmp(azArg[1],"delete")==0 ){
9400      if( nArg!=3 ){
9401        raw_printf(stderr, "Usage: .user delete USER\n");
9402        rc = 1;
9403        goto meta_command_exit;
9404      }
9405      rc = sqlite3_user_delete(p->db, azArg[2]);
9406      if( rc ){
9407        raw_printf(stderr, "User-Delete failed: %d\n", rc);
9408        rc = 1;
9409      }
9410    }else{
9411      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
9412      rc = 1;
9413      goto meta_command_exit;
9414    }
9415  }else
9416#endif /* SQLITE_USER_AUTHENTICATION */
9417
9418  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
9419    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
9420        sqlite3_libversion(), sqlite3_sourceid());
9421#if SQLITE_HAVE_ZLIB
9422    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
9423#endif
9424#define CTIMEOPT_VAL_(opt) #opt
9425#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
9426#if defined(__clang__) && defined(__clang_major__)
9427    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
9428                    CTIMEOPT_VAL(__clang_minor__) "."
9429                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
9430#elif defined(_MSC_VER)
9431    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
9432#elif defined(__GNUC__) && defined(__VERSION__)
9433    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9434#endif
9435  }else
9436
9437  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9438    const char *zDbName = nArg==2 ? azArg[1] : "main";
9439    sqlite3_vfs *pVfs = 0;
9440    if( p->db ){
9441      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9442      if( pVfs ){
9443        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
9444        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
9445        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
9446        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9447      }
9448    }
9449  }else
9450
9451  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9452    sqlite3_vfs *pVfs;
9453    sqlite3_vfs *pCurrent = 0;
9454    if( p->db ){
9455      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9456    }
9457    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9458      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
9459           pVfs==pCurrent ? "  <--- CURRENT" : "");
9460      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
9461      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
9462      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9463      if( pVfs->pNext ){
9464        raw_printf(p->out, "-----------------------------------\n");
9465      }
9466    }
9467  }else
9468
9469  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9470    const char *zDbName = nArg==2 ? azArg[1] : "main";
9471    char *zVfsName = 0;
9472    if( p->db ){
9473      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9474      if( zVfsName ){
9475        utf8_printf(p->out, "%s\n", zVfsName);
9476        sqlite3_free(zVfsName);
9477      }
9478    }
9479  }else
9480
9481#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9482  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9483    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9484  }else
9485#endif
9486
9487  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9488    int j;
9489    assert( nArg<=ArraySize(azArg) );
9490    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9491      p->colWidth[j-1] = (int)integerValue(azArg[j]);
9492    }
9493  }else
9494
9495  {
9496    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9497      " \"%s\". Enter \".help\" for help\n", azArg[0]);
9498    rc = 1;
9499  }
9500
9501meta_command_exit:
9502  if( p->outCount ){
9503    p->outCount--;
9504    if( p->outCount==0 ) output_reset(p);
9505  }
9506  return rc;
9507}
9508
9509/*
9510** Return TRUE if a semicolon occurs anywhere in the first N characters
9511** of string z[].
9512*/
9513static int line_contains_semicolon(const char *z, int N){
9514  int i;
9515  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
9516  return 0;
9517}
9518
9519/*
9520** Test to see if a line consists entirely of whitespace.
9521*/
9522static int _all_whitespace(const char *z){
9523  for(; *z; z++){
9524    if( IsSpace(z[0]) ) continue;
9525    if( *z=='/' && z[1]=='*' ){
9526      z += 2;
9527      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9528      if( *z==0 ) return 0;
9529      z++;
9530      continue;
9531    }
9532    if( *z=='-' && z[1]=='-' ){
9533      z += 2;
9534      while( *z && *z!='\n' ){ z++; }
9535      if( *z==0 ) return 1;
9536      continue;
9537    }
9538    return 0;
9539  }
9540  return 1;
9541}
9542
9543/*
9544** Return TRUE if the line typed in is an SQL command terminator other
9545** than a semi-colon.  The SQL Server style "go" command is understood
9546** as is the Oracle "/".
9547*/
9548static int line_is_command_terminator(const char *zLine){
9549  while( IsSpace(zLine[0]) ){ zLine++; };
9550  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9551    return 1;  /* Oracle */
9552  }
9553  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9554         && _all_whitespace(&zLine[2]) ){
9555    return 1;  /* SQL Server */
9556  }
9557  return 0;
9558}
9559
9560/*
9561** We need a default sqlite3_complete() implementation to use in case
9562** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
9563** any arbitrary text is a complete SQL statement.  This is not very
9564** user-friendly, but it does seem to work.
9565*/
9566#ifdef SQLITE_OMIT_COMPLETE
9567#define sqlite3_complete(x) 1
9568#endif
9569
9570/*
9571** Return true if zSql is a complete SQL statement.  Return false if it
9572** ends in the middle of a string literal or C-style comment.
9573*/
9574static int line_is_complete(char *zSql, int nSql){
9575  int rc;
9576  if( zSql==0 ) return 1;
9577  zSql[nSql] = ';';
9578  zSql[nSql+1] = 0;
9579  rc = sqlite3_complete(zSql);
9580  zSql[nSql] = 0;
9581  return rc;
9582}
9583
9584/*
9585** Run a single line of SQL.  Return the number of errors.
9586*/
9587static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9588  int rc;
9589  char *zErrMsg = 0;
9590
9591  open_db(p, 0);
9592  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
9593  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
9594  BEGIN_TIMER;
9595  rc = shell_exec(p, zSql, &zErrMsg);
9596  END_TIMER;
9597  if( rc || zErrMsg ){
9598    char zPrefix[100];
9599    if( in!=0 || !stdin_is_interactive ){
9600      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9601                       "Error: near line %d:", startline);
9602    }else{
9603      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9604    }
9605    if( zErrMsg!=0 ){
9606      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9607      sqlite3_free(zErrMsg);
9608      zErrMsg = 0;
9609    }else{
9610      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9611    }
9612    return 1;
9613  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9614    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
9615            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9616  }
9617  return 0;
9618}
9619
9620
9621/*
9622** Read input from *in and process it.  If *in==0 then input
9623** is interactive - the user is typing it it.  Otherwise, input
9624** is coming from a file or device.  A prompt is issued and history
9625** is saved only if input is interactive.  An interrupt signal will
9626** cause this routine to exit immediately, unless input is interactive.
9627**
9628** Return the number of errors.
9629*/
9630static int process_input(ShellState *p){
9631  char *zLine = 0;          /* A single input line */
9632  char *zSql = 0;           /* Accumulated SQL text */
9633  int nLine;                /* Length of current line */
9634  int nSql = 0;             /* Bytes of zSql[] used */
9635  int nAlloc = 0;           /* Allocated zSql[] space */
9636  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
9637  int rc;                   /* Error code */
9638  int errCnt = 0;           /* Number of errors seen */
9639  int startline = 0;        /* Line number for start of current input */
9640
9641  p->lineno = 0;
9642  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
9643    fflush(p->out);
9644    zLine = one_input_line(p->in, zLine, nSql>0);
9645    if( zLine==0 ){
9646      /* End of input */
9647      if( p->in==0 && stdin_is_interactive ) printf("\n");
9648      break;
9649    }
9650    if( seenInterrupt ){
9651      if( p->in!=0 ) break;
9652      seenInterrupt = 0;
9653    }
9654    p->lineno++;
9655    if( nSql==0 && _all_whitespace(zLine) ){
9656      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9657      continue;
9658    }
9659    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
9660      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9661      if( zLine[0]=='.' ){
9662        rc = do_meta_command(zLine, p);
9663        if( rc==2 ){ /* exit requested */
9664          break;
9665        }else if( rc ){
9666          errCnt++;
9667        }
9668      }
9669      continue;
9670    }
9671    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9672      memcpy(zLine,";",2);
9673    }
9674    nLine = strlen30(zLine);
9675    if( nSql+nLine+2>=nAlloc ){
9676      nAlloc = nSql+nLine+100;
9677      zSql = realloc(zSql, nAlloc);
9678      if( zSql==0 ) shell_out_of_memory();
9679    }
9680    nSqlPrior = nSql;
9681    if( nSql==0 ){
9682      int i;
9683      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9684      assert( nAlloc>0 && zSql!=0 );
9685      memcpy(zSql, zLine+i, nLine+1-i);
9686      startline = p->lineno;
9687      nSql = nLine-i;
9688    }else{
9689      zSql[nSql++] = '\n';
9690      memcpy(zSql+nSql, zLine, nLine+1);
9691      nSql += nLine;
9692    }
9693    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9694                && sqlite3_complete(zSql) ){
9695      errCnt += runOneSqlLine(p, zSql, p->in, startline);
9696      nSql = 0;
9697      if( p->outCount ){
9698        output_reset(p);
9699        p->outCount = 0;
9700      }else{
9701        clearTempFile(p);
9702      }
9703    }else if( nSql && _all_whitespace(zSql) ){
9704      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9705      nSql = 0;
9706    }
9707  }
9708  if( nSql && !_all_whitespace(zSql) ){
9709    errCnt += runOneSqlLine(p, zSql, p->in, startline);
9710  }
9711  free(zSql);
9712  free(zLine);
9713  return errCnt>0;
9714}
9715
9716/*
9717** Return a pathname which is the user's home directory.  A
9718** 0 return indicates an error of some kind.
9719*/
9720static char *find_home_dir(int clearFlag){
9721  static char *home_dir = NULL;
9722  if( clearFlag ){
9723    free(home_dir);
9724    home_dir = 0;
9725    return 0;
9726  }
9727  if( home_dir ) return home_dir;
9728
9729#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9730     && !defined(__RTP__) && !defined(_WRS_KERNEL)
9731  {
9732    struct passwd *pwent;
9733    uid_t uid = getuid();
9734    if( (pwent=getpwuid(uid)) != NULL) {
9735      home_dir = pwent->pw_dir;
9736    }
9737  }
9738#endif
9739
9740#if defined(_WIN32_WCE)
9741  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9742   */
9743  home_dir = "/";
9744#else
9745
9746#if defined(_WIN32) || defined(WIN32)
9747  if (!home_dir) {
9748    home_dir = getenv("USERPROFILE");
9749  }
9750#endif
9751
9752  if (!home_dir) {
9753    home_dir = getenv("HOME");
9754  }
9755
9756#if defined(_WIN32) || defined(WIN32)
9757  if (!home_dir) {
9758    char *zDrive, *zPath;
9759    int n;
9760    zDrive = getenv("HOMEDRIVE");
9761    zPath = getenv("HOMEPATH");
9762    if( zDrive && zPath ){
9763      n = strlen30(zDrive) + strlen30(zPath) + 1;
9764      home_dir = malloc( n );
9765      if( home_dir==0 ) return 0;
9766      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9767      return home_dir;
9768    }
9769    home_dir = "c:\\";
9770  }
9771#endif
9772
9773#endif /* !_WIN32_WCE */
9774
9775  if( home_dir ){
9776    int n = strlen30(home_dir) + 1;
9777    char *z = malloc( n );
9778    if( z ) memcpy(z, home_dir, n);
9779    home_dir = z;
9780  }
9781
9782  return home_dir;
9783}
9784
9785/*
9786** Read input from the file given by sqliterc_override.  Or if that
9787** parameter is NULL, take input from ~/.sqliterc
9788**
9789** Returns the number of errors.
9790*/
9791static void process_sqliterc(
9792  ShellState *p,                  /* Configuration data */
9793  const char *sqliterc_override   /* Name of config file. NULL to use default */
9794){
9795  char *home_dir = NULL;
9796  const char *sqliterc = sqliterc_override;
9797  char *zBuf = 0;
9798  FILE *inSaved = p->in;
9799  int savedLineno = p->lineno;
9800
9801  if (sqliterc == NULL) {
9802    home_dir = find_home_dir(0);
9803    if( home_dir==0 ){
9804      raw_printf(stderr, "-- warning: cannot find home directory;"
9805                      " cannot read ~/.sqliterc\n");
9806      return;
9807    }
9808    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
9809    sqliterc = zBuf;
9810  }
9811  p->in = fopen(sqliterc,"rb");
9812  if( p->in ){
9813    if( stdin_is_interactive ){
9814      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
9815    }
9816    process_input(p);
9817    fclose(p->in);
9818  }
9819  p->in = inSaved;
9820  p->lineno = savedLineno;
9821  sqlite3_free(zBuf);
9822}
9823
9824/*
9825** Show available command line options
9826*/
9827static const char zOptions[] =
9828#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
9829  "   -A ARGS...           run \".archive ARGS\" and exit\n"
9830#endif
9831  "   -append              append the database to the end of the file\n"
9832  "   -ascii               set output mode to 'ascii'\n"
9833  "   -bail                stop after hitting an error\n"
9834  "   -batch               force batch I/O\n"
9835  "   -column              set output mode to 'column'\n"
9836  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
9837  "   -csv                 set output mode to 'csv'\n"
9838#if defined(SQLITE_ENABLE_DESERIALIZE)
9839  "   -deserialize         open the database using sqlite3_deserialize()\n"
9840#endif
9841  "   -echo                print commands before execution\n"
9842  "   -init FILENAME       read/process named file\n"
9843  "   -[no]header          turn headers on or off\n"
9844#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9845  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
9846#endif
9847  "   -help                show this message\n"
9848  "   -html                set output mode to HTML\n"
9849  "   -interactive         force interactive I/O\n"
9850  "   -line                set output mode to 'line'\n"
9851  "   -list                set output mode to 'list'\n"
9852  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
9853#if defined(SQLITE_ENABLE_DESERIALIZE)
9854  "   -maxsize N           maximum size for a --deserialize database\n"
9855#endif
9856  "   -memtrace            trace all memory allocations and deallocations\n"
9857  "   -mmap N              default mmap size set to N\n"
9858#ifdef SQLITE_ENABLE_MULTIPLEX
9859  "   -multiplex           enable the multiplexor VFS\n"
9860#endif
9861  "   -newline SEP         set output row separator. Default: '\\n'\n"
9862  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
9863  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
9864  "   -quote               set output mode to 'quote'\n"
9865  "   -readonly            open the database read-only\n"
9866  "   -separator SEP       set output column separator. Default: '|'\n"
9867#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9868  "   -sorterref SIZE      sorter references threshold size\n"
9869#endif
9870  "   -stats               print memory stats before each finalize\n"
9871  "   -version             show SQLite version\n"
9872  "   -vfs NAME            use NAME as the default VFS\n"
9873#ifdef SQLITE_ENABLE_VFSTRACE
9874  "   -vfstrace            enable tracing of all VFS calls\n"
9875#endif
9876#ifdef SQLITE_HAVE_ZLIB
9877  "   -zip                 open the file as a ZIP Archive\n"
9878#endif
9879;
9880static void usage(int showDetail){
9881  utf8_printf(stderr,
9882      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
9883      "FILENAME is the name of an SQLite database. A new database is created\n"
9884      "if the file does not previously exist.\n", Argv0);
9885  if( showDetail ){
9886    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
9887  }else{
9888    raw_printf(stderr, "Use the -help option for additional information\n");
9889  }
9890  exit(1);
9891}
9892
9893/*
9894** Internal check:  Verify that the SQLite is uninitialized.  Print a
9895** error message if it is initialized.
9896*/
9897static void verify_uninitialized(void){
9898  if( sqlite3_config(-1)==SQLITE_MISUSE ){
9899    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
9900                        " initialization.\n");
9901  }
9902}
9903
9904/*
9905** Initialize the state information in data
9906*/
9907static void main_init(ShellState *data) {
9908  memset(data, 0, sizeof(*data));
9909  data->normalMode = data->cMode = data->mode = MODE_List;
9910  data->autoExplain = 1;
9911  memcpy(data->colSeparator,SEP_Column, 2);
9912  memcpy(data->rowSeparator,SEP_Row, 2);
9913  data->showHeader = 0;
9914  data->shellFlgs = SHFLG_Lookaside;
9915  verify_uninitialized();
9916  sqlite3_config(SQLITE_CONFIG_URI, 1);
9917  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
9918  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
9919  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
9920  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
9921}
9922
9923/*
9924** Output text to the console in a font that attracts extra attention.
9925*/
9926#ifdef _WIN32
9927static void printBold(const char *zText){
9928  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
9929  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
9930  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
9931  SetConsoleTextAttribute(out,
9932         FOREGROUND_RED|FOREGROUND_INTENSITY
9933  );
9934  printf("%s", zText);
9935  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
9936}
9937#else
9938static void printBold(const char *zText){
9939  printf("\033[1m%s\033[0m", zText);
9940}
9941#endif
9942
9943/*
9944** Get the argument to an --option.  Throw an error and die if no argument
9945** is available.
9946*/
9947static char *cmdline_option_value(int argc, char **argv, int i){
9948  if( i==argc ){
9949    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
9950            argv[0], argv[argc-1]);
9951    exit(1);
9952  }
9953  return argv[i];
9954}
9955
9956#ifndef SQLITE_SHELL_IS_UTF8
9957#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
9958#    define SQLITE_SHELL_IS_UTF8          (0)
9959#  else
9960#    define SQLITE_SHELL_IS_UTF8          (1)
9961#  endif
9962#endif
9963
9964#if SQLITE_SHELL_IS_UTF8
9965int SQLITE_CDECL main(int argc, char **argv){
9966#else
9967int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
9968  char **argv;
9969#endif
9970  char *zErrMsg = 0;
9971  ShellState data;
9972  const char *zInitFile = 0;
9973  int i;
9974  int rc = 0;
9975  int warnInmemoryDb = 0;
9976  int readStdin = 1;
9977  int nCmd = 0;
9978  char **azCmd = 0;
9979  const char *zVfs = 0;           /* Value of -vfs command-line option */
9980#if !SQLITE_SHELL_IS_UTF8
9981  char **argvToFree = 0;
9982  int argcToFree = 0;
9983#endif
9984
9985  setBinaryMode(stdin, 0);
9986  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
9987  stdin_is_interactive = isatty(0);
9988  stdout_is_console = isatty(1);
9989
9990#if !defined(_WIN32_WCE)
9991  if( getenv("SQLITE_DEBUG_BREAK") ){
9992    if( isatty(0) && isatty(2) ){
9993      fprintf(stderr,
9994          "attach debugger to process %d and press any key to continue.\n",
9995          GETPID());
9996      fgetc(stdin);
9997    }else{
9998#if defined(_WIN32) || defined(WIN32)
9999      DebugBreak();
10000#elif defined(SIGTRAP)
10001      raise(SIGTRAP);
10002#endif
10003    }
10004  }
10005#endif
10006
10007#if USE_SYSTEM_SQLITE+0!=1
10008  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
10009    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
10010            sqlite3_sourceid(), SQLITE_SOURCE_ID);
10011    exit(1);
10012  }
10013#endif
10014  main_init(&data);
10015
10016  /* On Windows, we must translate command-line arguments into UTF-8.
10017  ** The SQLite memory allocator subsystem has to be enabled in order to
10018  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
10019  ** subsequent sqlite3_config() calls will work.  So copy all results into
10020  ** memory that does not come from the SQLite memory allocator.
10021  */
10022#if !SQLITE_SHELL_IS_UTF8
10023  sqlite3_initialize();
10024  argvToFree = malloc(sizeof(argv[0])*argc*2);
10025  argcToFree = argc;
10026  argv = argvToFree + argc;
10027  if( argv==0 ) shell_out_of_memory();
10028  for(i=0; i<argc; i++){
10029    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
10030    int n;
10031    if( z==0 ) shell_out_of_memory();
10032    n = (int)strlen(z);
10033    argv[i] = malloc( n+1 );
10034    if( argv[i]==0 ) shell_out_of_memory();
10035    memcpy(argv[i], z, n+1);
10036    argvToFree[i] = argv[i];
10037    sqlite3_free(z);
10038  }
10039  sqlite3_shutdown();
10040#endif
10041
10042  assert( argc>=1 && argv && argv[0] );
10043  Argv0 = argv[0];
10044
10045  /* Make sure we have a valid signal handler early, before anything
10046  ** else is done.
10047  */
10048#ifdef SIGINT
10049  signal(SIGINT, interrupt_handler);
10050#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10051  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
10052#endif
10053
10054#ifdef SQLITE_SHELL_DBNAME_PROC
10055  {
10056    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
10057    ** of a C-function that will provide the name of the database file.  Use
10058    ** this compile-time option to embed this shell program in larger
10059    ** applications. */
10060    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
10061    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
10062    warnInmemoryDb = 0;
10063  }
10064#endif
10065
10066  /* Do an initial pass through the command-line argument to locate
10067  ** the name of the database file, the name of the initialization file,
10068  ** the size of the alternative malloc heap,
10069  ** and the first command to execute.
10070  */
10071  verify_uninitialized();
10072  for(i=1; i<argc; i++){
10073    char *z;
10074    z = argv[i];
10075    if( z[0]!='-' ){
10076      if( data.zDbFilename==0 ){
10077        data.zDbFilename = z;
10078      }else{
10079        /* Excesss arguments are interpreted as SQL (or dot-commands) and
10080        ** mean that nothing is read from stdin */
10081        readStdin = 0;
10082        nCmd++;
10083        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
10084        if( azCmd==0 ) shell_out_of_memory();
10085        azCmd[nCmd-1] = z;
10086      }
10087    }
10088    if( z[1]=='-' ) z++;
10089    if( strcmp(z,"-separator")==0
10090     || strcmp(z,"-nullvalue")==0
10091     || strcmp(z,"-newline")==0
10092     || strcmp(z,"-cmd")==0
10093    ){
10094      (void)cmdline_option_value(argc, argv, ++i);
10095    }else if( strcmp(z,"-init")==0 ){
10096      zInitFile = cmdline_option_value(argc, argv, ++i);
10097    }else if( strcmp(z,"-batch")==0 ){
10098      /* Need to check for batch mode here to so we can avoid printing
10099      ** informational messages (like from process_sqliterc) before
10100      ** we do the actual processing of arguments later in a second pass.
10101      */
10102      stdin_is_interactive = 0;
10103    }else if( strcmp(z,"-heap")==0 ){
10104#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10105      const char *zSize;
10106      sqlite3_int64 szHeap;
10107
10108      zSize = cmdline_option_value(argc, argv, ++i);
10109      szHeap = integerValue(zSize);
10110      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
10111      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
10112#else
10113      (void)cmdline_option_value(argc, argv, ++i);
10114#endif
10115    }else if( strcmp(z,"-pagecache")==0 ){
10116      int n, sz;
10117      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10118      if( sz>70000 ) sz = 70000;
10119      if( sz<0 ) sz = 0;
10120      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10121      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
10122                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
10123      data.shellFlgs |= SHFLG_Pagecache;
10124    }else if( strcmp(z,"-lookaside")==0 ){
10125      int n, sz;
10126      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10127      if( sz<0 ) sz = 0;
10128      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10129      if( n<0 ) n = 0;
10130      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
10131      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
10132#ifdef SQLITE_ENABLE_VFSTRACE
10133    }else if( strcmp(z,"-vfstrace")==0 ){
10134      extern int vfstrace_register(
10135         const char *zTraceName,
10136         const char *zOldVfsName,
10137         int (*xOut)(const char*,void*),
10138         void *pOutArg,
10139         int makeDefault
10140      );
10141      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
10142#endif
10143#ifdef SQLITE_ENABLE_MULTIPLEX
10144    }else if( strcmp(z,"-multiplex")==0 ){
10145      extern int sqlite3_multiple_initialize(const char*,int);
10146      sqlite3_multiplex_initialize(0, 1);
10147#endif
10148    }else if( strcmp(z,"-mmap")==0 ){
10149      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10150      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
10151#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10152    }else if( strcmp(z,"-sorterref")==0 ){
10153      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10154      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
10155#endif
10156    }else if( strcmp(z,"-vfs")==0 ){
10157      zVfs = cmdline_option_value(argc, argv, ++i);
10158#ifdef SQLITE_HAVE_ZLIB
10159    }else if( strcmp(z,"-zip")==0 ){
10160      data.openMode = SHELL_OPEN_ZIPFILE;
10161#endif
10162    }else if( strcmp(z,"-append")==0 ){
10163      data.openMode = SHELL_OPEN_APPENDVFS;
10164#ifdef SQLITE_ENABLE_DESERIALIZE
10165    }else if( strcmp(z,"-deserialize")==0 ){
10166      data.openMode = SHELL_OPEN_DESERIALIZE;
10167    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10168      data.szMax = integerValue(argv[++i]);
10169#endif
10170    }else if( strcmp(z,"-readonly")==0 ){
10171      data.openMode = SHELL_OPEN_READONLY;
10172#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
10173    }else if( strncmp(z, "-A",2)==0 ){
10174      /* All remaining command-line arguments are passed to the ".archive"
10175      ** command, so ignore them */
10176      break;
10177#endif
10178    }else if( strcmp(z, "-memtrace")==0 ){
10179      sqlite3MemTraceActivate(stderr);
10180    }
10181  }
10182  verify_uninitialized();
10183
10184
10185#ifdef SQLITE_SHELL_INIT_PROC
10186  {
10187    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
10188    ** of a C-function that will perform initialization actions on SQLite that
10189    ** occur just before or after sqlite3_initialize(). Use this compile-time
10190    ** option to embed this shell program in larger applications. */
10191    extern void SQLITE_SHELL_INIT_PROC(void);
10192    SQLITE_SHELL_INIT_PROC();
10193  }
10194#else
10195  /* All the sqlite3_config() calls have now been made. So it is safe
10196  ** to call sqlite3_initialize() and process any command line -vfs option. */
10197  sqlite3_initialize();
10198#endif
10199
10200  if( zVfs ){
10201    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
10202    if( pVfs ){
10203      sqlite3_vfs_register(pVfs, 1);
10204    }else{
10205      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
10206      exit(1);
10207    }
10208  }
10209
10210  if( data.zDbFilename==0 ){
10211#ifndef SQLITE_OMIT_MEMORYDB
10212    data.zDbFilename = ":memory:";
10213    warnInmemoryDb = argc==1;
10214#else
10215    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
10216    return 1;
10217#endif
10218  }
10219  data.out = stdout;
10220  sqlite3_appendvfs_init(0,0,0);
10221
10222  /* Go ahead and open the database file if it already exists.  If the
10223  ** file does not exist, delay opening it.  This prevents empty database
10224  ** files from being created if a user mistypes the database name argument
10225  ** to the sqlite command-line tool.
10226  */
10227  if( access(data.zDbFilename, 0)==0 ){
10228    open_db(&data, 0);
10229  }
10230
10231  /* Process the initialization file if there is one.  If no -init option
10232  ** is given on the command line, look for a file named ~/.sqliterc and
10233  ** try to process it.
10234  */
10235  process_sqliterc(&data,zInitFile);
10236
10237  /* Make a second pass through the command-line argument and set
10238  ** options.  This second pass is delayed until after the initialization
10239  ** file is processed so that the command-line arguments will override
10240  ** settings in the initialization file.
10241  */
10242  for(i=1; i<argc; i++){
10243    char *z = argv[i];
10244    if( z[0]!='-' ) continue;
10245    if( z[1]=='-' ){ z++; }
10246    if( strcmp(z,"-init")==0 ){
10247      i++;
10248    }else if( strcmp(z,"-html")==0 ){
10249      data.mode = MODE_Html;
10250    }else if( strcmp(z,"-list")==0 ){
10251      data.mode = MODE_List;
10252    }else if( strcmp(z,"-quote")==0 ){
10253      data.mode = MODE_Quote;
10254    }else if( strcmp(z,"-line")==0 ){
10255      data.mode = MODE_Line;
10256    }else if( strcmp(z,"-column")==0 ){
10257      data.mode = MODE_Column;
10258    }else if( strcmp(z,"-csv")==0 ){
10259      data.mode = MODE_Csv;
10260      memcpy(data.colSeparator,",",2);
10261#ifdef SQLITE_HAVE_ZLIB
10262    }else if( strcmp(z,"-zip")==0 ){
10263      data.openMode = SHELL_OPEN_ZIPFILE;
10264#endif
10265    }else if( strcmp(z,"-append")==0 ){
10266      data.openMode = SHELL_OPEN_APPENDVFS;
10267#ifdef SQLITE_ENABLE_DESERIALIZE
10268    }else if( strcmp(z,"-deserialize")==0 ){
10269      data.openMode = SHELL_OPEN_DESERIALIZE;
10270    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10271      data.szMax = integerValue(argv[++i]);
10272#endif
10273    }else if( strcmp(z,"-readonly")==0 ){
10274      data.openMode = SHELL_OPEN_READONLY;
10275    }else if( strcmp(z,"-ascii")==0 ){
10276      data.mode = MODE_Ascii;
10277      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10278                       SEP_Unit);
10279      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10280                       SEP_Record);
10281    }else if( strcmp(z,"-separator")==0 ){
10282      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10283                       "%s",cmdline_option_value(argc,argv,++i));
10284    }else if( strcmp(z,"-newline")==0 ){
10285      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10286                       "%s",cmdline_option_value(argc,argv,++i));
10287    }else if( strcmp(z,"-nullvalue")==0 ){
10288      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
10289                       "%s",cmdline_option_value(argc,argv,++i));
10290    }else if( strcmp(z,"-header")==0 ){
10291      data.showHeader = 1;
10292    }else if( strcmp(z,"-noheader")==0 ){
10293      data.showHeader = 0;
10294    }else if( strcmp(z,"-echo")==0 ){
10295      ShellSetFlag(&data, SHFLG_Echo);
10296    }else if( strcmp(z,"-eqp")==0 ){
10297      data.autoEQP = AUTOEQP_on;
10298    }else if( strcmp(z,"-eqpfull")==0 ){
10299      data.autoEQP = AUTOEQP_full;
10300    }else if( strcmp(z,"-stats")==0 ){
10301      data.statsOn = 1;
10302    }else if( strcmp(z,"-scanstats")==0 ){
10303      data.scanstatsOn = 1;
10304    }else if( strcmp(z,"-backslash")==0 ){
10305      /* Undocumented command-line option: -backslash
10306      ** Causes C-style backslash escapes to be evaluated in SQL statements
10307      ** prior to sending the SQL into SQLite.  Useful for injecting
10308      ** crazy bytes in the middle of SQL statements for testing and debugging.
10309      */
10310      ShellSetFlag(&data, SHFLG_Backslash);
10311    }else if( strcmp(z,"-bail")==0 ){
10312      bail_on_error = 1;
10313    }else if( strcmp(z,"-version")==0 ){
10314      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
10315      return 0;
10316    }else if( strcmp(z,"-interactive")==0 ){
10317      stdin_is_interactive = 1;
10318    }else if( strcmp(z,"-batch")==0 ){
10319      stdin_is_interactive = 0;
10320    }else if( strcmp(z,"-heap")==0 ){
10321      i++;
10322    }else if( strcmp(z,"-pagecache")==0 ){
10323      i+=2;
10324    }else if( strcmp(z,"-lookaside")==0 ){
10325      i+=2;
10326    }else if( strcmp(z,"-mmap")==0 ){
10327      i++;
10328    }else if( strcmp(z,"-memtrace")==0 ){
10329      i++;
10330#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10331    }else if( strcmp(z,"-sorterref")==0 ){
10332      i++;
10333#endif
10334    }else if( strcmp(z,"-vfs")==0 ){
10335      i++;
10336#ifdef SQLITE_ENABLE_VFSTRACE
10337    }else if( strcmp(z,"-vfstrace")==0 ){
10338      i++;
10339#endif
10340#ifdef SQLITE_ENABLE_MULTIPLEX
10341    }else if( strcmp(z,"-multiplex")==0 ){
10342      i++;
10343#endif
10344    }else if( strcmp(z,"-help")==0 ){
10345      usage(1);
10346    }else if( strcmp(z,"-cmd")==0 ){
10347      /* Run commands that follow -cmd first and separately from commands
10348      ** that simply appear on the command-line.  This seems goofy.  It would
10349      ** be better if all commands ran in the order that they appear.  But
10350      ** we retain the goofy behavior for historical compatibility. */
10351      if( i==argc-1 ) break;
10352      z = cmdline_option_value(argc,argv,++i);
10353      if( z[0]=='.' ){
10354        rc = do_meta_command(z, &data);
10355        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
10356      }else{
10357        open_db(&data, 0);
10358        rc = shell_exec(&data, z, &zErrMsg);
10359        if( zErrMsg!=0 ){
10360          utf8_printf(stderr,"Error: %s\n", zErrMsg);
10361          if( bail_on_error ) return rc!=0 ? rc : 1;
10362        }else if( rc!=0 ){
10363          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
10364          if( bail_on_error ) return rc;
10365        }
10366      }
10367#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
10368    }else if( strncmp(z, "-A", 2)==0 ){
10369      if( nCmd>0 ){
10370        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
10371                            " with \"%s\"\n", z);
10372        return 1;
10373      }
10374      open_db(&data, OPEN_DB_ZIPFILE);
10375      if( z[2] ){
10376        argv[i] = &z[2];
10377        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
10378      }else{
10379        arDotCommand(&data, 1, argv+i, argc-i);
10380      }
10381      readStdin = 0;
10382      break;
10383#endif
10384    }else{
10385      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
10386      raw_printf(stderr,"Use -help for a list of options.\n");
10387      return 1;
10388    }
10389    data.cMode = data.mode;
10390  }
10391
10392  if( !readStdin ){
10393    /* Run all arguments that do not begin with '-' as if they were separate
10394    ** command-line inputs, except for the argToSkip argument which contains
10395    ** the database filename.
10396    */
10397    for(i=0; i<nCmd; i++){
10398      if( azCmd[i][0]=='.' ){
10399        rc = do_meta_command(azCmd[i], &data);
10400        if( rc ) return rc==2 ? 0 : rc;
10401      }else{
10402        open_db(&data, 0);
10403        rc = shell_exec(&data, azCmd[i], &zErrMsg);
10404        if( zErrMsg!=0 ){
10405          utf8_printf(stderr,"Error: %s\n", zErrMsg);
10406          return rc!=0 ? rc : 1;
10407        }else if( rc!=0 ){
10408          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
10409          return rc;
10410        }
10411      }
10412    }
10413    free(azCmd);
10414  }else{
10415    /* Run commands received from standard input
10416    */
10417    if( stdin_is_interactive ){
10418      char *zHome;
10419      char *zHistory;
10420      int nHistory;
10421      printf(
10422        "SQLite version %s %.19s\n" /*extra-version-info*/
10423        "Enter \".help\" for usage hints.\n",
10424        sqlite3_libversion(), sqlite3_sourceid()
10425      );
10426      if( warnInmemoryDb ){
10427        printf("Connected to a ");
10428        printBold("transient in-memory database");
10429        printf(".\nUse \".open FILENAME\" to reopen on a "
10430               "persistent database.\n");
10431      }
10432      zHistory = getenv("SQLITE_HISTORY");
10433      if( zHistory ){
10434        zHistory = strdup(zHistory);
10435      }else if( (zHome = find_home_dir(0))!=0 ){
10436        nHistory = strlen30(zHome) + 20;
10437        if( (zHistory = malloc(nHistory))!=0 ){
10438          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10439        }
10440      }
10441      if( zHistory ){ shell_read_history(zHistory); }
10442#if HAVE_READLINE || HAVE_EDITLINE
10443      rl_attempted_completion_function = readline_completion;
10444#elif HAVE_LINENOISE
10445      linenoiseSetCompletionCallback(linenoise_completion);
10446#endif
10447      data.in = 0;
10448      rc = process_input(&data);
10449      if( zHistory ){
10450        shell_stifle_history(2000);
10451        shell_write_history(zHistory);
10452        free(zHistory);
10453      }
10454    }else{
10455      data.in = stdin;
10456      rc = process_input(&data);
10457    }
10458  }
10459  set_table_name(&data, 0);
10460  if( data.db ){
10461    session_close_all(&data);
10462    close_db(data.db);
10463  }
10464  sqlite3_free(data.zFreeOnClose);
10465  find_home_dir(1);
10466  output_reset(&data);
10467  data.doXdgOpen = 0;
10468  clearTempFile(&data);
10469#if !SQLITE_SHELL_IS_UTF8
10470  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10471  free(argvToFree);
10472#endif
10473  /* Clear the global data structure so that valgrind will detect memory
10474  ** leaks */
10475  memset(&data, 0, sizeof(data));
10476  return rc;
10477}
10478