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