xref: /sqlite-3.40.0/src/shell.c.in (revision fd779e2f)
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** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26#ifdef SQLITE_CUSTOM_INCLUDE
27# define INC_STRINGIFY_(f) #f
28# define INC_STRINGIFY(f) INC_STRINGIFY_(f)
29# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** Warning pragmas copied from msvc.h in the core.
42*/
43#if defined(_MSC_VER)
44#pragma warning(disable : 4054)
45#pragma warning(disable : 4055)
46#pragma warning(disable : 4100)
47#pragma warning(disable : 4127)
48#pragma warning(disable : 4130)
49#pragma warning(disable : 4152)
50#pragma warning(disable : 4189)
51#pragma warning(disable : 4206)
52#pragma warning(disable : 4210)
53#pragma warning(disable : 4232)
54#pragma warning(disable : 4244)
55#pragma warning(disable : 4305)
56#pragma warning(disable : 4306)
57#pragma warning(disable : 4702)
58#pragma warning(disable : 4706)
59#endif /* defined(_MSC_VER) */
60
61/*
62** No support for loadable extensions in VxWorks.
63*/
64#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
65# define SQLITE_OMIT_LOAD_EXTENSION 1
66#endif
67
68/*
69** Enable large-file support for fopen() and friends on unix.
70*/
71#ifndef SQLITE_DISABLE_LFS
72# define _LARGE_FILE       1
73# ifndef _FILE_OFFSET_BITS
74#   define _FILE_OFFSET_BITS 64
75# endif
76# define _LARGEFILE_SOURCE 1
77#endif
78
79#include <stdlib.h>
80#include <string.h>
81#include <stdio.h>
82#include <assert.h>
83#include "sqlite3.h"
84typedef sqlite3_int64 i64;
85typedef sqlite3_uint64 u64;
86typedef unsigned char u8;
87#if SQLITE_USER_AUTHENTICATION
88# include "sqlite3userauth.h"
89#endif
90#include <ctype.h>
91#include <stdarg.h>
92
93#if !defined(_WIN32) && !defined(WIN32)
94# include <signal.h>
95# if !defined(__RTP__) && !defined(_WRS_KERNEL)
96#  include <pwd.h>
97# endif
98#endif
99#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100# include <unistd.h>
101# include <dirent.h>
102# define GETPID getpid
103# if defined(__MINGW32__)
104#  define DIRENT dirent
105#  ifndef S_ISLNK
106#   define S_ISLNK(mode) (0)
107#  endif
108# endif
109#else
110# define GETPID (int)GetCurrentProcessId
111#endif
112#include <sys/types.h>
113#include <sys/stat.h>
114
115#if HAVE_READLINE
116# include <readline/readline.h>
117# include <readline/history.h>
118#endif
119
120#if HAVE_EDITLINE
121# include <editline/readline.h>
122#endif
123
124#if HAVE_EDITLINE || HAVE_READLINE
125
126# define shell_add_history(X) add_history(X)
127# define shell_read_history(X) read_history(X)
128# define shell_write_history(X) write_history(X)
129# define shell_stifle_history(X) stifle_history(X)
130# define shell_readline(X) readline(X)
131
132#elif HAVE_LINENOISE
133
134# include "linenoise.h"
135# define shell_add_history(X) linenoiseHistoryAdd(X)
136# define shell_read_history(X) linenoiseHistoryLoad(X)
137# define shell_write_history(X) linenoiseHistorySave(X)
138# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
139# define shell_readline(X) linenoise(X)
140
141#else
142
143# define shell_read_history(X)
144# define shell_write_history(X)
145# define shell_stifle_history(X)
146
147# define SHELL_USE_LOCAL_GETLINE 1
148#endif
149
150
151#if defined(_WIN32) || defined(WIN32)
152# if SQLITE_OS_WINRT
153#  define SQLITE_OMIT_POPEN 1
154# else
155#  include <io.h>
156#  include <fcntl.h>
157#  define isatty(h) _isatty(h)
158#  ifndef access
159#   define access(f,m) _access((f),(m))
160#  endif
161#  ifndef unlink
162#   define unlink _unlink
163#  endif
164#  ifndef strdup
165#   define strdup _strdup
166#  endif
167#  undef popen
168#  define popen _popen
169#  undef pclose
170#  define pclose _pclose
171# endif
172#else
173 /* Make sure isatty() has a prototype. */
174 extern int isatty(int);
175
176# if !defined(__RTP__) && !defined(_WRS_KERNEL)
177  /* popen and pclose are not C89 functions and so are
178  ** sometimes omitted from the <stdio.h> header */
179   extern FILE *popen(const char*,const char*);
180   extern int pclose(FILE*);
181# else
182#  define SQLITE_OMIT_POPEN 1
183# endif
184#endif
185
186#if defined(_WIN32_WCE)
187/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
188 * thus we always assume that we have a console. That can be
189 * overridden with the -batch command line option.
190 */
191#define isatty(x) 1
192#endif
193
194/* ctype macros that work with signed characters */
195#define IsSpace(X)  isspace((unsigned char)X)
196#define IsDigit(X)  isdigit((unsigned char)X)
197#define ToLower(X)  (char)tolower((unsigned char)X)
198
199#if defined(_WIN32) || defined(WIN32)
200#if SQLITE_OS_WINRT
201#include <intrin.h>
202#endif
203#include <windows.h>
204
205/* string conversion routines only needed on Win32 */
206extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
207extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
208extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
209extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
210#endif
211
212/* On Windows, we normally run with output mode of TEXT so that \n characters
213** are automatically translated into \r\n.  However, this behavior needs
214** to be disabled in some cases (ex: when generating CSV output and when
215** rendering quoted strings that contain \n characters).  The following
216** routines take care of that.
217*/
218#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
219static void setBinaryMode(FILE *file, int isOutput){
220  if( isOutput ) fflush(file);
221  _setmode(_fileno(file), _O_BINARY);
222}
223static void setTextMode(FILE *file, int isOutput){
224  if( isOutput ) fflush(file);
225  _setmode(_fileno(file), _O_TEXT);
226}
227#else
228# define setBinaryMode(X,Y)
229# define setTextMode(X,Y)
230#endif
231
232
233/* True if the timer is enabled */
234static int enableTimer = 0;
235
236/* Return the current wall-clock time */
237static sqlite3_int64 timeOfDay(void){
238  static sqlite3_vfs *clockVfs = 0;
239  sqlite3_int64 t;
240  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
241  if( clockVfs==0 ) return 0;  /* Never actually happens */
242  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
243    clockVfs->xCurrentTimeInt64(clockVfs, &t);
244  }else{
245    double r;
246    clockVfs->xCurrentTime(clockVfs, &r);
247    t = (sqlite3_int64)(r*86400000.0);
248  }
249  return t;
250}
251
252#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
253#include <sys/time.h>
254#include <sys/resource.h>
255
256/* VxWorks does not support getrusage() as far as we can determine */
257#if defined(_WRS_KERNEL) || defined(__RTP__)
258struct rusage {
259  struct timeval ru_utime; /* user CPU time used */
260  struct timeval ru_stime; /* system CPU time used */
261};
262#define getrusage(A,B) memset(B,0,sizeof(*B))
263#endif
264
265/* Saved resource information for the beginning of an operation */
266static struct rusage sBegin;  /* CPU time at start */
267static sqlite3_int64 iBegin;  /* Wall-clock time at start */
268
269/*
270** Begin timing an operation
271*/
272static void beginTimer(void){
273  if( enableTimer ){
274    getrusage(RUSAGE_SELF, &sBegin);
275    iBegin = timeOfDay();
276  }
277}
278
279/* Return the difference of two time_structs in seconds */
280static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
281  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
282         (double)(pEnd->tv_sec - pStart->tv_sec);
283}
284
285/*
286** Print the timing results.
287*/
288static void endTimer(void){
289  if( enableTimer ){
290    sqlite3_int64 iEnd = timeOfDay();
291    struct rusage sEnd;
292    getrusage(RUSAGE_SELF, &sEnd);
293    printf("Run Time: real %.3f user %f sys %f\n",
294       (iEnd - iBegin)*0.001,
295       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
296       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
297  }
298}
299
300#define BEGIN_TIMER beginTimer()
301#define END_TIMER endTimer()
302#define HAS_TIMER 1
303
304#elif (defined(_WIN32) || defined(WIN32))
305
306/* Saved resource information for the beginning of an operation */
307static HANDLE hProcess;
308static FILETIME ftKernelBegin;
309static FILETIME ftUserBegin;
310static sqlite3_int64 ftWallBegin;
311typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
312                                    LPFILETIME, LPFILETIME);
313static GETPROCTIMES getProcessTimesAddr = NULL;
314
315/*
316** Check to see if we have timer support.  Return 1 if necessary
317** support found (or found previously).
318*/
319static int hasTimer(void){
320  if( getProcessTimesAddr ){
321    return 1;
322  } else {
323#if !SQLITE_OS_WINRT
324    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
325    ** versions. See if the version we are running on has it, and if it
326    ** does, save off a pointer to it and the current process handle.
327    */
328    hProcess = GetCurrentProcess();
329    if( hProcess ){
330      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
331      if( NULL != hinstLib ){
332        getProcessTimesAddr =
333            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
334        if( NULL != getProcessTimesAddr ){
335          return 1;
336        }
337        FreeLibrary(hinstLib);
338      }
339    }
340#endif
341  }
342  return 0;
343}
344
345/*
346** Begin timing an operation
347*/
348static void beginTimer(void){
349  if( enableTimer && getProcessTimesAddr ){
350    FILETIME ftCreation, ftExit;
351    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
352                        &ftKernelBegin,&ftUserBegin);
353    ftWallBegin = timeOfDay();
354  }
355}
356
357/* Return the difference of two FILETIME structs in seconds */
358static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
359  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
360  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
361  return (double) ((i64End - i64Start) / 10000000.0);
362}
363
364/*
365** Print the timing results.
366*/
367static void endTimer(void){
368  if( enableTimer && getProcessTimesAddr){
369    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
370    sqlite3_int64 ftWallEnd = timeOfDay();
371    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
372    printf("Run Time: real %.3f user %f sys %f\n",
373       (ftWallEnd - ftWallBegin)*0.001,
374       timeDiff(&ftUserBegin, &ftUserEnd),
375       timeDiff(&ftKernelBegin, &ftKernelEnd));
376  }
377}
378
379#define BEGIN_TIMER beginTimer()
380#define END_TIMER endTimer()
381#define HAS_TIMER hasTimer()
382
383#else
384#define BEGIN_TIMER
385#define END_TIMER
386#define HAS_TIMER 0
387#endif
388
389/*
390** Used to prevent warnings about unused parameters
391*/
392#define UNUSED_PARAMETER(x) (void)(x)
393
394/*
395** Number of elements in an array
396*/
397#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
398
399/*
400** If the following flag is set, then command execution stops
401** at an error if we are not interactive.
402*/
403static int bail_on_error = 0;
404
405/*
406** Threat stdin as an interactive input if the following variable
407** is true.  Otherwise, assume stdin is connected to a file or pipe.
408*/
409static int stdin_is_interactive = 1;
410
411/*
412** On Windows systems we have to know if standard output is a console
413** in order to translate UTF-8 into MBCS.  The following variable is
414** true if translation is required.
415*/
416static int stdout_is_console = 1;
417
418/*
419** The following is the open SQLite database.  We make a pointer
420** to this database a static variable so that it can be accessed
421** by the SIGINT handler to interrupt database processing.
422*/
423static sqlite3 *globalDb = 0;
424
425/*
426** True if an interrupt (Control-C) has been received.
427*/
428static volatile int seenInterrupt = 0;
429
430#ifdef SQLITE_DEBUG
431/*
432** Out-of-memory simulator variables
433*/
434static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
435static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
436static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
437#endif /* SQLITE_DEBUG */
438
439/*
440** This is the name of our program. It is set in main(), used
441** in a number of other places, mostly for error messages.
442*/
443static char *Argv0;
444
445/*
446** Prompt strings. Initialized in main. Settable with
447**   .prompt main continue
448*/
449static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
450static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
451
452/*
453** Render output like fprintf().  Except, if the output is going to the
454** console and if this is running on a Windows machine, translate the
455** output from UTF-8 into MBCS.
456*/
457#if defined(_WIN32) || defined(WIN32)
458void utf8_printf(FILE *out, const char *zFormat, ...){
459  va_list ap;
460  va_start(ap, zFormat);
461  if( stdout_is_console && (out==stdout || out==stderr) ){
462    char *z1 = sqlite3_vmprintf(zFormat, ap);
463    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
464    sqlite3_free(z1);
465    fputs(z2, out);
466    sqlite3_free(z2);
467  }else{
468    vfprintf(out, zFormat, ap);
469  }
470  va_end(ap);
471}
472#elif !defined(utf8_printf)
473# define utf8_printf fprintf
474#endif
475
476/*
477** Render output like fprintf().  This should not be used on anything that
478** includes string formatting (e.g. "%s").
479*/
480#if !defined(raw_printf)
481# define raw_printf fprintf
482#endif
483
484/* Indicate out-of-memory and exit. */
485static void shell_out_of_memory(void){
486  raw_printf(stderr,"Error: out of memory\n");
487  exit(1);
488}
489
490#ifdef SQLITE_DEBUG
491/* This routine is called when a simulated OOM occurs.  It is broken
492** out as a separate routine to make it easy to set a breakpoint on
493** the OOM
494*/
495void shellOomFault(void){
496  if( oomRepeat>0 ){
497    oomRepeat--;
498  }else{
499    oomCounter--;
500  }
501}
502#endif /* SQLITE_DEBUG */
503
504#ifdef SQLITE_DEBUG
505/* This routine is a replacement malloc() that is used to simulate
506** Out-Of-Memory (OOM) errors for testing purposes.
507*/
508static void *oomMalloc(int nByte){
509  if( oomCounter ){
510    if( oomCounter==1 ){
511      shellOomFault();
512      return 0;
513    }else{
514      oomCounter--;
515    }
516  }
517  return defaultMalloc(nByte);
518}
519#endif /* SQLITE_DEBUG */
520
521#ifdef SQLITE_DEBUG
522/* Register the OOM simulator.  This must occur before any memory
523** allocations */
524static void registerOomSimulator(void){
525  sqlite3_mem_methods mem;
526  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
527  defaultMalloc = mem.xMalloc;
528  mem.xMalloc = oomMalloc;
529  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
530}
531#endif
532
533/*
534** Write I/O traces to the following stream.
535*/
536#ifdef SQLITE_ENABLE_IOTRACE
537static FILE *iotrace = 0;
538#endif
539
540/*
541** This routine works like printf in that its first argument is a
542** format string and subsequent arguments are values to be substituted
543** in place of % fields.  The result of formatting this string
544** is written to iotrace.
545*/
546#ifdef SQLITE_ENABLE_IOTRACE
547static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
548  va_list ap;
549  char *z;
550  if( iotrace==0 ) return;
551  va_start(ap, zFormat);
552  z = sqlite3_vmprintf(zFormat, ap);
553  va_end(ap);
554  utf8_printf(iotrace, "%s", z);
555  sqlite3_free(z);
556}
557#endif
558
559/*
560** Output string zUtf to stream pOut as w characters.  If w is negative,
561** then right-justify the text.  W is the width in UTF-8 characters, not
562** in bytes.  This is different from the %*.*s specification in printf
563** since with %*.*s the width is measured in bytes, not characters.
564*/
565static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
566  int i;
567  int n;
568  int aw = w<0 ? -w : w;
569  for(i=n=0; zUtf[i]; i++){
570    if( (zUtf[i]&0xc0)!=0x80 ){
571      n++;
572      if( n==aw ){
573        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
574        break;
575      }
576    }
577  }
578  if( n>=aw ){
579    utf8_printf(pOut, "%.*s", i, zUtf);
580  }else if( w<0 ){
581    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
582  }else{
583    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
584  }
585}
586
587
588/*
589** Determines if a string is a number of not.
590*/
591static int isNumber(const char *z, int *realnum){
592  if( *z=='-' || *z=='+' ) z++;
593  if( !IsDigit(*z) ){
594    return 0;
595  }
596  z++;
597  if( realnum ) *realnum = 0;
598  while( IsDigit(*z) ){ z++; }
599  if( *z=='.' ){
600    z++;
601    if( !IsDigit(*z) ) return 0;
602    while( IsDigit(*z) ){ z++; }
603    if( realnum ) *realnum = 1;
604  }
605  if( *z=='e' || *z=='E' ){
606    z++;
607    if( *z=='+' || *z=='-' ) z++;
608    if( !IsDigit(*z) ) return 0;
609    while( IsDigit(*z) ){ z++; }
610    if( realnum ) *realnum = 1;
611  }
612  return *z==0;
613}
614
615/*
616** Compute a string length that is limited to what can be stored in
617** lower 30 bits of a 32-bit signed integer.
618*/
619static int strlen30(const char *z){
620  const char *z2 = z;
621  while( *z2 ){ z2++; }
622  return 0x3fffffff & (int)(z2 - z);
623}
624
625/*
626** Return the length of a string in characters.  Multibyte UTF8 characters
627** count as a single character.
628*/
629static int strlenChar(const char *z){
630  int n = 0;
631  while( *z ){
632    if( (0xc0&*(z++))!=0x80 ) n++;
633  }
634  return n;
635}
636
637/*
638** Return true if zFile does not exist or if it is not an ordinary file.
639*/
640#ifdef _WIN32
641# define notNormalFile(X) 0
642#else
643static int notNormalFile(const char *zFile){
644  struct stat x;
645  int rc;
646  memset(&x, 0, sizeof(x));
647  rc = stat(zFile, &x);
648  return rc || !S_ISREG(x.st_mode);
649}
650#endif
651
652/*
653** This routine reads a line of text from FILE in, stores
654** the text in memory obtained from malloc() and returns a pointer
655** to the text.  NULL is returned at end of file, or if malloc()
656** fails.
657**
658** If zLine is not NULL then it is a malloced buffer returned from
659** a previous call to this routine that may be reused.
660*/
661static char *local_getline(char *zLine, FILE *in){
662  int nLine = zLine==0 ? 0 : 100;
663  int n = 0;
664
665  while( 1 ){
666    if( n+100>nLine ){
667      nLine = nLine*2 + 100;
668      zLine = realloc(zLine, nLine);
669      if( zLine==0 ) shell_out_of_memory();
670    }
671    if( fgets(&zLine[n], nLine - n, in)==0 ){
672      if( n==0 ){
673        free(zLine);
674        return 0;
675      }
676      zLine[n] = 0;
677      break;
678    }
679    while( zLine[n] ) n++;
680    if( n>0 && zLine[n-1]=='\n' ){
681      n--;
682      if( n>0 && zLine[n-1]=='\r' ) n--;
683      zLine[n] = 0;
684      break;
685    }
686  }
687#if defined(_WIN32) || defined(WIN32)
688  /* For interactive input on Windows systems, translate the
689  ** multi-byte characterset characters into UTF-8. */
690  if( stdin_is_interactive && in==stdin ){
691    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
692    if( zTrans ){
693      int nTrans = strlen30(zTrans)+1;
694      if( nTrans>nLine ){
695        zLine = realloc(zLine, nTrans);
696        if( zLine==0 ) shell_out_of_memory();
697      }
698      memcpy(zLine, zTrans, nTrans);
699      sqlite3_free(zTrans);
700    }
701  }
702#endif /* defined(_WIN32) || defined(WIN32) */
703  return zLine;
704}
705
706/*
707** Retrieve a single line of input text.
708**
709** If in==0 then read from standard input and prompt before each line.
710** If isContinuation is true, then a continuation prompt is appropriate.
711** If isContinuation is zero, then the main prompt should be used.
712**
713** If zPrior is not NULL then it is a buffer from a prior call to this
714** routine that can be reused.
715**
716** The result is stored in space obtained from malloc() and must either
717** be freed by the caller or else passed back into this routine via the
718** zPrior argument for reuse.
719*/
720static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
721  char *zPrompt;
722  char *zResult;
723  if( in!=0 ){
724    zResult = local_getline(zPrior, in);
725  }else{
726    zPrompt = isContinuation ? continuePrompt : mainPrompt;
727#if SHELL_USE_LOCAL_GETLINE
728    printf("%s", zPrompt);
729    fflush(stdout);
730    zResult = local_getline(zPrior, stdin);
731#else
732    free(zPrior);
733    zResult = shell_readline(zPrompt);
734    if( zResult && *zResult ) shell_add_history(zResult);
735#endif
736  }
737  return zResult;
738}
739
740
741/*
742** Return the value of a hexadecimal digit.  Return -1 if the input
743** is not a hex digit.
744*/
745static int hexDigitValue(char c){
746  if( c>='0' && c<='9' ) return c - '0';
747  if( c>='a' && c<='f' ) return c - 'a' + 10;
748  if( c>='A' && c<='F' ) return c - 'A' + 10;
749  return -1;
750}
751
752/*
753** Interpret zArg as an integer value, possibly with suffixes.
754*/
755static sqlite3_int64 integerValue(const char *zArg){
756  sqlite3_int64 v = 0;
757  static const struct { char *zSuffix; int iMult; } aMult[] = {
758    { "KiB", 1024 },
759    { "MiB", 1024*1024 },
760    { "GiB", 1024*1024*1024 },
761    { "KB",  1000 },
762    { "MB",  1000000 },
763    { "GB",  1000000000 },
764    { "K",   1000 },
765    { "M",   1000000 },
766    { "G",   1000000000 },
767  };
768  int i;
769  int isNeg = 0;
770  if( zArg[0]=='-' ){
771    isNeg = 1;
772    zArg++;
773  }else if( zArg[0]=='+' ){
774    zArg++;
775  }
776  if( zArg[0]=='0' && zArg[1]=='x' ){
777    int x;
778    zArg += 2;
779    while( (x = hexDigitValue(zArg[0]))>=0 ){
780      v = (v<<4) + x;
781      zArg++;
782    }
783  }else{
784    while( IsDigit(zArg[0]) ){
785      v = v*10 + zArg[0] - '0';
786      zArg++;
787    }
788  }
789  for(i=0; i<ArraySize(aMult); i++){
790    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
791      v *= aMult[i].iMult;
792      break;
793    }
794  }
795  return isNeg? -v : v;
796}
797
798/*
799** A variable length string to which one can append text.
800*/
801typedef struct ShellText ShellText;
802struct ShellText {
803  char *z;
804  int n;
805  int nAlloc;
806};
807
808/*
809** Initialize and destroy a ShellText object
810*/
811static void initText(ShellText *p){
812  memset(p, 0, sizeof(*p));
813}
814static void freeText(ShellText *p){
815  free(p->z);
816  initText(p);
817}
818
819/* zIn is either a pointer to a NULL-terminated string in memory obtained
820** from malloc(), or a NULL pointer. The string pointed to by zAppend is
821** added to zIn, and the result returned in memory obtained from malloc().
822** zIn, if it was not NULL, is freed.
823**
824** If the third argument, quote, is not '\0', then it is used as a
825** quote character for zAppend.
826*/
827static void appendText(ShellText *p, char const *zAppend, char quote){
828  int len;
829  int i;
830  int nAppend = strlen30(zAppend);
831
832  len = nAppend+p->n+1;
833  if( quote ){
834    len += 2;
835    for(i=0; i<nAppend; i++){
836      if( zAppend[i]==quote ) len++;
837    }
838  }
839
840  if( p->n+len>=p->nAlloc ){
841    p->nAlloc = p->nAlloc*2 + len + 20;
842    p->z = realloc(p->z, p->nAlloc);
843    if( p->z==0 ) shell_out_of_memory();
844  }
845
846  if( quote ){
847    char *zCsr = p->z+p->n;
848    *zCsr++ = quote;
849    for(i=0; i<nAppend; i++){
850      *zCsr++ = zAppend[i];
851      if( zAppend[i]==quote ) *zCsr++ = quote;
852    }
853    *zCsr++ = quote;
854    p->n = (int)(zCsr - p->z);
855    *zCsr = '\0';
856  }else{
857    memcpy(p->z+p->n, zAppend, nAppend);
858    p->n += nAppend;
859    p->z[p->n] = '\0';
860  }
861}
862
863/*
864** Attempt to determine if identifier zName needs to be quoted, either
865** because it contains non-alphanumeric characters, or because it is an
866** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
867** that quoting is required.
868**
869** Return '"' if quoting is required.  Return 0 if no quoting is required.
870*/
871static char quoteChar(const char *zName){
872  int i;
873  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
874  for(i=0; zName[i]; i++){
875    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
876  }
877  return sqlite3_keyword_check(zName, i) ? '"' : 0;
878}
879
880/*
881** Construct a fake object name and column list to describe the structure
882** of the view, virtual table, or table valued function zSchema.zName.
883*/
884static char *shellFakeSchema(
885  sqlite3 *db,            /* The database connection containing the vtab */
886  const char *zSchema,    /* Schema of the database holding the vtab */
887  const char *zName       /* The name of the virtual table */
888){
889  sqlite3_stmt *pStmt = 0;
890  char *zSql;
891  ShellText s;
892  char cQuote;
893  char *zDiv = "(";
894  int nRow = 0;
895
896  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
897                         zSchema ? zSchema : "main", zName);
898  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
899  sqlite3_free(zSql);
900  initText(&s);
901  if( zSchema ){
902    cQuote = quoteChar(zSchema);
903    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
904    appendText(&s, zSchema, cQuote);
905    appendText(&s, ".", 0);
906  }
907  cQuote = quoteChar(zName);
908  appendText(&s, zName, cQuote);
909  while( sqlite3_step(pStmt)==SQLITE_ROW ){
910    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
911    nRow++;
912    appendText(&s, zDiv, 0);
913    zDiv = ",";
914    cQuote = quoteChar(zCol);
915    appendText(&s, zCol, cQuote);
916  }
917  appendText(&s, ")", 0);
918  sqlite3_finalize(pStmt);
919  if( nRow==0 ){
920    freeText(&s);
921    s.z = 0;
922  }
923  return s.z;
924}
925
926/*
927** SQL function:  shell_module_schema(X)
928**
929** Return a fake schema for the table-valued function or eponymous virtual
930** table X.
931*/
932static void shellModuleSchema(
933  sqlite3_context *pCtx,
934  int nVal,
935  sqlite3_value **apVal
936){
937  const char *zName = (const char*)sqlite3_value_text(apVal[0]);
938  char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
939  UNUSED_PARAMETER(nVal);
940  if( zFake ){
941    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
942                        -1, sqlite3_free);
943    free(zFake);
944  }
945}
946
947/*
948** SQL function:  shell_add_schema(S,X)
949**
950** Add the schema name X to the CREATE statement in S and return the result.
951** Examples:
952**
953**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
954**
955** Also works on
956**
957**    CREATE INDEX
958**    CREATE UNIQUE INDEX
959**    CREATE VIEW
960**    CREATE TRIGGER
961**    CREATE VIRTUAL TABLE
962**
963** This UDF is used by the .schema command to insert the schema name of
964** attached databases into the middle of the sqlite_schema.sql field.
965*/
966static void shellAddSchemaName(
967  sqlite3_context *pCtx,
968  int nVal,
969  sqlite3_value **apVal
970){
971  static const char *aPrefix[] = {
972     "TABLE",
973     "INDEX",
974     "UNIQUE INDEX",
975     "VIEW",
976     "TRIGGER",
977     "VIRTUAL TABLE"
978  };
979  int i = 0;
980  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
981  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
982  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
983  sqlite3 *db = sqlite3_context_db_handle(pCtx);
984  UNUSED_PARAMETER(nVal);
985  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
986    for(i=0; i<ArraySize(aPrefix); i++){
987      int n = strlen30(aPrefix[i]);
988      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
989        char *z = 0;
990        char *zFake = 0;
991        if( zSchema ){
992          char cQuote = quoteChar(zSchema);
993          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
994            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
995          }else{
996            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
997          }
998        }
999        if( zName
1000         && aPrefix[i][0]=='V'
1001         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1002        ){
1003          if( z==0 ){
1004            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1005          }else{
1006            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1007          }
1008          free(zFake);
1009        }
1010        if( z ){
1011          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1012          return;
1013        }
1014      }
1015    }
1016  }
1017  sqlite3_result_value(pCtx, apVal[0]);
1018}
1019
1020/*
1021** The source code for several run-time loadable extensions is inserted
1022** below by the ../tool/mkshellc.tcl script.  Before processing that included
1023** code, we need to override some macros to make the included program code
1024** work here in the middle of this regular program.
1025*/
1026#define SQLITE_EXTENSION_INIT1
1027#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1028
1029#if defined(_WIN32) && defined(_MSC_VER)
1030INCLUDE test_windirent.h
1031INCLUDE test_windirent.c
1032#define dirent DIRENT
1033#endif
1034INCLUDE ../ext/misc/shathree.c
1035INCLUDE ../ext/misc/fileio.c
1036INCLUDE ../ext/misc/completion.c
1037INCLUDE ../ext/misc/appendvfs.c
1038INCLUDE ../ext/misc/memtrace.c
1039INCLUDE ../ext/misc/uint.c
1040INCLUDE ../ext/misc/decimal.c
1041INCLUDE ../ext/misc/ieee754.c
1042INCLUDE ../ext/misc/series.c
1043INCLUDE ../ext/misc/regexp.c
1044#ifdef SQLITE_HAVE_ZLIB
1045INCLUDE ../ext/misc/zipfile.c
1046INCLUDE ../ext/misc/sqlar.c
1047#endif
1048INCLUDE ../ext/expert/sqlite3expert.h
1049INCLUDE ../ext/expert/sqlite3expert.c
1050
1051#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1052INCLUDE ../ext/misc/dbdata.c
1053#endif
1054
1055#if defined(SQLITE_ENABLE_SESSION)
1056/*
1057** State information for a single open session
1058*/
1059typedef struct OpenSession OpenSession;
1060struct OpenSession {
1061  char *zName;             /* Symbolic name for this session */
1062  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1063  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1064  sqlite3_session *p;      /* The open session */
1065};
1066#endif
1067
1068typedef struct ExpertInfo ExpertInfo;
1069struct ExpertInfo {
1070  sqlite3expert *pExpert;
1071  int bVerbose;
1072};
1073
1074/* A single line in the EQP output */
1075typedef struct EQPGraphRow EQPGraphRow;
1076struct EQPGraphRow {
1077  int iEqpId;           /* ID for this row */
1078  int iParentId;        /* ID of the parent row */
1079  EQPGraphRow *pNext;   /* Next row in sequence */
1080  char zText[1];        /* Text to display for this row */
1081};
1082
1083/* All EQP output is collected into an instance of the following */
1084typedef struct EQPGraph EQPGraph;
1085struct EQPGraph {
1086  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1087  EQPGraphRow *pLast;   /* Last element of the pRow list */
1088  char zPrefix[100];    /* Graph prefix */
1089};
1090
1091/*
1092** State information about the database connection is contained in an
1093** instance of the following structure.
1094*/
1095typedef struct ShellState ShellState;
1096struct ShellState {
1097  sqlite3 *db;           /* The database */
1098  u8 autoExplain;        /* Automatically turn on .explain mode */
1099  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1100  u8 autoEQPtest;        /* autoEQP is in test mode */
1101  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1102  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1103  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1104  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1105  u8 nEqpLevel;          /* Depth of the EQP output graph */
1106  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1107  unsigned statsOn;      /* True to display memory stats before each finalize */
1108  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1109  int outCount;          /* Revert to stdout when reaching zero */
1110  int cnt;               /* Number of records displayed so far */
1111  int lineno;            /* Line number of last line read from in */
1112  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1113  FILE *in;              /* Read commands from this stream */
1114  FILE *out;             /* Write results here */
1115  FILE *traceOut;        /* Output for sqlite3_trace() */
1116  int nErr;              /* Number of errors seen */
1117  int mode;              /* An output mode setting */
1118  int modePrior;         /* Saved mode */
1119  int cMode;             /* temporary output mode for the current query */
1120  int normalMode;        /* Output mode before ".explain on" */
1121  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1122  int showHeader;        /* True to show column names in List or Column mode */
1123  int nCheck;            /* Number of ".check" commands run */
1124  unsigned nProgress;    /* Number of progress callbacks encountered */
1125  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1126  unsigned flgProgress;  /* Flags for the progress callback */
1127  unsigned shellFlgs;    /* Various flags */
1128  unsigned priorShFlgs;  /* Saved copy of flags */
1129  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1130  char *zDestTable;      /* Name of destination table when MODE_Insert */
1131  char *zTempFile;       /* Temporary file that might need deleting */
1132  char zTestcase[30];    /* Name of current test case */
1133  char colSeparator[20]; /* Column separator character for several modes */
1134  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1135  char colSepPrior[20];  /* Saved column separator */
1136  char rowSepPrior[20];  /* Saved row separator */
1137  int *colWidth;         /* Requested width of each column in columnar modes */
1138  int *actualWidth;      /* Actual width of each column */
1139  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1140  char nullValue[20];    /* The text to print when a NULL comes back from
1141                         ** the database */
1142  char outfile[FILENAME_MAX]; /* Filename for *out */
1143  sqlite3_stmt *pStmt;   /* Current statement if any. */
1144  FILE *pLog;            /* Write log output here */
1145  struct AuxDb {         /* Storage space for auxiliary database connections */
1146    sqlite3 *db;               /* Connection pointer */
1147    const char *zDbFilename;   /* Filename used to open the connection */
1148    char *zFreeOnClose;        /* Free this memory allocation on close */
1149#if defined(SQLITE_ENABLE_SESSION)
1150    int nSession;              /* Number of active sessions */
1151    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1152#endif
1153  } aAuxDb[5],           /* Array of all database connections */
1154    *pAuxDb;             /* Currently active database connection */
1155  int *aiIndent;         /* Array of indents used in MODE_Explain */
1156  int nIndent;           /* Size of array aiIndent[] */
1157  int iIndent;           /* Index of current op in aiIndent[] */
1158  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1159  ExpertInfo expert;        /* Valid if previous command was ".expert OPT..." */
1160};
1161
1162
1163/* Allowed values for ShellState.autoEQP
1164*/
1165#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1166#define AUTOEQP_on       1           /* Automatic EQP is on */
1167#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1168#define AUTOEQP_full     3           /* Show full EXPLAIN */
1169
1170/* Allowed values for ShellState.openMode
1171*/
1172#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1173#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1174#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1175#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1176#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1177#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1178#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1179
1180/* Allowed values for ShellState.eTraceType
1181*/
1182#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1183#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1184#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1185
1186/* Bits in the ShellState.flgProgress variable */
1187#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1188#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1189                                   ** callback limit is reached, and for each
1190                                   ** top-level SQL statement */
1191#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1192
1193/*
1194** These are the allowed shellFlgs values
1195*/
1196#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1197#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1198#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1199#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1200#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1201#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1202#define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
1203#define SHFLG_HeaderSet      0x00000080 /* .header has been used */
1204#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1205#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1206
1207/*
1208** Macros for testing and setting shellFlgs
1209*/
1210#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1211#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1212#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1213
1214/*
1215** These are the allowed modes.
1216*/
1217#define MODE_Line     0  /* One column per line.  Blank line between records */
1218#define MODE_Column   1  /* One record per line in neat columns */
1219#define MODE_List     2  /* One record per line with a separator */
1220#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1221#define MODE_Html     4  /* Generate an XHTML table */
1222#define MODE_Insert   5  /* Generate SQL "insert" statements */
1223#define MODE_Quote    6  /* Quote values as for SQL */
1224#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1225#define MODE_Csv      8  /* Quote strings, numbers are plain */
1226#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1227#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1228#define MODE_Pretty  11  /* Pretty-print schemas */
1229#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1230#define MODE_Json    13  /* Output JSON */
1231#define MODE_Markdown 14 /* Markdown formatting */
1232#define MODE_Table   15  /* MySQL-style table formatting */
1233#define MODE_Box     16  /* Unicode box-drawing characters */
1234
1235static const char *modeDescr[] = {
1236  "line",
1237  "column",
1238  "list",
1239  "semi",
1240  "html",
1241  "insert",
1242  "quote",
1243  "tcl",
1244  "csv",
1245  "explain",
1246  "ascii",
1247  "prettyprint",
1248  "eqp",
1249  "json",
1250  "markdown",
1251  "table",
1252  "box"
1253};
1254
1255/*
1256** These are the column/row/line separators used by the various
1257** import/export modes.
1258*/
1259#define SEP_Column    "|"
1260#define SEP_Row       "\n"
1261#define SEP_Tab       "\t"
1262#define SEP_Space     " "
1263#define SEP_Comma     ","
1264#define SEP_CrLf      "\r\n"
1265#define SEP_Unit      "\x1F"
1266#define SEP_Record    "\x1E"
1267
1268/*
1269** A callback for the sqlite3_log() interface.
1270*/
1271static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1272  ShellState *p = (ShellState*)pArg;
1273  if( p->pLog==0 ) return;
1274  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1275  fflush(p->pLog);
1276}
1277
1278/*
1279** SQL function:  shell_putsnl(X)
1280**
1281** Write the text X to the screen (or whatever output is being directed)
1282** adding a newline at the end, and then return X.
1283*/
1284static void shellPutsFunc(
1285  sqlite3_context *pCtx,
1286  int nVal,
1287  sqlite3_value **apVal
1288){
1289  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1290  (void)nVal;
1291  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1292  sqlite3_result_value(pCtx, apVal[0]);
1293}
1294
1295/*
1296** SQL function:   edit(VALUE)
1297**                 edit(VALUE,EDITOR)
1298**
1299** These steps:
1300**
1301**     (1) Write VALUE into a temporary file.
1302**     (2) Run program EDITOR on that temporary file.
1303**     (3) Read the temporary file back and return its content as the result.
1304**     (4) Delete the temporary file
1305**
1306** If the EDITOR argument is omitted, use the value in the VISUAL
1307** environment variable.  If still there is no EDITOR, through an error.
1308**
1309** Also throw an error if the EDITOR program returns a non-zero exit code.
1310*/
1311#ifndef SQLITE_NOHAVE_SYSTEM
1312static void editFunc(
1313  sqlite3_context *context,
1314  int argc,
1315  sqlite3_value **argv
1316){
1317  const char *zEditor;
1318  char *zTempFile = 0;
1319  sqlite3 *db;
1320  char *zCmd = 0;
1321  int bBin;
1322  int rc;
1323  int hasCRNL = 0;
1324  FILE *f = 0;
1325  sqlite3_int64 sz;
1326  sqlite3_int64 x;
1327  unsigned char *p = 0;
1328
1329  if( argc==2 ){
1330    zEditor = (const char*)sqlite3_value_text(argv[1]);
1331  }else{
1332    zEditor = getenv("VISUAL");
1333  }
1334  if( zEditor==0 ){
1335    sqlite3_result_error(context, "no editor for edit()", -1);
1336    return;
1337  }
1338  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1339    sqlite3_result_error(context, "NULL input to edit()", -1);
1340    return;
1341  }
1342  db = sqlite3_context_db_handle(context);
1343  zTempFile = 0;
1344  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1345  if( zTempFile==0 ){
1346    sqlite3_uint64 r = 0;
1347    sqlite3_randomness(sizeof(r), &r);
1348    zTempFile = sqlite3_mprintf("temp%llx", r);
1349    if( zTempFile==0 ){
1350      sqlite3_result_error_nomem(context);
1351      return;
1352    }
1353  }
1354  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1355  /* When writing the file to be edited, do \n to \r\n conversions on systems
1356  ** that want \r\n line endings */
1357  f = fopen(zTempFile, bBin ? "wb" : "w");
1358  if( f==0 ){
1359    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1360    goto edit_func_end;
1361  }
1362  sz = sqlite3_value_bytes(argv[0]);
1363  if( bBin ){
1364    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1365  }else{
1366    const char *z = (const char*)sqlite3_value_text(argv[0]);
1367    /* Remember whether or not the value originally contained \r\n */
1368    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1369    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1370  }
1371  fclose(f);
1372  f = 0;
1373  if( x!=sz ){
1374    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1375    goto edit_func_end;
1376  }
1377  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1378  if( zCmd==0 ){
1379    sqlite3_result_error_nomem(context);
1380    goto edit_func_end;
1381  }
1382  rc = system(zCmd);
1383  sqlite3_free(zCmd);
1384  if( rc ){
1385    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1386    goto edit_func_end;
1387  }
1388  f = fopen(zTempFile, "rb");
1389  if( f==0 ){
1390    sqlite3_result_error(context,
1391      "edit() cannot reopen temp file after edit", -1);
1392    goto edit_func_end;
1393  }
1394  fseek(f, 0, SEEK_END);
1395  sz = ftell(f);
1396  rewind(f);
1397  p = sqlite3_malloc64( sz+1 );
1398  if( p==0 ){
1399    sqlite3_result_error_nomem(context);
1400    goto edit_func_end;
1401  }
1402  x = fread(p, 1, (size_t)sz, f);
1403  fclose(f);
1404  f = 0;
1405  if( x!=sz ){
1406    sqlite3_result_error(context, "could not read back the whole file", -1);
1407    goto edit_func_end;
1408  }
1409  if( bBin ){
1410    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1411  }else{
1412    sqlite3_int64 i, j;
1413    if( hasCRNL ){
1414      /* If the original contains \r\n then do no conversions back to \n */
1415      j = sz;
1416    }else{
1417      /* If the file did not originally contain \r\n then convert any new
1418      ** \r\n back into \n */
1419      for(i=j=0; i<sz; i++){
1420        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1421        p[j++] = p[i];
1422      }
1423      sz = j;
1424      p[sz] = 0;
1425    }
1426    sqlite3_result_text64(context, (const char*)p, sz,
1427                          sqlite3_free, SQLITE_UTF8);
1428  }
1429  p = 0;
1430
1431edit_func_end:
1432  if( f ) fclose(f);
1433  unlink(zTempFile);
1434  sqlite3_free(zTempFile);
1435  sqlite3_free(p);
1436}
1437#endif /* SQLITE_NOHAVE_SYSTEM */
1438
1439/*
1440** Save or restore the current output mode
1441*/
1442static void outputModePush(ShellState *p){
1443  p->modePrior = p->mode;
1444  p->priorShFlgs = p->shellFlgs;
1445  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1446  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1447}
1448static void outputModePop(ShellState *p){
1449  p->mode = p->modePrior;
1450  p->shellFlgs = p->priorShFlgs;
1451  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1452  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1453}
1454
1455/*
1456** Output the given string as a hex-encoded blob (eg. X'1234' )
1457*/
1458static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1459  int i;
1460  char *zBlob = (char *)pBlob;
1461  raw_printf(out,"X'");
1462  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1463  raw_printf(out,"'");
1464}
1465
1466/*
1467** Find a string that is not found anywhere in z[].  Return a pointer
1468** to that string.
1469**
1470** Try to use zA and zB first.  If both of those are already found in z[]
1471** then make up some string and store it in the buffer zBuf.
1472*/
1473static const char *unused_string(
1474  const char *z,                    /* Result must not appear anywhere in z */
1475  const char *zA, const char *zB,   /* Try these first */
1476  char *zBuf                        /* Space to store a generated string */
1477){
1478  unsigned i = 0;
1479  if( strstr(z, zA)==0 ) return zA;
1480  if( strstr(z, zB)==0 ) return zB;
1481  do{
1482    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1483  }while( strstr(z,zBuf)!=0 );
1484  return zBuf;
1485}
1486
1487/*
1488** Output the given string as a quoted string using SQL quoting conventions.
1489**
1490** See also: output_quoted_escaped_string()
1491*/
1492static void output_quoted_string(FILE *out, const char *z){
1493  int i;
1494  char c;
1495  setBinaryMode(out, 1);
1496  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1497  if( c==0 ){
1498    utf8_printf(out,"'%s'",z);
1499  }else{
1500    raw_printf(out, "'");
1501    while( *z ){
1502      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1503      if( c=='\'' ) i++;
1504      if( i ){
1505        utf8_printf(out, "%.*s", i, z);
1506        z += i;
1507      }
1508      if( c=='\'' ){
1509        raw_printf(out, "'");
1510        continue;
1511      }
1512      if( c==0 ){
1513        break;
1514      }
1515      z++;
1516    }
1517    raw_printf(out, "'");
1518  }
1519  setTextMode(out, 1);
1520}
1521
1522/*
1523** Output the given string as a quoted string using SQL quoting conventions.
1524** Additionallly , escape the "\n" and "\r" characters so that they do not
1525** get corrupted by end-of-line translation facilities in some operating
1526** systems.
1527**
1528** This is like output_quoted_string() but with the addition of the \r\n
1529** escape mechanism.
1530*/
1531static void output_quoted_escaped_string(FILE *out, const char *z){
1532  int i;
1533  char c;
1534  setBinaryMode(out, 1);
1535  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1536  if( c==0 ){
1537    utf8_printf(out,"'%s'",z);
1538  }else{
1539    const char *zNL = 0;
1540    const char *zCR = 0;
1541    int nNL = 0;
1542    int nCR = 0;
1543    char zBuf1[20], zBuf2[20];
1544    for(i=0; z[i]; i++){
1545      if( z[i]=='\n' ) nNL++;
1546      if( z[i]=='\r' ) nCR++;
1547    }
1548    if( nNL ){
1549      raw_printf(out, "replace(");
1550      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1551    }
1552    if( nCR ){
1553      raw_printf(out, "replace(");
1554      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1555    }
1556    raw_printf(out, "'");
1557    while( *z ){
1558      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1559      if( c=='\'' ) i++;
1560      if( i ){
1561        utf8_printf(out, "%.*s", i, z);
1562        z += i;
1563      }
1564      if( c=='\'' ){
1565        raw_printf(out, "'");
1566        continue;
1567      }
1568      if( c==0 ){
1569        break;
1570      }
1571      z++;
1572      if( c=='\n' ){
1573        raw_printf(out, "%s", zNL);
1574        continue;
1575      }
1576      raw_printf(out, "%s", zCR);
1577    }
1578    raw_printf(out, "'");
1579    if( nCR ){
1580      raw_printf(out, ",'%s',char(13))", zCR);
1581    }
1582    if( nNL ){
1583      raw_printf(out, ",'%s',char(10))", zNL);
1584    }
1585  }
1586  setTextMode(out, 1);
1587}
1588
1589/*
1590** Output the given string as a quoted according to C or TCL quoting rules.
1591*/
1592static void output_c_string(FILE *out, const char *z){
1593  unsigned int c;
1594  fputc('"', out);
1595  while( (c = *(z++))!=0 ){
1596    if( c=='\\' ){
1597      fputc(c, out);
1598      fputc(c, out);
1599    }else if( c=='"' ){
1600      fputc('\\', out);
1601      fputc('"', out);
1602    }else if( c=='\t' ){
1603      fputc('\\', out);
1604      fputc('t', out);
1605    }else if( c=='\n' ){
1606      fputc('\\', out);
1607      fputc('n', out);
1608    }else if( c=='\r' ){
1609      fputc('\\', out);
1610      fputc('r', out);
1611    }else if( !isprint(c&0xff) ){
1612      raw_printf(out, "\\%03o", c&0xff);
1613    }else{
1614      fputc(c, out);
1615    }
1616  }
1617  fputc('"', out);
1618}
1619
1620/*
1621** Output the given string as a quoted according to JSON quoting rules.
1622*/
1623static void output_json_string(FILE *out, const char *z, int n){
1624  unsigned int c;
1625  if( n<0 ) n = (int)strlen(z);
1626  fputc('"', out);
1627  while( n-- ){
1628    c = *(z++);
1629    if( c=='\\' || c=='"' ){
1630      fputc('\\', out);
1631      fputc(c, out);
1632    }else if( c<=0x1f ){
1633      fputc('\\', out);
1634      if( c=='\b' ){
1635        fputc('b', out);
1636      }else if( c=='\f' ){
1637        fputc('f', out);
1638      }else if( c=='\n' ){
1639        fputc('n', out);
1640      }else if( c=='\r' ){
1641        fputc('r', out);
1642      }else if( c=='\t' ){
1643        fputc('t', out);
1644      }else{
1645         raw_printf(out, "u%04x",c);
1646      }
1647    }else{
1648      fputc(c, out);
1649    }
1650  }
1651  fputc('"', out);
1652}
1653
1654/*
1655** Output the given string with characters that are special to
1656** HTML escaped.
1657*/
1658static void output_html_string(FILE *out, const char *z){
1659  int i;
1660  if( z==0 ) z = "";
1661  while( *z ){
1662    for(i=0;   z[i]
1663            && z[i]!='<'
1664            && z[i]!='&'
1665            && z[i]!='>'
1666            && z[i]!='\"'
1667            && z[i]!='\'';
1668        i++){}
1669    if( i>0 ){
1670      utf8_printf(out,"%.*s",i,z);
1671    }
1672    if( z[i]=='<' ){
1673      raw_printf(out,"&lt;");
1674    }else if( z[i]=='&' ){
1675      raw_printf(out,"&amp;");
1676    }else if( z[i]=='>' ){
1677      raw_printf(out,"&gt;");
1678    }else if( z[i]=='\"' ){
1679      raw_printf(out,"&quot;");
1680    }else if( z[i]=='\'' ){
1681      raw_printf(out,"&#39;");
1682    }else{
1683      break;
1684    }
1685    z += i + 1;
1686  }
1687}
1688
1689/*
1690** If a field contains any character identified by a 1 in the following
1691** array, then the string must be quoted for CSV.
1692*/
1693static const char needCsvQuote[] = {
1694  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1695  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1696  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1697  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1698  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1699  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1700  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1701  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1702  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1703  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1704  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1705  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1706  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1707  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1708  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1709  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1710};
1711
1712/*
1713** Output a single term of CSV.  Actually, p->colSeparator is used for
1714** the separator, which may or may not be a comma.  p->nullValue is
1715** the null value.  Strings are quoted if necessary.  The separator
1716** is only issued if bSep is true.
1717*/
1718static void output_csv(ShellState *p, const char *z, int bSep){
1719  FILE *out = p->out;
1720  if( z==0 ){
1721    utf8_printf(out,"%s",p->nullValue);
1722  }else{
1723    int i;
1724    int nSep = strlen30(p->colSeparator);
1725    for(i=0; z[i]; i++){
1726      if( needCsvQuote[((unsigned char*)z)[i]]
1727         || (z[i]==p->colSeparator[0] &&
1728             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1729        i = 0;
1730        break;
1731      }
1732    }
1733    if( i==0 ){
1734      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1735      utf8_printf(out, "%s", zQuoted);
1736      sqlite3_free(zQuoted);
1737    }else{
1738      utf8_printf(out, "%s", z);
1739    }
1740  }
1741  if( bSep ){
1742    utf8_printf(p->out, "%s", p->colSeparator);
1743  }
1744}
1745
1746/*
1747** This routine runs when the user presses Ctrl-C
1748*/
1749static void interrupt_handler(int NotUsed){
1750  UNUSED_PARAMETER(NotUsed);
1751  seenInterrupt++;
1752  if( seenInterrupt>2 ) exit(1);
1753  if( globalDb ) sqlite3_interrupt(globalDb);
1754}
1755
1756#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1757/*
1758** This routine runs for console events (e.g. Ctrl-C) on Win32
1759*/
1760static BOOL WINAPI ConsoleCtrlHandler(
1761  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1762){
1763  if( dwCtrlType==CTRL_C_EVENT ){
1764    interrupt_handler(0);
1765    return TRUE;
1766  }
1767  return FALSE;
1768}
1769#endif
1770
1771#ifndef SQLITE_OMIT_AUTHORIZATION
1772/*
1773** When the ".auth ON" is set, the following authorizer callback is
1774** invoked.  It always returns SQLITE_OK.
1775*/
1776static int shellAuth(
1777  void *pClientData,
1778  int op,
1779  const char *zA1,
1780  const char *zA2,
1781  const char *zA3,
1782  const char *zA4
1783){
1784  ShellState *p = (ShellState*)pClientData;
1785  static const char *azAction[] = { 0,
1786     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1787     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1788     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1789     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1790     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1791     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1792     "PRAGMA",               "READ",                 "SELECT",
1793     "TRANSACTION",          "UPDATE",               "ATTACH",
1794     "DETACH",               "ALTER_TABLE",          "REINDEX",
1795     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1796     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1797  };
1798  int i;
1799  const char *az[4];
1800  az[0] = zA1;
1801  az[1] = zA2;
1802  az[2] = zA3;
1803  az[3] = zA4;
1804  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1805  for(i=0; i<4; i++){
1806    raw_printf(p->out, " ");
1807    if( az[i] ){
1808      output_c_string(p->out, az[i]);
1809    }else{
1810      raw_printf(p->out, "NULL");
1811    }
1812  }
1813  raw_printf(p->out, "\n");
1814  return SQLITE_OK;
1815}
1816#endif
1817
1818/*
1819** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1820**
1821** This routine converts some CREATE TABLE statements for shadow tables
1822** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1823*/
1824static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1825  if( z==0 ) return;
1826  if( zTail==0 ) return;
1827  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1828    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1829  }else{
1830    utf8_printf(out, "%s%s", z, zTail);
1831  }
1832}
1833static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1834  char c = z[n];
1835  z[n] = 0;
1836  printSchemaLine(out, z, zTail);
1837  z[n] = c;
1838}
1839
1840/*
1841** Return true if string z[] has nothing but whitespace and comments to the
1842** end of the first line.
1843*/
1844static int wsToEol(const char *z){
1845  int i;
1846  for(i=0; z[i]; i++){
1847    if( z[i]=='\n' ) return 1;
1848    if( IsSpace(z[i]) ) continue;
1849    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1850    return 0;
1851  }
1852  return 1;
1853}
1854
1855/*
1856** Add a new entry to the EXPLAIN QUERY PLAN data
1857*/
1858static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1859  EQPGraphRow *pNew;
1860  int nText = strlen30(zText);
1861  if( p->autoEQPtest ){
1862    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1863  }
1864  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1865  if( pNew==0 ) shell_out_of_memory();
1866  pNew->iEqpId = iEqpId;
1867  pNew->iParentId = p2;
1868  memcpy(pNew->zText, zText, nText+1);
1869  pNew->pNext = 0;
1870  if( p->sGraph.pLast ){
1871    p->sGraph.pLast->pNext = pNew;
1872  }else{
1873    p->sGraph.pRow = pNew;
1874  }
1875  p->sGraph.pLast = pNew;
1876}
1877
1878/*
1879** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1880** in p->sGraph.
1881*/
1882static void eqp_reset(ShellState *p){
1883  EQPGraphRow *pRow, *pNext;
1884  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1885    pNext = pRow->pNext;
1886    sqlite3_free(pRow);
1887  }
1888  memset(&p->sGraph, 0, sizeof(p->sGraph));
1889}
1890
1891/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1892** pOld, or return the first such line if pOld is NULL
1893*/
1894static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1895  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1896  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1897  return pRow;
1898}
1899
1900/* Render a single level of the graph that has iEqpId as its parent.  Called
1901** recursively to render sublevels.
1902*/
1903static void eqp_render_level(ShellState *p, int iEqpId){
1904  EQPGraphRow *pRow, *pNext;
1905  int n = strlen30(p->sGraph.zPrefix);
1906  char *z;
1907  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1908    pNext = eqp_next_row(p, iEqpId, pRow);
1909    z = pRow->zText;
1910    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1911                pNext ? "|--" : "`--", z);
1912    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
1913      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
1914      eqp_render_level(p, pRow->iEqpId);
1915      p->sGraph.zPrefix[n] = 0;
1916    }
1917  }
1918}
1919
1920/*
1921** Display and reset the EXPLAIN QUERY PLAN data
1922*/
1923static void eqp_render(ShellState *p){
1924  EQPGraphRow *pRow = p->sGraph.pRow;
1925  if( pRow ){
1926    if( pRow->zText[0]=='-' ){
1927      if( pRow->pNext==0 ){
1928        eqp_reset(p);
1929        return;
1930      }
1931      utf8_printf(p->out, "%s\n", pRow->zText+3);
1932      p->sGraph.pRow = pRow->pNext;
1933      sqlite3_free(pRow);
1934    }else{
1935      utf8_printf(p->out, "QUERY PLAN\n");
1936    }
1937    p->sGraph.zPrefix[0] = 0;
1938    eqp_render_level(p, 0);
1939    eqp_reset(p);
1940  }
1941}
1942
1943#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1944/*
1945** Progress handler callback.
1946*/
1947static int progress_handler(void *pClientData) {
1948  ShellState *p = (ShellState*)pClientData;
1949  p->nProgress++;
1950  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1951    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
1952    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1953    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
1954    return 1;
1955  }
1956  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
1957    raw_printf(p->out, "Progress %u\n", p->nProgress);
1958  }
1959  return 0;
1960}
1961#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
1962
1963/*
1964** Print N dashes
1965*/
1966static void print_dashes(FILE *out, int N){
1967  const char zDash[] = "--------------------------------------------------";
1968  const int nDash = sizeof(zDash) - 1;
1969  while( N>nDash ){
1970    fputs(zDash, out);
1971    N -= nDash;
1972  }
1973  raw_printf(out, "%.*s", N, zDash);
1974}
1975
1976/*
1977** Print a markdown or table-style row separator using ascii-art
1978*/
1979static void print_row_separator(
1980  ShellState *p,
1981  int nArg,
1982  const char *zSep
1983){
1984  int i;
1985  if( nArg>0 ){
1986    fputs(zSep, p->out);
1987    print_dashes(p->out, p->actualWidth[0]+2);
1988    for(i=1; i<nArg; i++){
1989      fputs(zSep, p->out);
1990      print_dashes(p->out, p->actualWidth[i]+2);
1991    }
1992    fputs(zSep, p->out);
1993  }
1994  fputs("\n", p->out);
1995}
1996
1997/*
1998** This is the callback routine that the shell
1999** invokes for each row of a query result.
2000*/
2001static int shell_callback(
2002  void *pArg,
2003  int nArg,        /* Number of result columns */
2004  char **azArg,    /* Text of each result column */
2005  char **azCol,    /* Column names */
2006  int *aiType      /* Column types.  Might be NULL */
2007){
2008  int i;
2009  ShellState *p = (ShellState*)pArg;
2010
2011  if( azArg==0 ) return 0;
2012  switch( p->cMode ){
2013    case MODE_Line: {
2014      int w = 5;
2015      if( azArg==0 ) break;
2016      for(i=0; i<nArg; i++){
2017        int len = strlen30(azCol[i] ? azCol[i] : "");
2018        if( len>w ) w = len;
2019      }
2020      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2021      for(i=0; i<nArg; i++){
2022        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2023                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2024      }
2025      break;
2026    }
2027    case MODE_Explain: {
2028      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2029      if( nArg>ArraySize(aExplainWidth) ){
2030        nArg = ArraySize(aExplainWidth);
2031      }
2032      if( p->cnt++==0 ){
2033        for(i=0; i<nArg; i++){
2034          int w = aExplainWidth[i];
2035          utf8_width_print(p->out, w, azCol[i]);
2036          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2037        }
2038        for(i=0; i<nArg; i++){
2039          int w = aExplainWidth[i];
2040          print_dashes(p->out, w);
2041          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2042        }
2043      }
2044      if( azArg==0 ) break;
2045      for(i=0; i<nArg; i++){
2046        int w = aExplainWidth[i];
2047        if( i==nArg-1 ) w = 0;
2048        if( azArg[i] && strlenChar(azArg[i])>w ){
2049          w = strlenChar(azArg[i]);
2050        }
2051        if( i==1 && p->aiIndent && p->pStmt ){
2052          if( p->iIndent<p->nIndent ){
2053            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2054          }
2055          p->iIndent++;
2056        }
2057        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2058        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2059      }
2060      break;
2061    }
2062    case MODE_Semi: {   /* .schema and .fullschema output */
2063      printSchemaLine(p->out, azArg[0], ";\n");
2064      break;
2065    }
2066    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2067      char *z;
2068      int j;
2069      int nParen = 0;
2070      char cEnd = 0;
2071      char c;
2072      int nLine = 0;
2073      assert( nArg==1 );
2074      if( azArg[0]==0 ) break;
2075      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2076       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2077      ){
2078        utf8_printf(p->out, "%s;\n", azArg[0]);
2079        break;
2080      }
2081      z = sqlite3_mprintf("%s", azArg[0]);
2082      j = 0;
2083      for(i=0; IsSpace(z[i]); i++){}
2084      for(; (c = z[i])!=0; i++){
2085        if( IsSpace(c) ){
2086          if( z[j-1]=='\r' ) z[j-1] = '\n';
2087          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2088        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2089          j--;
2090        }
2091        z[j++] = c;
2092      }
2093      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2094      z[j] = 0;
2095      if( strlen30(z)>=79 ){
2096        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2097          if( c==cEnd ){
2098            cEnd = 0;
2099          }else if( c=='"' || c=='\'' || c=='`' ){
2100            cEnd = c;
2101          }else if( c=='[' ){
2102            cEnd = ']';
2103          }else if( c=='-' && z[i+1]=='-' ){
2104            cEnd = '\n';
2105          }else if( c=='(' ){
2106            nParen++;
2107          }else if( c==')' ){
2108            nParen--;
2109            if( nLine>0 && nParen==0 && j>0 ){
2110              printSchemaLineN(p->out, z, j, "\n");
2111              j = 0;
2112            }
2113          }
2114          z[j++] = c;
2115          if( nParen==1 && cEnd==0
2116           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2117          ){
2118            if( c=='\n' ) j--;
2119            printSchemaLineN(p->out, z, j, "\n  ");
2120            j = 0;
2121            nLine++;
2122            while( IsSpace(z[i+1]) ){ i++; }
2123          }
2124        }
2125        z[j] = 0;
2126      }
2127      printSchemaLine(p->out, z, ";\n");
2128      sqlite3_free(z);
2129      break;
2130    }
2131    case MODE_List: {
2132      if( p->cnt++==0 && p->showHeader ){
2133        for(i=0; i<nArg; i++){
2134          utf8_printf(p->out,"%s%s",azCol[i],
2135                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2136        }
2137      }
2138      if( azArg==0 ) break;
2139      for(i=0; i<nArg; i++){
2140        char *z = azArg[i];
2141        if( z==0 ) z = p->nullValue;
2142        utf8_printf(p->out, "%s", z);
2143        if( i<nArg-1 ){
2144          utf8_printf(p->out, "%s", p->colSeparator);
2145        }else{
2146          utf8_printf(p->out, "%s", p->rowSeparator);
2147        }
2148      }
2149      break;
2150    }
2151    case MODE_Html: {
2152      if( p->cnt++==0 && p->showHeader ){
2153        raw_printf(p->out,"<TR>");
2154        for(i=0; i<nArg; i++){
2155          raw_printf(p->out,"<TH>");
2156          output_html_string(p->out, azCol[i]);
2157          raw_printf(p->out,"</TH>\n");
2158        }
2159        raw_printf(p->out,"</TR>\n");
2160      }
2161      if( azArg==0 ) break;
2162      raw_printf(p->out,"<TR>");
2163      for(i=0; i<nArg; i++){
2164        raw_printf(p->out,"<TD>");
2165        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2166        raw_printf(p->out,"</TD>\n");
2167      }
2168      raw_printf(p->out,"</TR>\n");
2169      break;
2170    }
2171    case MODE_Tcl: {
2172      if( p->cnt++==0 && p->showHeader ){
2173        for(i=0; i<nArg; i++){
2174          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2175          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2176        }
2177        utf8_printf(p->out, "%s", p->rowSeparator);
2178      }
2179      if( azArg==0 ) break;
2180      for(i=0; i<nArg; i++){
2181        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2182        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2183      }
2184      utf8_printf(p->out, "%s", p->rowSeparator);
2185      break;
2186    }
2187    case MODE_Csv: {
2188      setBinaryMode(p->out, 1);
2189      if( p->cnt++==0 && p->showHeader ){
2190        for(i=0; i<nArg; i++){
2191          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2192        }
2193        utf8_printf(p->out, "%s", p->rowSeparator);
2194      }
2195      if( nArg>0 ){
2196        for(i=0; i<nArg; i++){
2197          output_csv(p, azArg[i], i<nArg-1);
2198        }
2199        utf8_printf(p->out, "%s", p->rowSeparator);
2200      }
2201      setTextMode(p->out, 1);
2202      break;
2203    }
2204    case MODE_Insert: {
2205      if( azArg==0 ) break;
2206      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2207      if( p->showHeader ){
2208        raw_printf(p->out,"(");
2209        for(i=0; i<nArg; i++){
2210          if( i>0 ) raw_printf(p->out, ",");
2211          if( quoteChar(azCol[i]) ){
2212            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2213            utf8_printf(p->out, "%s", z);
2214            sqlite3_free(z);
2215          }else{
2216            raw_printf(p->out, "%s", azCol[i]);
2217          }
2218        }
2219        raw_printf(p->out,")");
2220      }
2221      p->cnt++;
2222      for(i=0; i<nArg; i++){
2223        raw_printf(p->out, i>0 ? "," : " VALUES(");
2224        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2225          utf8_printf(p->out,"NULL");
2226        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2227          if( ShellHasFlag(p, SHFLG_Newlines) ){
2228            output_quoted_string(p->out, azArg[i]);
2229          }else{
2230            output_quoted_escaped_string(p->out, azArg[i]);
2231          }
2232        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2233          utf8_printf(p->out,"%s", azArg[i]);
2234        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2235          char z[50];
2236          double r = sqlite3_column_double(p->pStmt, i);
2237          sqlite3_uint64 ur;
2238          memcpy(&ur,&r,sizeof(r));
2239          if( ur==0x7ff0000000000000LL ){
2240            raw_printf(p->out, "1e999");
2241          }else if( ur==0xfff0000000000000LL ){
2242            raw_printf(p->out, "-1e999");
2243          }else{
2244            sqlite3_snprintf(50,z,"%!.20g", r);
2245            raw_printf(p->out, "%s", z);
2246          }
2247        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2248          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2249          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2250          output_hex_blob(p->out, pBlob, nBlob);
2251        }else if( isNumber(azArg[i], 0) ){
2252          utf8_printf(p->out,"%s", azArg[i]);
2253        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2254          output_quoted_string(p->out, azArg[i]);
2255        }else{
2256          output_quoted_escaped_string(p->out, azArg[i]);
2257        }
2258      }
2259      raw_printf(p->out,");\n");
2260      break;
2261    }
2262    case MODE_Json: {
2263      if( azArg==0 ) break;
2264      if( p->cnt==0 ){
2265        fputs("[{", p->out);
2266      }else{
2267        fputs(",\n{", p->out);
2268      }
2269      p->cnt++;
2270      for(i=0; i<nArg; i++){
2271        output_json_string(p->out, azCol[i], -1);
2272        putc(':', p->out);
2273        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2274          fputs("null",p->out);
2275        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2276          char z[50];
2277          double r = sqlite3_column_double(p->pStmt, i);
2278          sqlite3_uint64 ur;
2279          memcpy(&ur,&r,sizeof(r));
2280          if( ur==0x7ff0000000000000LL ){
2281            raw_printf(p->out, "1e999");
2282          }else if( ur==0xfff0000000000000LL ){
2283            raw_printf(p->out, "-1e999");
2284          }else{
2285            sqlite3_snprintf(50,z,"%!.20g", r);
2286            raw_printf(p->out, "%s", z);
2287          }
2288        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2289          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2290          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2291          output_json_string(p->out, pBlob, nBlob);
2292        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2293          output_json_string(p->out, azArg[i], -1);
2294        }else{
2295          utf8_printf(p->out,"%s", azArg[i]);
2296        }
2297        if( i<nArg-1 ){
2298          putc(',', p->out);
2299        }
2300      }
2301      putc('}', p->out);
2302      break;
2303    }
2304    case MODE_Quote: {
2305      if( azArg==0 ) break;
2306      if( p->cnt==0 && p->showHeader ){
2307        for(i=0; i<nArg; i++){
2308          if( i>0 ) fputs(p->colSeparator, p->out);
2309          output_quoted_string(p->out, azCol[i]);
2310        }
2311        fputs(p->rowSeparator, p->out);
2312      }
2313      p->cnt++;
2314      for(i=0; i<nArg; i++){
2315        if( i>0 ) fputs(p->colSeparator, p->out);
2316        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2317          utf8_printf(p->out,"NULL");
2318        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2319          output_quoted_string(p->out, azArg[i]);
2320        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2321          utf8_printf(p->out,"%s", azArg[i]);
2322        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2323          char z[50];
2324          double r = sqlite3_column_double(p->pStmt, i);
2325          sqlite3_snprintf(50,z,"%!.20g", r);
2326          raw_printf(p->out, "%s", z);
2327        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2328          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2329          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2330          output_hex_blob(p->out, pBlob, nBlob);
2331        }else if( isNumber(azArg[i], 0) ){
2332          utf8_printf(p->out,"%s", azArg[i]);
2333        }else{
2334          output_quoted_string(p->out, azArg[i]);
2335        }
2336      }
2337      fputs(p->rowSeparator, p->out);
2338      break;
2339    }
2340    case MODE_Ascii: {
2341      if( p->cnt++==0 && p->showHeader ){
2342        for(i=0; i<nArg; i++){
2343          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2344          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2345        }
2346        utf8_printf(p->out, "%s", p->rowSeparator);
2347      }
2348      if( azArg==0 ) break;
2349      for(i=0; i<nArg; i++){
2350        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2351        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2352      }
2353      utf8_printf(p->out, "%s", p->rowSeparator);
2354      break;
2355    }
2356    case MODE_EQP: {
2357      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2358      break;
2359    }
2360  }
2361  return 0;
2362}
2363
2364/*
2365** This is the callback routine that the SQLite library
2366** invokes for each row of a query result.
2367*/
2368static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2369  /* since we don't have type info, call the shell_callback with a NULL value */
2370  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2371}
2372
2373/*
2374** This is the callback routine from sqlite3_exec() that appends all
2375** output onto the end of a ShellText object.
2376*/
2377static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2378  ShellText *p = (ShellText*)pArg;
2379  int i;
2380  UNUSED_PARAMETER(az);
2381  if( azArg==0 ) return 0;
2382  if( p->n ) appendText(p, "|", 0);
2383  for(i=0; i<nArg; i++){
2384    if( i ) appendText(p, ",", 0);
2385    if( azArg[i] ) appendText(p, azArg[i], 0);
2386  }
2387  return 0;
2388}
2389
2390/*
2391** Generate an appropriate SELFTEST table in the main database.
2392*/
2393static void createSelftestTable(ShellState *p){
2394  char *zErrMsg = 0;
2395  sqlite3_exec(p->db,
2396    "SAVEPOINT selftest_init;\n"
2397    "CREATE TABLE IF NOT EXISTS selftest(\n"
2398    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2399    "  op TEXT,\n"                   /* Operator:  memo run */
2400    "  cmd TEXT,\n"                  /* Command text */
2401    "  ans TEXT\n"                   /* Desired answer */
2402    ");"
2403    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2404    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2405    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2406    "         'memo','Tests generated by --init');\n"
2407    "INSERT INTO [_shell$self]\n"
2408    "  SELECT 'run',\n"
2409    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2410                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2411    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2412                          "FROM sqlite_schema ORDER BY 2',224));\n"
2413    "INSERT INTO [_shell$self]\n"
2414    "  SELECT 'run',"
2415    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2416    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2417    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2418    "  FROM (\n"
2419    "    SELECT name FROM sqlite_schema\n"
2420    "     WHERE type='table'\n"
2421    "       AND name<>'selftest'\n"
2422    "       AND coalesce(rootpage,0)>0\n"
2423    "  )\n"
2424    " ORDER BY name;\n"
2425    "INSERT INTO [_shell$self]\n"
2426    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2427    "INSERT INTO selftest(tno,op,cmd,ans)"
2428    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2429    "DROP TABLE [_shell$self];"
2430    ,0,0,&zErrMsg);
2431  if( zErrMsg ){
2432    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2433    sqlite3_free(zErrMsg);
2434  }
2435  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2436}
2437
2438
2439/*
2440** Set the destination table field of the ShellState structure to
2441** the name of the table given.  Escape any quote characters in the
2442** table name.
2443*/
2444static void set_table_name(ShellState *p, const char *zName){
2445  int i, n;
2446  char cQuote;
2447  char *z;
2448
2449  if( p->zDestTable ){
2450    free(p->zDestTable);
2451    p->zDestTable = 0;
2452  }
2453  if( zName==0 ) return;
2454  cQuote = quoteChar(zName);
2455  n = strlen30(zName);
2456  if( cQuote ) n += n+2;
2457  z = p->zDestTable = malloc( n+1 );
2458  if( z==0 ) shell_out_of_memory();
2459  n = 0;
2460  if( cQuote ) z[n++] = cQuote;
2461  for(i=0; zName[i]; i++){
2462    z[n++] = zName[i];
2463    if( zName[i]==cQuote ) z[n++] = cQuote;
2464  }
2465  if( cQuote ) z[n++] = cQuote;
2466  z[n] = 0;
2467}
2468
2469
2470/*
2471** Execute a query statement that will generate SQL output.  Print
2472** the result columns, comma-separated, on a line and then add a
2473** semicolon terminator to the end of that line.
2474**
2475** If the number of columns is 1 and that column contains text "--"
2476** then write the semicolon on a separate line.  That way, if a
2477** "--" comment occurs at the end of the statement, the comment
2478** won't consume the semicolon terminator.
2479*/
2480static int run_table_dump_query(
2481  ShellState *p,           /* Query context */
2482  const char *zSelect      /* SELECT statement to extract content */
2483){
2484  sqlite3_stmt *pSelect;
2485  int rc;
2486  int nResult;
2487  int i;
2488  const char *z;
2489  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2490  if( rc!=SQLITE_OK || !pSelect ){
2491    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2492                sqlite3_errmsg(p->db));
2493    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2494    return rc;
2495  }
2496  rc = sqlite3_step(pSelect);
2497  nResult = sqlite3_column_count(pSelect);
2498  while( rc==SQLITE_ROW ){
2499    z = (const char*)sqlite3_column_text(pSelect, 0);
2500    utf8_printf(p->out, "%s", z);
2501    for(i=1; i<nResult; i++){
2502      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2503    }
2504    if( z==0 ) z = "";
2505    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2506    if( z[0] ){
2507      raw_printf(p->out, "\n;\n");
2508    }else{
2509      raw_printf(p->out, ";\n");
2510    }
2511    rc = sqlite3_step(pSelect);
2512  }
2513  rc = sqlite3_finalize(pSelect);
2514  if( rc!=SQLITE_OK ){
2515    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2516                sqlite3_errmsg(p->db));
2517    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2518  }
2519  return rc;
2520}
2521
2522/*
2523** Allocate space and save off current error string.
2524*/
2525static char *save_err_msg(
2526  sqlite3 *db            /* Database to query */
2527){
2528  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2529  char *zErrMsg = sqlite3_malloc64(nErrMsg);
2530  if( zErrMsg ){
2531    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2532  }
2533  return zErrMsg;
2534}
2535
2536#ifdef __linux__
2537/*
2538** Attempt to display I/O stats on Linux using /proc/PID/io
2539*/
2540static void displayLinuxIoStats(FILE *out){
2541  FILE *in;
2542  char z[200];
2543  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2544  in = fopen(z, "rb");
2545  if( in==0 ) return;
2546  while( fgets(z, sizeof(z), in)!=0 ){
2547    static const struct {
2548      const char *zPattern;
2549      const char *zDesc;
2550    } aTrans[] = {
2551      { "rchar: ",                  "Bytes received by read():" },
2552      { "wchar: ",                  "Bytes sent to write():"    },
2553      { "syscr: ",                  "Read() system calls:"      },
2554      { "syscw: ",                  "Write() system calls:"     },
2555      { "read_bytes: ",             "Bytes read from storage:"  },
2556      { "write_bytes: ",            "Bytes written to storage:" },
2557      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2558    };
2559    int i;
2560    for(i=0; i<ArraySize(aTrans); i++){
2561      int n = strlen30(aTrans[i].zPattern);
2562      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2563        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2564        break;
2565      }
2566    }
2567  }
2568  fclose(in);
2569}
2570#endif
2571
2572/*
2573** Display a single line of status using 64-bit values.
2574*/
2575static void displayStatLine(
2576  ShellState *p,            /* The shell context */
2577  char *zLabel,             /* Label for this one line */
2578  char *zFormat,            /* Format for the result */
2579  int iStatusCtrl,          /* Which status to display */
2580  int bReset                /* True to reset the stats */
2581){
2582  sqlite3_int64 iCur = -1;
2583  sqlite3_int64 iHiwtr = -1;
2584  int i, nPercent;
2585  char zLine[200];
2586  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2587  for(i=0, nPercent=0; zFormat[i]; i++){
2588    if( zFormat[i]=='%' ) nPercent++;
2589  }
2590  if( nPercent>1 ){
2591    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2592  }else{
2593    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2594  }
2595  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2596}
2597
2598/*
2599** Display memory stats.
2600*/
2601static int display_stats(
2602  sqlite3 *db,                /* Database to query */
2603  ShellState *pArg,           /* Pointer to ShellState */
2604  int bReset                  /* True to reset the stats */
2605){
2606  int iCur;
2607  int iHiwtr;
2608  FILE *out;
2609  if( pArg==0 || pArg->out==0 ) return 0;
2610  out = pArg->out;
2611
2612  if( pArg->pStmt && pArg->statsOn==2 ){
2613    int nCol, i, x;
2614    sqlite3_stmt *pStmt = pArg->pStmt;
2615    char z[100];
2616    nCol = sqlite3_column_count(pStmt);
2617    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2618    for(i=0; i<nCol; i++){
2619      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2620      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2621#ifndef SQLITE_OMIT_DECLTYPE
2622      sqlite3_snprintf(30, z+x, "declared type:");
2623      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2624#endif
2625#ifdef SQLITE_ENABLE_COLUMN_METADATA
2626      sqlite3_snprintf(30, z+x, "database name:");
2627      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2628      sqlite3_snprintf(30, z+x, "table name:");
2629      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2630      sqlite3_snprintf(30, z+x, "origin name:");
2631      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2632#endif
2633    }
2634  }
2635
2636  if( pArg->statsOn==3 ){
2637    if( pArg->pStmt ){
2638      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2639      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2640    }
2641    return 0;
2642  }
2643
2644  displayStatLine(pArg, "Memory Used:",
2645     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2646  displayStatLine(pArg, "Number of Outstanding Allocations:",
2647     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2648  if( pArg->shellFlgs & SHFLG_Pagecache ){
2649    displayStatLine(pArg, "Number of Pcache Pages Used:",
2650       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2651  }
2652  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2653     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2654  displayStatLine(pArg, "Largest Allocation:",
2655     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2656  displayStatLine(pArg, "Largest Pcache Allocation:",
2657     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2658#ifdef YYTRACKMAXSTACKDEPTH
2659  displayStatLine(pArg, "Deepest Parser Stack:",
2660     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2661#endif
2662
2663  if( db ){
2664    if( pArg->shellFlgs & SHFLG_Lookaside ){
2665      iHiwtr = iCur = -1;
2666      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2667                        &iCur, &iHiwtr, bReset);
2668      raw_printf(pArg->out,
2669              "Lookaside Slots Used:                %d (max %d)\n",
2670              iCur, iHiwtr);
2671      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2672                        &iCur, &iHiwtr, bReset);
2673      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2674              iHiwtr);
2675      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2676                        &iCur, &iHiwtr, bReset);
2677      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2678              iHiwtr);
2679      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2680                        &iCur, &iHiwtr, bReset);
2681      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2682              iHiwtr);
2683    }
2684    iHiwtr = iCur = -1;
2685    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2686    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2687            iCur);
2688    iHiwtr = iCur = -1;
2689    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2690    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2691    iHiwtr = iCur = -1;
2692    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2693    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2694    iHiwtr = iCur = -1;
2695    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2696    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2697    iHiwtr = iCur = -1;
2698    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2699    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2700    iHiwtr = iCur = -1;
2701    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2702    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2703            iCur);
2704    iHiwtr = iCur = -1;
2705    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2706    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2707            iCur);
2708  }
2709
2710  if( pArg->pStmt ){
2711    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2712                               bReset);
2713    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2714    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2715    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2716    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2717    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2718    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2719    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2720    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2721    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2722    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2723    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2724    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2725    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2726  }
2727
2728#ifdef __linux__
2729  displayLinuxIoStats(pArg->out);
2730#endif
2731
2732  /* Do not remove this machine readable comment: extra-stats-output-here */
2733
2734  return 0;
2735}
2736
2737/*
2738** Display scan stats.
2739*/
2740static void display_scanstats(
2741  sqlite3 *db,                    /* Database to query */
2742  ShellState *pArg                /* Pointer to ShellState */
2743){
2744#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2745  UNUSED_PARAMETER(db);
2746  UNUSED_PARAMETER(pArg);
2747#else
2748  int i, k, n, mx;
2749  raw_printf(pArg->out, "-------- scanstats --------\n");
2750  mx = 0;
2751  for(k=0; k<=mx; k++){
2752    double rEstLoop = 1.0;
2753    for(i=n=0; 1; i++){
2754      sqlite3_stmt *p = pArg->pStmt;
2755      sqlite3_int64 nLoop, nVisit;
2756      double rEst;
2757      int iSid;
2758      const char *zExplain;
2759      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2760        break;
2761      }
2762      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2763      if( iSid>mx ) mx = iSid;
2764      if( iSid!=k ) continue;
2765      if( n==0 ){
2766        rEstLoop = (double)nLoop;
2767        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2768      }
2769      n++;
2770      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2771      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2772      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2773      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2774      rEstLoop *= rEst;
2775      raw_printf(pArg->out,
2776          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2777          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2778      );
2779    }
2780  }
2781  raw_printf(pArg->out, "---------------------------\n");
2782#endif
2783}
2784
2785/*
2786** Parameter azArray points to a zero-terminated array of strings. zStr
2787** points to a single nul-terminated string. Return non-zero if zStr
2788** is equal, according to strcmp(), to any of the strings in the array.
2789** Otherwise, return zero.
2790*/
2791static int str_in_array(const char *zStr, const char **azArray){
2792  int i;
2793  for(i=0; azArray[i]; i++){
2794    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2795  }
2796  return 0;
2797}
2798
2799/*
2800** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2801** and populate the ShellState.aiIndent[] array with the number of
2802** spaces each opcode should be indented before it is output.
2803**
2804** The indenting rules are:
2805**
2806**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2807**       all opcodes that occur between the p2 jump destination and the opcode
2808**       itself by 2 spaces.
2809**
2810**     * For each "Goto", if the jump destination is earlier in the program
2811**       and ends on one of:
2812**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2813**       or if the P1 parameter is one instead of zero,
2814**       then indent all opcodes between the earlier instruction
2815**       and "Goto" by 2 spaces.
2816*/
2817static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2818  const char *zSql;               /* The text of the SQL statement */
2819  const char *z;                  /* Used to check if this is an EXPLAIN */
2820  int *abYield = 0;               /* True if op is an OP_Yield */
2821  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2822  int iOp;                        /* Index of operation in p->aiIndent[] */
2823
2824  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2825  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2826                            "Rewind", 0 };
2827  const char *azGoto[] = { "Goto", 0 };
2828
2829  /* Try to figure out if this is really an EXPLAIN statement. If this
2830  ** cannot be verified, return early.  */
2831  if( sqlite3_column_count(pSql)!=8 ){
2832    p->cMode = p->mode;
2833    return;
2834  }
2835  zSql = sqlite3_sql(pSql);
2836  if( zSql==0 ) return;
2837  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2838  if( sqlite3_strnicmp(z, "explain", 7) ){
2839    p->cMode = p->mode;
2840    return;
2841  }
2842
2843  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2844    int i;
2845    int iAddr = sqlite3_column_int(pSql, 0);
2846    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2847
2848    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2849    ** p2 is an instruction address, set variable p2op to the index of that
2850    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2851    ** the current instruction is part of a sub-program generated by an
2852    ** SQL trigger or foreign key.  */
2853    int p2 = sqlite3_column_int(pSql, 3);
2854    int p2op = (p2 + (iOp-iAddr));
2855
2856    /* Grow the p->aiIndent array as required */
2857    if( iOp>=nAlloc ){
2858      if( iOp==0 ){
2859        /* Do further verfication that this is explain output.  Abort if
2860        ** it is not */
2861        static const char *explainCols[] = {
2862           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2863        int jj;
2864        for(jj=0; jj<ArraySize(explainCols); jj++){
2865          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2866            p->cMode = p->mode;
2867            sqlite3_reset(pSql);
2868            return;
2869          }
2870        }
2871      }
2872      nAlloc += 100;
2873      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2874      if( p->aiIndent==0 ) shell_out_of_memory();
2875      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2876      if( abYield==0 ) shell_out_of_memory();
2877    }
2878    abYield[iOp] = str_in_array(zOp, azYield);
2879    p->aiIndent[iOp] = 0;
2880    p->nIndent = iOp+1;
2881
2882    if( str_in_array(zOp, azNext) ){
2883      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2884    }
2885    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2886     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2887    ){
2888      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2889    }
2890  }
2891
2892  p->iIndent = 0;
2893  sqlite3_free(abYield);
2894  sqlite3_reset(pSql);
2895}
2896
2897/*
2898** Free the array allocated by explain_data_prepare().
2899*/
2900static void explain_data_delete(ShellState *p){
2901  sqlite3_free(p->aiIndent);
2902  p->aiIndent = 0;
2903  p->nIndent = 0;
2904  p->iIndent = 0;
2905}
2906
2907/*
2908** Disable and restore .wheretrace and .selecttrace settings.
2909*/
2910static unsigned int savedSelectTrace;
2911static unsigned int savedWhereTrace;
2912static void disable_debug_trace_modes(void){
2913  unsigned int zero = 0;
2914  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
2915  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
2916  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
2917  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
2918}
2919static void restore_debug_trace_modes(void){
2920  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
2921  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
2922}
2923
2924/* Create the TEMP table used to store parameter bindings */
2925static void bind_table_init(ShellState *p){
2926  int wrSchema = 0;
2927  int defensiveMode = 0;
2928  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
2929  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
2930  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2931  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
2932  sqlite3_exec(p->db,
2933    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
2934    "  key TEXT PRIMARY KEY,\n"
2935    "  value\n"
2936    ") WITHOUT ROWID;",
2937    0, 0, 0);
2938  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
2939  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
2940}
2941
2942/*
2943** Bind parameters on a prepared statement.
2944**
2945** Parameter bindings are taken from a TEMP table of the form:
2946**
2947**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
2948**    WITHOUT ROWID;
2949**
2950** No bindings occur if this table does not exist.  The name of the table
2951** begins with "sqlite_" so that it will not collide with ordinary application
2952** tables.  The table must be in the TEMP schema.
2953*/
2954static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2955  int nVar;
2956  int i;
2957  int rc;
2958  sqlite3_stmt *pQ = 0;
2959
2960  nVar = sqlite3_bind_parameter_count(pStmt);
2961  if( nVar==0 ) return;  /* Nothing to do */
2962  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
2963                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2964    return; /* Parameter table does not exist */
2965  }
2966  rc = sqlite3_prepare_v2(pArg->db,
2967          "SELECT value FROM temp.sqlite_parameters"
2968          " WHERE key=?1", -1, &pQ, 0);
2969  if( rc || pQ==0 ) return;
2970  for(i=1; i<=nVar; i++){
2971    char zNum[30];
2972    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2973    if( zVar==0 ){
2974      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2975      zVar = zNum;
2976    }
2977    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2978    if( sqlite3_step(pQ)==SQLITE_ROW ){
2979      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2980    }else{
2981      sqlite3_bind_null(pStmt, i);
2982    }
2983    sqlite3_reset(pQ);
2984  }
2985  sqlite3_finalize(pQ);
2986}
2987
2988/*
2989** UTF8 box-drawing characters.  Imagine box lines like this:
2990**
2991**           1
2992**           |
2993**       4 --+-- 2
2994**           |
2995**           3
2996**
2997** Each box characters has between 2 and 4 of the lines leading from
2998** the center.  The characters are here identified by the numbers of
2999** their corresponding lines.
3000*/
3001#define BOX_24   "\342\224\200"  /* U+2500 --- */
3002#define BOX_13   "\342\224\202"  /* U+2502  |  */
3003#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3004#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3005#define BOX_12   "\342\224\224"  /* U+2514  '- */
3006#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3007#define BOX_123  "\342\224\234"  /* U+251c  |- */
3008#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3009#define BOX_234  "\342\224\254"  /* U+252c -,- */
3010#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3011#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3012
3013/* Draw horizontal line N characters long using unicode box
3014** characters
3015*/
3016static void print_box_line(FILE *out, int N){
3017  const char zDash[] =
3018      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3019      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3020  const int nDash = sizeof(zDash) - 1;
3021  N *= 3;
3022  while( N>nDash ){
3023    utf8_printf(out, zDash);
3024    N -= nDash;
3025  }
3026  utf8_printf(out, "%.*s", N, zDash);
3027}
3028
3029/*
3030** Draw a horizontal separator for a MODE_Box table.
3031*/
3032static void print_box_row_separator(
3033  ShellState *p,
3034  int nArg,
3035  const char *zSep1,
3036  const char *zSep2,
3037  const char *zSep3
3038){
3039  int i;
3040  if( nArg>0 ){
3041    utf8_printf(p->out, "%s", zSep1);
3042    print_box_line(p->out, p->actualWidth[0]+2);
3043    for(i=1; i<nArg; i++){
3044      utf8_printf(p->out, "%s", zSep2);
3045      print_box_line(p->out, p->actualWidth[i]+2);
3046    }
3047    utf8_printf(p->out, "%s", zSep3);
3048  }
3049  fputs("\n", p->out);
3050}
3051
3052
3053
3054/*
3055** Run a prepared statement and output the result in one of the
3056** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3057** or MODE_Box.
3058**
3059** This is different from ordinary exec_prepared_stmt() in that
3060** it has to run the entire query and gather the results into memory
3061** first, in order to determine column widths, before providing
3062** any output.
3063*/
3064static void exec_prepared_stmt_columnar(
3065  ShellState *p,                        /* Pointer to ShellState */
3066  sqlite3_stmt *pStmt                   /* Statment to run */
3067){
3068  sqlite3_int64 nRow = 0;
3069  int nColumn = 0;
3070  char **azData = 0;
3071  sqlite3_int64 nAlloc = 0;
3072  const char *z;
3073  int rc;
3074  sqlite3_int64 i, nData;
3075  int j, nTotal, w, n;
3076  const char *colSep = 0;
3077  const char *rowSep = 0;
3078
3079  rc = sqlite3_step(pStmt);
3080  if( rc!=SQLITE_ROW ) return;
3081  nColumn = sqlite3_column_count(pStmt);
3082  nAlloc = nColumn*4;
3083  if( nAlloc<=0 ) nAlloc = 1;
3084  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3085  if( azData==0 ) shell_out_of_memory();
3086  for(i=0; i<nColumn; i++){
3087    azData[i] = strdup(sqlite3_column_name(pStmt,i));
3088  }
3089  do{
3090    if( (nRow+2)*nColumn >= nAlloc ){
3091      nAlloc *= 2;
3092      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3093      if( azData==0 ) shell_out_of_memory();
3094    }
3095    nRow++;
3096    for(i=0; i<nColumn; i++){
3097      z = (const char*)sqlite3_column_text(pStmt,i);
3098      azData[nRow*nColumn + i] = z ? strdup(z) : 0;
3099    }
3100  }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
3101  if( nColumn>p->nWidth ){
3102    p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
3103    if( p->colWidth==0 ) shell_out_of_memory();
3104    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3105    p->nWidth = nColumn;
3106    p->actualWidth = &p->colWidth[nColumn];
3107  }
3108  memset(p->actualWidth, 0, nColumn*sizeof(int));
3109  for(i=0; i<nColumn; i++){
3110    w = p->colWidth[i];
3111    if( w<0 ) w = -w;
3112    p->actualWidth[i] = w;
3113  }
3114  nTotal = nColumn*(nRow+1);
3115  for(i=0; i<nTotal; i++){
3116    z = azData[i];
3117    if( z==0 ) z = p->nullValue;
3118    n = strlenChar(z);
3119    j = i%nColumn;
3120    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3121  }
3122  if( seenInterrupt ) goto columnar_end;
3123  if( nColumn==0 ) goto columnar_end;
3124  switch( p->cMode ){
3125    case MODE_Column: {
3126      colSep = "  ";
3127      rowSep = "\n";
3128      if( p->showHeader ){
3129        for(i=0; i<nColumn; i++){
3130          w = p->actualWidth[i];
3131          if( p->colWidth[i]<0 ) w = -w;
3132          utf8_width_print(p->out, w, azData[i]);
3133          fputs(i==nColumn-1?"\n":"  ", p->out);
3134        }
3135        for(i=0; i<nColumn; i++){
3136          print_dashes(p->out, p->actualWidth[i]);
3137          fputs(i==nColumn-1?"\n":"  ", p->out);
3138        }
3139      }
3140      break;
3141    }
3142    case MODE_Table: {
3143      colSep = " | ";
3144      rowSep = " |\n";
3145      print_row_separator(p, nColumn, "+");
3146      fputs("| ", p->out);
3147      for(i=0; i<nColumn; i++){
3148        w = p->actualWidth[i];
3149        n = strlenChar(azData[i]);
3150        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3151        fputs(i==nColumn-1?" |\n":" | ", p->out);
3152      }
3153      print_row_separator(p, nColumn, "+");
3154      break;
3155    }
3156    case MODE_Markdown: {
3157      colSep = " | ";
3158      rowSep = " |\n";
3159      fputs("| ", p->out);
3160      for(i=0; i<nColumn; i++){
3161        w = p->actualWidth[i];
3162        n = strlenChar(azData[i]);
3163        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3164        fputs(i==nColumn-1?" |\n":" | ", p->out);
3165      }
3166      print_row_separator(p, nColumn, "|");
3167      break;
3168    }
3169    case MODE_Box: {
3170      colSep = " " BOX_13 " ";
3171      rowSep = " " BOX_13 "\n";
3172      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3173      utf8_printf(p->out, BOX_13 " ");
3174      for(i=0; i<nColumn; i++){
3175        w = p->actualWidth[i];
3176        n = strlenChar(azData[i]);
3177        utf8_printf(p->out, "%*s%s%*s%s",
3178            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3179            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3180      }
3181      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3182      break;
3183    }
3184  }
3185  for(i=nColumn, j=0; i<nTotal; i++, j++){
3186    if( j==0 && p->cMode!=MODE_Column ){
3187      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3188    }
3189    z = azData[i];
3190    if( z==0 ) z = p->nullValue;
3191    w = p->actualWidth[j];
3192    if( p->colWidth[j]<0 ) w = -w;
3193    utf8_width_print(p->out, w, z);
3194    if( j==nColumn-1 ){
3195      utf8_printf(p->out, "%s", rowSep);
3196      j = -1;
3197      if( seenInterrupt ) goto columnar_end;
3198    }else{
3199      utf8_printf(p->out, "%s", colSep);
3200    }
3201  }
3202  if( p->cMode==MODE_Table ){
3203    print_row_separator(p, nColumn, "+");
3204  }else if( p->cMode==MODE_Box ){
3205    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3206  }
3207columnar_end:
3208  if( seenInterrupt ){
3209    utf8_printf(p->out, "Interrupt\n");
3210  }
3211  nData = (nRow+1)*nColumn;
3212  for(i=0; i<nData; i++) free(azData[i]);
3213  sqlite3_free(azData);
3214}
3215
3216/*
3217** Run a prepared statement
3218*/
3219static void exec_prepared_stmt(
3220  ShellState *pArg,                                /* Pointer to ShellState */
3221  sqlite3_stmt *pStmt                              /* Statment to run */
3222){
3223  int rc;
3224
3225  if( pArg->cMode==MODE_Column
3226   || pArg->cMode==MODE_Table
3227   || pArg->cMode==MODE_Box
3228   || pArg->cMode==MODE_Markdown
3229  ){
3230    exec_prepared_stmt_columnar(pArg, pStmt);
3231    return;
3232  }
3233
3234  /* perform the first step.  this will tell us if we
3235  ** have a result set or not and how wide it is.
3236  */
3237  rc = sqlite3_step(pStmt);
3238  /* if we have a result set... */
3239  if( SQLITE_ROW == rc ){
3240    /* allocate space for col name ptr, value ptr, and type */
3241    int nCol = sqlite3_column_count(pStmt);
3242    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3243    if( !pData ){
3244      rc = SQLITE_NOMEM;
3245    }else{
3246      char **azCols = (char **)pData;      /* Names of result columns */
3247      char **azVals = &azCols[nCol];       /* Results */
3248      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3249      int i, x;
3250      assert(sizeof(int) <= sizeof(char *));
3251      /* save off ptrs to column names */
3252      for(i=0; i<nCol; i++){
3253        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3254      }
3255      do{
3256        /* extract the data and data types */
3257        for(i=0; i<nCol; i++){
3258          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3259          if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3260            azVals[i] = "";
3261          }else{
3262            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3263          }
3264          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3265            rc = SQLITE_NOMEM;
3266            break; /* from for */
3267          }
3268        } /* end for */
3269
3270        /* if data and types extracted successfully... */
3271        if( SQLITE_ROW == rc ){
3272          /* call the supplied callback with the result row data */
3273          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3274            rc = SQLITE_ABORT;
3275          }else{
3276            rc = sqlite3_step(pStmt);
3277          }
3278        }
3279      } while( SQLITE_ROW == rc );
3280      sqlite3_free(pData);
3281      if( pArg->cMode==MODE_Json ){
3282        fputs("]\n", pArg->out);
3283      }
3284    }
3285  }
3286}
3287
3288#ifndef SQLITE_OMIT_VIRTUALTABLE
3289/*
3290** This function is called to process SQL if the previous shell command
3291** was ".expert". It passes the SQL in the second argument directly to
3292** the sqlite3expert object.
3293**
3294** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3295** code. In this case, (*pzErr) may be set to point to a buffer containing
3296** an English language error message. It is the responsibility of the
3297** caller to eventually free this buffer using sqlite3_free().
3298*/
3299static int expertHandleSQL(
3300  ShellState *pState,
3301  const char *zSql,
3302  char **pzErr
3303){
3304  assert( pState->expert.pExpert );
3305  assert( pzErr==0 || *pzErr==0 );
3306  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3307}
3308
3309/*
3310** This function is called either to silently clean up the object
3311** created by the ".expert" command (if bCancel==1), or to generate a
3312** report from it and then clean it up (if bCancel==0).
3313**
3314** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3315** code. In this case, (*pzErr) may be set to point to a buffer containing
3316** an English language error message. It is the responsibility of the
3317** caller to eventually free this buffer using sqlite3_free().
3318*/
3319static int expertFinish(
3320  ShellState *pState,
3321  int bCancel,
3322  char **pzErr
3323){
3324  int rc = SQLITE_OK;
3325  sqlite3expert *p = pState->expert.pExpert;
3326  assert( p );
3327  assert( bCancel || pzErr==0 || *pzErr==0 );
3328  if( bCancel==0 ){
3329    FILE *out = pState->out;
3330    int bVerbose = pState->expert.bVerbose;
3331
3332    rc = sqlite3_expert_analyze(p, pzErr);
3333    if( rc==SQLITE_OK ){
3334      int nQuery = sqlite3_expert_count(p);
3335      int i;
3336
3337      if( bVerbose ){
3338        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3339        raw_printf(out, "-- Candidates -----------------------------\n");
3340        raw_printf(out, "%s\n", zCand);
3341      }
3342      for(i=0; i<nQuery; i++){
3343        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3344        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3345        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3346        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3347        if( bVerbose ){
3348          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3349          raw_printf(out, "%s\n\n", zSql);
3350        }
3351        raw_printf(out, "%s\n", zIdx);
3352        raw_printf(out, "%s\n", zEQP);
3353      }
3354    }
3355  }
3356  sqlite3_expert_destroy(p);
3357  pState->expert.pExpert = 0;
3358  return rc;
3359}
3360
3361/*
3362** Implementation of ".expert" dot command.
3363*/
3364static int expertDotCommand(
3365  ShellState *pState,             /* Current shell tool state */
3366  char **azArg,                   /* Array of arguments passed to dot command */
3367  int nArg                        /* Number of entries in azArg[] */
3368){
3369  int rc = SQLITE_OK;
3370  char *zErr = 0;
3371  int i;
3372  int iSample = 0;
3373
3374  assert( pState->expert.pExpert==0 );
3375  memset(&pState->expert, 0, sizeof(ExpertInfo));
3376
3377  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3378    char *z = azArg[i];
3379    int n;
3380    if( z[0]=='-' && z[1]=='-' ) z++;
3381    n = strlen30(z);
3382    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3383      pState->expert.bVerbose = 1;
3384    }
3385    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3386      if( i==(nArg-1) ){
3387        raw_printf(stderr, "option requires an argument: %s\n", z);
3388        rc = SQLITE_ERROR;
3389      }else{
3390        iSample = (int)integerValue(azArg[++i]);
3391        if( iSample<0 || iSample>100 ){
3392          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3393          rc = SQLITE_ERROR;
3394        }
3395      }
3396    }
3397    else{
3398      raw_printf(stderr, "unknown option: %s\n", z);
3399      rc = SQLITE_ERROR;
3400    }
3401  }
3402
3403  if( rc==SQLITE_OK ){
3404    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3405    if( pState->expert.pExpert==0 ){
3406      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
3407      rc = SQLITE_ERROR;
3408    }else{
3409      sqlite3_expert_config(
3410          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3411      );
3412    }
3413  }
3414
3415  return rc;
3416}
3417#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3418
3419/*
3420** Execute a statement or set of statements.  Print
3421** any result rows/columns depending on the current mode
3422** set via the supplied callback.
3423**
3424** This is very similar to SQLite's built-in sqlite3_exec()
3425** function except it takes a slightly different callback
3426** and callback data argument.
3427*/
3428static int shell_exec(
3429  ShellState *pArg,                         /* Pointer to ShellState */
3430  const char *zSql,                         /* SQL to be evaluated */
3431  char **pzErrMsg                           /* Error msg written here */
3432){
3433  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3434  int rc = SQLITE_OK;             /* Return Code */
3435  int rc2;
3436  const char *zLeftover;          /* Tail of unprocessed SQL */
3437  sqlite3 *db = pArg->db;
3438
3439  if( pzErrMsg ){
3440    *pzErrMsg = NULL;
3441  }
3442
3443#ifndef SQLITE_OMIT_VIRTUALTABLE
3444  if( pArg->expert.pExpert ){
3445    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3446    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3447  }
3448#endif
3449
3450  while( zSql[0] && (SQLITE_OK == rc) ){
3451    static const char *zStmtSql;
3452    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3453    if( SQLITE_OK != rc ){
3454      if( pzErrMsg ){
3455        *pzErrMsg = save_err_msg(db);
3456      }
3457    }else{
3458      if( !pStmt ){
3459        /* this happens for a comment or white-space */
3460        zSql = zLeftover;
3461        while( IsSpace(zSql[0]) ) zSql++;
3462        continue;
3463      }
3464      zStmtSql = sqlite3_sql(pStmt);
3465      if( zStmtSql==0 ) zStmtSql = "";
3466      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3467
3468      /* save off the prepared statment handle and reset row count */
3469      if( pArg ){
3470        pArg->pStmt = pStmt;
3471        pArg->cnt = 0;
3472      }
3473
3474      /* echo the sql statement if echo on */
3475      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3476        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3477      }
3478
3479      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3480      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3481        sqlite3_stmt *pExplain;
3482        char *zEQP;
3483        int triggerEQP = 0;
3484        disable_debug_trace_modes();
3485        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3486        if( pArg->autoEQP>=AUTOEQP_trigger ){
3487          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3488        }
3489        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3490        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3491        if( rc==SQLITE_OK ){
3492          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3493            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3494            int iEqpId = sqlite3_column_int(pExplain, 0);
3495            int iParentId = sqlite3_column_int(pExplain, 1);
3496            if( zEQPLine==0 ) zEQPLine = "";
3497            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3498            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3499          }
3500          eqp_render(pArg);
3501        }
3502        sqlite3_finalize(pExplain);
3503        sqlite3_free(zEQP);
3504        if( pArg->autoEQP>=AUTOEQP_full ){
3505          /* Also do an EXPLAIN for ".eqp full" mode */
3506          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3507          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3508          if( rc==SQLITE_OK ){
3509            pArg->cMode = MODE_Explain;
3510            explain_data_prepare(pArg, pExplain);
3511            exec_prepared_stmt(pArg, pExplain);
3512            explain_data_delete(pArg);
3513          }
3514          sqlite3_finalize(pExplain);
3515          sqlite3_free(zEQP);
3516        }
3517        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3518          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3519          /* Reprepare pStmt before reactiving trace modes */
3520          sqlite3_finalize(pStmt);
3521          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3522          if( pArg ) pArg->pStmt = pStmt;
3523        }
3524        restore_debug_trace_modes();
3525      }
3526
3527      if( pArg ){
3528        pArg->cMode = pArg->mode;
3529        if( pArg->autoExplain ){
3530          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3531            pArg->cMode = MODE_Explain;
3532          }
3533          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3534            pArg->cMode = MODE_EQP;
3535          }
3536        }
3537
3538        /* If the shell is currently in ".explain" mode, gather the extra
3539        ** data required to add indents to the output.*/
3540        if( pArg->cMode==MODE_Explain ){
3541          explain_data_prepare(pArg, pStmt);
3542        }
3543      }
3544
3545      bind_prepared_stmt(pArg, pStmt);
3546      exec_prepared_stmt(pArg, pStmt);
3547      explain_data_delete(pArg);
3548      eqp_render(pArg);
3549
3550      /* print usage stats if stats on */
3551      if( pArg && pArg->statsOn ){
3552        display_stats(db, pArg, 0);
3553      }
3554
3555      /* print loop-counters if required */
3556      if( pArg && pArg->scanstatsOn ){
3557        display_scanstats(db, pArg);
3558      }
3559
3560      /* Finalize the statement just executed. If this fails, save a
3561      ** copy of the error message. Otherwise, set zSql to point to the
3562      ** next statement to execute. */
3563      rc2 = sqlite3_finalize(pStmt);
3564      if( rc!=SQLITE_NOMEM ) rc = rc2;
3565      if( rc==SQLITE_OK ){
3566        zSql = zLeftover;
3567        while( IsSpace(zSql[0]) ) zSql++;
3568      }else if( pzErrMsg ){
3569        *pzErrMsg = save_err_msg(db);
3570      }
3571
3572      /* clear saved stmt handle */
3573      if( pArg ){
3574        pArg->pStmt = NULL;
3575      }
3576    }
3577  } /* end while */
3578
3579  return rc;
3580}
3581
3582/*
3583** Release memory previously allocated by tableColumnList().
3584*/
3585static void freeColumnList(char **azCol){
3586  int i;
3587  for(i=1; azCol[i]; i++){
3588    sqlite3_free(azCol[i]);
3589  }
3590  /* azCol[0] is a static string */
3591  sqlite3_free(azCol);
3592}
3593
3594/*
3595** Return a list of pointers to strings which are the names of all
3596** columns in table zTab.   The memory to hold the names is dynamically
3597** allocated and must be released by the caller using a subsequent call
3598** to freeColumnList().
3599**
3600** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3601** value that needs to be preserved, then azCol[0] is filled in with the
3602** name of the rowid column.
3603**
3604** The first regular column in the table is azCol[1].  The list is terminated
3605** by an entry with azCol[i]==0.
3606*/
3607static char **tableColumnList(ShellState *p, const char *zTab){
3608  char **azCol = 0;
3609  sqlite3_stmt *pStmt;
3610  char *zSql;
3611  int nCol = 0;
3612  int nAlloc = 0;
3613  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3614  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3615  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3616  int rc;
3617
3618  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3619  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3620  sqlite3_free(zSql);
3621  if( rc ) return 0;
3622  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3623    if( nCol>=nAlloc-2 ){
3624      nAlloc = nAlloc*2 + nCol + 10;
3625      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3626      if( azCol==0 ) shell_out_of_memory();
3627    }
3628    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3629    if( sqlite3_column_int(pStmt, 5) ){
3630      nPK++;
3631      if( nPK==1
3632       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3633                          "INTEGER")==0
3634      ){
3635        isIPK = 1;
3636      }else{
3637        isIPK = 0;
3638      }
3639    }
3640  }
3641  sqlite3_finalize(pStmt);
3642  if( azCol==0 ) return 0;
3643  azCol[0] = 0;
3644  azCol[nCol+1] = 0;
3645
3646  /* The decision of whether or not a rowid really needs to be preserved
3647  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
3648  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
3649  ** rowids on tables where the rowid is inaccessible because there are other
3650  ** columns in the table named "rowid", "_rowid_", and "oid".
3651  */
3652  if( preserveRowid && isIPK ){
3653    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3654    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
3655    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3656    ** ROWID aliases.  To distinguish these cases, check to see if
3657    ** there is a "pk" entry in "PRAGMA index_list".  There will be
3658    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3659    */
3660    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3661                           " WHERE origin='pk'", zTab);
3662    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3663    sqlite3_free(zSql);
3664    if( rc ){
3665      freeColumnList(azCol);
3666      return 0;
3667    }
3668    rc = sqlite3_step(pStmt);
3669    sqlite3_finalize(pStmt);
3670    preserveRowid = rc==SQLITE_ROW;
3671  }
3672  if( preserveRowid ){
3673    /* Only preserve the rowid if we can find a name to use for the
3674    ** rowid */
3675    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3676    int i, j;
3677    for(j=0; j<3; j++){
3678      for(i=1; i<=nCol; i++){
3679        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3680      }
3681      if( i>nCol ){
3682        /* At this point, we know that azRowid[j] is not the name of any
3683        ** ordinary column in the table.  Verify that azRowid[j] is a valid
3684        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
3685        ** tables will fail this last check */
3686        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3687        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3688        break;
3689      }
3690    }
3691  }
3692  return azCol;
3693}
3694
3695/*
3696** Toggle the reverse_unordered_selects setting.
3697*/
3698static void toggleSelectOrder(sqlite3 *db){
3699  sqlite3_stmt *pStmt = 0;
3700  int iSetting = 0;
3701  char zStmt[100];
3702  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3703  if( sqlite3_step(pStmt)==SQLITE_ROW ){
3704    iSetting = sqlite3_column_int(pStmt, 0);
3705  }
3706  sqlite3_finalize(pStmt);
3707  sqlite3_snprintf(sizeof(zStmt), zStmt,
3708       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3709  sqlite3_exec(db, zStmt, 0, 0, 0);
3710}
3711
3712/*
3713** This is a different callback routine used for dumping the database.
3714** Each row received by this callback consists of a table name,
3715** the table type ("index" or "table") and SQL to create the table.
3716** This routine should print text sufficient to recreate the table.
3717*/
3718static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3719  int rc;
3720  const char *zTable;
3721  const char *zType;
3722  const char *zSql;
3723  ShellState *p = (ShellState *)pArg;
3724  int dataOnly;
3725  int noSys;
3726
3727  UNUSED_PARAMETER(azNotUsed);
3728  if( nArg!=3 || azArg==0 ) return 0;
3729  zTable = azArg[0];
3730  zType = azArg[1];
3731  zSql = azArg[2];
3732  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
3733  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
3734
3735  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
3736    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3737  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
3738    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
3739  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3740    return 0;
3741  }else if( dataOnly ){
3742    /* no-op */
3743  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3744    char *zIns;
3745    if( !p->writableSchema ){
3746      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3747      p->writableSchema = 1;
3748    }
3749    zIns = sqlite3_mprintf(
3750       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
3751       "VALUES('table','%q','%q',0,'%q');",
3752       zTable, zTable, zSql);
3753    utf8_printf(p->out, "%s\n", zIns);
3754    sqlite3_free(zIns);
3755    return 0;
3756  }else{
3757    printSchemaLine(p->out, zSql, ";\n");
3758  }
3759
3760  if( strcmp(zType, "table")==0 ){
3761    ShellText sSelect;
3762    ShellText sTable;
3763    char **azCol;
3764    int i;
3765    char *savedDestTable;
3766    int savedMode;
3767
3768    azCol = tableColumnList(p, zTable);
3769    if( azCol==0 ){
3770      p->nErr++;
3771      return 0;
3772    }
3773
3774    /* Always quote the table name, even if it appears to be pure ascii,
3775    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
3776    initText(&sTable);
3777    appendText(&sTable, zTable, quoteChar(zTable));
3778    /* If preserving the rowid, add a column list after the table name.
3779    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3780    ** instead of the usual "INSERT INTO tab VALUES(...)".
3781    */
3782    if( azCol[0] ){
3783      appendText(&sTable, "(", 0);
3784      appendText(&sTable, azCol[0], 0);
3785      for(i=1; azCol[i]; i++){
3786        appendText(&sTable, ",", 0);
3787        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3788      }
3789      appendText(&sTable, ")", 0);
3790    }
3791
3792    /* Build an appropriate SELECT statement */
3793    initText(&sSelect);
3794    appendText(&sSelect, "SELECT ", 0);
3795    if( azCol[0] ){
3796      appendText(&sSelect, azCol[0], 0);
3797      appendText(&sSelect, ",", 0);
3798    }
3799    for(i=1; azCol[i]; i++){
3800      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3801      if( azCol[i+1] ){
3802        appendText(&sSelect, ",", 0);
3803      }
3804    }
3805    freeColumnList(azCol);
3806    appendText(&sSelect, " FROM ", 0);
3807    appendText(&sSelect, zTable, quoteChar(zTable));
3808
3809    savedDestTable = p->zDestTable;
3810    savedMode = p->mode;
3811    p->zDestTable = sTable.z;
3812    p->mode = p->cMode = MODE_Insert;
3813    rc = shell_exec(p, sSelect.z, 0);
3814    if( (rc&0xff)==SQLITE_CORRUPT ){
3815      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3816      toggleSelectOrder(p->db);
3817      shell_exec(p, sSelect.z, 0);
3818      toggleSelectOrder(p->db);
3819    }
3820    p->zDestTable = savedDestTable;
3821    p->mode = savedMode;
3822    freeText(&sTable);
3823    freeText(&sSelect);
3824    if( rc ) p->nErr++;
3825  }
3826  return 0;
3827}
3828
3829/*
3830** Run zQuery.  Use dump_callback() as the callback routine so that
3831** the contents of the query are output as SQL statements.
3832**
3833** If we get a SQLITE_CORRUPT error, rerun the query after appending
3834** "ORDER BY rowid DESC" to the end.
3835*/
3836static int run_schema_dump_query(
3837  ShellState *p,
3838  const char *zQuery
3839){
3840  int rc;
3841  char *zErr = 0;
3842  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3843  if( rc==SQLITE_CORRUPT ){
3844    char *zQ2;
3845    int len = strlen30(zQuery);
3846    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3847    if( zErr ){
3848      utf8_printf(p->out, "/****** %s ******/\n", zErr);
3849      sqlite3_free(zErr);
3850      zErr = 0;
3851    }
3852    zQ2 = malloc( len+100 );
3853    if( zQ2==0 ) return rc;
3854    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3855    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3856    if( rc ){
3857      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3858    }else{
3859      rc = SQLITE_CORRUPT;
3860    }
3861    sqlite3_free(zErr);
3862    free(zQ2);
3863  }
3864  return rc;
3865}
3866
3867/*
3868** Text of help messages.
3869**
3870** The help text for each individual command begins with a line that starts
3871** with ".".  Subsequent lines are supplimental information.
3872**
3873** There must be two or more spaces between the end of the command and the
3874** start of the description of what that command does.
3875*/
3876static const char *(azHelp[]) = {
3877#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3878  ".archive ...             Manage SQL archives",
3879  "   Each command must have exactly one of the following options:",
3880  "     -c, --create               Create a new archive",
3881  "     -u, --update               Add or update files with changed mtime",
3882  "     -i, --insert               Like -u but always add even if unchanged",
3883  "     -t, --list                 List contents of archive",
3884  "     -x, --extract              Extract files from archive",
3885  "   Optional arguments:",
3886  "     -v, --verbose              Print each filename as it is processed",
3887  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
3888  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
3889  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
3890  "     -n, --dryrun               Show the SQL that would have occurred",
3891  "   Examples:",
3892  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
3893  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
3894  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
3895  "   See also:",
3896  "      http://sqlite.org/cli.html#sqlite_archive_support",
3897#endif
3898#ifndef SQLITE_OMIT_AUTHORIZATION
3899  ".auth ON|OFF             Show authorizer callbacks",
3900#endif
3901  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
3902  "       --append            Use the appendvfs",
3903  "       --async             Write to FILE without journal and fsync()",
3904  ".bail on|off             Stop after hitting an error.  Default OFF",
3905  ".binary on|off           Turn binary output on or off.  Default OFF",
3906  ".cd DIRECTORY            Change the working directory to DIRECTORY",
3907  ".changes on|off          Show number of rows changed by SQL",
3908  ".check GLOB              Fail if output since .testcase does not match",
3909  ".clone NEWDB             Clone data into NEWDB from the existing database",
3910  ".connection [close] [#]  Open or close an auxiliary database connection",
3911  ".databases               List names and files of attached databases",
3912  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
3913  ".dbinfo ?DB?             Show status information about the database",
3914  ".dump ?OBJECTS?          Render database content as SQL",
3915  "   Options:",
3916  "     --data-only            Output only INSERT statements",
3917  "     --newlines             Allow unescaped newline characters in output",
3918  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
3919  "     --preserve-rowids      Include ROWID values in the output",
3920  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
3921  "   Additional LIKE patterns can be given in subsequent arguments",
3922  ".echo on|off             Turn command echo on or off",
3923  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
3924  "   Other Modes:",
3925#ifdef SQLITE_DEBUG
3926  "      test                  Show raw EXPLAIN QUERY PLAN output",
3927  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
3928#endif
3929  "      trigger               Like \"full\" but also show trigger bytecode",
3930  ".excel                   Display the output of next command in spreadsheet",
3931  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
3932  ".exit ?CODE?             Exit this program with return-code CODE",
3933  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
3934  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
3935  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
3936  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
3937  "   --help                  Show CMD details",
3938  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
3939  ".headers on|off          Turn display of headers on or off",
3940  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
3941  ".import FILE TABLE       Import data from FILE into TABLE",
3942  "   Options:",
3943  "     --ascii               Use \\037 and \\036 as column and row separators",
3944  "     --csv                 Use , and \\n as column and row separators",
3945  "     --skip N              Skip the first N rows of input",
3946  "     -v                    \"Verbose\" - increase auxiliary output",
3947  "   Notes:",
3948  "     *  If TABLE does not exist, it is created.  The first row of input",
3949  "        determines the column names.",
3950  "     *  If neither --csv or --ascii are used, the input mode is derived",
3951  "        from the \".mode\" output mode",
3952  "     *  If FILE begins with \"|\" then it is a command that generates the",
3953  "        input text.",
3954#ifndef SQLITE_OMIT_TEST_CONTROL
3955  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
3956#endif
3957  ".indexes ?TABLE?         Show names of indexes",
3958  "                           If TABLE is specified, only show indexes for",
3959  "                           tables matching TABLE using the LIKE operator.",
3960#ifdef SQLITE_ENABLE_IOTRACE
3961  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
3962#endif
3963  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
3964  ".lint OPTIONS            Report potential schema issues.",
3965  "     Options:",
3966  "        fkey-indexes     Find missing foreign key indexes",
3967#ifndef SQLITE_OMIT_LOAD_EXTENSION
3968  ".load FILE ?ENTRY?       Load an extension library",
3969#endif
3970  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
3971  ".mode MODE ?TABLE?       Set output mode",
3972  "   MODE is one of:",
3973  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
3974  "     box       Tables using unicode box-drawing characters",
3975  "     csv       Comma-separated values",
3976  "     column    Output in columns.  (See .width)",
3977  "     html      HTML <table> code",
3978  "     insert    SQL insert statements for TABLE",
3979  "     json      Results in a JSON array",
3980  "     line      One value per line",
3981  "     list      Values delimited by \"|\"",
3982  "     markdown  Markdown table format",
3983  "     quote     Escape answers as for SQL",
3984  "     table     ASCII-art table",
3985  "     tabs      Tab-separated values",
3986  "     tcl       TCL list elements",
3987  ".nullvalue STRING        Use STRING in place of NULL values",
3988  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
3989  "     If FILE begins with '|' then open as a pipe",
3990  "       --bom  Put a UTF8 byte-order mark at the beginning",
3991  "       -e     Send output to the system text editor",
3992  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
3993#ifdef SQLITE_DEBUG
3994  ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
3995#endif
3996  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
3997  "     Options:",
3998  "        --append        Use appendvfs to append database to the end of FILE",
3999#ifndef SQLITE_OMIT_DESERIALIZE
4000  "        --deserialize   Load into memory using sqlite3_deserialize()",
4001  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4002  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4003#endif
4004  "        --new           Initialize FILE to an empty database",
4005  "        --nofollow      Do not follow symbolic links",
4006  "        --readonly      Open FILE readonly",
4007  "        --zip           FILE is a ZIP archive",
4008  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4009  "   If FILE begins with '|' then open it as a pipe.",
4010  "   Options:",
4011  "     --bom                 Prefix output with a UTF8 byte-order mark",
4012  "     -e                    Send output to the system text editor",
4013  "     -x                    Send output as CSV to a spreadsheet",
4014  ".parameter CMD ...       Manage SQL parameter bindings",
4015  "   clear                   Erase all bindings",
4016  "   init                    Initialize the TEMP table that holds bindings",
4017  "   list                    List the current parameter bindings",
4018  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4019  "                           PARAMETER should start with one of: $ : @ ?",
4020  "   unset PARAMETER         Remove PARAMETER from the binding table",
4021  ".print STRING...         Print literal STRING",
4022#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4023  ".progress N              Invoke progress handler after every N opcodes",
4024  "   --limit N                 Interrupt after N progress callbacks",
4025  "   --once                    Do no more than one progress interrupt",
4026  "   --quiet|-q                No output except at interrupts",
4027  "   --reset                   Reset the count for each input and interrupt",
4028#endif
4029  ".prompt MAIN CONTINUE    Replace the standard prompts",
4030  ".quit                    Exit this program",
4031  ".read FILE               Read input from FILE",
4032#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4033  ".recover                 Recover as much data as possible from corrupt db.",
4034  "   --freelist-corrupt       Assume the freelist is corrupt",
4035  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4036  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4037  "   --no-rowids              Do not attempt to recover rowid values",
4038  "                            that are not also INTEGER PRIMARY KEYs",
4039#endif
4040  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4041  ".save FILE               Write in-memory database into FILE",
4042  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4043  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4044  "   Options:",
4045  "      --indent             Try to pretty-print the schema",
4046  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4047  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4048  "    Options:",
4049  "       --init               Create a new SELFTEST table",
4050  "       -v                   Verbose output",
4051  ".separator COL ?ROW?     Change the column and row separators",
4052#if defined(SQLITE_ENABLE_SESSION)
4053  ".session ?NAME? CMD ...  Create or control sessions",
4054  "   Subcommands:",
4055  "     attach TABLE             Attach TABLE",
4056  "     changeset FILE           Write a changeset into FILE",
4057  "     close                    Close one session",
4058  "     enable ?BOOLEAN?         Set or query the enable bit",
4059  "     filter GLOB...           Reject tables matching GLOBs",
4060  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4061  "     isempty                  Query whether the session is empty",
4062  "     list                     List currently open session names",
4063  "     open DB NAME             Open a new session on DB",
4064  "     patchset FILE            Write a patchset into FILE",
4065  "   If ?NAME? is omitted, the first defined session is used.",
4066#endif
4067  ".sha3sum ...             Compute a SHA3 hash of database content",
4068  "    Options:",
4069  "      --schema              Also hash the sqlite_schema table",
4070  "      --sha3-224            Use the sha3-224 algorithm",
4071  "      --sha3-256            Use the sha3-256 algorithm (default)",
4072  "      --sha3-384            Use the sha3-384 algorithm",
4073  "      --sha3-512            Use the sha3-512 algorithm",
4074  "    Any other argument is a LIKE pattern for tables to hash",
4075#ifndef SQLITE_NOHAVE_SYSTEM
4076  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4077#endif
4078  ".show                    Show the current values for various settings",
4079  ".stats ?ARG?             Show stats or turn stats on or off",
4080  "   off                      Turn off automatic stat display",
4081  "   on                       Turn on automatic stat display",
4082  "   stmt                     Show statement stats",
4083  "   vmstep                   Show the virtual machine step count only",
4084#ifndef SQLITE_NOHAVE_SYSTEM
4085  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4086#endif
4087  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4088  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4089  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4090  "                           Run \".testctrl\" with no arguments for details",
4091  ".timeout MS              Try opening locked tables for MS milliseconds",
4092  ".timer on|off            Turn SQL timer on or off",
4093#ifndef SQLITE_OMIT_TRACE
4094  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4095  "    FILE                    Send output to FILE",
4096  "    stdout                  Send output to stdout",
4097  "    stderr                  Send output to stderr",
4098  "    off                     Disable tracing",
4099  "    --expanded              Expand query parameters",
4100#ifdef SQLITE_ENABLE_NORMALIZE
4101  "    --normalized            Normal the SQL statements",
4102#endif
4103  "    --plain                 Show SQL as it is input",
4104  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4105  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4106  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4107  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4108#endif /* SQLITE_OMIT_TRACE */
4109#ifdef SQLITE_DEBUG
4110  ".unmodule NAME ...       Unregister virtual table modules",
4111  "    --allexcept             Unregister everything except those named",
4112#endif
4113  ".vfsinfo ?AUX?           Information about the top-level VFS",
4114  ".vfslist                 List all available VFSes",
4115  ".vfsname ?AUX?           Print the name of the VFS stack",
4116  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4117  "     Negative values right-justify",
4118};
4119
4120/*
4121** Output help text.
4122**
4123** zPattern describes the set of commands for which help text is provided.
4124** If zPattern is NULL, then show all commands, but only give a one-line
4125** description of each.
4126**
4127** Return the number of matches.
4128*/
4129static int showHelp(FILE *out, const char *zPattern){
4130  int i = 0;
4131  int j = 0;
4132  int n = 0;
4133  char *zPat;
4134  if( zPattern==0
4135   || zPattern[0]=='0'
4136   || strcmp(zPattern,"-a")==0
4137   || strcmp(zPattern,"-all")==0
4138   || strcmp(zPattern,"--all")==0
4139  ){
4140    /* Show all commands, but only one line per command */
4141    if( zPattern==0 ) zPattern = "";
4142    for(i=0; i<ArraySize(azHelp); i++){
4143      if( azHelp[i][0]=='.' || zPattern[0] ){
4144        utf8_printf(out, "%s\n", azHelp[i]);
4145        n++;
4146      }
4147    }
4148  }else{
4149    /* Look for commands that for which zPattern is an exact prefix */
4150    zPat = sqlite3_mprintf(".%s*", zPattern);
4151    for(i=0; i<ArraySize(azHelp); i++){
4152      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4153        utf8_printf(out, "%s\n", azHelp[i]);
4154        j = i+1;
4155        n++;
4156      }
4157    }
4158    sqlite3_free(zPat);
4159    if( n ){
4160      if( n==1 ){
4161        /* when zPattern is a prefix of exactly one command, then include the
4162        ** details of that command, which should begin at offset j */
4163        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4164          utf8_printf(out, "%s\n", azHelp[j]);
4165          j++;
4166        }
4167      }
4168      return n;
4169    }
4170    /* Look for commands that contain zPattern anywhere.  Show the complete
4171    ** text of all commands that match. */
4172    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4173    for(i=0; i<ArraySize(azHelp); i++){
4174      if( azHelp[i][0]=='.' ) j = i;
4175      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4176        utf8_printf(out, "%s\n", azHelp[j]);
4177        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4178          j++;
4179          utf8_printf(out, "%s\n", azHelp[j]);
4180        }
4181        i = j;
4182        n++;
4183      }
4184    }
4185    sqlite3_free(zPat);
4186  }
4187  return n;
4188}
4189
4190/* Forward reference */
4191static int process_input(ShellState *p);
4192
4193/*
4194** Read the content of file zName into memory obtained from sqlite3_malloc64()
4195** and return a pointer to the buffer. The caller is responsible for freeing
4196** the memory.
4197**
4198** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4199** read.
4200**
4201** For convenience, a nul-terminator byte is always appended to the data read
4202** from the file before the buffer is returned. This byte is not included in
4203** the final value of (*pnByte), if applicable.
4204**
4205** NULL is returned if any error is encountered. The final value of *pnByte
4206** is undefined in this case.
4207*/
4208static char *readFile(const char *zName, int *pnByte){
4209  FILE *in = fopen(zName, "rb");
4210  long nIn;
4211  size_t nRead;
4212  char *pBuf;
4213  if( in==0 ) return 0;
4214  fseek(in, 0, SEEK_END);
4215  nIn = ftell(in);
4216  rewind(in);
4217  pBuf = sqlite3_malloc64( nIn+1 );
4218  if( pBuf==0 ){ fclose(in); return 0; }
4219  nRead = fread(pBuf, nIn, 1, in);
4220  fclose(in);
4221  if( nRead!=1 ){
4222    sqlite3_free(pBuf);
4223    return 0;
4224  }
4225  pBuf[nIn] = 0;
4226  if( pnByte ) *pnByte = nIn;
4227  return pBuf;
4228}
4229
4230#if defined(SQLITE_ENABLE_SESSION)
4231/*
4232** Close a single OpenSession object and release all of its associated
4233** resources.
4234*/
4235static void session_close(OpenSession *pSession){
4236  int i;
4237  sqlite3session_delete(pSession->p);
4238  sqlite3_free(pSession->zName);
4239  for(i=0; i<pSession->nFilter; i++){
4240    sqlite3_free(pSession->azFilter[i]);
4241  }
4242  sqlite3_free(pSession->azFilter);
4243  memset(pSession, 0, sizeof(OpenSession));
4244}
4245#endif
4246
4247/*
4248** Close all OpenSession objects and release all associated resources.
4249*/
4250#if defined(SQLITE_ENABLE_SESSION)
4251static void session_close_all(ShellState *p, int i){
4252  int j;
4253  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4254  for(j=0; j<pAuxDb->nSession; j++){
4255    session_close(&pAuxDb->aSession[j]);
4256  }
4257  pAuxDb->nSession = 0;
4258}
4259#else
4260# define session_close_all(X,Y)
4261#endif
4262
4263/*
4264** Implementation of the xFilter function for an open session.  Omit
4265** any tables named by ".session filter" but let all other table through.
4266*/
4267#if defined(SQLITE_ENABLE_SESSION)
4268static int session_filter(void *pCtx, const char *zTab){
4269  OpenSession *pSession = (OpenSession*)pCtx;
4270  int i;
4271  for(i=0; i<pSession->nFilter; i++){
4272    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4273  }
4274  return 1;
4275}
4276#endif
4277
4278/*
4279** Try to deduce the type of file for zName based on its content.  Return
4280** one of the SHELL_OPEN_* constants.
4281**
4282** If the file does not exist or is empty but its name looks like a ZIP
4283** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4284** Otherwise, assume an ordinary database regardless of the filename if
4285** the type cannot be determined from content.
4286*/
4287int deduceDatabaseType(const char *zName, int dfltZip){
4288  FILE *f = fopen(zName, "rb");
4289  size_t n;
4290  int rc = SHELL_OPEN_UNSPEC;
4291  char zBuf[100];
4292  if( f==0 ){
4293    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4294       return SHELL_OPEN_ZIPFILE;
4295    }else{
4296       return SHELL_OPEN_NORMAL;
4297    }
4298  }
4299  n = fread(zBuf, 16, 1, f);
4300  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4301    fclose(f);
4302    return SHELL_OPEN_NORMAL;
4303  }
4304  fseek(f, -25, SEEK_END);
4305  n = fread(zBuf, 25, 1, f);
4306  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4307    rc = SHELL_OPEN_APPENDVFS;
4308  }else{
4309    fseek(f, -22, SEEK_END);
4310    n = fread(zBuf, 22, 1, f);
4311    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4312       && zBuf[3]==0x06 ){
4313      rc = SHELL_OPEN_ZIPFILE;
4314    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4315      rc = SHELL_OPEN_ZIPFILE;
4316    }
4317  }
4318  fclose(f);
4319  return rc;
4320}
4321
4322#ifndef SQLITE_OMIT_DESERIALIZE
4323/*
4324** Reconstruct an in-memory database using the output from the "dbtotxt"
4325** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4326** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4327*/
4328static unsigned char *readHexDb(ShellState *p, int *pnData){
4329  unsigned char *a = 0;
4330  int nLine;
4331  int n = 0;
4332  int pgsz = 0;
4333  int iOffset = 0;
4334  int j, k;
4335  int rc;
4336  FILE *in;
4337  const char *zDbFilename = p->pAuxDb->zDbFilename;
4338  unsigned int x[16];
4339  char zLine[1000];
4340  if( zDbFilename ){
4341    in = fopen(zDbFilename, "r");
4342    if( in==0 ){
4343      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4344      return 0;
4345    }
4346    nLine = 0;
4347  }else{
4348    in = p->in;
4349    nLine = p->lineno;
4350    if( in==0 ) in = stdin;
4351  }
4352  *pnData = 0;
4353  nLine++;
4354  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4355  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4356  if( rc!=2 ) goto readHexDb_error;
4357  if( n<0 ) goto readHexDb_error;
4358  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4359  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4360  a = sqlite3_malloc( n ? n : 1 );
4361  if( a==0 ){
4362    utf8_printf(stderr, "Out of memory!\n");
4363    goto readHexDb_error;
4364  }
4365  memset(a, 0, n);
4366  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4367    utf8_printf(stderr, "invalid pagesize\n");
4368    goto readHexDb_error;
4369  }
4370  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4371    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4372    if( rc==2 ){
4373      iOffset = k;
4374      continue;
4375    }
4376    if( strncmp(zLine, "| end ", 6)==0 ){
4377      break;
4378    }
4379    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4380                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4381                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4382    if( rc==17 ){
4383      k = iOffset+j;
4384      if( k+16<=n ){
4385        int ii;
4386        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4387      }
4388    }
4389  }
4390  *pnData = n;
4391  if( in!=p->in ){
4392    fclose(in);
4393  }else{
4394    p->lineno = nLine;
4395  }
4396  return a;
4397
4398readHexDb_error:
4399  if( in!=p->in ){
4400    fclose(in);
4401  }else{
4402    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4403      nLine++;
4404      if(strncmp(zLine, "| end ", 6)==0 ) break;
4405    }
4406    p->lineno = nLine;
4407  }
4408  sqlite3_free(a);
4409  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4410  return 0;
4411}
4412#endif /* SQLITE_OMIT_DESERIALIZE */
4413
4414/*
4415** Scalar function "shell_int32". The first argument to this function
4416** must be a blob. The second a non-negative integer. This function
4417** reads and returns a 32-bit big-endian integer from byte
4418** offset (4*<arg2>) of the blob.
4419*/
4420static void shellInt32(
4421  sqlite3_context *context,
4422  int argc,
4423  sqlite3_value **argv
4424){
4425  const unsigned char *pBlob;
4426  int nBlob;
4427  int iInt;
4428
4429  UNUSED_PARAMETER(argc);
4430  nBlob = sqlite3_value_bytes(argv[0]);
4431  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4432  iInt = sqlite3_value_int(argv[1]);
4433
4434  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4435    const unsigned char *a = &pBlob[iInt*4];
4436    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4437                       + ((sqlite3_int64)a[1]<<16)
4438                       + ((sqlite3_int64)a[2]<< 8)
4439                       + ((sqlite3_int64)a[3]<< 0);
4440    sqlite3_result_int64(context, iVal);
4441  }
4442}
4443
4444/*
4445** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4446** using "..." with internal double-quote characters doubled.
4447*/
4448static void shellIdQuote(
4449  sqlite3_context *context,
4450  int argc,
4451  sqlite3_value **argv
4452){
4453  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4454  UNUSED_PARAMETER(argc);
4455  if( zName ){
4456    char *z = sqlite3_mprintf("\"%w\"", zName);
4457    sqlite3_result_text(context, z, -1, sqlite3_free);
4458  }
4459}
4460
4461/*
4462** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4463*/
4464static void shellUSleepFunc(
4465  sqlite3_context *context,
4466  int argcUnused,
4467  sqlite3_value **argv
4468){
4469  int sleep = sqlite3_value_int(argv[0]);
4470  (void)argcUnused;
4471  sqlite3_sleep(sleep/1000);
4472  sqlite3_result_int(context, sleep);
4473}
4474
4475/*
4476** Scalar function "shell_escape_crnl" used by the .recover command.
4477** The argument passed to this function is the output of built-in
4478** function quote(). If the first character of the input is "'",
4479** indicating that the value passed to quote() was a text value,
4480** then this function searches the input for "\n" and "\r" characters
4481** and adds a wrapper similar to the following:
4482**
4483**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4484**
4485** Or, if the first character of the input is not "'", then a copy
4486** of the input is returned.
4487*/
4488static void shellEscapeCrnl(
4489  sqlite3_context *context,
4490  int argc,
4491  sqlite3_value **argv
4492){
4493  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4494  UNUSED_PARAMETER(argc);
4495  if( zText[0]=='\'' ){
4496    int nText = sqlite3_value_bytes(argv[0]);
4497    int i;
4498    char zBuf1[20];
4499    char zBuf2[20];
4500    const char *zNL = 0;
4501    const char *zCR = 0;
4502    int nCR = 0;
4503    int nNL = 0;
4504
4505    for(i=0; zText[i]; i++){
4506      if( zNL==0 && zText[i]=='\n' ){
4507        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4508        nNL = (int)strlen(zNL);
4509      }
4510      if( zCR==0 && zText[i]=='\r' ){
4511        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4512        nCR = (int)strlen(zCR);
4513      }
4514    }
4515
4516    if( zNL || zCR ){
4517      int iOut = 0;
4518      i64 nMax = (nNL > nCR) ? nNL : nCR;
4519      i64 nAlloc = nMax * nText + (nMax+64)*2;
4520      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4521      if( zOut==0 ){
4522        sqlite3_result_error_nomem(context);
4523        return;
4524      }
4525
4526      if( zNL && zCR ){
4527        memcpy(&zOut[iOut], "replace(replace(", 16);
4528        iOut += 16;
4529      }else{
4530        memcpy(&zOut[iOut], "replace(", 8);
4531        iOut += 8;
4532      }
4533      for(i=0; zText[i]; i++){
4534        if( zText[i]=='\n' ){
4535          memcpy(&zOut[iOut], zNL, nNL);
4536          iOut += nNL;
4537        }else if( zText[i]=='\r' ){
4538          memcpy(&zOut[iOut], zCR, nCR);
4539          iOut += nCR;
4540        }else{
4541          zOut[iOut] = zText[i];
4542          iOut++;
4543        }
4544      }
4545
4546      if( zNL ){
4547        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4548        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4549        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4550      }
4551      if( zCR ){
4552        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4553        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4554        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4555      }
4556
4557      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4558      sqlite3_free(zOut);
4559      return;
4560    }
4561  }
4562
4563  sqlite3_result_value(context, argv[0]);
4564}
4565
4566/* Flags for open_db().
4567**
4568** The default behavior of open_db() is to exit(1) if the database fails to
4569** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4570** but still returns without calling exit.
4571**
4572** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4573** ZIP archive if the file does not exist or is empty and its name matches
4574** the *.zip pattern.
4575*/
4576#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4577#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4578
4579/*
4580** Make sure the database is open.  If it is not, then open it.  If
4581** the database fails to open, print an error message and exit.
4582*/
4583static void open_db(ShellState *p, int openFlags){
4584  if( p->db==0 ){
4585    const char *zDbFilename = p->pAuxDb->zDbFilename;
4586    if( p->openMode==SHELL_OPEN_UNSPEC ){
4587      if( zDbFilename==0 || zDbFilename[0]==0 ){
4588        p->openMode = SHELL_OPEN_NORMAL;
4589      }else{
4590        p->openMode = (u8)deduceDatabaseType(zDbFilename,
4591                             (openFlags & OPEN_DB_ZIPFILE)!=0);
4592      }
4593    }
4594    switch( p->openMode ){
4595      case SHELL_OPEN_APPENDVFS: {
4596        sqlite3_open_v2(zDbFilename, &p->db,
4597           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
4598        break;
4599      }
4600      case SHELL_OPEN_HEXDB:
4601      case SHELL_OPEN_DESERIALIZE: {
4602        sqlite3_open(0, &p->db);
4603        break;
4604      }
4605      case SHELL_OPEN_ZIPFILE: {
4606        sqlite3_open(":memory:", &p->db);
4607        break;
4608      }
4609      case SHELL_OPEN_READONLY: {
4610        sqlite3_open_v2(zDbFilename, &p->db,
4611            SQLITE_OPEN_READONLY|p->openFlags, 0);
4612        break;
4613      }
4614      case SHELL_OPEN_UNSPEC:
4615      case SHELL_OPEN_NORMAL: {
4616        sqlite3_open_v2(zDbFilename, &p->db,
4617           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
4618        break;
4619      }
4620    }
4621    globalDb = p->db;
4622    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4623      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4624          zDbFilename, sqlite3_errmsg(p->db));
4625      if( openFlags & OPEN_DB_KEEPALIVE ){
4626        sqlite3_open(":memory:", &p->db);
4627        return;
4628      }
4629      exit(1);
4630    }
4631#ifndef SQLITE_OMIT_LOAD_EXTENSION
4632    sqlite3_enable_load_extension(p->db, 1);
4633#endif
4634    sqlite3_fileio_init(p->db, 0, 0);
4635    sqlite3_shathree_init(p->db, 0, 0);
4636    sqlite3_completion_init(p->db, 0, 0);
4637    sqlite3_uint_init(p->db, 0, 0);
4638    sqlite3_decimal_init(p->db, 0, 0);
4639    sqlite3_regexp_init(p->db, 0, 0);
4640    sqlite3_ieee_init(p->db, 0, 0);
4641    sqlite3_series_init(p->db, 0, 0);
4642#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4643    sqlite3_dbdata_init(p->db, 0, 0);
4644#endif
4645#ifdef SQLITE_HAVE_ZLIB
4646    sqlite3_zipfile_init(p->db, 0, 0);
4647    sqlite3_sqlar_init(p->db, 0, 0);
4648#endif
4649    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
4650                            shellAddSchemaName, 0, 0);
4651    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4652                            shellModuleSchema, 0, 0);
4653    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4654                            shellPutsFunc, 0, 0);
4655    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4656                            shellEscapeCrnl, 0, 0);
4657    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4658                            shellInt32, 0, 0);
4659    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4660                            shellIdQuote, 0, 0);
4661    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
4662                            shellUSleepFunc, 0, 0);
4663#ifndef SQLITE_NOHAVE_SYSTEM
4664    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4665                            editFunc, 0, 0);
4666    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4667                            editFunc, 0, 0);
4668#endif
4669    if( p->openMode==SHELL_OPEN_ZIPFILE ){
4670      char *zSql = sqlite3_mprintf(
4671         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
4672      sqlite3_exec(p->db, zSql, 0, 0, 0);
4673      sqlite3_free(zSql);
4674    }
4675#ifndef SQLITE_OMIT_DESERIALIZE
4676    else
4677    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
4678      int rc;
4679      int nData = 0;
4680      unsigned char *aData;
4681      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4682        aData = (unsigned char*)readFile(zDbFilename, &nData);
4683      }else{
4684        aData = readHexDb(p, &nData);
4685        if( aData==0 ){
4686          return;
4687        }
4688      }
4689      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
4690                   SQLITE_DESERIALIZE_RESIZEABLE |
4691                   SQLITE_DESERIALIZE_FREEONCLOSE);
4692      if( rc ){
4693        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4694      }
4695      if( p->szMax>0 ){
4696        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4697      }
4698    }
4699#endif
4700  }
4701}
4702
4703/*
4704** Attempt to close the databaes connection.  Report errors.
4705*/
4706void close_db(sqlite3 *db){
4707  int rc = sqlite3_close(db);
4708  if( rc ){
4709    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4710        rc, sqlite3_errmsg(db));
4711  }
4712}
4713
4714#if HAVE_READLINE || HAVE_EDITLINE
4715/*
4716** Readline completion callbacks
4717*/
4718static char *readline_completion_generator(const char *text, int state){
4719  static sqlite3_stmt *pStmt = 0;
4720  char *zRet;
4721  if( state==0 ){
4722    char *zSql;
4723    sqlite3_finalize(pStmt);
4724    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4725                           "  FROM completion(%Q) ORDER BY 1", text);
4726    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4727    sqlite3_free(zSql);
4728  }
4729  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4730    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
4731  }else{
4732    sqlite3_finalize(pStmt);
4733    pStmt = 0;
4734    zRet = 0;
4735  }
4736  return zRet;
4737}
4738static char **readline_completion(const char *zText, int iStart, int iEnd){
4739  rl_attempted_completion_over = 1;
4740  return rl_completion_matches(zText, readline_completion_generator);
4741}
4742
4743#elif HAVE_LINENOISE
4744/*
4745** Linenoise completion callback
4746*/
4747static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4748  int nLine = strlen30(zLine);
4749  int i, iStart;
4750  sqlite3_stmt *pStmt = 0;
4751  char *zSql;
4752  char zBuf[1000];
4753
4754  if( nLine>sizeof(zBuf)-30 ) return;
4755  if( zLine[0]=='.' || zLine[0]=='#') return;
4756  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4757  if( i==nLine-1 ) return;
4758  iStart = i+1;
4759  memcpy(zBuf, zLine, iStart);
4760  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4761                         "  FROM completion(%Q,%Q) ORDER BY 1",
4762                         &zLine[iStart], zLine);
4763  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4764  sqlite3_free(zSql);
4765  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4766  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4767    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4768    int nCompletion = sqlite3_column_bytes(pStmt, 0);
4769    if( iStart+nCompletion < sizeof(zBuf)-1 ){
4770      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4771      linenoiseAddCompletion(lc, zBuf);
4772    }
4773  }
4774  sqlite3_finalize(pStmt);
4775}
4776#endif
4777
4778/*
4779** Do C-language style dequoting.
4780**
4781**    \a    -> alarm
4782**    \b    -> backspace
4783**    \t    -> tab
4784**    \n    -> newline
4785**    \v    -> vertical tab
4786**    \f    -> form feed
4787**    \r    -> carriage return
4788**    \s    -> space
4789**    \"    -> "
4790**    \'    -> '
4791**    \\    -> backslash
4792**    \NNN  -> ascii character NNN in octal
4793*/
4794static void resolve_backslashes(char *z){
4795  int i, j;
4796  char c;
4797  while( *z && *z!='\\' ) z++;
4798  for(i=j=0; (c = z[i])!=0; i++, j++){
4799    if( c=='\\' && z[i+1]!=0 ){
4800      c = z[++i];
4801      if( c=='a' ){
4802        c = '\a';
4803      }else if( c=='b' ){
4804        c = '\b';
4805      }else if( c=='t' ){
4806        c = '\t';
4807      }else if( c=='n' ){
4808        c = '\n';
4809      }else if( c=='v' ){
4810        c = '\v';
4811      }else if( c=='f' ){
4812        c = '\f';
4813      }else if( c=='r' ){
4814        c = '\r';
4815      }else if( c=='"' ){
4816        c = '"';
4817      }else if( c=='\'' ){
4818        c = '\'';
4819      }else if( c=='\\' ){
4820        c = '\\';
4821      }else if( c>='0' && c<='7' ){
4822        c -= '0';
4823        if( z[i+1]>='0' && z[i+1]<='7' ){
4824          i++;
4825          c = (c<<3) + z[i] - '0';
4826          if( z[i+1]>='0' && z[i+1]<='7' ){
4827            i++;
4828            c = (c<<3) + z[i] - '0';
4829          }
4830        }
4831      }
4832    }
4833    z[j] = c;
4834  }
4835  if( j<i ) z[j] = 0;
4836}
4837
4838/*
4839** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
4840** for TRUE and FALSE.  Return the integer value if appropriate.
4841*/
4842static int booleanValue(const char *zArg){
4843  int i;
4844  if( zArg[0]=='0' && zArg[1]=='x' ){
4845    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4846  }else{
4847    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4848  }
4849  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4850  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4851    return 1;
4852  }
4853  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4854    return 0;
4855  }
4856  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4857          zArg);
4858  return 0;
4859}
4860
4861/*
4862** Set or clear a shell flag according to a boolean value.
4863*/
4864static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4865  if( booleanValue(zArg) ){
4866    ShellSetFlag(p, mFlag);
4867  }else{
4868    ShellClearFlag(p, mFlag);
4869  }
4870}
4871
4872/*
4873** Close an output file, assuming it is not stderr or stdout
4874*/
4875static void output_file_close(FILE *f){
4876  if( f && f!=stdout && f!=stderr ) fclose(f);
4877}
4878
4879/*
4880** Try to open an output file.   The names "stdout" and "stderr" are
4881** recognized and do the right thing.  NULL is returned if the output
4882** filename is "off".
4883*/
4884static FILE *output_file_open(const char *zFile, int bTextMode){
4885  FILE *f;
4886  if( strcmp(zFile,"stdout")==0 ){
4887    f = stdout;
4888  }else if( strcmp(zFile, "stderr")==0 ){
4889    f = stderr;
4890  }else if( strcmp(zFile, "off")==0 ){
4891    f = 0;
4892  }else{
4893    f = fopen(zFile, bTextMode ? "w" : "wb");
4894    if( f==0 ){
4895      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4896    }
4897  }
4898  return f;
4899}
4900
4901#ifndef SQLITE_OMIT_TRACE
4902/*
4903** A routine for handling output from sqlite3_trace().
4904*/
4905static int sql_trace_callback(
4906  unsigned mType,         /* The trace type */
4907  void *pArg,             /* The ShellState pointer */
4908  void *pP,               /* Usually a pointer to sqlite_stmt */
4909  void *pX                /* Auxiliary output */
4910){
4911  ShellState *p = (ShellState*)pArg;
4912  sqlite3_stmt *pStmt;
4913  const char *zSql;
4914  int nSql;
4915  if( p->traceOut==0 ) return 0;
4916  if( mType==SQLITE_TRACE_CLOSE ){
4917    utf8_printf(p->traceOut, "-- closing database connection\n");
4918    return 0;
4919  }
4920  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4921    zSql = (const char*)pX;
4922  }else{
4923    pStmt = (sqlite3_stmt*)pP;
4924    switch( p->eTraceType ){
4925      case SHELL_TRACE_EXPANDED: {
4926        zSql = sqlite3_expanded_sql(pStmt);
4927        break;
4928      }
4929#ifdef SQLITE_ENABLE_NORMALIZE
4930      case SHELL_TRACE_NORMALIZED: {
4931        zSql = sqlite3_normalized_sql(pStmt);
4932        break;
4933      }
4934#endif
4935      default: {
4936        zSql = sqlite3_sql(pStmt);
4937        break;
4938      }
4939    }
4940  }
4941  if( zSql==0 ) return 0;
4942  nSql = strlen30(zSql);
4943  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4944  switch( mType ){
4945    case SQLITE_TRACE_ROW:
4946    case SQLITE_TRACE_STMT: {
4947      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4948      break;
4949    }
4950    case SQLITE_TRACE_PROFILE: {
4951      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4952      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4953      break;
4954    }
4955  }
4956  return 0;
4957}
4958#endif
4959
4960/*
4961** A no-op routine that runs with the ".breakpoint" doc-command.  This is
4962** a useful spot to set a debugger breakpoint.
4963*/
4964static void test_breakpoint(void){
4965  static int nCall = 0;
4966  nCall++;
4967}
4968
4969/*
4970** An object used to read a CSV and other files for import.
4971*/
4972typedef struct ImportCtx ImportCtx;
4973struct ImportCtx {
4974  const char *zFile;  /* Name of the input file */
4975  FILE *in;           /* Read the CSV text from this input stream */
4976  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
4977  char *z;            /* Accumulated text for a field */
4978  int n;              /* Number of bytes in z */
4979  int nAlloc;         /* Space allocated for z[] */
4980  int nLine;          /* Current line number */
4981  int nRow;           /* Number of rows imported */
4982  int nErr;           /* Number of errors encountered */
4983  int bNotFirst;      /* True if one or more bytes already read */
4984  int cTerm;          /* Character that terminated the most recent field */
4985  int cColSep;        /* The column separator character.  (Usually ",") */
4986  int cRowSep;        /* The row separator character.  (Usually "\n") */
4987};
4988
4989/* Clean up resourced used by an ImportCtx */
4990static void import_cleanup(ImportCtx *p){
4991  if( p->in!=0 && p->xCloser!=0 ){
4992    p->xCloser(p->in);
4993    p->in = 0;
4994  }
4995  sqlite3_free(p->z);
4996  p->z = 0;
4997}
4998
4999/* Append a single byte to z[] */
5000static void import_append_char(ImportCtx *p, int c){
5001  if( p->n+1>=p->nAlloc ){
5002    p->nAlloc += p->nAlloc + 100;
5003    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5004    if( p->z==0 ) shell_out_of_memory();
5005  }
5006  p->z[p->n++] = (char)c;
5007}
5008
5009/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5010** with the option of having a separator other than ",".
5011**
5012**   +  Input comes from p->in.
5013**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5014**      from sqlite3_malloc64().
5015**   +  Use p->cSep as the column separator.  The default is ",".
5016**   +  Use p->rSep as the row separator.  The default is "\n".
5017**   +  Keep track of the line number in p->nLine.
5018**   +  Store the character that terminates the field in p->cTerm.  Store
5019**      EOF on end-of-file.
5020**   +  Report syntax errors on stderr
5021*/
5022static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5023  int c;
5024  int cSep = p->cColSep;
5025  int rSep = p->cRowSep;
5026  p->n = 0;
5027  c = fgetc(p->in);
5028  if( c==EOF || seenInterrupt ){
5029    p->cTerm = EOF;
5030    return 0;
5031  }
5032  if( c=='"' ){
5033    int pc, ppc;
5034    int startLine = p->nLine;
5035    int cQuote = c;
5036    pc = ppc = 0;
5037    while( 1 ){
5038      c = fgetc(p->in);
5039      if( c==rSep ) p->nLine++;
5040      if( c==cQuote ){
5041        if( pc==cQuote ){
5042          pc = 0;
5043          continue;
5044        }
5045      }
5046      if( (c==cSep && pc==cQuote)
5047       || (c==rSep && pc==cQuote)
5048       || (c==rSep && pc=='\r' && ppc==cQuote)
5049       || (c==EOF && pc==cQuote)
5050      ){
5051        do{ p->n--; }while( p->z[p->n]!=cQuote );
5052        p->cTerm = c;
5053        break;
5054      }
5055      if( pc==cQuote && c!='\r' ){
5056        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5057                p->zFile, p->nLine, cQuote);
5058      }
5059      if( c==EOF ){
5060        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5061                p->zFile, startLine, cQuote);
5062        p->cTerm = c;
5063        break;
5064      }
5065      import_append_char(p, c);
5066      ppc = pc;
5067      pc = c;
5068    }
5069  }else{
5070    /* If this is the first field being parsed and it begins with the
5071    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5072    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5073      import_append_char(p, c);
5074      c = fgetc(p->in);
5075      if( (c&0xff)==0xbb ){
5076        import_append_char(p, c);
5077        c = fgetc(p->in);
5078        if( (c&0xff)==0xbf ){
5079          p->bNotFirst = 1;
5080          p->n = 0;
5081          return csv_read_one_field(p);
5082        }
5083      }
5084    }
5085    while( c!=EOF && c!=cSep && c!=rSep ){
5086      import_append_char(p, c);
5087      c = fgetc(p->in);
5088    }
5089    if( c==rSep ){
5090      p->nLine++;
5091      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5092    }
5093    p->cTerm = c;
5094  }
5095  if( p->z ) p->z[p->n] = 0;
5096  p->bNotFirst = 1;
5097  return p->z;
5098}
5099
5100/* Read a single field of ASCII delimited text.
5101**
5102**   +  Input comes from p->in.
5103**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5104**      from sqlite3_malloc64().
5105**   +  Use p->cSep as the column separator.  The default is "\x1F".
5106**   +  Use p->rSep as the row separator.  The default is "\x1E".
5107**   +  Keep track of the row number in p->nLine.
5108**   +  Store the character that terminates the field in p->cTerm.  Store
5109**      EOF on end-of-file.
5110**   +  Report syntax errors on stderr
5111*/
5112static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5113  int c;
5114  int cSep = p->cColSep;
5115  int rSep = p->cRowSep;
5116  p->n = 0;
5117  c = fgetc(p->in);
5118  if( c==EOF || seenInterrupt ){
5119    p->cTerm = EOF;
5120    return 0;
5121  }
5122  while( c!=EOF && c!=cSep && c!=rSep ){
5123    import_append_char(p, c);
5124    c = fgetc(p->in);
5125  }
5126  if( c==rSep ){
5127    p->nLine++;
5128  }
5129  p->cTerm = c;
5130  if( p->z ) p->z[p->n] = 0;
5131  return p->z;
5132}
5133
5134/*
5135** Try to transfer data for table zTable.  If an error is seen while
5136** moving forward, try to go backwards.  The backwards movement won't
5137** work for WITHOUT ROWID tables.
5138*/
5139static void tryToCloneData(
5140  ShellState *p,
5141  sqlite3 *newDb,
5142  const char *zTable
5143){
5144  sqlite3_stmt *pQuery = 0;
5145  sqlite3_stmt *pInsert = 0;
5146  char *zQuery = 0;
5147  char *zInsert = 0;
5148  int rc;
5149  int i, j, n;
5150  int nTable = strlen30(zTable);
5151  int k = 0;
5152  int cnt = 0;
5153  const int spinRate = 10000;
5154
5155  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5156  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5157  if( rc ){
5158    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5159            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5160            zQuery);
5161    goto end_data_xfer;
5162  }
5163  n = sqlite3_column_count(pQuery);
5164  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5165  if( zInsert==0 ) shell_out_of_memory();
5166  sqlite3_snprintf(200+nTable,zInsert,
5167                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5168  i = strlen30(zInsert);
5169  for(j=1; j<n; j++){
5170    memcpy(zInsert+i, ",?", 2);
5171    i += 2;
5172  }
5173  memcpy(zInsert+i, ");", 3);
5174  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5175  if( rc ){
5176    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5177            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5178            zQuery);
5179    goto end_data_xfer;
5180  }
5181  for(k=0; k<2; k++){
5182    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5183      for(i=0; i<n; i++){
5184        switch( sqlite3_column_type(pQuery, i) ){
5185          case SQLITE_NULL: {
5186            sqlite3_bind_null(pInsert, i+1);
5187            break;
5188          }
5189          case SQLITE_INTEGER: {
5190            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5191            break;
5192          }
5193          case SQLITE_FLOAT: {
5194            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5195            break;
5196          }
5197          case SQLITE_TEXT: {
5198            sqlite3_bind_text(pInsert, i+1,
5199                             (const char*)sqlite3_column_text(pQuery,i),
5200                             -1, SQLITE_STATIC);
5201            break;
5202          }
5203          case SQLITE_BLOB: {
5204            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5205                                            sqlite3_column_bytes(pQuery,i),
5206                                            SQLITE_STATIC);
5207            break;
5208          }
5209        }
5210      } /* End for */
5211      rc = sqlite3_step(pInsert);
5212      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5213        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5214                        sqlite3_errmsg(newDb));
5215      }
5216      sqlite3_reset(pInsert);
5217      cnt++;
5218      if( (cnt%spinRate)==0 ){
5219        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5220        fflush(stdout);
5221      }
5222    } /* End while */
5223    if( rc==SQLITE_DONE ) break;
5224    sqlite3_finalize(pQuery);
5225    sqlite3_free(zQuery);
5226    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5227                             zTable);
5228    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5229    if( rc ){
5230      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5231      break;
5232    }
5233  } /* End for(k=0...) */
5234
5235end_data_xfer:
5236  sqlite3_finalize(pQuery);
5237  sqlite3_finalize(pInsert);
5238  sqlite3_free(zQuery);
5239  sqlite3_free(zInsert);
5240}
5241
5242
5243/*
5244** Try to transfer all rows of the schema that match zWhere.  For
5245** each row, invoke xForEach() on the object defined by that row.
5246** If an error is encountered while moving forward through the
5247** sqlite_schema table, try again moving backwards.
5248*/
5249static void tryToCloneSchema(
5250  ShellState *p,
5251  sqlite3 *newDb,
5252  const char *zWhere,
5253  void (*xForEach)(ShellState*,sqlite3*,const char*)
5254){
5255  sqlite3_stmt *pQuery = 0;
5256  char *zQuery = 0;
5257  int rc;
5258  const unsigned char *zName;
5259  const unsigned char *zSql;
5260  char *zErrMsg = 0;
5261
5262  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5263                           " WHERE %s", zWhere);
5264  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5265  if( rc ){
5266    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5267                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5268                    zQuery);
5269    goto end_schema_xfer;
5270  }
5271  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5272    zName = sqlite3_column_text(pQuery, 0);
5273    zSql = sqlite3_column_text(pQuery, 1);
5274    printf("%s... ", zName); fflush(stdout);
5275    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5276    if( zErrMsg ){
5277      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5278      sqlite3_free(zErrMsg);
5279      zErrMsg = 0;
5280    }
5281    if( xForEach ){
5282      xForEach(p, newDb, (const char*)zName);
5283    }
5284    printf("done\n");
5285  }
5286  if( rc!=SQLITE_DONE ){
5287    sqlite3_finalize(pQuery);
5288    sqlite3_free(zQuery);
5289    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5290                             " WHERE %s ORDER BY rowid DESC", zWhere);
5291    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5292    if( rc ){
5293      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5294                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5295                      zQuery);
5296      goto end_schema_xfer;
5297    }
5298    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5299      zName = sqlite3_column_text(pQuery, 0);
5300      zSql = sqlite3_column_text(pQuery, 1);
5301      printf("%s... ", zName); fflush(stdout);
5302      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5303      if( zErrMsg ){
5304        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5305        sqlite3_free(zErrMsg);
5306        zErrMsg = 0;
5307      }
5308      if( xForEach ){
5309        xForEach(p, newDb, (const char*)zName);
5310      }
5311      printf("done\n");
5312    }
5313  }
5314end_schema_xfer:
5315  sqlite3_finalize(pQuery);
5316  sqlite3_free(zQuery);
5317}
5318
5319/*
5320** Open a new database file named "zNewDb".  Try to recover as much information
5321** as possible out of the main database (which might be corrupt) and write it
5322** into zNewDb.
5323*/
5324static void tryToClone(ShellState *p, const char *zNewDb){
5325  int rc;
5326  sqlite3 *newDb = 0;
5327  if( access(zNewDb,0)==0 ){
5328    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5329    return;
5330  }
5331  rc = sqlite3_open(zNewDb, &newDb);
5332  if( rc ){
5333    utf8_printf(stderr, "Cannot create output database: %s\n",
5334            sqlite3_errmsg(newDb));
5335  }else{
5336    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5337    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5338    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5339    tryToCloneSchema(p, newDb, "type!='table'", 0);
5340    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5341    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5342  }
5343  close_db(newDb);
5344}
5345
5346/*
5347** Change the output file back to stdout.
5348**
5349** If the p->doXdgOpen flag is set, that means the output was being
5350** redirected to a temporary file named by p->zTempFile.  In that case,
5351** launch start/open/xdg-open on that temporary file.
5352*/
5353static void output_reset(ShellState *p){
5354  if( p->outfile[0]=='|' ){
5355#ifndef SQLITE_OMIT_POPEN
5356    pclose(p->out);
5357#endif
5358  }else{
5359    output_file_close(p->out);
5360#ifndef SQLITE_NOHAVE_SYSTEM
5361    if( p->doXdgOpen ){
5362      const char *zXdgOpenCmd =
5363#if defined(_WIN32)
5364      "start";
5365#elif defined(__APPLE__)
5366      "open";
5367#else
5368      "xdg-open";
5369#endif
5370      char *zCmd;
5371      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5372      if( system(zCmd) ){
5373        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5374      }else{
5375        /* Give the start/open/xdg-open command some time to get
5376        ** going before we continue, and potential delete the
5377        ** p->zTempFile data file out from under it */
5378        sqlite3_sleep(2000);
5379      }
5380      sqlite3_free(zCmd);
5381      outputModePop(p);
5382      p->doXdgOpen = 0;
5383    }
5384#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5385  }
5386  p->outfile[0] = 0;
5387  p->out = stdout;
5388}
5389
5390/*
5391** Run an SQL command and return the single integer result.
5392*/
5393static int db_int(ShellState *p, const char *zSql){
5394  sqlite3_stmt *pStmt;
5395  int res = 0;
5396  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5397  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5398    res = sqlite3_column_int(pStmt,0);
5399  }
5400  sqlite3_finalize(pStmt);
5401  return res;
5402}
5403
5404/*
5405** Convert a 2-byte or 4-byte big-endian integer into a native integer
5406*/
5407static unsigned int get2byteInt(unsigned char *a){
5408  return (a[0]<<8) + a[1];
5409}
5410static unsigned int get4byteInt(unsigned char *a){
5411  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5412}
5413
5414/*
5415** Implementation of the ".dbinfo" command.
5416**
5417** Return 1 on error, 2 to exit, and 0 otherwise.
5418*/
5419static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5420  static const struct { const char *zName; int ofst; } aField[] = {
5421     { "file change counter:",  24  },
5422     { "database page count:",  28  },
5423     { "freelist page count:",  36  },
5424     { "schema cookie:",        40  },
5425     { "schema format:",        44  },
5426     { "default cache size:",   48  },
5427     { "autovacuum top root:",  52  },
5428     { "incremental vacuum:",   64  },
5429     { "text encoding:",        56  },
5430     { "user version:",         60  },
5431     { "application id:",       68  },
5432     { "software version:",     96  },
5433  };
5434  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5435     { "number of tables:",
5436       "SELECT count(*) FROM %s WHERE type='table'" },
5437     { "number of indexes:",
5438       "SELECT count(*) FROM %s WHERE type='index'" },
5439     { "number of triggers:",
5440       "SELECT count(*) FROM %s WHERE type='trigger'" },
5441     { "number of views:",
5442       "SELECT count(*) FROM %s WHERE type='view'" },
5443     { "schema size:",
5444       "SELECT total(length(sql)) FROM %s" },
5445  };
5446  int i, rc;
5447  unsigned iDataVersion;
5448  char *zSchemaTab;
5449  char *zDb = nArg>=2 ? azArg[1] : "main";
5450  sqlite3_stmt *pStmt = 0;
5451  unsigned char aHdr[100];
5452  open_db(p, 0);
5453  if( p->db==0 ) return 1;
5454  rc = sqlite3_prepare_v2(p->db,
5455             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5456             -1, &pStmt, 0);
5457  if( rc ){
5458    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5459    sqlite3_finalize(pStmt);
5460    return 1;
5461  }
5462  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5463  if( sqlite3_step(pStmt)==SQLITE_ROW
5464   && sqlite3_column_bytes(pStmt,0)>100
5465  ){
5466    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5467    sqlite3_finalize(pStmt);
5468  }else{
5469    raw_printf(stderr, "unable to read database header\n");
5470    sqlite3_finalize(pStmt);
5471    return 1;
5472  }
5473  i = get2byteInt(aHdr+16);
5474  if( i==1 ) i = 65536;
5475  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5476  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5477  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5478  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5479  for(i=0; i<ArraySize(aField); i++){
5480    int ofst = aField[i].ofst;
5481    unsigned int val = get4byteInt(aHdr + ofst);
5482    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5483    switch( ofst ){
5484      case 56: {
5485        if( val==1 ) raw_printf(p->out, " (utf8)");
5486        if( val==2 ) raw_printf(p->out, " (utf16le)");
5487        if( val==3 ) raw_printf(p->out, " (utf16be)");
5488      }
5489    }
5490    raw_printf(p->out, "\n");
5491  }
5492  if( zDb==0 ){
5493    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5494  }else if( strcmp(zDb,"temp")==0 ){
5495    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5496  }else{
5497    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5498  }
5499  for(i=0; i<ArraySize(aQuery); i++){
5500    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5501    int val = db_int(p, zSql);
5502    sqlite3_free(zSql);
5503    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5504  }
5505  sqlite3_free(zSchemaTab);
5506  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5507  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5508  return 0;
5509}
5510
5511/*
5512** Print the current sqlite3_errmsg() value to stderr and return 1.
5513*/
5514static int shellDatabaseError(sqlite3 *db){
5515  const char *zErr = sqlite3_errmsg(db);
5516  utf8_printf(stderr, "Error: %s\n", zErr);
5517  return 1;
5518}
5519
5520/*
5521** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5522** if they match and FALSE (0) if they do not match.
5523**
5524** Globbing rules:
5525**
5526**      '*'       Matches any sequence of zero or more characters.
5527**
5528**      '?'       Matches exactly one character.
5529**
5530**     [...]      Matches one character from the enclosed list of
5531**                characters.
5532**
5533**     [^...]     Matches one character not in the enclosed list.
5534**
5535**      '#'       Matches any sequence of one or more digits with an
5536**                optional + or - sign in front
5537**
5538**      ' '       Any span of whitespace matches any other span of
5539**                whitespace.
5540**
5541** Extra whitespace at the end of z[] is ignored.
5542*/
5543static int testcase_glob(const char *zGlob, const char *z){
5544  int c, c2;
5545  int invert;
5546  int seen;
5547
5548  while( (c = (*(zGlob++)))!=0 ){
5549    if( IsSpace(c) ){
5550      if( !IsSpace(*z) ) return 0;
5551      while( IsSpace(*zGlob) ) zGlob++;
5552      while( IsSpace(*z) ) z++;
5553    }else if( c=='*' ){
5554      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5555        if( c=='?' && (*(z++))==0 ) return 0;
5556      }
5557      if( c==0 ){
5558        return 1;
5559      }else if( c=='[' ){
5560        while( *z && testcase_glob(zGlob-1,z)==0 ){
5561          z++;
5562        }
5563        return (*z)!=0;
5564      }
5565      while( (c2 = (*(z++)))!=0 ){
5566        while( c2!=c ){
5567          c2 = *(z++);
5568          if( c2==0 ) return 0;
5569        }
5570        if( testcase_glob(zGlob,z) ) return 1;
5571      }
5572      return 0;
5573    }else if( c=='?' ){
5574      if( (*(z++))==0 ) return 0;
5575    }else if( c=='[' ){
5576      int prior_c = 0;
5577      seen = 0;
5578      invert = 0;
5579      c = *(z++);
5580      if( c==0 ) return 0;
5581      c2 = *(zGlob++);
5582      if( c2=='^' ){
5583        invert = 1;
5584        c2 = *(zGlob++);
5585      }
5586      if( c2==']' ){
5587        if( c==']' ) seen = 1;
5588        c2 = *(zGlob++);
5589      }
5590      while( c2 && c2!=']' ){
5591        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5592          c2 = *(zGlob++);
5593          if( c>=prior_c && c<=c2 ) seen = 1;
5594          prior_c = 0;
5595        }else{
5596          if( c==c2 ){
5597            seen = 1;
5598          }
5599          prior_c = c2;
5600        }
5601        c2 = *(zGlob++);
5602      }
5603      if( c2==0 || (seen ^ invert)==0 ) return 0;
5604    }else if( c=='#' ){
5605      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5606      if( !IsDigit(z[0]) ) return 0;
5607      z++;
5608      while( IsDigit(z[0]) ){ z++; }
5609    }else{
5610      if( c!=(*(z++)) ) return 0;
5611    }
5612  }
5613  while( IsSpace(*z) ){ z++; }
5614  return *z==0;
5615}
5616
5617
5618/*
5619** Compare the string as a command-line option with either one or two
5620** initial "-" characters.
5621*/
5622static int optionMatch(const char *zStr, const char *zOpt){
5623  if( zStr[0]!='-' ) return 0;
5624  zStr++;
5625  if( zStr[0]=='-' ) zStr++;
5626  return strcmp(zStr, zOpt)==0;
5627}
5628
5629/*
5630** Delete a file.
5631*/
5632int shellDeleteFile(const char *zFilename){
5633  int rc;
5634#ifdef _WIN32
5635  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5636  rc = _wunlink(z);
5637  sqlite3_free(z);
5638#else
5639  rc = unlink(zFilename);
5640#endif
5641  return rc;
5642}
5643
5644/*
5645** Try to delete the temporary file (if there is one) and free the
5646** memory used to hold the name of the temp file.
5647*/
5648static void clearTempFile(ShellState *p){
5649  if( p->zTempFile==0 ) return;
5650  if( p->doXdgOpen ) return;
5651  if( shellDeleteFile(p->zTempFile) ) return;
5652  sqlite3_free(p->zTempFile);
5653  p->zTempFile = 0;
5654}
5655
5656/*
5657** Create a new temp file name with the given suffix.
5658*/
5659static void newTempFile(ShellState *p, const char *zSuffix){
5660  clearTempFile(p);
5661  sqlite3_free(p->zTempFile);
5662  p->zTempFile = 0;
5663  if( p->db ){
5664    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5665  }
5666  if( p->zTempFile==0 ){
5667    /* If p->db is an in-memory database then the TEMPFILENAME file-control
5668    ** will not work and we will need to fallback to guessing */
5669    char *zTemp;
5670    sqlite3_uint64 r;
5671    sqlite3_randomness(sizeof(r), &r);
5672    zTemp = getenv("TEMP");
5673    if( zTemp==0 ) zTemp = getenv("TMP");
5674    if( zTemp==0 ){
5675#ifdef _WIN32
5676      zTemp = "\\tmp";
5677#else
5678      zTemp = "/tmp";
5679#endif
5680    }
5681    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
5682  }else{
5683    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5684  }
5685  if( p->zTempFile==0 ){
5686    raw_printf(stderr, "out of memory\n");
5687    exit(1);
5688  }
5689}
5690
5691
5692/*
5693** The implementation of SQL scalar function fkey_collate_clause(), used
5694** by the ".lint fkey-indexes" command. This scalar function is always
5695** called with four arguments - the parent table name, the parent column name,
5696** the child table name and the child column name.
5697**
5698**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5699**
5700** If either of the named tables or columns do not exist, this function
5701** returns an empty string. An empty string is also returned if both tables
5702** and columns exist but have the same default collation sequence. Or,
5703** if both exist but the default collation sequences are different, this
5704** function returns the string " COLLATE <parent-collation>", where
5705** <parent-collation> is the default collation sequence of the parent column.
5706*/
5707static void shellFkeyCollateClause(
5708  sqlite3_context *pCtx,
5709  int nVal,
5710  sqlite3_value **apVal
5711){
5712  sqlite3 *db = sqlite3_context_db_handle(pCtx);
5713  const char *zParent;
5714  const char *zParentCol;
5715  const char *zParentSeq;
5716  const char *zChild;
5717  const char *zChildCol;
5718  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
5719  int rc;
5720
5721  assert( nVal==4 );
5722  zParent = (const char*)sqlite3_value_text(apVal[0]);
5723  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5724  zChild = (const char*)sqlite3_value_text(apVal[2]);
5725  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5726
5727  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5728  rc = sqlite3_table_column_metadata(
5729      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5730  );
5731  if( rc==SQLITE_OK ){
5732    rc = sqlite3_table_column_metadata(
5733        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5734    );
5735  }
5736
5737  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5738    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5739    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5740    sqlite3_free(z);
5741  }
5742}
5743
5744
5745/*
5746** The implementation of dot-command ".lint fkey-indexes".
5747*/
5748static int lintFkeyIndexes(
5749  ShellState *pState,             /* Current shell tool state */
5750  char **azArg,                   /* Array of arguments passed to dot command */
5751  int nArg                        /* Number of entries in azArg[] */
5752){
5753  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
5754  FILE *out = pState->out;        /* Stream to write non-error output to */
5755  int bVerbose = 0;               /* If -verbose is present */
5756  int bGroupByParent = 0;         /* If -groupbyparent is present */
5757  int i;                          /* To iterate through azArg[] */
5758  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
5759  int rc;                         /* Return code */
5760  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
5761
5762  /*
5763  ** This SELECT statement returns one row for each foreign key constraint
5764  ** in the schema of the main database. The column values are:
5765  **
5766  ** 0. The text of an SQL statement similar to:
5767  **
5768  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
5769  **
5770  **    This SELECT is similar to the one that the foreign keys implementation
5771  **    needs to run internally on child tables. If there is an index that can
5772  **    be used to optimize this query, then it can also be used by the FK
5773  **    implementation to optimize DELETE or UPDATE statements on the parent
5774  **    table.
5775  **
5776  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5777  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5778  **    contains an index that can be used to optimize the query.
5779  **
5780  ** 2. Human readable text that describes the child table and columns. e.g.
5781  **
5782  **       "child_table(child_key1, child_key2)"
5783  **
5784  ** 3. Human readable text that describes the parent table and columns. e.g.
5785  **
5786  **       "parent_table(parent_key1, parent_key2)"
5787  **
5788  ** 4. A full CREATE INDEX statement for an index that could be used to
5789  **    optimize DELETE or UPDATE statements on the parent table. e.g.
5790  **
5791  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
5792  **
5793  ** 5. The name of the parent table.
5794  **
5795  ** These six values are used by the C logic below to generate the report.
5796  */
5797  const char *zSql =
5798  "SELECT "
5799    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
5800    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5801    "  || fkey_collate_clause("
5802    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5803    ", "
5804    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
5805    "  || group_concat('*=?', ' AND ') || ')'"
5806    ", "
5807    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
5808    ", "
5809    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5810    ", "
5811    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5812    "  || ' ON ' || quote(s.name) || '('"
5813    "  || group_concat(quote(f.[from]) ||"
5814    "        fkey_collate_clause("
5815    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5816    "  || ');'"
5817    ", "
5818    "     f.[table] "
5819    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
5820    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5821    "GROUP BY s.name, f.id "
5822    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5823  ;
5824  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
5825
5826  for(i=2; i<nArg; i++){
5827    int n = strlen30(azArg[i]);
5828    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5829      bVerbose = 1;
5830    }
5831    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5832      bGroupByParent = 1;
5833      zIndent = "    ";
5834    }
5835    else{
5836      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5837          azArg[0], azArg[1]
5838      );
5839      return SQLITE_ERROR;
5840    }
5841  }
5842
5843  /* Register the fkey_collate_clause() SQL function */
5844  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5845      0, shellFkeyCollateClause, 0, 0
5846  );
5847
5848
5849  if( rc==SQLITE_OK ){
5850    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5851  }
5852  if( rc==SQLITE_OK ){
5853    sqlite3_bind_int(pSql, 1, bGroupByParent);
5854  }
5855
5856  if( rc==SQLITE_OK ){
5857    int rc2;
5858    char *zPrev = 0;
5859    while( SQLITE_ROW==sqlite3_step(pSql) ){
5860      int res = -1;
5861      sqlite3_stmt *pExplain = 0;
5862      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5863      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5864      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5865      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5866      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5867      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5868
5869      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5870      if( rc!=SQLITE_OK ) break;
5871      if( SQLITE_ROW==sqlite3_step(pExplain) ){
5872        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5873        res = (
5874              0==sqlite3_strglob(zGlob, zPlan)
5875           || 0==sqlite3_strglob(zGlobIPK, zPlan)
5876        );
5877      }
5878      rc = sqlite3_finalize(pExplain);
5879      if( rc!=SQLITE_OK ) break;
5880
5881      if( res<0 ){
5882        raw_printf(stderr, "Error: internal error");
5883        break;
5884      }else{
5885        if( bGroupByParent
5886        && (bVerbose || res==0)
5887        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5888        ){
5889          raw_printf(out, "-- Parent table %s\n", zParent);
5890          sqlite3_free(zPrev);
5891          zPrev = sqlite3_mprintf("%s", zParent);
5892        }
5893
5894        if( res==0 ){
5895          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5896        }else if( bVerbose ){
5897          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5898              zIndent, zFrom, zTarget
5899          );
5900        }
5901      }
5902    }
5903    sqlite3_free(zPrev);
5904
5905    if( rc!=SQLITE_OK ){
5906      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5907    }
5908
5909    rc2 = sqlite3_finalize(pSql);
5910    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5911      rc = rc2;
5912      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5913    }
5914  }else{
5915    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5916  }
5917
5918  return rc;
5919}
5920
5921/*
5922** Implementation of ".lint" dot command.
5923*/
5924static int lintDotCommand(
5925  ShellState *pState,             /* Current shell tool state */
5926  char **azArg,                   /* Array of arguments passed to dot command */
5927  int nArg                        /* Number of entries in azArg[] */
5928){
5929  int n;
5930  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
5931  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5932  return lintFkeyIndexes(pState, azArg, nArg);
5933
5934 usage:
5935  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5936  raw_printf(stderr, "Where sub-commands are:\n");
5937  raw_printf(stderr, "    fkey-indexes\n");
5938  return SQLITE_ERROR;
5939}
5940
5941#if !defined SQLITE_OMIT_VIRTUALTABLE
5942static void shellPrepare(
5943  sqlite3 *db,
5944  int *pRc,
5945  const char *zSql,
5946  sqlite3_stmt **ppStmt
5947){
5948  *ppStmt = 0;
5949  if( *pRc==SQLITE_OK ){
5950    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
5951    if( rc!=SQLITE_OK ){
5952      raw_printf(stderr, "sql error: %s (%d)\n",
5953          sqlite3_errmsg(db), sqlite3_errcode(db)
5954      );
5955      *pRc = rc;
5956    }
5957  }
5958}
5959
5960/*
5961** Create a prepared statement using printf-style arguments for the SQL.
5962**
5963** This routine is could be marked "static".  But it is not always used,
5964** depending on compile-time options.  By omitting the "static", we avoid
5965** nuisance compiler warnings about "defined but not used".
5966*/
5967void shellPreparePrintf(
5968  sqlite3 *db,
5969  int *pRc,
5970  sqlite3_stmt **ppStmt,
5971  const char *zFmt,
5972  ...
5973){
5974  *ppStmt = 0;
5975  if( *pRc==SQLITE_OK ){
5976    va_list ap;
5977    char *z;
5978    va_start(ap, zFmt);
5979    z = sqlite3_vmprintf(zFmt, ap);
5980    va_end(ap);
5981    if( z==0 ){
5982      *pRc = SQLITE_NOMEM;
5983    }else{
5984      shellPrepare(db, pRc, z, ppStmt);
5985      sqlite3_free(z);
5986    }
5987  }
5988}
5989
5990/* Finalize the prepared statement created using shellPreparePrintf().
5991**
5992** This routine is could be marked "static".  But it is not always used,
5993** depending on compile-time options.  By omitting the "static", we avoid
5994** nuisance compiler warnings about "defined but not used".
5995*/
5996void shellFinalize(
5997  int *pRc,
5998  sqlite3_stmt *pStmt
5999){
6000  if( pStmt ){
6001    sqlite3 *db = sqlite3_db_handle(pStmt);
6002    int rc = sqlite3_finalize(pStmt);
6003    if( *pRc==SQLITE_OK ){
6004      if( rc!=SQLITE_OK ){
6005        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6006      }
6007      *pRc = rc;
6008    }
6009  }
6010}
6011
6012/* Reset the prepared statement created using shellPreparePrintf().
6013**
6014** This routine is could be marked "static".  But it is not always used,
6015** depending on compile-time options.  By omitting the "static", we avoid
6016** nuisance compiler warnings about "defined but not used".
6017*/
6018void shellReset(
6019  int *pRc,
6020  sqlite3_stmt *pStmt
6021){
6022  int rc = sqlite3_reset(pStmt);
6023  if( *pRc==SQLITE_OK ){
6024    if( rc!=SQLITE_OK ){
6025      sqlite3 *db = sqlite3_db_handle(pStmt);
6026      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6027    }
6028    *pRc = rc;
6029  }
6030}
6031#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6032
6033#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6034/******************************************************************************
6035** The ".archive" or ".ar" command.
6036*/
6037/*
6038** Structure representing a single ".ar" command.
6039*/
6040typedef struct ArCommand ArCommand;
6041struct ArCommand {
6042  u8 eCmd;                        /* An AR_CMD_* value */
6043  u8 bVerbose;                    /* True if --verbose */
6044  u8 bZip;                        /* True if the archive is a ZIP */
6045  u8 bDryRun;                     /* True if --dry-run */
6046  u8 bAppend;                     /* True if --append */
6047  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6048  int nArg;                       /* Number of command arguments */
6049  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6050  const char *zFile;              /* --file argument, or NULL */
6051  const char *zDir;               /* --directory argument, or NULL */
6052  char **azArg;                   /* Array of command arguments */
6053  ShellState *p;                  /* Shell state */
6054  sqlite3 *db;                    /* Database containing the archive */
6055};
6056
6057/*
6058** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6059*/
6060static int arUsage(FILE *f){
6061  showHelp(f,"archive");
6062  return SQLITE_ERROR;
6063}
6064
6065/*
6066** Print an error message for the .ar command to stderr and return
6067** SQLITE_ERROR.
6068*/
6069static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6070  va_list ap;
6071  char *z;
6072  va_start(ap, zFmt);
6073  z = sqlite3_vmprintf(zFmt, ap);
6074  va_end(ap);
6075  utf8_printf(stderr, "Error: %s\n", z);
6076  if( pAr->fromCmdLine ){
6077    utf8_printf(stderr, "Use \"-A\" for more help\n");
6078  }else{
6079    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6080  }
6081  sqlite3_free(z);
6082  return SQLITE_ERROR;
6083}
6084
6085/*
6086** Values for ArCommand.eCmd.
6087*/
6088#define AR_CMD_CREATE       1
6089#define AR_CMD_UPDATE       2
6090#define AR_CMD_INSERT       3
6091#define AR_CMD_EXTRACT      4
6092#define AR_CMD_LIST         5
6093#define AR_CMD_HELP         6
6094
6095/*
6096** Other (non-command) switches.
6097*/
6098#define AR_SWITCH_VERBOSE     7
6099#define AR_SWITCH_FILE        8
6100#define AR_SWITCH_DIRECTORY   9
6101#define AR_SWITCH_APPEND     10
6102#define AR_SWITCH_DRYRUN     11
6103
6104static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6105  switch( eSwitch ){
6106    case AR_CMD_CREATE:
6107    case AR_CMD_EXTRACT:
6108    case AR_CMD_LIST:
6109    case AR_CMD_UPDATE:
6110    case AR_CMD_INSERT:
6111    case AR_CMD_HELP:
6112      if( pAr->eCmd ){
6113        return arErrorMsg(pAr, "multiple command options");
6114      }
6115      pAr->eCmd = eSwitch;
6116      break;
6117
6118    case AR_SWITCH_DRYRUN:
6119      pAr->bDryRun = 1;
6120      break;
6121    case AR_SWITCH_VERBOSE:
6122      pAr->bVerbose = 1;
6123      break;
6124    case AR_SWITCH_APPEND:
6125      pAr->bAppend = 1;
6126      /* Fall thru into --file */
6127    case AR_SWITCH_FILE:
6128      pAr->zFile = zArg;
6129      break;
6130    case AR_SWITCH_DIRECTORY:
6131      pAr->zDir = zArg;
6132      break;
6133  }
6134
6135  return SQLITE_OK;
6136}
6137
6138/*
6139** Parse the command line for an ".ar" command. The results are written into
6140** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6141** successfully, otherwise an error message is written to stderr and
6142** SQLITE_ERROR returned.
6143*/
6144static int arParseCommand(
6145  char **azArg,                   /* Array of arguments passed to dot command */
6146  int nArg,                       /* Number of entries in azArg[] */
6147  ArCommand *pAr                  /* Populate this object */
6148){
6149  struct ArSwitch {
6150    const char *zLong;
6151    char cShort;
6152    u8 eSwitch;
6153    u8 bArg;
6154  } aSwitch[] = {
6155    { "create",    'c', AR_CMD_CREATE,       0 },
6156    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6157    { "insert",    'i', AR_CMD_INSERT,       0 },
6158    { "list",      't', AR_CMD_LIST,         0 },
6159    { "update",    'u', AR_CMD_UPDATE,       0 },
6160    { "help",      'h', AR_CMD_HELP,         0 },
6161    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6162    { "file",      'f', AR_SWITCH_FILE,      1 },
6163    { "append",    'a', AR_SWITCH_APPEND,    1 },
6164    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6165    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6166  };
6167  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6168  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6169
6170  if( nArg<=1 ){
6171    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6172    return arUsage(stderr);
6173  }else{
6174    char *z = azArg[1];
6175    if( z[0]!='-' ){
6176      /* Traditional style [tar] invocation */
6177      int i;
6178      int iArg = 2;
6179      for(i=0; z[i]; i++){
6180        const char *zArg = 0;
6181        struct ArSwitch *pOpt;
6182        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6183          if( z[i]==pOpt->cShort ) break;
6184        }
6185        if( pOpt==pEnd ){
6186          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6187        }
6188        if( pOpt->bArg ){
6189          if( iArg>=nArg ){
6190            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6191          }
6192          zArg = azArg[iArg++];
6193        }
6194        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6195      }
6196      pAr->nArg = nArg-iArg;
6197      if( pAr->nArg>0 ){
6198        pAr->azArg = &azArg[iArg];
6199      }
6200    }else{
6201      /* Non-traditional invocation */
6202      int iArg;
6203      for(iArg=1; iArg<nArg; iArg++){
6204        int n;
6205        z = azArg[iArg];
6206        if( z[0]!='-' ){
6207          /* All remaining command line words are command arguments. */
6208          pAr->azArg = &azArg[iArg];
6209          pAr->nArg = nArg-iArg;
6210          break;
6211        }
6212        n = strlen30(z);
6213
6214        if( z[1]!='-' ){
6215          int i;
6216          /* One or more short options */
6217          for(i=1; i<n; i++){
6218            const char *zArg = 0;
6219            struct ArSwitch *pOpt;
6220            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6221              if( z[i]==pOpt->cShort ) break;
6222            }
6223            if( pOpt==pEnd ){
6224              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6225            }
6226            if( pOpt->bArg ){
6227              if( i<(n-1) ){
6228                zArg = &z[i+1];
6229                i = n;
6230              }else{
6231                if( iArg>=(nArg-1) ){
6232                  return arErrorMsg(pAr, "option requires an argument: %c",
6233                                    z[i]);
6234                }
6235                zArg = azArg[++iArg];
6236              }
6237            }
6238            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6239          }
6240        }else if( z[2]=='\0' ){
6241          /* A -- option, indicating that all remaining command line words
6242          ** are command arguments.  */
6243          pAr->azArg = &azArg[iArg+1];
6244          pAr->nArg = nArg-iArg-1;
6245          break;
6246        }else{
6247          /* A long option */
6248          const char *zArg = 0;             /* Argument for option, if any */
6249          struct ArSwitch *pMatch = 0;      /* Matching option */
6250          struct ArSwitch *pOpt;            /* Iterator */
6251          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6252            const char *zLong = pOpt->zLong;
6253            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6254              if( pMatch ){
6255                return arErrorMsg(pAr, "ambiguous option: %s",z);
6256              }else{
6257                pMatch = pOpt;
6258              }
6259            }
6260          }
6261
6262          if( pMatch==0 ){
6263            return arErrorMsg(pAr, "unrecognized option: %s", z);
6264          }
6265          if( pMatch->bArg ){
6266            if( iArg>=(nArg-1) ){
6267              return arErrorMsg(pAr, "option requires an argument: %s", z);
6268            }
6269            zArg = azArg[++iArg];
6270          }
6271          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6272        }
6273      }
6274    }
6275  }
6276
6277  return SQLITE_OK;
6278}
6279
6280/*
6281** This function assumes that all arguments within the ArCommand.azArg[]
6282** array refer to archive members, as for the --extract or --list commands.
6283** It checks that each of them are present. If any specified file is not
6284** present in the archive, an error is printed to stderr and an error
6285** code returned. Otherwise, if all specified arguments are present in
6286** the archive, SQLITE_OK is returned.
6287**
6288** This function strips any trailing '/' characters from each argument.
6289** This is consistent with the way the [tar] command seems to work on
6290** Linux.
6291*/
6292static int arCheckEntries(ArCommand *pAr){
6293  int rc = SQLITE_OK;
6294  if( pAr->nArg ){
6295    int i, j;
6296    sqlite3_stmt *pTest = 0;
6297
6298    shellPreparePrintf(pAr->db, &rc, &pTest,
6299        "SELECT name FROM %s WHERE name=$name",
6300        pAr->zSrcTable
6301    );
6302    j = sqlite3_bind_parameter_index(pTest, "$name");
6303    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6304      char *z = pAr->azArg[i];
6305      int n = strlen30(z);
6306      int bOk = 0;
6307      while( n>0 && z[n-1]=='/' ) n--;
6308      z[n] = '\0';
6309      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6310      if( SQLITE_ROW==sqlite3_step(pTest) ){
6311        bOk = 1;
6312      }
6313      shellReset(&rc, pTest);
6314      if( rc==SQLITE_OK && bOk==0 ){
6315        utf8_printf(stderr, "not found in archive: %s\n", z);
6316        rc = SQLITE_ERROR;
6317      }
6318    }
6319    shellFinalize(&rc, pTest);
6320  }
6321  return rc;
6322}
6323
6324/*
6325** Format a WHERE clause that can be used against the "sqlar" table to
6326** identify all archive members that match the command arguments held
6327** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6328** The caller is responsible for eventually calling sqlite3_free() on
6329** any non-NULL (*pzWhere) value.
6330*/
6331static void arWhereClause(
6332  int *pRc,
6333  ArCommand *pAr,
6334  char **pzWhere                  /* OUT: New WHERE clause */
6335){
6336  char *zWhere = 0;
6337  if( *pRc==SQLITE_OK ){
6338    if( pAr->nArg==0 ){
6339      zWhere = sqlite3_mprintf("1");
6340    }else{
6341      int i;
6342      const char *zSep = "";
6343      for(i=0; i<pAr->nArg; i++){
6344        const char *z = pAr->azArg[i];
6345        zWhere = sqlite3_mprintf(
6346          "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
6347          zWhere, zSep, z, strlen30(z)+1, z
6348        );
6349        if( zWhere==0 ){
6350          *pRc = SQLITE_NOMEM;
6351          break;
6352        }
6353        zSep = " OR ";
6354      }
6355    }
6356  }
6357  *pzWhere = zWhere;
6358}
6359
6360/*
6361** Implementation of .ar "lisT" command.
6362*/
6363static int arListCommand(ArCommand *pAr){
6364  const char *zSql = "SELECT %s FROM %s WHERE %s";
6365  const char *azCols[] = {
6366    "name",
6367    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6368  };
6369
6370  char *zWhere = 0;
6371  sqlite3_stmt *pSql = 0;
6372  int rc;
6373
6374  rc = arCheckEntries(pAr);
6375  arWhereClause(&rc, pAr, &zWhere);
6376
6377  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6378                     pAr->zSrcTable, zWhere);
6379  if( pAr->bDryRun ){
6380    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6381  }else{
6382    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6383      if( pAr->bVerbose ){
6384        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6385            sqlite3_column_text(pSql, 0),
6386            sqlite3_column_int(pSql, 1),
6387            sqlite3_column_text(pSql, 2),
6388            sqlite3_column_text(pSql, 3)
6389        );
6390      }else{
6391        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6392      }
6393    }
6394  }
6395  shellFinalize(&rc, pSql);
6396  sqlite3_free(zWhere);
6397  return rc;
6398}
6399
6400
6401/*
6402** Implementation of .ar "eXtract" command.
6403*/
6404static int arExtractCommand(ArCommand *pAr){
6405  const char *zSql1 =
6406    "SELECT "
6407    " ($dir || name),"
6408    " writefile(($dir || name), %s, mode, mtime) "
6409    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6410    " AND name NOT GLOB '*..[/\\]*'";
6411
6412  const char *azExtraArg[] = {
6413    "sqlar_uncompress(data, sz)",
6414    "data"
6415  };
6416
6417  sqlite3_stmt *pSql = 0;
6418  int rc = SQLITE_OK;
6419  char *zDir = 0;
6420  char *zWhere = 0;
6421  int i, j;
6422
6423  /* If arguments are specified, check that they actually exist within
6424  ** the archive before proceeding. And formulate a WHERE clause to
6425  ** match them.  */
6426  rc = arCheckEntries(pAr);
6427  arWhereClause(&rc, pAr, &zWhere);
6428
6429  if( rc==SQLITE_OK ){
6430    if( pAr->zDir ){
6431      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6432    }else{
6433      zDir = sqlite3_mprintf("");
6434    }
6435    if( zDir==0 ) rc = SQLITE_NOMEM;
6436  }
6437
6438  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6439      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6440  );
6441
6442  if( rc==SQLITE_OK ){
6443    j = sqlite3_bind_parameter_index(pSql, "$dir");
6444    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6445
6446    /* Run the SELECT statement twice. The first time, writefile() is called
6447    ** for all archive members that should be extracted. The second time,
6448    ** only for the directories. This is because the timestamps for
6449    ** extracted directories must be reset after they are populated (as
6450    ** populating them changes the timestamp).  */
6451    for(i=0; i<2; i++){
6452      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6453      sqlite3_bind_int(pSql, j, i);
6454      if( pAr->bDryRun ){
6455        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6456      }else{
6457        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6458          if( i==0 && pAr->bVerbose ){
6459            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6460          }
6461        }
6462      }
6463      shellReset(&rc, pSql);
6464    }
6465    shellFinalize(&rc, pSql);
6466  }
6467
6468  sqlite3_free(zDir);
6469  sqlite3_free(zWhere);
6470  return rc;
6471}
6472
6473/*
6474** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6475*/
6476static int arExecSql(ArCommand *pAr, const char *zSql){
6477  int rc;
6478  if( pAr->bDryRun ){
6479    utf8_printf(pAr->p->out, "%s\n", zSql);
6480    rc = SQLITE_OK;
6481  }else{
6482    char *zErr = 0;
6483    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6484    if( zErr ){
6485      utf8_printf(stdout, "ERROR: %s\n", zErr);
6486      sqlite3_free(zErr);
6487    }
6488  }
6489  return rc;
6490}
6491
6492
6493/*
6494** Implementation of .ar "create", "insert", and "update" commands.
6495**
6496**     create    ->     Create a new SQL archive
6497**     insert    ->     Insert or reinsert all files listed
6498**     update    ->     Insert files that have changed or that were not
6499**                      previously in the archive
6500**
6501** Create the "sqlar" table in the database if it does not already exist.
6502** Then add each file in the azFile[] array to the archive. Directories
6503** are added recursively. If argument bVerbose is non-zero, a message is
6504** printed on stdout for each file archived.
6505**
6506** The create command is the same as update, except that it drops
6507** any existing "sqlar" table before beginning.  The "insert" command
6508** always overwrites every file named on the command-line, where as
6509** "update" only overwrites if the size or mtime or mode has changed.
6510*/
6511static int arCreateOrUpdateCommand(
6512  ArCommand *pAr,                 /* Command arguments and options */
6513  int bUpdate,                    /* true for a --create. */
6514  int bOnlyIfChanged              /* Only update if file has changed */
6515){
6516  const char *zCreate =
6517      "CREATE TABLE IF NOT EXISTS sqlar(\n"
6518      "  name TEXT PRIMARY KEY,  -- name of the file\n"
6519      "  mode INT,               -- access permissions\n"
6520      "  mtime INT,              -- last modification time\n"
6521      "  sz INT,                 -- original file size\n"
6522      "  data BLOB               -- compressed content\n"
6523      ")";
6524  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
6525  const char *zInsertFmt[2] = {
6526     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
6527     "  SELECT\n"
6528     "    %s,\n"
6529     "    mode,\n"
6530     "    mtime,\n"
6531     "    CASE substr(lsmode(mode),1,1)\n"
6532     "      WHEN '-' THEN length(data)\n"
6533     "      WHEN 'd' THEN 0\n"
6534     "      ELSE -1 END,\n"
6535     "    sqlar_compress(data)\n"
6536     "  FROM fsdir(%Q,%Q) AS disk\n"
6537     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6538     ,
6539     "REPLACE INTO %s(name,mode,mtime,data)\n"
6540     "  SELECT\n"
6541     "    %s,\n"
6542     "    mode,\n"
6543     "    mtime,\n"
6544     "    data\n"
6545     "  FROM fsdir(%Q,%Q) AS disk\n"
6546     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6547  };
6548  int i;                          /* For iterating through azFile[] */
6549  int rc;                         /* Return code */
6550  const char *zTab = 0;           /* SQL table into which to insert */
6551  char *zSql;
6552  char zTemp[50];
6553  char *zExists = 0;
6554
6555  arExecSql(pAr, "PRAGMA page_size=512");
6556  rc = arExecSql(pAr, "SAVEPOINT ar;");
6557  if( rc!=SQLITE_OK ) return rc;
6558  zTemp[0] = 0;
6559  if( pAr->bZip ){
6560    /* Initialize the zipfile virtual table, if necessary */
6561    if( pAr->zFile ){
6562      sqlite3_uint64 r;
6563      sqlite3_randomness(sizeof(r),&r);
6564      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6565      zTab = zTemp;
6566      zSql = sqlite3_mprintf(
6567         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6568         zTab, pAr->zFile
6569      );
6570      rc = arExecSql(pAr, zSql);
6571      sqlite3_free(zSql);
6572    }else{
6573      zTab = "zip";
6574    }
6575  }else{
6576    /* Initialize the table for an SQLAR */
6577    zTab = "sqlar";
6578    if( bUpdate==0 ){
6579      rc = arExecSql(pAr, zDrop);
6580      if( rc!=SQLITE_OK ) goto end_ar_transaction;
6581    }
6582    rc = arExecSql(pAr, zCreate);
6583  }
6584  if( bOnlyIfChanged ){
6585    zExists = sqlite3_mprintf(
6586      " AND NOT EXISTS("
6587          "SELECT 1 FROM %s AS mem"
6588          " WHERE mem.name=disk.name"
6589          " AND mem.mtime=disk.mtime"
6590          " AND mem.mode=disk.mode)", zTab);
6591  }else{
6592    zExists = sqlite3_mprintf("");
6593  }
6594  if( zExists==0 ) rc = SQLITE_NOMEM;
6595  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6596    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
6597        pAr->bVerbose ? "shell_putsnl(name)" : "name",
6598        pAr->azArg[i], pAr->zDir, zExists);
6599    rc = arExecSql(pAr, zSql2);
6600    sqlite3_free(zSql2);
6601  }
6602end_ar_transaction:
6603  if( rc!=SQLITE_OK ){
6604    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6605  }else{
6606    rc = arExecSql(pAr, "RELEASE ar;");
6607    if( pAr->bZip && pAr->zFile ){
6608      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6609      arExecSql(pAr, zSql);
6610      sqlite3_free(zSql);
6611    }
6612  }
6613  sqlite3_free(zExists);
6614  return rc;
6615}
6616
6617/*
6618** Implementation of ".ar" dot command.
6619*/
6620static int arDotCommand(
6621  ShellState *pState,          /* Current shell tool state */
6622  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
6623  char **azArg,                /* Array of arguments passed to dot command */
6624  int nArg                     /* Number of entries in azArg[] */
6625){
6626  ArCommand cmd;
6627  int rc;
6628  memset(&cmd, 0, sizeof(cmd));
6629  cmd.fromCmdLine = fromCmdLine;
6630  rc = arParseCommand(azArg, nArg, &cmd);
6631  if( rc==SQLITE_OK ){
6632    int eDbType = SHELL_OPEN_UNSPEC;
6633    cmd.p = pState;
6634    cmd.db = pState->db;
6635    if( cmd.zFile ){
6636      eDbType = deduceDatabaseType(cmd.zFile, 1);
6637    }else{
6638      eDbType = pState->openMode;
6639    }
6640    if( eDbType==SHELL_OPEN_ZIPFILE ){
6641      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6642        if( cmd.zFile==0 ){
6643          cmd.zSrcTable = sqlite3_mprintf("zip");
6644        }else{
6645          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6646        }
6647      }
6648      cmd.bZip = 1;
6649    }else if( cmd.zFile ){
6650      int flags;
6651      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
6652      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6653           || cmd.eCmd==AR_CMD_UPDATE ){
6654        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6655      }else{
6656        flags = SQLITE_OPEN_READONLY;
6657      }
6658      cmd.db = 0;
6659      if( cmd.bDryRun ){
6660        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6661             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6662      }
6663      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6664             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
6665      if( rc!=SQLITE_OK ){
6666        utf8_printf(stderr, "cannot open file: %s (%s)\n",
6667            cmd.zFile, sqlite3_errmsg(cmd.db)
6668        );
6669        goto end_ar_command;
6670      }
6671      sqlite3_fileio_init(cmd.db, 0, 0);
6672      sqlite3_sqlar_init(cmd.db, 0, 0);
6673      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6674                              shellPutsFunc, 0, 0);
6675
6676    }
6677    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
6678      if( cmd.eCmd!=AR_CMD_CREATE
6679       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6680      ){
6681        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6682        rc = SQLITE_ERROR;
6683        goto end_ar_command;
6684      }
6685      cmd.zSrcTable = sqlite3_mprintf("sqlar");
6686    }
6687
6688    switch( cmd.eCmd ){
6689      case AR_CMD_CREATE:
6690        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
6691        break;
6692
6693      case AR_CMD_EXTRACT:
6694        rc = arExtractCommand(&cmd);
6695        break;
6696
6697      case AR_CMD_LIST:
6698        rc = arListCommand(&cmd);
6699        break;
6700
6701      case AR_CMD_HELP:
6702        arUsage(pState->out);
6703        break;
6704
6705      case AR_CMD_INSERT:
6706        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6707        break;
6708
6709      default:
6710        assert( cmd.eCmd==AR_CMD_UPDATE );
6711        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
6712        break;
6713    }
6714  }
6715end_ar_command:
6716  if( cmd.db!=pState->db ){
6717    close_db(cmd.db);
6718  }
6719  sqlite3_free(cmd.zSrcTable);
6720
6721  return rc;
6722}
6723/* End of the ".archive" or ".ar" command logic
6724*******************************************************************************/
6725#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
6726
6727#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
6728/*
6729** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6730** Otherwise, the SQL statement or statements in zSql are executed using
6731** database connection db and the error code written to *pRc before
6732** this function returns.
6733*/
6734static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6735  int rc = *pRc;
6736  if( rc==SQLITE_OK ){
6737    char *zErr = 0;
6738    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6739    if( rc!=SQLITE_OK ){
6740      raw_printf(stderr, "SQL error: %s\n", zErr);
6741    }
6742    sqlite3_free(zErr);
6743    *pRc = rc;
6744  }
6745}
6746
6747/*
6748** Like shellExec(), except that zFmt is a printf() style format string.
6749*/
6750static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6751  char *z = 0;
6752  if( *pRc==SQLITE_OK ){
6753    va_list ap;
6754    va_start(ap, zFmt);
6755    z = sqlite3_vmprintf(zFmt, ap);
6756    va_end(ap);
6757    if( z==0 ){
6758      *pRc = SQLITE_NOMEM;
6759    }else{
6760      shellExec(db, pRc, z);
6761    }
6762    sqlite3_free(z);
6763  }
6764}
6765
6766/*
6767** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6768** Otherwise, an attempt is made to allocate, zero and return a pointer
6769** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6770** to SQLITE_NOMEM and NULL returned.
6771*/
6772static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6773  void *pRet = 0;
6774  if( *pRc==SQLITE_OK ){
6775    pRet = sqlite3_malloc64(nByte);
6776    if( pRet==0 ){
6777      *pRc = SQLITE_NOMEM;
6778    }else{
6779      memset(pRet, 0, nByte);
6780    }
6781  }
6782  return pRet;
6783}
6784
6785/*
6786** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6787** Otherwise, zFmt is treated as a printf() style string. The result of
6788** formatting it along with any trailing arguments is written into a
6789** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6790** It is the responsibility of the caller to eventually free this buffer
6791** using a call to sqlite3_free().
6792**
6793** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6794** pointer returned.
6795*/
6796static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6797  char *z = 0;
6798  if( *pRc==SQLITE_OK ){
6799    va_list ap;
6800    va_start(ap, zFmt);
6801    z = sqlite3_vmprintf(zFmt, ap);
6802    va_end(ap);
6803    if( z==0 ){
6804      *pRc = SQLITE_NOMEM;
6805    }
6806  }
6807  return z;
6808}
6809
6810/*
6811** When running the ".recover" command, each output table, and the special
6812** orphaned row table if it is required, is represented by an instance
6813** of the following struct.
6814*/
6815typedef struct RecoverTable RecoverTable;
6816struct RecoverTable {
6817  char *zQuoted;                  /* Quoted version of table name */
6818  int nCol;                       /* Number of columns in table */
6819  char **azlCol;                  /* Array of column lists */
6820  int iPk;                        /* Index of IPK column */
6821};
6822
6823/*
6824** Free a RecoverTable object allocated by recoverFindTable() or
6825** recoverOrphanTable().
6826*/
6827static void recoverFreeTable(RecoverTable *pTab){
6828  if( pTab ){
6829    sqlite3_free(pTab->zQuoted);
6830    if( pTab->azlCol ){
6831      int i;
6832      for(i=0; i<=pTab->nCol; i++){
6833        sqlite3_free(pTab->azlCol[i]);
6834      }
6835      sqlite3_free(pTab->azlCol);
6836    }
6837    sqlite3_free(pTab);
6838  }
6839}
6840
6841/*
6842** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6843** Otherwise, it allocates and returns a RecoverTable object based on the
6844** final four arguments passed to this function. It is the responsibility
6845** of the caller to eventually free the returned object using
6846** recoverFreeTable().
6847*/
6848static RecoverTable *recoverNewTable(
6849  int *pRc,                       /* IN/OUT: Error code */
6850  const char *zName,              /* Name of table */
6851  const char *zSql,               /* CREATE TABLE statement */
6852  int bIntkey,
6853  int nCol
6854){
6855  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
6856  int rc = *pRc;
6857  RecoverTable *pTab = 0;
6858
6859  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
6860  if( rc==SQLITE_OK ){
6861    int nSqlCol = 0;
6862    int bSqlIntkey = 0;
6863    sqlite3_stmt *pStmt = 0;
6864
6865    rc = sqlite3_open("", &dbtmp);
6866    if( rc==SQLITE_OK ){
6867      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
6868                              shellIdQuote, 0, 0);
6869    }
6870    if( rc==SQLITE_OK ){
6871      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6872    }
6873    if( rc==SQLITE_OK ){
6874      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6875      if( rc==SQLITE_ERROR ){
6876        rc = SQLITE_OK;
6877        goto finished;
6878      }
6879    }
6880    shellPreparePrintf(dbtmp, &rc, &pStmt,
6881        "SELECT count(*) FROM pragma_table_info(%Q)", zName
6882    );
6883    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6884      nSqlCol = sqlite3_column_int(pStmt, 0);
6885    }
6886    shellFinalize(&rc, pStmt);
6887
6888    if( rc!=SQLITE_OK || nSqlCol<nCol ){
6889      goto finished;
6890    }
6891
6892    shellPreparePrintf(dbtmp, &rc, &pStmt,
6893      "SELECT ("
6894      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6895      ") FROM sqlite_schema WHERE name = %Q", zName
6896    );
6897    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6898      bSqlIntkey = sqlite3_column_int(pStmt, 0);
6899    }
6900    shellFinalize(&rc, pStmt);
6901
6902    if( bIntkey==bSqlIntkey ){
6903      int i;
6904      const char *zPk = "_rowid_";
6905      sqlite3_stmt *pPkFinder = 0;
6906
6907      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6908      ** set zPk to the name of the PK column, and pTab->iPk to the index
6909      ** of the column, where columns are 0-numbered from left to right.
6910      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6911      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
6912      pTab->iPk = -2;
6913      if( bIntkey ){
6914        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6915          "SELECT cid, name FROM pragma_table_info(%Q) "
6916          "  WHERE pk=1 AND type='integer' COLLATE nocase"
6917          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6918          , zName, zName
6919        );
6920        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6921          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6922          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6923        }
6924      }
6925
6926      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
6927      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
6928      pTab->nCol = nSqlCol;
6929
6930      if( bIntkey ){
6931        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
6932      }else{
6933        pTab->azlCol[0] = shellMPrintf(&rc, "");
6934      }
6935      i = 1;
6936      shellPreparePrintf(dbtmp, &rc, &pStmt,
6937          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
6938          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
6939          "FROM pragma_table_info(%Q)",
6940          bIntkey ? ", " : "", pTab->iPk,
6941          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6942          zName
6943      );
6944      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6945        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6946        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6947        i++;
6948      }
6949      shellFinalize(&rc, pStmt);
6950
6951      shellFinalize(&rc, pPkFinder);
6952    }
6953  }
6954
6955 finished:
6956  sqlite3_close(dbtmp);
6957  *pRc = rc;
6958  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
6959    recoverFreeTable(pTab);
6960    pTab = 0;
6961  }
6962  return pTab;
6963}
6964
6965/*
6966** This function is called to search the schema recovered from the
6967** sqlite_schema table of the (possibly) corrupt database as part
6968** of a ".recover" command. Specifically, for a table with root page
6969** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6970** table must be a WITHOUT ROWID table, or if non-zero, not one of
6971** those.
6972**
6973** If a table is found, a (RecoverTable*) object is returned. Or, if
6974** no such table is found, but bIntkey is false and iRoot is the
6975** root page of an index in the recovered schema, then (*pbNoop) is
6976** set to true and NULL returned. Or, if there is no such table or
6977** index, NULL is returned and (*pbNoop) set to 0, indicating that
6978** the caller should write data to the orphans table.
6979*/
6980static RecoverTable *recoverFindTable(
6981  ShellState *pState,             /* Shell state object */
6982  int *pRc,                       /* IN/OUT: Error code */
6983  int iRoot,                      /* Root page of table */
6984  int bIntkey,                    /* True for an intkey table */
6985  int nCol,                       /* Number of columns in table */
6986  int *pbNoop                     /* OUT: True if iRoot is root of index */
6987){
6988  sqlite3_stmt *pStmt = 0;
6989  RecoverTable *pRet = 0;
6990  int bNoop = 0;
6991  const char *zSql = 0;
6992  const char *zName = 0;
6993
6994  /* Search the recovered schema for an object with root page iRoot. */
6995  shellPreparePrintf(pState->db, pRc, &pStmt,
6996      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6997  );
6998  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6999    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7000    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7001      bNoop = 1;
7002      break;
7003    }
7004    if( sqlite3_stricmp(zType, "table")==0 ){
7005      zName = (const char*)sqlite3_column_text(pStmt, 1);
7006      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7007      pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7008      break;
7009    }
7010  }
7011
7012  shellFinalize(pRc, pStmt);
7013  *pbNoop = bNoop;
7014  return pRet;
7015}
7016
7017/*
7018** Return a RecoverTable object representing the orphans table.
7019*/
7020static RecoverTable *recoverOrphanTable(
7021  ShellState *pState,             /* Shell state object */
7022  int *pRc,                       /* IN/OUT: Error code */
7023  const char *zLostAndFound,      /* Base name for orphans table */
7024  int nCol                        /* Number of user data columns */
7025){
7026  RecoverTable *pTab = 0;
7027  if( nCol>=0 && *pRc==SQLITE_OK ){
7028    int i;
7029
7030    /* This block determines the name of the orphan table. The prefered
7031    ** name is zLostAndFound. But if that clashes with another name
7032    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7033    ** and so on until a non-clashing name is found.  */
7034    int iTab = 0;
7035    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7036    sqlite3_stmt *pTest = 0;
7037    shellPrepare(pState->db, pRc,
7038        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7039    );
7040    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7041    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7042      shellReset(pRc, pTest);
7043      sqlite3_free(zTab);
7044      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7045      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7046    }
7047    shellFinalize(pRc, pTest);
7048
7049    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7050    if( pTab ){
7051      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7052      pTab->nCol = nCol;
7053      pTab->iPk = -2;
7054      if( nCol>0 ){
7055        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7056        if( pTab->azlCol ){
7057          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7058          for(i=nCol-1; i>=0; i--){
7059            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7060          }
7061        }
7062      }
7063
7064      if( *pRc!=SQLITE_OK ){
7065        recoverFreeTable(pTab);
7066        pTab = 0;
7067      }else{
7068        raw_printf(pState->out,
7069            "CREATE TABLE %s(rootpgno INTEGER, "
7070            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7071        );
7072        for(i=0; i<nCol; i++){
7073          raw_printf(pState->out, ", c%d", i);
7074        }
7075        raw_printf(pState->out, ");\n");
7076      }
7077    }
7078    sqlite3_free(zTab);
7079  }
7080  return pTab;
7081}
7082
7083/*
7084** This function is called to recover data from the database. A script
7085** to construct a new database containing all recovered data is output
7086** on stream pState->out.
7087*/
7088static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7089  int rc = SQLITE_OK;
7090  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7091  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7092  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7093  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7094  const char *zLostAndFound = "lost_and_found";
7095  int i;
7096  int nOrphan = -1;
7097  RecoverTable *pOrphan = 0;
7098
7099  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7100  int bRowids = 1;                /* 0 if --no-rowids */
7101  for(i=1; i<nArg; i++){
7102    char *z = azArg[i];
7103    int n;
7104    if( z[0]=='-' && z[1]=='-' ) z++;
7105    n = strlen30(z);
7106    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7107      bFreelist = 0;
7108    }else
7109    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7110      i++;
7111      zRecoveryDb = azArg[i];
7112    }else
7113    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7114      i++;
7115      zLostAndFound = azArg[i];
7116    }else
7117    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7118      bRowids = 0;
7119    }
7120    else{
7121      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7122      showHelp(pState->out, azArg[0]);
7123      return 1;
7124    }
7125  }
7126
7127  shellExecPrintf(pState->db, &rc,
7128    /* Attach an in-memory database named 'recovery'. Create an indexed
7129    ** cache of the sqlite_dbptr virtual table. */
7130    "PRAGMA writable_schema = on;"
7131    "ATTACH %Q AS recovery;"
7132    "DROP TABLE IF EXISTS recovery.dbptr;"
7133    "DROP TABLE IF EXISTS recovery.freelist;"
7134    "DROP TABLE IF EXISTS recovery.map;"
7135    "DROP TABLE IF EXISTS recovery.schema;"
7136    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7137  );
7138
7139  if( bFreelist ){
7140    shellExec(pState->db, &rc,
7141      "WITH trunk(pgno) AS ("
7142      "  SELECT shell_int32("
7143      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7144      "      WHERE x>0"
7145      "    UNION"
7146      "  SELECT shell_int32("
7147      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7148      "      FROM trunk WHERE x>0"
7149      "),"
7150      "freelist(data, n, freepgno) AS ("
7151      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7152      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7153      "    UNION ALL"
7154      "  SELECT data, n-1, shell_int32(data, 2+n) "
7155      "      FROM freelist WHERE n>=0"
7156      ")"
7157      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7158    );
7159  }
7160
7161  /* If this is an auto-vacuum database, add all pointer-map pages to
7162  ** the freelist table. Do this regardless of whether or not
7163  ** --freelist-corrupt was specified.  */
7164  shellExec(pState->db, &rc,
7165    "WITH ptrmap(pgno) AS ("
7166    "  SELECT 2 WHERE shell_int32("
7167    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7168    "  )"
7169    "    UNION ALL "
7170    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7171    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7172    ")"
7173    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7174  );
7175
7176  shellExec(pState->db, &rc,
7177    "CREATE TABLE recovery.dbptr("
7178    "      pgno, child, PRIMARY KEY(child, pgno)"
7179    ") WITHOUT ROWID;"
7180    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7181    "    SELECT * FROM sqlite_dbptr"
7182    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7183
7184    /* Delete any pointer to page 1. This ensures that page 1 is considered
7185    ** a root page, regardless of how corrupt the db is. */
7186    "DELETE FROM recovery.dbptr WHERE child = 1;"
7187
7188    /* Delete all pointers to any pages that have more than one pointer
7189    ** to them. Such pages will be treated as root pages when recovering
7190    ** data.  */
7191    "DELETE FROM recovery.dbptr WHERE child IN ("
7192    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7193    ");"
7194
7195    /* Create the "map" table that will (eventually) contain instructions
7196    ** for dealing with each page in the db that contains one or more
7197    ** records. */
7198    "CREATE TABLE recovery.map("
7199      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7200    ");"
7201
7202    /* Populate table [map]. If there are circular loops of pages in the
7203    ** database, the following adds all pages in such a loop to the map
7204    ** as individual root pages. This could be handled better.  */
7205    "WITH pages(i, maxlen) AS ("
7206    "  SELECT page_count, ("
7207    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7208    "  ) FROM pragma_page_count WHERE page_count>0"
7209    "    UNION ALL"
7210    "  SELECT i-1, ("
7211    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7212    "  ) FROM pages WHERE i>=2"
7213    ")"
7214    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7215    "  SELECT i, maxlen, NULL, ("
7216    "    WITH p(orig, pgno, parent) AS ("
7217    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7218    "        UNION "
7219    "      SELECT i, p.parent, "
7220    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7221    "    )"
7222    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7223    ") "
7224    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7225    "UPDATE recovery.map AS o SET intkey = ("
7226    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7227    ");"
7228
7229    /* Extract data from page 1 and any linked pages into table
7230    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7231    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7232    "INSERT INTO recovery.schema SELECT "
7233    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7234    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7235    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7236    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7237    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7238    "FROM sqlite_dbdata WHERE pgno IN ("
7239    "  SELECT pgno FROM recovery.map WHERE root=1"
7240    ")"
7241    "GROUP BY pgno, cell;"
7242    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7243  );
7244
7245  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7246  ** CREATE TABLE statements that extracted from the existing schema.  */
7247  if( rc==SQLITE_OK ){
7248    sqlite3_stmt *pStmt = 0;
7249    /* ".recover" might output content in an order which causes immediate
7250    ** foreign key constraints to be violated. So disable foreign-key
7251    ** constraint enforcement to prevent problems when running the output
7252    ** script. */
7253    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7254    raw_printf(pState->out, "BEGIN;\n");
7255    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7256    shellPrepare(pState->db, &rc,
7257        "SELECT sql FROM recovery.schema "
7258        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7259    );
7260    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7261      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7262      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7263          &zCreateTable[12]
7264      );
7265    }
7266    shellFinalize(&rc, pStmt);
7267  }
7268
7269  /* Figure out if an orphan table will be required. And if so, how many
7270  ** user columns it should contain */
7271  shellPrepare(pState->db, &rc,
7272      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7273      , &pLoop
7274  );
7275  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7276    nOrphan = sqlite3_column_int(pLoop, 0);
7277  }
7278  shellFinalize(&rc, pLoop);
7279  pLoop = 0;
7280
7281  shellPrepare(pState->db, &rc,
7282      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7283  );
7284
7285  shellPrepare(pState->db, &rc,
7286      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7287      "(case when (? AND field<0) then NULL else value end)"
7288      "), ', ')"
7289      ", min(field) "
7290      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7291      "GROUP BY cell", &pCells
7292  );
7293
7294  /* Loop through each root page. */
7295  shellPrepare(pState->db, &rc,
7296      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7297      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7298      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7299      ")", &pLoop
7300  );
7301  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7302    int iRoot = sqlite3_column_int(pLoop, 0);
7303    int bIntkey = sqlite3_column_int(pLoop, 1);
7304    int nCol = sqlite3_column_int(pLoop, 2);
7305    int bNoop = 0;
7306    RecoverTable *pTab;
7307
7308    assert( bIntkey==0 || bIntkey==1 );
7309    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7310    if( bNoop || rc ) continue;
7311    if( pTab==0 ){
7312      if( pOrphan==0 ){
7313        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7314      }
7315      pTab = pOrphan;
7316      if( pTab==0 ) break;
7317    }
7318
7319    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7320      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7321    }
7322    sqlite3_bind_int(pPages, 1, iRoot);
7323    if( bRowids==0 && pTab->iPk<0 ){
7324      sqlite3_bind_int(pCells, 1, 1);
7325    }else{
7326      sqlite3_bind_int(pCells, 1, 0);
7327    }
7328    sqlite3_bind_int(pCells, 3, pTab->iPk);
7329
7330    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7331      int iPgno = sqlite3_column_int(pPages, 0);
7332      sqlite3_bind_int(pCells, 2, iPgno);
7333      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7334        int nField = sqlite3_column_int(pCells, 0);
7335        int iMin = sqlite3_column_int(pCells, 2);
7336        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7337
7338        RecoverTable *pTab2 = pTab;
7339        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7340          if( pOrphan==0 ){
7341            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7342          }
7343          pTab2 = pOrphan;
7344          if( pTab2==0 ) break;
7345        }
7346
7347        nField = nField+1;
7348        if( pTab2==pOrphan ){
7349          raw_printf(pState->out,
7350              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7351              pTab2->zQuoted, iRoot, iPgno, nField,
7352              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7353          );
7354        }else{
7355          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7356              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7357          );
7358        }
7359      }
7360      shellReset(&rc, pCells);
7361    }
7362    shellReset(&rc, pPages);
7363    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7364  }
7365  shellFinalize(&rc, pLoop);
7366  shellFinalize(&rc, pPages);
7367  shellFinalize(&rc, pCells);
7368  recoverFreeTable(pOrphan);
7369
7370  /* The rest of the schema */
7371  if( rc==SQLITE_OK ){
7372    sqlite3_stmt *pStmt = 0;
7373    shellPrepare(pState->db, &rc,
7374        "SELECT sql, name FROM recovery.schema "
7375        "WHERE sql NOT LIKE 'create table%'", &pStmt
7376    );
7377    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7378      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7379      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7380        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7381        char *zPrint = shellMPrintf(&rc,
7382          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7383          zName, zName, zSql
7384        );
7385        raw_printf(pState->out, "%s;\n", zPrint);
7386        sqlite3_free(zPrint);
7387      }else{
7388        raw_printf(pState->out, "%s;\n", zSql);
7389      }
7390    }
7391    shellFinalize(&rc, pStmt);
7392  }
7393
7394  if( rc==SQLITE_OK ){
7395    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7396    raw_printf(pState->out, "COMMIT;\n");
7397  }
7398  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7399  return rc;
7400}
7401#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7402
7403/*
7404** If an input line begins with "." then invoke this routine to
7405** process that line.
7406**
7407** Return 1 on error, 2 to exit, and 0 otherwise.
7408*/
7409static int do_meta_command(char *zLine, ShellState *p){
7410  int h = 1;
7411  int nArg = 0;
7412  int n, c;
7413  int rc = 0;
7414  char *azArg[52];
7415
7416#ifndef SQLITE_OMIT_VIRTUALTABLE
7417  if( p->expert.pExpert ){
7418    expertFinish(p, 1, 0);
7419  }
7420#endif
7421
7422  /* Parse the input line into tokens.
7423  */
7424  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7425    while( IsSpace(zLine[h]) ){ h++; }
7426    if( zLine[h]==0 ) break;
7427    if( zLine[h]=='\'' || zLine[h]=='"' ){
7428      int delim = zLine[h++];
7429      azArg[nArg++] = &zLine[h];
7430      while( zLine[h] && zLine[h]!=delim ){
7431        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7432        h++;
7433      }
7434      if( zLine[h]==delim ){
7435        zLine[h++] = 0;
7436      }
7437      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7438    }else{
7439      azArg[nArg++] = &zLine[h];
7440      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7441      if( zLine[h] ) zLine[h++] = 0;
7442      resolve_backslashes(azArg[nArg-1]);
7443    }
7444  }
7445  azArg[nArg] = 0;
7446
7447  /* Process the input line.
7448  */
7449  if( nArg==0 ) return 0; /* no tokens, no error */
7450  n = strlen30(azArg[0]);
7451  c = azArg[0][0];
7452  clearTempFile(p);
7453
7454#ifndef SQLITE_OMIT_AUTHORIZATION
7455  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
7456    if( nArg!=2 ){
7457      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7458      rc = 1;
7459      goto meta_command_exit;
7460    }
7461    open_db(p, 0);
7462    if( booleanValue(azArg[1]) ){
7463      sqlite3_set_authorizer(p->db, shellAuth, p);
7464    }else{
7465      sqlite3_set_authorizer(p->db, 0, 0);
7466    }
7467  }else
7468#endif
7469
7470#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
7471  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
7472    open_db(p, 0);
7473    rc = arDotCommand(p, 0, azArg, nArg);
7474  }else
7475#endif
7476
7477  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
7478   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
7479  ){
7480    const char *zDestFile = 0;
7481    const char *zDb = 0;
7482    sqlite3 *pDest;
7483    sqlite3_backup *pBackup;
7484    int j;
7485    int bAsync = 0;
7486    const char *zVfs = 0;
7487    for(j=1; j<nArg; j++){
7488      const char *z = azArg[j];
7489      if( z[0]=='-' ){
7490        if( z[1]=='-' ) z++;
7491        if( strcmp(z, "-append")==0 ){
7492          zVfs = "apndvfs";
7493        }else
7494        if( strcmp(z, "-async")==0 ){
7495          bAsync = 1;
7496        }else
7497        {
7498          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7499          return 1;
7500        }
7501      }else if( zDestFile==0 ){
7502        zDestFile = azArg[j];
7503      }else if( zDb==0 ){
7504        zDb = zDestFile;
7505        zDestFile = azArg[j];
7506      }else{
7507        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7508        return 1;
7509      }
7510    }
7511    if( zDestFile==0 ){
7512      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7513      return 1;
7514    }
7515    if( zDb==0 ) zDb = "main";
7516    rc = sqlite3_open_v2(zDestFile, &pDest,
7517                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7518    if( rc!=SQLITE_OK ){
7519      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7520      close_db(pDest);
7521      return 1;
7522    }
7523    if( bAsync ){
7524      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7525                   0, 0, 0);
7526    }
7527    open_db(p, 0);
7528    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7529    if( pBackup==0 ){
7530      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7531      close_db(pDest);
7532      return 1;
7533    }
7534    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7535    sqlite3_backup_finish(pBackup);
7536    if( rc==SQLITE_DONE ){
7537      rc = 0;
7538    }else{
7539      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7540      rc = 1;
7541    }
7542    close_db(pDest);
7543  }else
7544
7545  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7546    if( nArg==2 ){
7547      bail_on_error = booleanValue(azArg[1]);
7548    }else{
7549      raw_printf(stderr, "Usage: .bail on|off\n");
7550      rc = 1;
7551    }
7552  }else
7553
7554  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7555    if( nArg==2 ){
7556      if( booleanValue(azArg[1]) ){
7557        setBinaryMode(p->out, 1);
7558      }else{
7559        setTextMode(p->out, 1);
7560      }
7561    }else{
7562      raw_printf(stderr, "Usage: .binary on|off\n");
7563      rc = 1;
7564    }
7565  }else
7566
7567  /* The undocumented ".breakpoint" command causes a call to the no-op
7568  ** routine named test_breakpoint().
7569  */
7570  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7571    test_breakpoint();
7572  }else
7573
7574  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7575    if( nArg==2 ){
7576#if defined(_WIN32) || defined(WIN32)
7577      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7578      rc = !SetCurrentDirectoryW(z);
7579      sqlite3_free(z);
7580#else
7581      rc = chdir(azArg[1]);
7582#endif
7583      if( rc ){
7584        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7585        rc = 1;
7586      }
7587    }else{
7588      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7589      rc = 1;
7590    }
7591  }else
7592
7593  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7594    if( nArg==2 ){
7595      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7596    }else{
7597      raw_printf(stderr, "Usage: .changes on|off\n");
7598      rc = 1;
7599    }
7600  }else
7601
7602  /* Cancel output redirection, if it is currently set (by .testcase)
7603  ** Then read the content of the testcase-out.txt file and compare against
7604  ** azArg[1].  If there are differences, report an error and exit.
7605  */
7606  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7607    char *zRes = 0;
7608    output_reset(p);
7609    if( nArg!=2 ){
7610      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7611      rc = 2;
7612    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7613      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7614      rc = 2;
7615    }else if( testcase_glob(azArg[1],zRes)==0 ){
7616      utf8_printf(stderr,
7617                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7618                 p->zTestcase, azArg[1], zRes);
7619      rc = 1;
7620    }else{
7621      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7622      p->nCheck++;
7623    }
7624    sqlite3_free(zRes);
7625  }else
7626
7627  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7628    if( nArg==2 ){
7629      tryToClone(p, azArg[1]);
7630    }else{
7631      raw_printf(stderr, "Usage: .clone FILENAME\n");
7632      rc = 1;
7633    }
7634  }else
7635
7636  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
7637    if( nArg==1 ){
7638      /* List available connections */
7639      int i;
7640      for(i=0; i<ArraySize(p->aAuxDb); i++){
7641        const char *zFile = p->aAuxDb[i].zDbFilename;
7642        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7643          zFile = "(not open)";
7644        }else if( zFile==0 ){
7645          zFile = "(memory)";
7646        }else if( zFile[0]==0 ){
7647          zFile = "(temporary-file)";
7648        }
7649        if( p->pAuxDb == &p->aAuxDb[i] ){
7650          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7651        }else if( p->aAuxDb[i].db!=0 ){
7652          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7653        }
7654      }
7655    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7656      int i = azArg[1][0] - '0';
7657      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7658        p->pAuxDb->db = p->db;
7659        p->pAuxDb = &p->aAuxDb[i];
7660        globalDb = p->db = p->pAuxDb->db;
7661        p->pAuxDb->db = 0;
7662      }
7663    }else if( nArg==3 && strcmp(azArg[1], "close")==0
7664           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7665      int i = azArg[2][0] - '0';
7666      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7667        /* No-op */
7668      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7669        raw_printf(stderr, "cannot close the active database connection\n");
7670        rc = 1;
7671      }else if( p->aAuxDb[i].db ){
7672        session_close_all(p, i);
7673        close_db(p->aAuxDb[i].db);
7674        p->aAuxDb[i].db = 0;
7675      }
7676    }else{
7677      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7678      rc = 1;
7679    }
7680  }else
7681
7682  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7683    char **azName = 0;
7684    int nName = 0;
7685    sqlite3_stmt *pStmt;
7686    int i;
7687    open_db(p, 0);
7688    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7689    if( rc ){
7690      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7691      rc = 1;
7692    }else{
7693      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7694        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7695        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7696        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7697        if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
7698        azName[nName*2] = strdup(zSchema);
7699        azName[nName*2+1] = strdup(zFile);
7700        nName++;
7701      }
7702    }
7703    sqlite3_finalize(pStmt);
7704    for(i=0; i<nName; i++){
7705      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7706      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7707      const char *z = azName[i*2+1];
7708      utf8_printf(p->out, "%s: %s %s%s\n",
7709         azName[i*2],
7710         z && z[0] ? z : "\"\"",
7711         bRdonly ? "r/o" : "r/w",
7712         eTxn==SQLITE_TXN_NONE ? "" :
7713            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7714      free(azName[i*2]);
7715      free(azName[i*2+1]);
7716    }
7717    sqlite3_free(azName);
7718  }else
7719
7720  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
7721    static const struct DbConfigChoices {
7722      const char *zName;
7723      int op;
7724    } aDbConfig[] = {
7725        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7726        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7727        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7728        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7729        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7730        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7731        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7732        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7733        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7734        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7735        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7736        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7737        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7738        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7739        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7740        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7741    };
7742    int ii, v;
7743    open_db(p, 0);
7744    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7745      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7746      if( nArg>=3 ){
7747        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7748      }
7749      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7750      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7751      if( nArg>1 ) break;
7752    }
7753    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7754      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7755      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7756    }
7757  }else
7758
7759  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
7760    rc = shell_dbinfo_command(p, nArg, azArg);
7761  }else
7762
7763#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7764  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7765    open_db(p, 0);
7766    rc = recoverDatabaseCmd(p, nArg, azArg);
7767  }else
7768#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7769
7770  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7771    char *zLike = 0;
7772    char *zSql;
7773    int i;
7774    int savedShowHeader = p->showHeader;
7775    int savedShellFlags = p->shellFlgs;
7776    ShellClearFlag(p,
7777       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7778       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7779    for(i=1; i<nArg; i++){
7780      if( azArg[i][0]=='-' ){
7781        const char *z = azArg[i]+1;
7782        if( z[0]=='-' ) z++;
7783        if( strcmp(z,"preserve-rowids")==0 ){
7784#ifdef SQLITE_OMIT_VIRTUALTABLE
7785          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7786                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7787          rc = 1;
7788          sqlite3_free(zLike);
7789          goto meta_command_exit;
7790#else
7791          ShellSetFlag(p, SHFLG_PreserveRowid);
7792#endif
7793        }else
7794        if( strcmp(z,"newlines")==0 ){
7795          ShellSetFlag(p, SHFLG_Newlines);
7796        }else
7797        if( strcmp(z,"data-only")==0 ){
7798          ShellSetFlag(p, SHFLG_DumpDataOnly);
7799        }else
7800        if( strcmp(z,"nosys")==0 ){
7801          ShellSetFlag(p, SHFLG_DumpNoSys);
7802        }else
7803        {
7804          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7805          rc = 1;
7806          sqlite3_free(zLike);
7807          goto meta_command_exit;
7808        }
7809      }else{
7810        /* azArg[i] contains a LIKE pattern. This ".dump" request should
7811        ** only dump data for tables for which either the table name matches
7812        ** the LIKE pattern, or the table appears to be a shadow table of
7813        ** a virtual table for which the name matches the LIKE pattern.
7814        */
7815        char *zExpr = sqlite3_mprintf(
7816            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
7817            "  SELECT 1 FROM sqlite_schema WHERE "
7818            "    name LIKE %Q ESCAPE '\\' AND"
7819            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
7820            "    substr(o.name, 1, length(name)+1) == (name||'_')"
7821            ")", azArg[i], azArg[i]
7822        );
7823
7824        if( zLike ){
7825          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
7826        }else{
7827          zLike = zExpr;
7828        }
7829      }
7830    }
7831
7832    open_db(p, 0);
7833
7834    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7835      /* When playing back a "dump", the content might appear in an order
7836      ** which causes immediate foreign key constraints to be violated.
7837      ** So disable foreign-key constraint enforcement to prevent problems. */
7838      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7839      raw_printf(p->out, "BEGIN TRANSACTION;\n");
7840    }
7841    p->writableSchema = 0;
7842    p->showHeader = 0;
7843    /* Set writable_schema=ON since doing so forces SQLite to initialize
7844    ** as much of the schema as it can even if the sqlite_schema table is
7845    ** corrupt. */
7846    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7847    p->nErr = 0;
7848    if( zLike==0 ) zLike = sqlite3_mprintf("true");
7849    zSql = sqlite3_mprintf(
7850      "SELECT name, type, sql FROM sqlite_schema AS o "
7851      "WHERE (%s) AND type=='table'"
7852      "  AND sql NOT NULL"
7853      " ORDER BY tbl_name='sqlite_sequence', rowid",
7854      zLike
7855    );
7856    run_schema_dump_query(p,zSql);
7857    sqlite3_free(zSql);
7858    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7859      zSql = sqlite3_mprintf(
7860        "SELECT sql FROM sqlite_schema AS o "
7861        "WHERE (%s) AND sql NOT NULL"
7862        "  AND type IN ('index','trigger','view')",
7863        zLike
7864      );
7865      run_table_dump_query(p, zSql);
7866      sqlite3_free(zSql);
7867    }
7868    sqlite3_free(zLike);
7869    if( p->writableSchema ){
7870      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7871      p->writableSchema = 0;
7872    }
7873    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7874    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
7875    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
7876      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
7877    }
7878    p->showHeader = savedShowHeader;
7879    p->shellFlgs = savedShellFlags;
7880  }else
7881
7882  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7883    if( nArg==2 ){
7884      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7885    }else{
7886      raw_printf(stderr, "Usage: .echo on|off\n");
7887      rc = 1;
7888    }
7889  }else
7890
7891  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7892    if( nArg==2 ){
7893      p->autoEQPtest = 0;
7894      if( p->autoEQPtrace ){
7895        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7896        p->autoEQPtrace = 0;
7897      }
7898      if( strcmp(azArg[1],"full")==0 ){
7899        p->autoEQP = AUTOEQP_full;
7900      }else if( strcmp(azArg[1],"trigger")==0 ){
7901        p->autoEQP = AUTOEQP_trigger;
7902#ifdef SQLITE_DEBUG
7903      }else if( strcmp(azArg[1],"test")==0 ){
7904        p->autoEQP = AUTOEQP_on;
7905        p->autoEQPtest = 1;
7906      }else if( strcmp(azArg[1],"trace")==0 ){
7907        p->autoEQP = AUTOEQP_full;
7908        p->autoEQPtrace = 1;
7909        open_db(p, 0);
7910        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
7911        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7912#endif
7913      }else{
7914        p->autoEQP = (u8)booleanValue(azArg[1]);
7915      }
7916    }else{
7917      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
7918      rc = 1;
7919    }
7920  }else
7921
7922  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7923    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7924    rc = 2;
7925  }else
7926
7927  /* The ".explain" command is automatic now.  It is largely pointless.  It
7928  ** retained purely for backwards compatibility */
7929  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7930    int val = 1;
7931    if( nArg>=2 ){
7932      if( strcmp(azArg[1],"auto")==0 ){
7933        val = 99;
7934      }else{
7935        val =  booleanValue(azArg[1]);
7936      }
7937    }
7938    if( val==1 && p->mode!=MODE_Explain ){
7939      p->normalMode = p->mode;
7940      p->mode = MODE_Explain;
7941      p->autoExplain = 0;
7942    }else if( val==0 ){
7943      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7944      p->autoExplain = 0;
7945    }else if( val==99 ){
7946      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7947      p->autoExplain = 1;
7948    }
7949  }else
7950
7951#ifndef SQLITE_OMIT_VIRTUALTABLE
7952  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7953    open_db(p, 0);
7954    expertDotCommand(p, azArg, nArg);
7955  }else
7956#endif
7957
7958  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7959    static const struct {
7960       const char *zCtrlName;   /* Name of a test-control option */
7961       int ctrlCode;            /* Integer code for that option */
7962       const char *zUsage;      /* Usage notes */
7963    } aCtrl[] = {
7964      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
7965      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
7966      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
7967      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
7968      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
7969   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
7970      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
7971      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
7972      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
7973      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
7974   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
7975    };
7976    int filectrl = -1;
7977    int iCtrl = -1;
7978    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
7979    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
7980    int n2, i;
7981    const char *zCmd = 0;
7982    const char *zSchema = 0;
7983
7984    open_db(p, 0);
7985    zCmd = nArg>=2 ? azArg[1] : "help";
7986
7987    if( zCmd[0]=='-'
7988     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
7989     && nArg>=4
7990    ){
7991      zSchema = azArg[2];
7992      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
7993      nArg -= 2;
7994      zCmd = azArg[1];
7995    }
7996
7997    /* The argument can optionally begin with "-" or "--" */
7998    if( zCmd[0]=='-' && zCmd[1] ){
7999      zCmd++;
8000      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8001    }
8002
8003    /* --help lists all file-controls */
8004    if( strcmp(zCmd,"help")==0 ){
8005      utf8_printf(p->out, "Available file-controls:\n");
8006      for(i=0; i<ArraySize(aCtrl); i++){
8007        utf8_printf(p->out, "  .filectrl %s %s\n",
8008                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8009      }
8010      rc = 1;
8011      goto meta_command_exit;
8012    }
8013
8014    /* convert filectrl text option to value. allow any unique prefix
8015    ** of the option name, or a numerical value. */
8016    n2 = strlen30(zCmd);
8017    for(i=0; i<ArraySize(aCtrl); i++){
8018      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8019        if( filectrl<0 ){
8020          filectrl = aCtrl[i].ctrlCode;
8021          iCtrl = i;
8022        }else{
8023          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8024                              "Use \".filectrl --help\" for help\n", zCmd);
8025          rc = 1;
8026          goto meta_command_exit;
8027        }
8028      }
8029    }
8030    if( filectrl<0 ){
8031      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8032                         "Use \".filectrl --help\" for help\n", zCmd);
8033    }else{
8034      switch(filectrl){
8035        case SQLITE_FCNTL_SIZE_LIMIT: {
8036          if( nArg!=2 && nArg!=3 ) break;
8037          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8038          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8039          isOk = 1;
8040          break;
8041        }
8042        case SQLITE_FCNTL_LOCK_TIMEOUT:
8043        case SQLITE_FCNTL_CHUNK_SIZE: {
8044          int x;
8045          if( nArg!=3 ) break;
8046          x = (int)integerValue(azArg[2]);
8047          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8048          isOk = 2;
8049          break;
8050        }
8051        case SQLITE_FCNTL_PERSIST_WAL:
8052        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8053          int x;
8054          if( nArg!=2 && nArg!=3 ) break;
8055          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8056          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8057          iRes = x;
8058          isOk = 1;
8059          break;
8060        }
8061        case SQLITE_FCNTL_DATA_VERSION:
8062        case SQLITE_FCNTL_HAS_MOVED: {
8063          int x;
8064          if( nArg!=2 ) break;
8065          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8066          iRes = x;
8067          isOk = 1;
8068          break;
8069        }
8070        case SQLITE_FCNTL_TEMPFILENAME: {
8071          char *z = 0;
8072          if( nArg!=2 ) break;
8073          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8074          if( z ){
8075            utf8_printf(p->out, "%s\n", z);
8076            sqlite3_free(z);
8077          }
8078          isOk = 2;
8079          break;
8080        }
8081        case SQLITE_FCNTL_RESERVE_BYTES: {
8082          int x;
8083          if( nArg>=3 ){
8084            x = atoi(azArg[2]);
8085            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8086          }
8087          x = -1;
8088          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8089          utf8_printf(p->out,"%d\n", x);
8090          isOk = 2;
8091          break;
8092        }
8093      }
8094    }
8095    if( isOk==0 && iCtrl>=0 ){
8096      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8097      rc = 1;
8098    }else if( isOk==1 ){
8099      char zBuf[100];
8100      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8101      raw_printf(p->out, "%s\n", zBuf);
8102    }
8103  }else
8104
8105  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8106    ShellState data;
8107    int doStats = 0;
8108    memcpy(&data, p, sizeof(data));
8109    data.showHeader = 0;
8110    data.cMode = data.mode = MODE_Semi;
8111    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8112      data.cMode = data.mode = MODE_Pretty;
8113      nArg = 1;
8114    }
8115    if( nArg!=1 ){
8116      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8117      rc = 1;
8118      goto meta_command_exit;
8119    }
8120    open_db(p, 0);
8121    rc = sqlite3_exec(p->db,
8122       "SELECT sql FROM"
8123       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8124       "     FROM sqlite_schema UNION ALL"
8125       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8126       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8127       "ORDER BY x",
8128       callback, &data, 0
8129    );
8130    if( rc==SQLITE_OK ){
8131      sqlite3_stmt *pStmt;
8132      rc = sqlite3_prepare_v2(p->db,
8133               "SELECT rowid FROM sqlite_schema"
8134               " WHERE name GLOB 'sqlite_stat[134]'",
8135               -1, &pStmt, 0);
8136      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8137      sqlite3_finalize(pStmt);
8138    }
8139    if( doStats==0 ){
8140      raw_printf(p->out, "/* No STAT tables available */\n");
8141    }else{
8142      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8143      data.cMode = data.mode = MODE_Insert;
8144      data.zDestTable = "sqlite_stat1";
8145      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8146      data.zDestTable = "sqlite_stat4";
8147      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8148      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8149    }
8150  }else
8151
8152  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8153    if( nArg==2 ){
8154      p->showHeader = booleanValue(azArg[1]);
8155      p->shellFlgs |= SHFLG_HeaderSet;
8156    }else{
8157      raw_printf(stderr, "Usage: .headers on|off\n");
8158      rc = 1;
8159    }
8160  }else
8161
8162  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8163    if( nArg>=2 ){
8164      n = showHelp(p->out, azArg[1]);
8165      if( n==0 ){
8166        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8167      }
8168    }else{
8169      showHelp(p->out, 0);
8170    }
8171  }else
8172
8173  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8174    char *zTable = 0;           /* Insert data into this table */
8175    char *zFile = 0;            /* Name of file to extra content from */
8176    sqlite3_stmt *pStmt = NULL; /* A statement */
8177    int nCol;                   /* Number of columns in the table */
8178    int nByte;                  /* Number of bytes in an SQL string */
8179    int i, j;                   /* Loop counters */
8180    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8181    int nSep;                   /* Number of bytes in p->colSeparator[] */
8182    char *zSql;                 /* An SQL statement */
8183    ImportCtx sCtx;             /* Reader context */
8184    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8185    int eVerbose = 0;           /* Larger for more console output */
8186    int nSkip = 0;              /* Initial lines to skip */
8187    int useOutputMode = 1;      /* Use output mode to determine separators */
8188
8189    memset(&sCtx, 0, sizeof(sCtx));
8190    if( p->mode==MODE_Ascii ){
8191      xRead = ascii_read_one_field;
8192    }else{
8193      xRead = csv_read_one_field;
8194    }
8195    for(i=1; i<nArg; i++){
8196      char *z = azArg[i];
8197      if( z[0]=='-' && z[1]=='-' ) z++;
8198      if( z[0]!='-' ){
8199        if( zFile==0 ){
8200          zFile = z;
8201        }else if( zTable==0 ){
8202          zTable = z;
8203        }else{
8204          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8205          showHelp(p->out, "import");
8206          rc = 1;
8207          goto meta_command_exit;
8208        }
8209      }else if( strcmp(z,"-v")==0 ){
8210        eVerbose++;
8211      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8212        nSkip = integerValue(azArg[++i]);
8213      }else if( strcmp(z,"-ascii")==0 ){
8214        sCtx.cColSep = SEP_Unit[0];
8215        sCtx.cRowSep = SEP_Record[0];
8216        xRead = ascii_read_one_field;
8217        useOutputMode = 0;
8218      }else if( strcmp(z,"-csv")==0 ){
8219        sCtx.cColSep = ',';
8220        sCtx.cRowSep = '\n';
8221        xRead = csv_read_one_field;
8222        useOutputMode = 0;
8223      }else{
8224        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8225        showHelp(p->out, "import");
8226        rc = 1;
8227        goto meta_command_exit;
8228      }
8229    }
8230    if( zTable==0 ){
8231      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8232                  zFile==0 ? "FILE" : "TABLE");
8233      showHelp(p->out, "import");
8234      rc = 1;
8235      goto meta_command_exit;
8236    }
8237    seenInterrupt = 0;
8238    open_db(p, 0);
8239    if( useOutputMode ){
8240      /* If neither the --csv or --ascii options are specified, then set
8241      ** the column and row separator characters from the output mode. */
8242      nSep = strlen30(p->colSeparator);
8243      if( nSep==0 ){
8244        raw_printf(stderr,
8245                   "Error: non-null column separator required for import\n");
8246        rc = 1;
8247        goto meta_command_exit;
8248      }
8249      if( nSep>1 ){
8250        raw_printf(stderr,
8251              "Error: multi-character column separators not allowed"
8252              " for import\n");
8253        rc = 1;
8254        goto meta_command_exit;
8255      }
8256      nSep = strlen30(p->rowSeparator);
8257      if( nSep==0 ){
8258        raw_printf(stderr,
8259            "Error: non-null row separator required for import\n");
8260        rc = 1;
8261        goto meta_command_exit;
8262      }
8263      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
8264        /* When importing CSV (only), if the row separator is set to the
8265        ** default output row separator, change it to the default input
8266        ** row separator.  This avoids having to maintain different input
8267        ** and output row separators. */
8268        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8269        nSep = strlen30(p->rowSeparator);
8270      }
8271      if( nSep>1 ){
8272        raw_printf(stderr, "Error: multi-character row separators not allowed"
8273                           " for import\n");
8274        rc = 1;
8275        goto meta_command_exit;
8276      }
8277      sCtx.cColSep = p->colSeparator[0];
8278      sCtx.cRowSep = p->rowSeparator[0];
8279    }
8280    sCtx.zFile = zFile;
8281    sCtx.nLine = 1;
8282    if( sCtx.zFile[0]=='|' ){
8283#ifdef SQLITE_OMIT_POPEN
8284      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8285      rc = 1;
8286      goto meta_command_exit;
8287#else
8288      sCtx.in = popen(sCtx.zFile+1, "r");
8289      sCtx.zFile = "<pipe>";
8290      sCtx.xCloser = pclose;
8291#endif
8292    }else{
8293      sCtx.in = fopen(sCtx.zFile, "rb");
8294      sCtx.xCloser = fclose;
8295    }
8296    if( sCtx.in==0 ){
8297      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8298      rc = 1;
8299      goto meta_command_exit;
8300    }
8301    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8302      char zSep[2];
8303      zSep[1] = 0;
8304      zSep[0] = sCtx.cColSep;
8305      utf8_printf(p->out, "Column separator ");
8306      output_c_string(p->out, zSep);
8307      utf8_printf(p->out, ", row separator ");
8308      zSep[0] = sCtx.cRowSep;
8309      output_c_string(p->out, zSep);
8310      utf8_printf(p->out, "\n");
8311    }
8312    while( (nSkip--)>0 ){
8313      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8314    }
8315    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
8316    if( zSql==0 ){
8317      import_cleanup(&sCtx);
8318      shell_out_of_memory();
8319    }
8320    nByte = strlen30(zSql);
8321    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8322    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8323    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8324      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
8325      char cSep = '(';
8326      while( xRead(&sCtx) ){
8327        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
8328        cSep = ',';
8329        if( sCtx.cTerm!=sCtx.cColSep ) break;
8330      }
8331      if( cSep=='(' ){
8332        sqlite3_free(zCreate);
8333        import_cleanup(&sCtx);
8334        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8335        rc = 1;
8336        goto meta_command_exit;
8337      }
8338      zCreate = sqlite3_mprintf("%z\n)", zCreate);
8339      if( eVerbose>=1 ){
8340        utf8_printf(p->out, "%s\n", zCreate);
8341      }
8342      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8343      sqlite3_free(zCreate);
8344      if( rc ){
8345        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
8346                sqlite3_errmsg(p->db));
8347        import_cleanup(&sCtx);
8348        rc = 1;
8349        goto meta_command_exit;
8350      }
8351      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8352    }
8353    sqlite3_free(zSql);
8354    if( rc ){
8355      if (pStmt) sqlite3_finalize(pStmt);
8356      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8357      import_cleanup(&sCtx);
8358      rc = 1;
8359      goto meta_command_exit;
8360    }
8361    nCol = sqlite3_column_count(pStmt);
8362    sqlite3_finalize(pStmt);
8363    pStmt = 0;
8364    if( nCol==0 ) return 0; /* no columns, no error */
8365    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8366    if( zSql==0 ){
8367      import_cleanup(&sCtx);
8368      shell_out_of_memory();
8369    }
8370    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
8371    j = strlen30(zSql);
8372    for(i=1; i<nCol; i++){
8373      zSql[j++] = ',';
8374      zSql[j++] = '?';
8375    }
8376    zSql[j++] = ')';
8377    zSql[j] = 0;
8378    if( eVerbose>=2 ){
8379      utf8_printf(p->out, "Insert using: %s\n", zSql);
8380    }
8381    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8382    sqlite3_free(zSql);
8383    if( rc ){
8384      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8385      if (pStmt) sqlite3_finalize(pStmt);
8386      import_cleanup(&sCtx);
8387      rc = 1;
8388      goto meta_command_exit;
8389    }
8390    needCommit = sqlite3_get_autocommit(p->db);
8391    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8392    do{
8393      int startLine = sCtx.nLine;
8394      for(i=0; i<nCol; i++){
8395        char *z = xRead(&sCtx);
8396        /*
8397        ** Did we reach end-of-file before finding any columns?
8398        ** If so, stop instead of NULL filling the remaining columns.
8399        */
8400        if( z==0 && i==0 ) break;
8401        /*
8402        ** Did we reach end-of-file OR end-of-line before finding any
8403        ** columns in ASCII mode?  If so, stop instead of NULL filling
8404        ** the remaining columns.
8405        */
8406        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8407        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8408        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8409          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8410                          "filling the rest with NULL\n",
8411                          sCtx.zFile, startLine, nCol, i+1);
8412          i += 2;
8413          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8414        }
8415      }
8416      if( sCtx.cTerm==sCtx.cColSep ){
8417        do{
8418          xRead(&sCtx);
8419          i++;
8420        }while( sCtx.cTerm==sCtx.cColSep );
8421        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8422                        "extras ignored\n",
8423                        sCtx.zFile, startLine, nCol, i);
8424      }
8425      if( i>=nCol ){
8426        sqlite3_step(pStmt);
8427        rc = sqlite3_reset(pStmt);
8428        if( rc!=SQLITE_OK ){
8429          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8430                      startLine, sqlite3_errmsg(p->db));
8431          sCtx.nErr++;
8432        }else{
8433          sCtx.nRow++;
8434        }
8435      }
8436    }while( sCtx.cTerm!=EOF );
8437
8438    import_cleanup(&sCtx);
8439    sqlite3_finalize(pStmt);
8440    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8441    if( eVerbose>0 ){
8442      utf8_printf(p->out,
8443          "Added %d rows with %d errors using %d lines of input\n",
8444          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8445    }
8446  }else
8447
8448#ifndef SQLITE_UNTESTABLE
8449  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
8450    char *zSql;
8451    char *zCollist = 0;
8452    sqlite3_stmt *pStmt;
8453    int tnum = 0;
8454    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8455    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8456    int i;
8457    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8458      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8459                          "       .imposter off\n");
8460      /* Also allowed, but not documented:
8461      **
8462      **    .imposter TABLE IMPOSTER
8463      **
8464      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8465      ** imposter is another WITHOUT ROWID table with the columns in
8466      ** storage order. */
8467      rc = 1;
8468      goto meta_command_exit;
8469    }
8470    open_db(p, 0);
8471    if( nArg==2 ){
8472      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8473      goto meta_command_exit;
8474    }
8475    zSql = sqlite3_mprintf(
8476      "SELECT rootpage, 0 FROM sqlite_schema"
8477      " WHERE name='%q' AND type='index'"
8478      "UNION ALL "
8479      "SELECT rootpage, 1 FROM sqlite_schema"
8480      " WHERE name='%q' AND type='table'"
8481      "   AND sql LIKE '%%without%%rowid%%'",
8482      azArg[1], azArg[1]
8483    );
8484    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8485    sqlite3_free(zSql);
8486    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8487      tnum = sqlite3_column_int(pStmt, 0);
8488      isWO = sqlite3_column_int(pStmt, 1);
8489    }
8490    sqlite3_finalize(pStmt);
8491    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8492    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8493    sqlite3_free(zSql);
8494    i = 0;
8495    while( sqlite3_step(pStmt)==SQLITE_ROW ){
8496      char zLabel[20];
8497      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8498      i++;
8499      if( zCol==0 ){
8500        if( sqlite3_column_int(pStmt,1)==-1 ){
8501          zCol = "_ROWID_";
8502        }else{
8503          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8504          zCol = zLabel;
8505        }
8506      }
8507      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8508        lenPK = (int)strlen(zCollist);
8509      }
8510      if( zCollist==0 ){
8511        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8512      }else{
8513        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8514      }
8515    }
8516    sqlite3_finalize(pStmt);
8517    if( i==0 || tnum==0 ){
8518      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8519      rc = 1;
8520      sqlite3_free(zCollist);
8521      goto meta_command_exit;
8522    }
8523    if( lenPK==0 ) lenPK = 100000;
8524    zSql = sqlite3_mprintf(
8525          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8526          azArg[2], zCollist, lenPK, zCollist);
8527    sqlite3_free(zCollist);
8528    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8529    if( rc==SQLITE_OK ){
8530      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8531      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8532      if( rc ){
8533        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8534      }else{
8535        utf8_printf(stdout, "%s;\n", zSql);
8536        raw_printf(stdout,
8537          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8538          azArg[1], isWO ? "table" : "index"
8539        );
8540      }
8541    }else{
8542      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8543      rc = 1;
8544    }
8545    sqlite3_free(zSql);
8546  }else
8547#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8548
8549#ifdef SQLITE_ENABLE_IOTRACE
8550  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
8551    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8552    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8553    iotrace = 0;
8554    if( nArg<2 ){
8555      sqlite3IoTrace = 0;
8556    }else if( strcmp(azArg[1], "-")==0 ){
8557      sqlite3IoTrace = iotracePrintf;
8558      iotrace = stdout;
8559    }else{
8560      iotrace = fopen(azArg[1], "w");
8561      if( iotrace==0 ){
8562        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8563        sqlite3IoTrace = 0;
8564        rc = 1;
8565      }else{
8566        sqlite3IoTrace = iotracePrintf;
8567      }
8568    }
8569  }else
8570#endif
8571
8572  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
8573    static const struct {
8574       const char *zLimitName;   /* Name of a limit */
8575       int limitCode;            /* Integer code for that limit */
8576    } aLimit[] = {
8577      { "length",                SQLITE_LIMIT_LENGTH                    },
8578      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8579      { "column",                SQLITE_LIMIT_COLUMN                    },
8580      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8581      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8582      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8583      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8584      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8585      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8586      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8587      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8588      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8589    };
8590    int i, n2;
8591    open_db(p, 0);
8592    if( nArg==1 ){
8593      for(i=0; i<ArraySize(aLimit); i++){
8594        printf("%20s %d\n", aLimit[i].zLimitName,
8595               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8596      }
8597    }else if( nArg>3 ){
8598      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8599      rc = 1;
8600      goto meta_command_exit;
8601    }else{
8602      int iLimit = -1;
8603      n2 = strlen30(azArg[1]);
8604      for(i=0; i<ArraySize(aLimit); i++){
8605        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8606          if( iLimit<0 ){
8607            iLimit = i;
8608          }else{
8609            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8610            rc = 1;
8611            goto meta_command_exit;
8612          }
8613        }
8614      }
8615      if( iLimit<0 ){
8616        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8617                        "enter \".limits\" with no arguments for a list.\n",
8618                         azArg[1]);
8619        rc = 1;
8620        goto meta_command_exit;
8621      }
8622      if( nArg==3 ){
8623        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8624                      (int)integerValue(azArg[2]));
8625      }
8626      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8627             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8628    }
8629  }else
8630
8631  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
8632    open_db(p, 0);
8633    lintDotCommand(p, azArg, nArg);
8634  }else
8635
8636#ifndef SQLITE_OMIT_LOAD_EXTENSION
8637  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
8638    const char *zFile, *zProc;
8639    char *zErrMsg = 0;
8640    if( nArg<2 ){
8641      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8642      rc = 1;
8643      goto meta_command_exit;
8644    }
8645    zFile = azArg[1];
8646    zProc = nArg>=3 ? azArg[2] : 0;
8647    open_db(p, 0);
8648    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8649    if( rc!=SQLITE_OK ){
8650      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8651      sqlite3_free(zErrMsg);
8652      rc = 1;
8653    }
8654  }else
8655#endif
8656
8657  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
8658    if( nArg!=2 ){
8659      raw_printf(stderr, "Usage: .log FILENAME\n");
8660      rc = 1;
8661    }else{
8662      const char *zFile = azArg[1];
8663      output_file_close(p->pLog);
8664      p->pLog = output_file_open(zFile, 0);
8665    }
8666  }else
8667
8668  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
8669    const char *zMode = nArg>=2 ? azArg[1] : "";
8670    int n2 = strlen30(zMode);
8671    int c2 = zMode[0];
8672    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
8673      p->mode = MODE_Line;
8674      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8675    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
8676      p->mode = MODE_Column;
8677      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8678        p->showHeader = 1;
8679      }
8680      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8681    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
8682      p->mode = MODE_List;
8683      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8684      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8685    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
8686      p->mode = MODE_Html;
8687    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
8688      p->mode = MODE_Tcl;
8689      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8690      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8691    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
8692      p->mode = MODE_Csv;
8693      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8694      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8695    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8696      p->mode = MODE_List;
8697      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8698    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8699      p->mode = MODE_Insert;
8700      set_table_name(p, nArg>=3 ? azArg[2] : "table");
8701    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8702      p->mode = MODE_Quote;
8703      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8704      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8705    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8706      p->mode = MODE_Ascii;
8707      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8708      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8709    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
8710      p->mode = MODE_Markdown;
8711    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
8712      p->mode = MODE_Table;
8713    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
8714      p->mode = MODE_Box;
8715    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
8716      p->mode = MODE_Json;
8717    }else if( nArg==1 ){
8718      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8719    }else{
8720      raw_printf(stderr, "Error: mode should be one of: "
8721         "ascii box column csv html insert json line list markdown "
8722         "quote table tabs tcl\n");
8723      rc = 1;
8724    }
8725    p->cMode = p->mode;
8726  }else
8727
8728  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8729    if( nArg==2 ){
8730      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8731                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8732    }else{
8733      raw_printf(stderr, "Usage: .nullvalue STRING\n");
8734      rc = 1;
8735    }
8736  }else
8737
8738#ifdef SQLITE_DEBUG
8739  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
8740    int i;
8741    for(i=1; i<nArg; i++){
8742      const char *z = azArg[i];
8743      if( z[0]=='-' && z[1]=='-' ) z++;
8744      if( strcmp(z,"-repeat")==0 ){
8745        if( i==nArg-1 ){
8746          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
8747          rc = 1;
8748        }else{
8749          oomRepeat = (int)integerValue(azArg[++i]);
8750        }
8751      }else if( IsDigit(z[0]) ){
8752        oomCounter = (int)integerValue(azArg[i]);
8753      }else{
8754        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
8755        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
8756        rc = 1;
8757      }
8758    }
8759    if( rc==0 ){
8760      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
8761      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
8762    }
8763  }else
8764#endif /* SQLITE_DEBUG */
8765
8766  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8767    char *zNewFilename = 0;  /* Name of the database file to open */
8768    int iName = 1;           /* Index in azArg[] of the filename */
8769    int newFlag = 0;         /* True to delete file before opening */
8770    /* Close the existing database */
8771    session_close_all(p, -1);
8772    close_db(p->db);
8773    p->db = 0;
8774    p->pAuxDb->zDbFilename = 0;
8775    sqlite3_free(p->pAuxDb->zFreeOnClose);
8776    p->pAuxDb->zFreeOnClose = 0;
8777    p->openMode = SHELL_OPEN_UNSPEC;
8778    p->openFlags = 0;
8779    p->szMax = 0;
8780    /* Check for command-line arguments */
8781    for(iName=1; iName<nArg; iName++){
8782      const char *z = azArg[iName];
8783      if( optionMatch(z,"new") ){
8784        newFlag = 1;
8785#ifdef SQLITE_HAVE_ZLIB
8786      }else if( optionMatch(z, "zip") ){
8787        p->openMode = SHELL_OPEN_ZIPFILE;
8788#endif
8789      }else if( optionMatch(z, "append") ){
8790        p->openMode = SHELL_OPEN_APPENDVFS;
8791      }else if( optionMatch(z, "readonly") ){
8792        p->openMode = SHELL_OPEN_READONLY;
8793      }else if( optionMatch(z, "nofollow") ){
8794        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
8795      }else if( optionMatch(z, "excl") ){
8796        p->openFlags |= SQLITE_OPEN_EXCLUSIVE;
8797#ifndef SQLITE_OMIT_DESERIALIZE
8798      }else if( optionMatch(z, "deserialize") ){
8799        p->openMode = SHELL_OPEN_DESERIALIZE;
8800      }else if( optionMatch(z, "hexdb") ){
8801        p->openMode = SHELL_OPEN_HEXDB;
8802      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8803        p->szMax = integerValue(azArg[++iName]);
8804#endif /* SQLITE_OMIT_DESERIALIZE */
8805      }else if( z[0]=='-' ){
8806        utf8_printf(stderr, "unknown option: %s\n", z);
8807        rc = 1;
8808        goto meta_command_exit;
8809      }else if( zNewFilename ){
8810        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8811        rc = 1;
8812        goto meta_command_exit;
8813      }else{
8814        zNewFilename = sqlite3_mprintf("%s", z);
8815      }
8816    }
8817    /* If a filename is specified, try to open it first */
8818    if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
8819      if( newFlag ) shellDeleteFile(zNewFilename);
8820      p->pAuxDb->zDbFilename = zNewFilename;
8821      open_db(p, OPEN_DB_KEEPALIVE);
8822      if( p->db==0 ){
8823        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8824        sqlite3_free(zNewFilename);
8825      }else{
8826        p->pAuxDb->zFreeOnClose = zNewFilename;
8827      }
8828    }
8829    if( p->db==0 ){
8830      /* As a fall-back open a TEMP database */
8831      p->pAuxDb->zDbFilename = 0;
8832      open_db(p, 0);
8833    }
8834  }else
8835
8836  if( (c=='o'
8837        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8838   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
8839  ){
8840    char *zFile = 0;
8841    int bTxtMode = 0;
8842    int i;
8843    int eMode = 0;
8844    int bBOM = 0;
8845    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
8846
8847    if( c=='e' ){
8848      eMode = 'x';
8849      bOnce = 2;
8850    }else if( strncmp(azArg[0],"once",n)==0 ){
8851      bOnce = 1;
8852    }
8853    for(i=1; i<nArg; i++){
8854      char *z = azArg[i];
8855      if( z[0]=='-' ){
8856        if( z[1]=='-' ) z++;
8857        if( strcmp(z,"-bom")==0 ){
8858          bBOM = 1;
8859        }else if( c!='e' && strcmp(z,"-x")==0 ){
8860          eMode = 'x';  /* spreadsheet */
8861        }else if( c!='e' && strcmp(z,"-e")==0 ){
8862          eMode = 'e';  /* text editor */
8863        }else{
8864          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
8865                      azArg[i]);
8866          showHelp(p->out, azArg[0]);
8867          rc = 1;
8868          goto meta_command_exit;
8869        }
8870      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
8871        zFile = sqlite3_mprintf("%s", z);
8872        if( zFile[0]=='|' ){
8873          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
8874          break;
8875        }
8876      }else{
8877        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
8878                    azArg[i]);
8879        showHelp(p->out, azArg[0]);
8880        rc = 1;
8881        sqlite3_free(zFile);
8882        goto meta_command_exit;
8883      }
8884    }
8885    if( zFile==0 ) zFile = sqlite3_mprintf("stdout");
8886    if( bOnce ){
8887      p->outCount = 2;
8888    }else{
8889      p->outCount = 0;
8890    }
8891    output_reset(p);
8892#ifndef SQLITE_NOHAVE_SYSTEM
8893    if( eMode=='e' || eMode=='x' ){
8894      p->doXdgOpen = 1;
8895      outputModePush(p);
8896      if( eMode=='x' ){
8897        /* spreadsheet mode.  Output as CSV. */
8898        newTempFile(p, "csv");
8899        ShellClearFlag(p, SHFLG_Echo);
8900        p->mode = MODE_Csv;
8901        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8902        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8903      }else{
8904        /* text editor mode */
8905        newTempFile(p, "txt");
8906        bTxtMode = 1;
8907      }
8908      sqlite3_free(zFile);
8909      zFile = sqlite3_mprintf("%s", p->zTempFile);
8910    }
8911#endif /* SQLITE_NOHAVE_SYSTEM */
8912    if( zFile[0]=='|' ){
8913#ifdef SQLITE_OMIT_POPEN
8914      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8915      rc = 1;
8916      p->out = stdout;
8917#else
8918      p->out = popen(zFile + 1, "w");
8919      if( p->out==0 ){
8920        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8921        p->out = stdout;
8922        rc = 1;
8923      }else{
8924        if( bBOM ) fprintf(p->out,"\357\273\277");
8925        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8926      }
8927#endif
8928    }else{
8929      p->out = output_file_open(zFile, bTxtMode);
8930      if( p->out==0 ){
8931        if( strcmp(zFile,"off")!=0 ){
8932          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8933        }
8934        p->out = stdout;
8935        rc = 1;
8936      } else {
8937        if( bBOM ) fprintf(p->out,"\357\273\277");
8938        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8939      }
8940    }
8941    sqlite3_free(zFile);
8942  }else
8943
8944  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8945    open_db(p,0);
8946    if( nArg<=1 ) goto parameter_syntax_error;
8947
8948    /* .parameter clear
8949    ** Clear all bind parameters by dropping the TEMP table that holds them.
8950    */
8951    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
8952      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
8953                   0, 0, 0);
8954    }else
8955
8956    /* .parameter list
8957    ** List all bind parameters.
8958    */
8959    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8960      sqlite3_stmt *pStmt = 0;
8961      int rx;
8962      int len = 0;
8963      rx = sqlite3_prepare_v2(p->db,
8964             "SELECT max(length(key)) "
8965             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8966      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8967        len = sqlite3_column_int(pStmt, 0);
8968        if( len>40 ) len = 40;
8969      }
8970      sqlite3_finalize(pStmt);
8971      pStmt = 0;
8972      if( len ){
8973        rx = sqlite3_prepare_v2(p->db,
8974             "SELECT key, quote(value) "
8975             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
8976        while( sqlite3_step(pStmt)==SQLITE_ROW ){
8977          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8978                      sqlite3_column_text(pStmt,1));
8979        }
8980        sqlite3_finalize(pStmt);
8981      }
8982    }else
8983
8984    /* .parameter init
8985    ** Make sure the TEMP table used to hold bind parameters exists.
8986    ** Create it if necessary.
8987    */
8988    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8989      bind_table_init(p);
8990    }else
8991
8992    /* .parameter set NAME VALUE
8993    ** Set or reset a bind parameter.  NAME should be the full parameter
8994    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
8995    ** VALUE can be in either SQL literal notation, or if not it will be
8996    ** understood to be a text string.
8997    */
8998    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8999      int rx;
9000      char *zSql;
9001      sqlite3_stmt *pStmt;
9002      const char *zKey = azArg[2];
9003      const char *zValue = azArg[3];
9004      bind_table_init(p);
9005      zSql = sqlite3_mprintf(
9006                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9007                  "VALUES(%Q,%s);", zKey, zValue);
9008      if( zSql==0 ) shell_out_of_memory();
9009      pStmt = 0;
9010      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9011      sqlite3_free(zSql);
9012      if( rx!=SQLITE_OK ){
9013        sqlite3_finalize(pStmt);
9014        pStmt = 0;
9015        zSql = sqlite3_mprintf(
9016                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9017                   "VALUES(%Q,%Q);", zKey, zValue);
9018        if( zSql==0 ) shell_out_of_memory();
9019        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9020        sqlite3_free(zSql);
9021        if( rx!=SQLITE_OK ){
9022          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9023          sqlite3_finalize(pStmt);
9024          pStmt = 0;
9025          rc = 1;
9026        }
9027      }
9028      sqlite3_step(pStmt);
9029      sqlite3_finalize(pStmt);
9030    }else
9031
9032    /* .parameter unset NAME
9033    ** Remove the NAME binding from the parameter binding table, if it
9034    ** exists.
9035    */
9036    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9037      char *zSql = sqlite3_mprintf(
9038          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9039      if( zSql==0 ) shell_out_of_memory();
9040      sqlite3_exec(p->db, zSql, 0, 0, 0);
9041      sqlite3_free(zSql);
9042    }else
9043    /* If no command name matches, show a syntax error */
9044    parameter_syntax_error:
9045    showHelp(p->out, "parameter");
9046  }else
9047
9048  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9049    int i;
9050    for(i=1; i<nArg; i++){
9051      if( i>1 ) raw_printf(p->out, " ");
9052      utf8_printf(p->out, "%s", azArg[i]);
9053    }
9054    raw_printf(p->out, "\n");
9055  }else
9056
9057#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9058  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9059    int i;
9060    int nn = 0;
9061    p->flgProgress = 0;
9062    p->mxProgress = 0;
9063    p->nProgress = 0;
9064    for(i=1; i<nArg; i++){
9065      const char *z = azArg[i];
9066      if( z[0]=='-' ){
9067        z++;
9068        if( z[0]=='-' ) z++;
9069        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9070          p->flgProgress |= SHELL_PROGRESS_QUIET;
9071          continue;
9072        }
9073        if( strcmp(z,"reset")==0 ){
9074          p->flgProgress |= SHELL_PROGRESS_RESET;
9075          continue;
9076        }
9077        if( strcmp(z,"once")==0 ){
9078          p->flgProgress |= SHELL_PROGRESS_ONCE;
9079          continue;
9080        }
9081        if( strcmp(z,"limit")==0 ){
9082          if( i+1>=nArg ){
9083            utf8_printf(stderr, "Error: missing argument on --limit\n");
9084            rc = 1;
9085            goto meta_command_exit;
9086          }else{
9087            p->mxProgress = (int)integerValue(azArg[++i]);
9088          }
9089          continue;
9090        }
9091        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9092        rc = 1;
9093        goto meta_command_exit;
9094      }else{
9095        nn = (int)integerValue(z);
9096      }
9097    }
9098    open_db(p, 0);
9099    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9100  }else
9101#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9102
9103  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9104    if( nArg >= 2) {
9105      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9106    }
9107    if( nArg >= 3) {
9108      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9109    }
9110  }else
9111
9112  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9113    rc = 2;
9114  }else
9115
9116  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9117    FILE *inSaved = p->in;
9118    int savedLineno = p->lineno;
9119    if( nArg!=2 ){
9120      raw_printf(stderr, "Usage: .read FILE\n");
9121      rc = 1;
9122      goto meta_command_exit;
9123    }
9124    if( azArg[1][0]=='|' ){
9125#ifdef SQLITE_OMIT_POPEN
9126      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9127      rc = 1;
9128      p->out = stdout;
9129#else
9130      p->in = popen(azArg[1]+1, "r");
9131      if( p->in==0 ){
9132        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9133        rc = 1;
9134      }else{
9135        rc = process_input(p);
9136        pclose(p->in);
9137      }
9138#endif
9139    }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
9140      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9141      rc = 1;
9142    }else{
9143      rc = process_input(p);
9144      fclose(p->in);
9145    }
9146    p->in = inSaved;
9147    p->lineno = savedLineno;
9148  }else
9149
9150  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
9151    const char *zSrcFile;
9152    const char *zDb;
9153    sqlite3 *pSrc;
9154    sqlite3_backup *pBackup;
9155    int nTimeout = 0;
9156
9157    if( nArg==2 ){
9158      zSrcFile = azArg[1];
9159      zDb = "main";
9160    }else if( nArg==3 ){
9161      zSrcFile = azArg[2];
9162      zDb = azArg[1];
9163    }else{
9164      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9165      rc = 1;
9166      goto meta_command_exit;
9167    }
9168    rc = sqlite3_open(zSrcFile, &pSrc);
9169    if( rc!=SQLITE_OK ){
9170      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9171      close_db(pSrc);
9172      return 1;
9173    }
9174    open_db(p, 0);
9175    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9176    if( pBackup==0 ){
9177      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9178      close_db(pSrc);
9179      return 1;
9180    }
9181    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9182          || rc==SQLITE_BUSY  ){
9183      if( rc==SQLITE_BUSY ){
9184        if( nTimeout++ >= 3 ) break;
9185        sqlite3_sleep(100);
9186      }
9187    }
9188    sqlite3_backup_finish(pBackup);
9189    if( rc==SQLITE_DONE ){
9190      rc = 0;
9191    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9192      raw_printf(stderr, "Error: source database is busy\n");
9193      rc = 1;
9194    }else{
9195      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9196      rc = 1;
9197    }
9198    close_db(pSrc);
9199  }else
9200
9201  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
9202    if( nArg==2 ){
9203      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9204#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9205      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9206#endif
9207    }else{
9208      raw_printf(stderr, "Usage: .scanstats on|off\n");
9209      rc = 1;
9210    }
9211  }else
9212
9213  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
9214    ShellText sSelect;
9215    ShellState data;
9216    char *zErrMsg = 0;
9217    const char *zDiv = "(";
9218    const char *zName = 0;
9219    int iSchema = 0;
9220    int bDebug = 0;
9221    int bNoSystemTabs = 0;
9222    int ii;
9223
9224    open_db(p, 0);
9225    memcpy(&data, p, sizeof(data));
9226    data.showHeader = 0;
9227    data.cMode = data.mode = MODE_Semi;
9228    initText(&sSelect);
9229    for(ii=1; ii<nArg; ii++){
9230      if( optionMatch(azArg[ii],"indent") ){
9231        data.cMode = data.mode = MODE_Pretty;
9232      }else if( optionMatch(azArg[ii],"debug") ){
9233        bDebug = 1;
9234      }else if( optionMatch(azArg[ii],"nosys") ){
9235        bNoSystemTabs = 1;
9236      }else if( azArg[ii][0]=='-' ){
9237        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9238        rc = 1;
9239        goto meta_command_exit;
9240      }else if( zName==0 ){
9241        zName = azArg[ii];
9242      }else{
9243        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9244        rc = 1;
9245        goto meta_command_exit;
9246      }
9247    }
9248    if( zName!=0 ){
9249      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9250                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9251                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9252                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9253      if( isSchema ){
9254        char *new_argv[2], *new_colv[2];
9255        new_argv[0] = sqlite3_mprintf(
9256                      "CREATE TABLE %s (\n"
9257                      "  type text,\n"
9258                      "  name text,\n"
9259                      "  tbl_name text,\n"
9260                      "  rootpage integer,\n"
9261                      "  sql text\n"
9262                      ")", zName);
9263        new_argv[1] = 0;
9264        new_colv[0] = "sql";
9265        new_colv[1] = 0;
9266        callback(&data, 1, new_argv, new_colv);
9267        sqlite3_free(new_argv[0]);
9268      }
9269    }
9270    if( zDiv ){
9271      sqlite3_stmt *pStmt = 0;
9272      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9273                              -1, &pStmt, 0);
9274      if( rc ){
9275        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9276        sqlite3_finalize(pStmt);
9277        rc = 1;
9278        goto meta_command_exit;
9279      }
9280      appendText(&sSelect, "SELECT sql FROM", 0);
9281      iSchema = 0;
9282      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9283        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9284        char zScNum[30];
9285        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9286        appendText(&sSelect, zDiv, 0);
9287        zDiv = " UNION ALL ";
9288        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9289        if( sqlite3_stricmp(zDb, "main")!=0 ){
9290          appendText(&sSelect, zDb, '\'');
9291        }else{
9292          appendText(&sSelect, "NULL", 0);
9293        }
9294        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9295        appendText(&sSelect, zScNum, 0);
9296        appendText(&sSelect, " AS snum, ", 0);
9297        appendText(&sSelect, zDb, '\'');
9298        appendText(&sSelect, " AS sname FROM ", 0);
9299        appendText(&sSelect, zDb, quoteChar(zDb));
9300        appendText(&sSelect, ".sqlite_schema", 0);
9301      }
9302      sqlite3_finalize(pStmt);
9303#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9304      if( zName ){
9305        appendText(&sSelect,
9306           " UNION ALL SELECT shell_module_schema(name),"
9307           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9308        0);
9309      }
9310#endif
9311      appendText(&sSelect, ") WHERE ", 0);
9312      if( zName ){
9313        char *zQarg = sqlite3_mprintf("%Q", zName);
9314        int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9315                    strchr(zName, '[') != 0;
9316        if( strchr(zName, '.') ){
9317          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9318        }else{
9319          appendText(&sSelect, "lower(tbl_name)", 0);
9320        }
9321        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9322        appendText(&sSelect, zQarg, 0);
9323        if( !bGlob ){
9324          appendText(&sSelect, " ESCAPE '\\' ", 0);
9325        }
9326        appendText(&sSelect, " AND ", 0);
9327        sqlite3_free(zQarg);
9328      }
9329      if( bNoSystemTabs ){
9330        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9331      }
9332      appendText(&sSelect, "sql IS NOT NULL"
9333                           " ORDER BY snum, rowid", 0);
9334      if( bDebug ){
9335        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9336      }else{
9337        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9338      }
9339      freeText(&sSelect);
9340    }
9341    if( zErrMsg ){
9342      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9343      sqlite3_free(zErrMsg);
9344      rc = 1;
9345    }else if( rc != SQLITE_OK ){
9346      raw_printf(stderr,"Error: querying schema information\n");
9347      rc = 1;
9348    }else{
9349      rc = 0;
9350    }
9351  }else
9352
9353  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
9354    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9355    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9356  }else
9357
9358#if defined(SQLITE_ENABLE_SESSION)
9359  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
9360    struct AuxDb *pAuxDb = p->pAuxDb;
9361    OpenSession *pSession = &pAuxDb->aSession[0];
9362    char **azCmd = &azArg[1];
9363    int iSes = 0;
9364    int nCmd = nArg - 1;
9365    int i;
9366    if( nArg<=1 ) goto session_syntax_error;
9367    open_db(p, 0);
9368    if( nArg>=3 ){
9369      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9370        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9371      }
9372      if( iSes<pAuxDb->nSession ){
9373        pSession = &pAuxDb->aSession[iSes];
9374        azCmd++;
9375        nCmd--;
9376      }else{
9377        pSession = &pAuxDb->aSession[0];
9378        iSes = 0;
9379      }
9380    }
9381
9382    /* .session attach TABLE
9383    ** Invoke the sqlite3session_attach() interface to attach a particular
9384    ** table so that it is never filtered.
9385    */
9386    if( strcmp(azCmd[0],"attach")==0 ){
9387      if( nCmd!=2 ) goto session_syntax_error;
9388      if( pSession->p==0 ){
9389        session_not_open:
9390        raw_printf(stderr, "ERROR: No sessions are open\n");
9391      }else{
9392        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9393        if( rc ){
9394          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9395          rc = 0;
9396        }
9397      }
9398    }else
9399
9400    /* .session changeset FILE
9401    ** .session patchset FILE
9402    ** Write a changeset or patchset into a file.  The file is overwritten.
9403    */
9404    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
9405      FILE *out = 0;
9406      if( nCmd!=2 ) goto session_syntax_error;
9407      if( pSession->p==0 ) goto session_not_open;
9408      out = fopen(azCmd[1], "wb");
9409      if( out==0 ){
9410        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9411                    azCmd[1]);
9412      }else{
9413        int szChng;
9414        void *pChng;
9415        if( azCmd[0][0]=='c' ){
9416          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9417        }else{
9418          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9419        }
9420        if( rc ){
9421          printf("Error: error code %d\n", rc);
9422          rc = 0;
9423        }
9424        if( pChng
9425          && fwrite(pChng, szChng, 1, out)!=1 ){
9426          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9427                  szChng);
9428        }
9429        sqlite3_free(pChng);
9430        fclose(out);
9431      }
9432    }else
9433
9434    /* .session close
9435    ** Close the identified session
9436    */
9437    if( strcmp(azCmd[0], "close")==0 ){
9438      if( nCmd!=1 ) goto session_syntax_error;
9439      if( pAuxDb->nSession ){
9440        session_close(pSession);
9441        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9442      }
9443    }else
9444
9445    /* .session enable ?BOOLEAN?
9446    ** Query or set the enable flag
9447    */
9448    if( strcmp(azCmd[0], "enable")==0 ){
9449      int ii;
9450      if( nCmd>2 ) goto session_syntax_error;
9451      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9452      if( pAuxDb->nSession ){
9453        ii = sqlite3session_enable(pSession->p, ii);
9454        utf8_printf(p->out, "session %s enable flag = %d\n",
9455                    pSession->zName, ii);
9456      }
9457    }else
9458
9459    /* .session filter GLOB ....
9460    ** Set a list of GLOB patterns of table names to be excluded.
9461    */
9462    if( strcmp(azCmd[0], "filter")==0 ){
9463      int ii, nByte;
9464      if( nCmd<2 ) goto session_syntax_error;
9465      if( pAuxDb->nSession ){
9466        for(ii=0; ii<pSession->nFilter; ii++){
9467          sqlite3_free(pSession->azFilter[ii]);
9468        }
9469        sqlite3_free(pSession->azFilter);
9470        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9471        pSession->azFilter = sqlite3_malloc( nByte );
9472        if( pSession->azFilter==0 ){
9473          raw_printf(stderr, "Error: out or memory\n");
9474          exit(1);
9475        }
9476        for(ii=1; ii<nCmd; ii++){
9477          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9478        }
9479        pSession->nFilter = ii-1;
9480      }
9481    }else
9482
9483    /* .session indirect ?BOOLEAN?
9484    ** Query or set the indirect flag
9485    */
9486    if( strcmp(azCmd[0], "indirect")==0 ){
9487      int ii;
9488      if( nCmd>2 ) goto session_syntax_error;
9489      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9490      if( pAuxDb->nSession ){
9491        ii = sqlite3session_indirect(pSession->p, ii);
9492        utf8_printf(p->out, "session %s indirect flag = %d\n",
9493                    pSession->zName, ii);
9494      }
9495    }else
9496
9497    /* .session isempty
9498    ** Determine if the session is empty
9499    */
9500    if( strcmp(azCmd[0], "isempty")==0 ){
9501      int ii;
9502      if( nCmd!=1 ) goto session_syntax_error;
9503      if( pAuxDb->nSession ){
9504        ii = sqlite3session_isempty(pSession->p);
9505        utf8_printf(p->out, "session %s isempty flag = %d\n",
9506                    pSession->zName, ii);
9507      }
9508    }else
9509
9510    /* .session list
9511    ** List all currently open sessions
9512    */
9513    if( strcmp(azCmd[0],"list")==0 ){
9514      for(i=0; i<pAuxDb->nSession; i++){
9515        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9516      }
9517    }else
9518
9519    /* .session open DB NAME
9520    ** Open a new session called NAME on the attached database DB.
9521    ** DB is normally "main".
9522    */
9523    if( strcmp(azCmd[0],"open")==0 ){
9524      char *zName;
9525      if( nCmd!=3 ) goto session_syntax_error;
9526      zName = azCmd[2];
9527      if( zName[0]==0 ) goto session_syntax_error;
9528      for(i=0; i<pAuxDb->nSession; i++){
9529        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9530          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9531          goto meta_command_exit;
9532        }
9533      }
9534      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9535        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9536        goto meta_command_exit;
9537      }
9538      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9539      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9540      if( rc ){
9541        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9542        rc = 0;
9543        goto meta_command_exit;
9544      }
9545      pSession->nFilter = 0;
9546      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9547      pAuxDb->nSession++;
9548      pSession->zName = sqlite3_mprintf("%s", zName);
9549    }else
9550    /* If no command name matches, show a syntax error */
9551    session_syntax_error:
9552    showHelp(p->out, "session");
9553  }else
9554#endif
9555
9556#ifdef SQLITE_DEBUG
9557  /* Undocumented commands for internal testing.  Subject to change
9558  ** without notice. */
9559  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
9560    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9561      int i, v;
9562      for(i=1; i<nArg; i++){
9563        v = booleanValue(azArg[i]);
9564        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9565      }
9566    }
9567    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
9568      int i; sqlite3_int64 v;
9569      for(i=1; i<nArg; i++){
9570        char zBuf[200];
9571        v = integerValue(azArg[i]);
9572        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9573        utf8_printf(p->out, "%s", zBuf);
9574      }
9575    }
9576  }else
9577#endif
9578
9579  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
9580    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9581    int bVerbose = 0;        /* Verbose output */
9582    int bSelftestExists;     /* True if SELFTEST already exists */
9583    int i, k;                /* Loop counters */
9584    int nTest = 0;           /* Number of tests runs */
9585    int nErr = 0;            /* Number of errors seen */
9586    ShellText str;           /* Answer for a query */
9587    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9588
9589    open_db(p,0);
9590    for(i=1; i<nArg; i++){
9591      const char *z = azArg[i];
9592      if( z[0]=='-' && z[1]=='-' ) z++;
9593      if( strcmp(z,"-init")==0 ){
9594        bIsInit = 1;
9595      }else
9596      if( strcmp(z,"-v")==0 ){
9597        bVerbose++;
9598      }else
9599      {
9600        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9601                    azArg[i], azArg[0]);
9602        raw_printf(stderr, "Should be one of: --init -v\n");
9603        rc = 1;
9604        goto meta_command_exit;
9605      }
9606    }
9607    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9608           != SQLITE_OK ){
9609      bSelftestExists = 0;
9610    }else{
9611      bSelftestExists = 1;
9612    }
9613    if( bIsInit ){
9614      createSelftestTable(p);
9615      bSelftestExists = 1;
9616    }
9617    initText(&str);
9618    appendText(&str, "x", 0);
9619    for(k=bSelftestExists; k>=0; k--){
9620      if( k==1 ){
9621        rc = sqlite3_prepare_v2(p->db,
9622            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9623            -1, &pStmt, 0);
9624      }else{
9625        rc = sqlite3_prepare_v2(p->db,
9626          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9627          "      (1,'run','PRAGMA integrity_check','ok')",
9628          -1, &pStmt, 0);
9629      }
9630      if( rc ){
9631        raw_printf(stderr, "Error querying the selftest table\n");
9632        rc = 1;
9633        sqlite3_finalize(pStmt);
9634        goto meta_command_exit;
9635      }
9636      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9637        int tno = sqlite3_column_int(pStmt, 0);
9638        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9639        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9640        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9641
9642        k = 0;
9643        if( bVerbose>0 ){
9644          char *zQuote = sqlite3_mprintf("%q", zSql);
9645          printf("%d: %s %s\n", tno, zOp, zSql);
9646          sqlite3_free(zQuote);
9647        }
9648        if( strcmp(zOp,"memo")==0 ){
9649          utf8_printf(p->out, "%s\n", zSql);
9650        }else
9651        if( strcmp(zOp,"run")==0 ){
9652          char *zErrMsg = 0;
9653          str.n = 0;
9654          str.z[0] = 0;
9655          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9656          nTest++;
9657          if( bVerbose ){
9658            utf8_printf(p->out, "Result: %s\n", str.z);
9659          }
9660          if( rc || zErrMsg ){
9661            nErr++;
9662            rc = 1;
9663            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9664            sqlite3_free(zErrMsg);
9665          }else if( strcmp(zAns,str.z)!=0 ){
9666            nErr++;
9667            rc = 1;
9668            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9669            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9670          }
9671        }else
9672        {
9673          utf8_printf(stderr,
9674            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
9675          rc = 1;
9676          break;
9677        }
9678      } /* End loop over rows of content from SELFTEST */
9679      sqlite3_finalize(pStmt);
9680    } /* End loop over k */
9681    freeText(&str);
9682    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
9683  }else
9684
9685  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
9686    if( nArg<2 || nArg>3 ){
9687      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
9688      rc = 1;
9689    }
9690    if( nArg>=2 ){
9691      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
9692                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
9693    }
9694    if( nArg>=3 ){
9695      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
9696                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
9697    }
9698  }else
9699
9700  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
9701    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
9702    int i;                   /* Loop counter */
9703    int bSchema = 0;         /* Also hash the schema */
9704    int bSeparate = 0;       /* Hash each table separately */
9705    int iSize = 224;         /* Hash algorithm to use */
9706    int bDebug = 0;          /* Only show the query that would have run */
9707    sqlite3_stmt *pStmt;     /* For querying tables names */
9708    char *zSql;              /* SQL to be run */
9709    char *zSep;              /* Separator */
9710    ShellText sSql;          /* Complete SQL for the query to run the hash */
9711    ShellText sQuery;        /* Set of queries used to read all content */
9712    open_db(p, 0);
9713    for(i=1; i<nArg; i++){
9714      const char *z = azArg[i];
9715      if( z[0]=='-' ){
9716        z++;
9717        if( z[0]=='-' ) z++;
9718        if( strcmp(z,"schema")==0 ){
9719          bSchema = 1;
9720        }else
9721        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
9722         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
9723        ){
9724          iSize = atoi(&z[5]);
9725        }else
9726        if( strcmp(z,"debug")==0 ){
9727          bDebug = 1;
9728        }else
9729        {
9730          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9731                      azArg[i], azArg[0]);
9732          showHelp(p->out, azArg[0]);
9733          rc = 1;
9734          goto meta_command_exit;
9735        }
9736      }else if( zLike ){
9737        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
9738        rc = 1;
9739        goto meta_command_exit;
9740      }else{
9741        zLike = z;
9742        bSeparate = 1;
9743        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
9744      }
9745    }
9746    if( bSchema ){
9747      zSql = "SELECT lower(name) FROM sqlite_schema"
9748             " WHERE type='table' AND coalesce(rootpage,0)>1"
9749             " UNION ALL SELECT 'sqlite_schema'"
9750             " ORDER BY 1 collate nocase";
9751    }else{
9752      zSql = "SELECT lower(name) FROM sqlite_schema"
9753             " WHERE type='table' AND coalesce(rootpage,0)>1"
9754             " AND name NOT LIKE 'sqlite_%'"
9755             " ORDER BY 1 collate nocase";
9756    }
9757    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9758    initText(&sQuery);
9759    initText(&sSql);
9760    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
9761    zSep = "VALUES(";
9762    while( SQLITE_ROW==sqlite3_step(pStmt) ){
9763      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
9764      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
9765      if( strncmp(zTab, "sqlite_",7)!=0 ){
9766        appendText(&sQuery,"SELECT * FROM ", 0);
9767        appendText(&sQuery,zTab,'"');
9768        appendText(&sQuery," NOT INDEXED;", 0);
9769      }else if( strcmp(zTab, "sqlite_schema")==0 ){
9770        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
9771                           " ORDER BY name;", 0);
9772      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
9773        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
9774                           " ORDER BY name;", 0);
9775      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
9776        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
9777                           " ORDER BY tbl,idx;", 0);
9778      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
9779        appendText(&sQuery, "SELECT * FROM ", 0);
9780        appendText(&sQuery, zTab, 0);
9781        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
9782      }
9783      appendText(&sSql, zSep, 0);
9784      appendText(&sSql, sQuery.z, '\'');
9785      sQuery.n = 0;
9786      appendText(&sSql, ",", 0);
9787      appendText(&sSql, zTab, '\'');
9788      zSep = "),(";
9789    }
9790    sqlite3_finalize(pStmt);
9791    if( bSeparate ){
9792      zSql = sqlite3_mprintf(
9793          "%s))"
9794          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
9795          "   FROM [sha3sum$query]",
9796          sSql.z, iSize);
9797    }else{
9798      zSql = sqlite3_mprintf(
9799          "%s))"
9800          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
9801          "   FROM [sha3sum$query]",
9802          sSql.z, iSize);
9803    }
9804    freeText(&sQuery);
9805    freeText(&sSql);
9806    if( bDebug ){
9807      utf8_printf(p->out, "%s\n", zSql);
9808    }else{
9809      shell_exec(p, zSql, 0);
9810    }
9811    sqlite3_free(zSql);
9812  }else
9813
9814#ifndef SQLITE_NOHAVE_SYSTEM
9815  if( c=='s'
9816   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
9817  ){
9818    char *zCmd;
9819    int i, x;
9820    if( nArg<2 ){
9821      raw_printf(stderr, "Usage: .system COMMAND\n");
9822      rc = 1;
9823      goto meta_command_exit;
9824    }
9825    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
9826    for(i=2; i<nArg; i++){
9827      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
9828                             zCmd, azArg[i]);
9829    }
9830    x = system(zCmd);
9831    sqlite3_free(zCmd);
9832    if( x ) raw_printf(stderr, "System command returns %d\n", x);
9833  }else
9834#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
9835
9836  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
9837    static const char *azBool[] = { "off", "on", "trigger", "full"};
9838    const char *zOut;
9839    int i;
9840    if( nArg!=1 ){
9841      raw_printf(stderr, "Usage: .show\n");
9842      rc = 1;
9843      goto meta_command_exit;
9844    }
9845    utf8_printf(p->out, "%12.12s: %s\n","echo",
9846                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
9847    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
9848    utf8_printf(p->out, "%12.12s: %s\n","explain",
9849         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
9850    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
9851    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
9852    utf8_printf(p->out, "%12.12s: ", "nullvalue");
9853      output_c_string(p->out, p->nullValue);
9854      raw_printf(p->out, "\n");
9855    utf8_printf(p->out,"%12.12s: %s\n","output",
9856            strlen30(p->outfile) ? p->outfile : "stdout");
9857    utf8_printf(p->out,"%12.12s: ", "colseparator");
9858      output_c_string(p->out, p->colSeparator);
9859      raw_printf(p->out, "\n");
9860    utf8_printf(p->out,"%12.12s: ", "rowseparator");
9861      output_c_string(p->out, p->rowSeparator);
9862      raw_printf(p->out, "\n");
9863    switch( p->statsOn ){
9864      case 0:  zOut = "off";     break;
9865      default: zOut = "on";      break;
9866      case 2:  zOut = "stmt";    break;
9867      case 3:  zOut = "vmstep";  break;
9868    }
9869    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
9870    utf8_printf(p->out, "%12.12s: ", "width");
9871    for (i=0;i<p->nWidth;i++) {
9872      raw_printf(p->out, "%d ", p->colWidth[i]);
9873    }
9874    raw_printf(p->out, "\n");
9875    utf8_printf(p->out, "%12.12s: %s\n", "filename",
9876                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
9877  }else
9878
9879  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9880    if( nArg==2 ){
9881      if( strcmp(azArg[1],"stmt")==0 ){
9882        p->statsOn = 2;
9883      }else if( strcmp(azArg[1],"vmstep")==0 ){
9884        p->statsOn = 3;
9885      }else{
9886        p->statsOn = (u8)booleanValue(azArg[1]);
9887      }
9888    }else if( nArg==1 ){
9889      display_stats(p->db, p, 0);
9890    }else{
9891      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
9892      rc = 1;
9893    }
9894  }else
9895
9896  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9897   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9898                 || strncmp(azArg[0], "indexes", n)==0) )
9899  ){
9900    sqlite3_stmt *pStmt;
9901    char **azResult;
9902    int nRow, nAlloc;
9903    int ii;
9904    ShellText s;
9905    initText(&s);
9906    open_db(p, 0);
9907    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
9908    if( rc ){
9909      sqlite3_finalize(pStmt);
9910      return shellDatabaseError(p->db);
9911    }
9912
9913    if( nArg>2 && c=='i' ){
9914      /* It is an historical accident that the .indexes command shows an error
9915      ** when called with the wrong number of arguments whereas the .tables
9916      ** command does not. */
9917      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9918      rc = 1;
9919      sqlite3_finalize(pStmt);
9920      goto meta_command_exit;
9921    }
9922    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9923      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9924      if( zDbName==0 ) continue;
9925      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9926      if( sqlite3_stricmp(zDbName, "main")==0 ){
9927        appendText(&s, "SELECT name FROM ", 0);
9928      }else{
9929        appendText(&s, "SELECT ", 0);
9930        appendText(&s, zDbName, '\'');
9931        appendText(&s, "||'.'||name FROM ", 0);
9932      }
9933      appendText(&s, zDbName, '"');
9934      appendText(&s, ".sqlite_schema ", 0);
9935      if( c=='t' ){
9936        appendText(&s," WHERE type IN ('table','view')"
9937                      "   AND name NOT LIKE 'sqlite_%'"
9938                      "   AND name LIKE ?1", 0);
9939      }else{
9940        appendText(&s," WHERE type='index'"
9941                      "   AND tbl_name LIKE ?1", 0);
9942      }
9943    }
9944    rc = sqlite3_finalize(pStmt);
9945    appendText(&s, " ORDER BY 1", 0);
9946    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9947    freeText(&s);
9948    if( rc ) return shellDatabaseError(p->db);
9949
9950    /* Run the SQL statement prepared by the above block. Store the results
9951    ** as an array of nul-terminated strings in azResult[].  */
9952    nRow = nAlloc = 0;
9953    azResult = 0;
9954    if( nArg>1 ){
9955      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9956    }else{
9957      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9958    }
9959    while( sqlite3_step(pStmt)==SQLITE_ROW ){
9960      if( nRow>=nAlloc ){
9961        char **azNew;
9962        int n2 = nAlloc*2 + 10;
9963        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
9964        if( azNew==0 ) shell_out_of_memory();
9965        nAlloc = n2;
9966        azResult = azNew;
9967      }
9968      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
9969      if( 0==azResult[nRow] ) shell_out_of_memory();
9970      nRow++;
9971    }
9972    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9973      rc = shellDatabaseError(p->db);
9974    }
9975
9976    /* Pretty-print the contents of array azResult[] to the output */
9977    if( rc==0 && nRow>0 ){
9978      int len, maxlen = 0;
9979      int i, j;
9980      int nPrintCol, nPrintRow;
9981      for(i=0; i<nRow; i++){
9982        len = strlen30(azResult[i]);
9983        if( len>maxlen ) maxlen = len;
9984      }
9985      nPrintCol = 80/(maxlen+2);
9986      if( nPrintCol<1 ) nPrintCol = 1;
9987      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9988      for(i=0; i<nPrintRow; i++){
9989        for(j=i; j<nRow; j+=nPrintRow){
9990          char *zSp = j<nPrintRow ? "" : "  ";
9991          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9992                      azResult[j] ? azResult[j]:"");
9993        }
9994        raw_printf(p->out, "\n");
9995      }
9996    }
9997
9998    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9999    sqlite3_free(azResult);
10000  }else
10001
10002  /* Begin redirecting output to the file "testcase-out.txt" */
10003  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10004    output_reset(p);
10005    p->out = output_file_open("testcase-out.txt", 0);
10006    if( p->out==0 ){
10007      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10008    }
10009    if( nArg>=2 ){
10010      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10011    }else{
10012      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10013    }
10014  }else
10015
10016#ifndef SQLITE_UNTESTABLE
10017  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10018    static const struct {
10019       const char *zCtrlName;   /* Name of a test-control option */
10020       int ctrlCode;            /* Integer code for that option */
10021       const char *zUsage;      /* Usage notes */
10022    } aCtrl[] = {
10023      { "always",             SQLITE_TESTCTRL_ALWAYS,        "BOOLEAN"        },
10024      { "assert",             SQLITE_TESTCTRL_ASSERT,        "BOOLEAN"        },
10025    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, ""       },*/
10026    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST,   ""             },*/
10027      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER,     ""               },
10028      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
10029    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
10030      { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
10031      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
10032      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
10033      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
10034      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
10035#ifdef YYCOVERAGE
10036      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE, ""             },
10037#endif
10038      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,  "OFFSET  "       },
10039      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
10040      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
10041      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
10042      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
10043      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP,   "NMAX"           },
10044      { "tune",               SQLITE_TESTCTRL_TUNE,          "ID VALUE"       },
10045    };
10046    int testctrl = -1;
10047    int iCtrl = -1;
10048    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10049    int isOk = 0;
10050    int i, n2;
10051    const char *zCmd = 0;
10052
10053    open_db(p, 0);
10054    zCmd = nArg>=2 ? azArg[1] : "help";
10055
10056    /* The argument can optionally begin with "-" or "--" */
10057    if( zCmd[0]=='-' && zCmd[1] ){
10058      zCmd++;
10059      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10060    }
10061
10062    /* --help lists all test-controls */
10063    if( strcmp(zCmd,"help")==0 ){
10064      utf8_printf(p->out, "Available test-controls:\n");
10065      for(i=0; i<ArraySize(aCtrl); i++){
10066        utf8_printf(p->out, "  .testctrl %s %s\n",
10067                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10068      }
10069      rc = 1;
10070      goto meta_command_exit;
10071    }
10072
10073    /* convert testctrl text option to value. allow any unique prefix
10074    ** of the option name, or a numerical value. */
10075    n2 = strlen30(zCmd);
10076    for(i=0; i<ArraySize(aCtrl); i++){
10077      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10078        if( testctrl<0 ){
10079          testctrl = aCtrl[i].ctrlCode;
10080          iCtrl = i;
10081        }else{
10082          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10083                              "Use \".testctrl --help\" for help\n", zCmd);
10084          rc = 1;
10085          goto meta_command_exit;
10086        }
10087      }
10088    }
10089    if( testctrl<0 ){
10090      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10091                         "Use \".testctrl --help\" for help\n", zCmd);
10092    }else{
10093      switch(testctrl){
10094
10095        /* sqlite3_test_control(int, db, int) */
10096        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10097          if( nArg==3 ){
10098            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10099            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10100            isOk = 3;
10101          }
10102          break;
10103
10104        /* sqlite3_test_control(int) */
10105        case SQLITE_TESTCTRL_PRNG_SAVE:
10106        case SQLITE_TESTCTRL_PRNG_RESTORE:
10107        case SQLITE_TESTCTRL_BYTEORDER:
10108          if( nArg==2 ){
10109            rc2 = sqlite3_test_control(testctrl);
10110            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10111          }
10112          break;
10113
10114        /* sqlite3_test_control(int, uint) */
10115        case SQLITE_TESTCTRL_PENDING_BYTE:
10116          if( nArg==3 ){
10117            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10118            rc2 = sqlite3_test_control(testctrl, opt);
10119            isOk = 3;
10120          }
10121          break;
10122
10123        /* sqlite3_test_control(int, int, sqlite3*) */
10124        case SQLITE_TESTCTRL_PRNG_SEED:
10125          if( nArg==3 || nArg==4 ){
10126            int ii = (int)integerValue(azArg[2]);
10127            sqlite3 *db;
10128            if( ii==0 && strcmp(azArg[2],"random")==0 ){
10129              sqlite3_randomness(sizeof(ii),&ii);
10130              printf("-- random seed: %d\n", ii);
10131            }
10132            if( nArg==3 ){
10133              db = 0;
10134            }else{
10135              db = p->db;
10136              /* Make sure the schema has been loaded */
10137              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10138            }
10139            rc2 = sqlite3_test_control(testctrl, ii, db);
10140            isOk = 3;
10141          }
10142          break;
10143
10144        /* sqlite3_test_control(int, int) */
10145        case SQLITE_TESTCTRL_ASSERT:
10146        case SQLITE_TESTCTRL_ALWAYS:
10147          if( nArg==3 ){
10148            int opt = booleanValue(azArg[2]);
10149            rc2 = sqlite3_test_control(testctrl, opt);
10150            isOk = 1;
10151          }
10152          break;
10153
10154        /* sqlite3_test_control(int, int) */
10155        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10156        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10157          if( nArg==3 ){
10158            int opt = booleanValue(azArg[2]);
10159            rc2 = sqlite3_test_control(testctrl, opt);
10160            isOk = 3;
10161          }
10162          break;
10163
10164        /* sqlite3_test_control(sqlite3*) */
10165        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10166          rc2 = sqlite3_test_control(testctrl, p->db);
10167          isOk = 3;
10168          break;
10169
10170        case SQLITE_TESTCTRL_IMPOSTER:
10171          if( nArg==5 ){
10172            rc2 = sqlite3_test_control(testctrl, p->db,
10173                          azArg[2],
10174                          integerValue(azArg[3]),
10175                          integerValue(azArg[4]));
10176            isOk = 3;
10177          }
10178          break;
10179
10180        case SQLITE_TESTCTRL_SEEK_COUNT: {
10181          u64 x = 0;
10182          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10183          utf8_printf(p->out, "%llu\n", x);
10184          isOk = 3;
10185          break;
10186        }
10187
10188#ifdef YYCOVERAGE
10189        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10190          if( nArg==2 ){
10191            sqlite3_test_control(testctrl, p->out);
10192            isOk = 3;
10193          }
10194          break;
10195        }
10196#endif
10197#ifdef SQLITE_DEBUG
10198        case SQLITE_TESTCTRL_TUNE: {
10199          if( nArg==4 ){
10200            int id = (int)integerValue(azArg[2]);
10201            int val = (int)integerValue(azArg[3]);
10202            sqlite3_test_control(testctrl, id, &val);
10203            isOk = 3;
10204          }else if( nArg==3 ){
10205            int id = (int)integerValue(azArg[2]);
10206            sqlite3_test_control(testctrl, -id, &rc2);
10207            isOk = 1;
10208          }else if( nArg==2 ){
10209            int id = 1;
10210            while(1){
10211              int val = 0;
10212              rc2 = sqlite3_test_control(testctrl, -id, &val);
10213              if( rc2!=SQLITE_OK ) break;
10214              if( id>1 ) utf8_printf(p->out, "  ");
10215              utf8_printf(p->out, "%d: %d", id, val);
10216              id++;
10217            }
10218            if( id>1 ) utf8_printf(p->out, "\n");
10219            isOk = 3;
10220          }
10221          break;
10222        }
10223#endif
10224        case SQLITE_TESTCTRL_SORTER_MMAP:
10225          if( nArg==3 ){
10226            int opt = (unsigned int)integerValue(azArg[2]);
10227            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10228            isOk = 3;
10229          }
10230          break;
10231      }
10232    }
10233    if( isOk==0 && iCtrl>=0 ){
10234      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10235      rc = 1;
10236    }else if( isOk==1 ){
10237      raw_printf(p->out, "%d\n", rc2);
10238    }else if( isOk==2 ){
10239      raw_printf(p->out, "0x%08x\n", rc2);
10240    }
10241  }else
10242#endif /* !defined(SQLITE_UNTESTABLE) */
10243
10244  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
10245    open_db(p, 0);
10246    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10247  }else
10248
10249  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
10250    if( nArg==2 ){
10251      enableTimer = booleanValue(azArg[1]);
10252      if( enableTimer && !HAS_TIMER ){
10253        raw_printf(stderr, "Error: timer not available on this system.\n");
10254        enableTimer = 0;
10255      }
10256    }else{
10257      raw_printf(stderr, "Usage: .timer on|off\n");
10258      rc = 1;
10259    }
10260  }else
10261
10262#ifndef SQLITE_OMIT_TRACE
10263  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
10264    int mType = 0;
10265    int jj;
10266    open_db(p, 0);
10267    for(jj=1; jj<nArg; jj++){
10268      const char *z = azArg[jj];
10269      if( z[0]=='-' ){
10270        if( optionMatch(z, "expanded") ){
10271          p->eTraceType = SHELL_TRACE_EXPANDED;
10272        }
10273#ifdef SQLITE_ENABLE_NORMALIZE
10274        else if( optionMatch(z, "normalized") ){
10275          p->eTraceType = SHELL_TRACE_NORMALIZED;
10276        }
10277#endif
10278        else if( optionMatch(z, "plain") ){
10279          p->eTraceType = SHELL_TRACE_PLAIN;
10280        }
10281        else if( optionMatch(z, "profile") ){
10282          mType |= SQLITE_TRACE_PROFILE;
10283        }
10284        else if( optionMatch(z, "row") ){
10285          mType |= SQLITE_TRACE_ROW;
10286        }
10287        else if( optionMatch(z, "stmt") ){
10288          mType |= SQLITE_TRACE_STMT;
10289        }
10290        else if( optionMatch(z, "close") ){
10291          mType |= SQLITE_TRACE_CLOSE;
10292        }
10293        else {
10294          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10295          rc = 1;
10296          goto meta_command_exit;
10297        }
10298      }else{
10299        output_file_close(p->traceOut);
10300        p->traceOut = output_file_open(azArg[1], 0);
10301      }
10302    }
10303    if( p->traceOut==0 ){
10304      sqlite3_trace_v2(p->db, 0, 0, 0);
10305    }else{
10306      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10307      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10308    }
10309  }else
10310#endif /* !defined(SQLITE_OMIT_TRACE) */
10311
10312#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10313  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
10314    int ii;
10315    int lenOpt;
10316    char *zOpt;
10317    if( nArg<2 ){
10318      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10319      rc = 1;
10320      goto meta_command_exit;
10321    }
10322    open_db(p, 0);
10323    zOpt = azArg[1];
10324    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10325    lenOpt = (int)strlen(zOpt);
10326    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10327      assert( azArg[nArg]==0 );
10328      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10329    }else{
10330      for(ii=1; ii<nArg; ii++){
10331        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10332      }
10333    }
10334  }else
10335#endif
10336
10337#if SQLITE_USER_AUTHENTICATION
10338  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
10339    if( nArg<2 ){
10340      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10341      rc = 1;
10342      goto meta_command_exit;
10343    }
10344    open_db(p, 0);
10345    if( strcmp(azArg[1],"login")==0 ){
10346      if( nArg!=4 ){
10347        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10348        rc = 1;
10349        goto meta_command_exit;
10350      }
10351      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10352                                     strlen30(azArg[3]));
10353      if( rc ){
10354        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10355        rc = 1;
10356      }
10357    }else if( strcmp(azArg[1],"add")==0 ){
10358      if( nArg!=5 ){
10359        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10360        rc = 1;
10361        goto meta_command_exit;
10362      }
10363      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10364                            booleanValue(azArg[4]));
10365      if( rc ){
10366        raw_printf(stderr, "User-Add failed: %d\n", rc);
10367        rc = 1;
10368      }
10369    }else if( strcmp(azArg[1],"edit")==0 ){
10370      if( nArg!=5 ){
10371        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10372        rc = 1;
10373        goto meta_command_exit;
10374      }
10375      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10376                              booleanValue(azArg[4]));
10377      if( rc ){
10378        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10379        rc = 1;
10380      }
10381    }else if( strcmp(azArg[1],"delete")==0 ){
10382      if( nArg!=3 ){
10383        raw_printf(stderr, "Usage: .user delete USER\n");
10384        rc = 1;
10385        goto meta_command_exit;
10386      }
10387      rc = sqlite3_user_delete(p->db, azArg[2]);
10388      if( rc ){
10389        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10390        rc = 1;
10391      }
10392    }else{
10393      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10394      rc = 1;
10395      goto meta_command_exit;
10396    }
10397  }else
10398#endif /* SQLITE_USER_AUTHENTICATION */
10399
10400  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
10401    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10402        sqlite3_libversion(), sqlite3_sourceid());
10403#if SQLITE_HAVE_ZLIB
10404    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10405#endif
10406#define CTIMEOPT_VAL_(opt) #opt
10407#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10408#if defined(__clang__) && defined(__clang_major__)
10409    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10410                    CTIMEOPT_VAL(__clang_minor__) "."
10411                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10412#elif defined(_MSC_VER)
10413    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10414#elif defined(__GNUC__) && defined(__VERSION__)
10415    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10416#endif
10417  }else
10418
10419  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
10420    const char *zDbName = nArg==2 ? azArg[1] : "main";
10421    sqlite3_vfs *pVfs = 0;
10422    if( p->db ){
10423      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10424      if( pVfs ){
10425        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10426        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10427        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10428        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10429      }
10430    }
10431  }else
10432
10433  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
10434    sqlite3_vfs *pVfs;
10435    sqlite3_vfs *pCurrent = 0;
10436    if( p->db ){
10437      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10438    }
10439    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10440      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10441           pVfs==pCurrent ? "  <--- CURRENT" : "");
10442      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10443      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10444      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10445      if( pVfs->pNext ){
10446        raw_printf(p->out, "-----------------------------------\n");
10447      }
10448    }
10449  }else
10450
10451  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
10452    const char *zDbName = nArg==2 ? azArg[1] : "main";
10453    char *zVfsName = 0;
10454    if( p->db ){
10455      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10456      if( zVfsName ){
10457        utf8_printf(p->out, "%s\n", zVfsName);
10458        sqlite3_free(zVfsName);
10459      }
10460    }
10461  }else
10462
10463  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
10464    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10465    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10466  }else
10467
10468  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
10469    int j;
10470    assert( nArg<=ArraySize(azArg) );
10471    p->nWidth = nArg-1;
10472    p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
10473    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10474    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10475    for(j=1; j<nArg; j++){
10476      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10477    }
10478  }else
10479
10480  {
10481    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10482      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10483    rc = 1;
10484  }
10485
10486meta_command_exit:
10487  if( p->outCount ){
10488    p->outCount--;
10489    if( p->outCount==0 ) output_reset(p);
10490  }
10491  return rc;
10492}
10493
10494/*
10495** Return TRUE if a semicolon occurs anywhere in the first N characters
10496** of string z[].
10497*/
10498static int line_contains_semicolon(const char *z, int N){
10499  int i;
10500  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
10501  return 0;
10502}
10503
10504/*
10505** Test to see if a line consists entirely of whitespace.
10506*/
10507static int _all_whitespace(const char *z){
10508  for(; *z; z++){
10509    if( IsSpace(z[0]) ) continue;
10510    if( *z=='/' && z[1]=='*' ){
10511      z += 2;
10512      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
10513      if( *z==0 ) return 0;
10514      z++;
10515      continue;
10516    }
10517    if( *z=='-' && z[1]=='-' ){
10518      z += 2;
10519      while( *z && *z!='\n' ){ z++; }
10520      if( *z==0 ) return 1;
10521      continue;
10522    }
10523    return 0;
10524  }
10525  return 1;
10526}
10527
10528/*
10529** Return TRUE if the line typed in is an SQL command terminator other
10530** than a semi-colon.  The SQL Server style "go" command is understood
10531** as is the Oracle "/".
10532*/
10533static int line_is_command_terminator(const char *zLine){
10534  while( IsSpace(zLine[0]) ){ zLine++; };
10535  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
10536    return 1;  /* Oracle */
10537  }
10538  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
10539         && _all_whitespace(&zLine[2]) ){
10540    return 1;  /* SQL Server */
10541  }
10542  return 0;
10543}
10544
10545/*
10546** We need a default sqlite3_complete() implementation to use in case
10547** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10548** any arbitrary text is a complete SQL statement.  This is not very
10549** user-friendly, but it does seem to work.
10550*/
10551#ifdef SQLITE_OMIT_COMPLETE
10552#define sqlite3_complete(x) 1
10553#endif
10554
10555/*
10556** Return true if zSql is a complete SQL statement.  Return false if it
10557** ends in the middle of a string literal or C-style comment.
10558*/
10559static int line_is_complete(char *zSql, int nSql){
10560  int rc;
10561  if( zSql==0 ) return 1;
10562  zSql[nSql] = ';';
10563  zSql[nSql+1] = 0;
10564  rc = sqlite3_complete(zSql);
10565  zSql[nSql] = 0;
10566  return rc;
10567}
10568
10569/*
10570** Run a single line of SQL.  Return the number of errors.
10571*/
10572static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10573  int rc;
10574  char *zErrMsg = 0;
10575
10576  open_db(p, 0);
10577  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10578  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10579  BEGIN_TIMER;
10580  rc = shell_exec(p, zSql, &zErrMsg);
10581  END_TIMER;
10582  if( rc || zErrMsg ){
10583    char zPrefix[100];
10584    if( in!=0 || !stdin_is_interactive ){
10585      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
10586                       "Error: near line %d:", startline);
10587    }else{
10588      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
10589    }
10590    if( zErrMsg!=0 ){
10591      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
10592      sqlite3_free(zErrMsg);
10593      zErrMsg = 0;
10594    }else{
10595      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
10596    }
10597    return 1;
10598  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
10599    raw_printf(p->out, "changes: %3lld   total_changes: %lld\n",
10600            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
10601  }
10602  return 0;
10603}
10604
10605
10606/*
10607** Read input from *in and process it.  If *in==0 then input
10608** is interactive - the user is typing it it.  Otherwise, input
10609** is coming from a file or device.  A prompt is issued and history
10610** is saved only if input is interactive.  An interrupt signal will
10611** cause this routine to exit immediately, unless input is interactive.
10612**
10613** Return the number of errors.
10614*/
10615static int process_input(ShellState *p){
10616  char *zLine = 0;          /* A single input line */
10617  char *zSql = 0;           /* Accumulated SQL text */
10618  int nLine;                /* Length of current line */
10619  int nSql = 0;             /* Bytes of zSql[] used */
10620  int nAlloc = 0;           /* Allocated zSql[] space */
10621  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
10622  int rc;                   /* Error code */
10623  int errCnt = 0;           /* Number of errors seen */
10624  int startline = 0;        /* Line number for start of current input */
10625
10626  p->lineno = 0;
10627  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
10628    fflush(p->out);
10629    zLine = one_input_line(p->in, zLine, nSql>0);
10630    if( zLine==0 ){
10631      /* End of input */
10632      if( p->in==0 && stdin_is_interactive ) printf("\n");
10633      break;
10634    }
10635    if( seenInterrupt ){
10636      if( p->in!=0 ) break;
10637      seenInterrupt = 0;
10638    }
10639    p->lineno++;
10640    if( nSql==0 && _all_whitespace(zLine) ){
10641      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10642      continue;
10643    }
10644    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
10645      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
10646      if( zLine[0]=='.' ){
10647        rc = do_meta_command(zLine, p);
10648        if( rc==2 ){ /* exit requested */
10649          break;
10650        }else if( rc ){
10651          errCnt++;
10652        }
10653      }
10654      continue;
10655    }
10656    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
10657      memcpy(zLine,";",2);
10658    }
10659    nLine = strlen30(zLine);
10660    if( nSql+nLine+2>=nAlloc ){
10661      nAlloc = nSql+nLine+100;
10662      zSql = realloc(zSql, nAlloc);
10663      if( zSql==0 ) shell_out_of_memory();
10664    }
10665    nSqlPrior = nSql;
10666    if( nSql==0 ){
10667      int i;
10668      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
10669      assert( nAlloc>0 && zSql!=0 );
10670      memcpy(zSql, zLine+i, nLine+1-i);
10671      startline = p->lineno;
10672      nSql = nLine-i;
10673    }else{
10674      zSql[nSql++] = '\n';
10675      memcpy(zSql+nSql, zLine, nLine+1);
10676      nSql += nLine;
10677    }
10678    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
10679                && sqlite3_complete(zSql) ){
10680      errCnt += runOneSqlLine(p, zSql, p->in, startline);
10681      nSql = 0;
10682      if( p->outCount ){
10683        output_reset(p);
10684        p->outCount = 0;
10685      }else{
10686        clearTempFile(p);
10687      }
10688    }else if( nSql && _all_whitespace(zSql) ){
10689      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
10690      nSql = 0;
10691    }
10692  }
10693  if( nSql && !_all_whitespace(zSql) ){
10694    errCnt += runOneSqlLine(p, zSql, p->in, startline);
10695  }
10696  free(zSql);
10697  free(zLine);
10698  return errCnt>0;
10699}
10700
10701/*
10702** Return a pathname which is the user's home directory.  A
10703** 0 return indicates an error of some kind.
10704*/
10705static char *find_home_dir(int clearFlag){
10706  static char *home_dir = NULL;
10707  if( clearFlag ){
10708    free(home_dir);
10709    home_dir = 0;
10710    return 0;
10711  }
10712  if( home_dir ) return home_dir;
10713
10714#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
10715     && !defined(__RTP__) && !defined(_WRS_KERNEL)
10716  {
10717    struct passwd *pwent;
10718    uid_t uid = getuid();
10719    if( (pwent=getpwuid(uid)) != NULL) {
10720      home_dir = pwent->pw_dir;
10721    }
10722  }
10723#endif
10724
10725#if defined(_WIN32_WCE)
10726  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
10727   */
10728  home_dir = "/";
10729#else
10730
10731#if defined(_WIN32) || defined(WIN32)
10732  if (!home_dir) {
10733    home_dir = getenv("USERPROFILE");
10734  }
10735#endif
10736
10737  if (!home_dir) {
10738    home_dir = getenv("HOME");
10739  }
10740
10741#if defined(_WIN32) || defined(WIN32)
10742  if (!home_dir) {
10743    char *zDrive, *zPath;
10744    int n;
10745    zDrive = getenv("HOMEDRIVE");
10746    zPath = getenv("HOMEPATH");
10747    if( zDrive && zPath ){
10748      n = strlen30(zDrive) + strlen30(zPath) + 1;
10749      home_dir = malloc( n );
10750      if( home_dir==0 ) return 0;
10751      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
10752      return home_dir;
10753    }
10754    home_dir = "c:\\";
10755  }
10756#endif
10757
10758#endif /* !_WIN32_WCE */
10759
10760  if( home_dir ){
10761    int n = strlen30(home_dir) + 1;
10762    char *z = malloc( n );
10763    if( z ) memcpy(z, home_dir, n);
10764    home_dir = z;
10765  }
10766
10767  return home_dir;
10768}
10769
10770/*
10771** Read input from the file given by sqliterc_override.  Or if that
10772** parameter is NULL, take input from ~/.sqliterc
10773**
10774** Returns the number of errors.
10775*/
10776static void process_sqliterc(
10777  ShellState *p,                  /* Configuration data */
10778  const char *sqliterc_override   /* Name of config file. NULL to use default */
10779){
10780  char *home_dir = NULL;
10781  const char *sqliterc = sqliterc_override;
10782  char *zBuf = 0;
10783  FILE *inSaved = p->in;
10784  int savedLineno = p->lineno;
10785
10786  if (sqliterc == NULL) {
10787    home_dir = find_home_dir(0);
10788    if( home_dir==0 ){
10789      raw_printf(stderr, "-- warning: cannot find home directory;"
10790                      " cannot read ~/.sqliterc\n");
10791      return;
10792    }
10793    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
10794    sqliterc = zBuf;
10795  }
10796  p->in = fopen(sqliterc,"rb");
10797  if( p->in ){
10798    if( stdin_is_interactive ){
10799      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
10800    }
10801    if( process_input(p) && bail_on_error ) exit(1);
10802    fclose(p->in);
10803  }else if( sqliterc_override!=0 ){
10804    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
10805    if( bail_on_error ) exit(1);
10806  }
10807  p->in = inSaved;
10808  p->lineno = savedLineno;
10809  sqlite3_free(zBuf);
10810}
10811
10812/*
10813** Show available command line options
10814*/
10815static const char zOptions[] =
10816#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10817  "   -A ARGS...           run \".archive ARGS\" and exit\n"
10818#endif
10819  "   -append              append the database to the end of the file\n"
10820  "   -ascii               set output mode to 'ascii'\n"
10821  "   -bail                stop after hitting an error\n"
10822  "   -batch               force batch I/O\n"
10823  "   -box                 set output mode to 'box'\n"
10824  "   -column              set output mode to 'column'\n"
10825  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
10826  "   -csv                 set output mode to 'csv'\n"
10827#if !defined(SQLITE_OMIT_DESERIALIZE)
10828  "   -deserialize         open the database using sqlite3_deserialize()\n"
10829#endif
10830  "   -echo                print commands before execution\n"
10831  "   -init FILENAME       read/process named file\n"
10832  "   -[no]header          turn headers on or off\n"
10833#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10834  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
10835#endif
10836  "   -help                show this message\n"
10837  "   -html                set output mode to HTML\n"
10838  "   -interactive         force interactive I/O\n"
10839  "   -json                set output mode to 'json'\n"
10840  "   -line                set output mode to 'line'\n"
10841  "   -list                set output mode to 'list'\n"
10842  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
10843  "   -markdown            set output mode to 'markdown'\n"
10844#if !defined(SQLITE_OMIT_DESERIALIZE)
10845  "   -maxsize N           maximum size for a --deserialize database\n"
10846#endif
10847  "   -memtrace            trace all memory allocations and deallocations\n"
10848  "   -mmap N              default mmap size set to N\n"
10849#ifdef SQLITE_ENABLE_MULTIPLEX
10850  "   -multiplex           enable the multiplexor VFS\n"
10851#endif
10852  "   -newline SEP         set output row separator. Default: '\\n'\n"
10853  "   -nofollow            refuse to open symbolic links to database files\n"
10854  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
10855  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
10856  "   -quote               set output mode to 'quote'\n"
10857  "   -readonly            open the database read-only\n"
10858  "   -separator SEP       set output column separator. Default: '|'\n"
10859#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10860  "   -sorterref SIZE      sorter references threshold size\n"
10861#endif
10862  "   -stats               print memory stats before each finalize\n"
10863  "   -table               set output mode to 'table'\n"
10864  "   -tabs                set output mode to 'tabs'\n"
10865  "   -version             show SQLite version\n"
10866  "   -vfs NAME            use NAME as the default VFS\n"
10867#ifdef SQLITE_ENABLE_VFSTRACE
10868  "   -vfstrace            enable tracing of all VFS calls\n"
10869#endif
10870#ifdef SQLITE_HAVE_ZLIB
10871  "   -zip                 open the file as a ZIP Archive\n"
10872#endif
10873;
10874static void usage(int showDetail){
10875  utf8_printf(stderr,
10876      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
10877      "FILENAME is the name of an SQLite database. A new database is created\n"
10878      "if the file does not previously exist.\n", Argv0);
10879  if( showDetail ){
10880    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
10881  }else{
10882    raw_printf(stderr, "Use the -help option for additional information\n");
10883  }
10884  exit(1);
10885}
10886
10887/*
10888** Internal check:  Verify that the SQLite is uninitialized.  Print a
10889** error message if it is initialized.
10890*/
10891static void verify_uninitialized(void){
10892  if( sqlite3_config(-1)==SQLITE_MISUSE ){
10893    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
10894                        " initialization.\n");
10895  }
10896}
10897
10898/*
10899** Initialize the state information in data
10900*/
10901static void main_init(ShellState *data) {
10902  memset(data, 0, sizeof(*data));
10903  data->normalMode = data->cMode = data->mode = MODE_List;
10904  data->autoExplain = 1;
10905  data->pAuxDb = &data->aAuxDb[0];
10906  memcpy(data->colSeparator,SEP_Column, 2);
10907  memcpy(data->rowSeparator,SEP_Row, 2);
10908  data->showHeader = 0;
10909  data->shellFlgs = SHFLG_Lookaside;
10910  verify_uninitialized();
10911  sqlite3_config(SQLITE_CONFIG_URI, 1);
10912  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
10913  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
10914  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
10915  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
10916}
10917
10918/*
10919** Output text to the console in a font that attracts extra attention.
10920*/
10921#ifdef _WIN32
10922static void printBold(const char *zText){
10923#if !SQLITE_OS_WINRT
10924  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
10925  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
10926  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
10927  SetConsoleTextAttribute(out,
10928         FOREGROUND_RED|FOREGROUND_INTENSITY
10929  );
10930#endif
10931  printf("%s", zText);
10932#if !SQLITE_OS_WINRT
10933  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
10934#endif
10935}
10936#else
10937static void printBold(const char *zText){
10938  printf("\033[1m%s\033[0m", zText);
10939}
10940#endif
10941
10942/*
10943** Get the argument to an --option.  Throw an error and die if no argument
10944** is available.
10945*/
10946static char *cmdline_option_value(int argc, char **argv, int i){
10947  if( i==argc ){
10948    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
10949            argv[0], argv[argc-1]);
10950    exit(1);
10951  }
10952  return argv[i];
10953}
10954
10955#ifndef SQLITE_SHELL_IS_UTF8
10956#  if (defined(_WIN32) || defined(WIN32)) \
10957   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
10958#    define SQLITE_SHELL_IS_UTF8          (0)
10959#  else
10960#    define SQLITE_SHELL_IS_UTF8          (1)
10961#  endif
10962#endif
10963
10964#if SQLITE_SHELL_IS_UTF8
10965int SQLITE_CDECL main(int argc, char **argv){
10966#else
10967int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
10968  char **argv;
10969#endif
10970  char *zErrMsg = 0;
10971  ShellState data;
10972  const char *zInitFile = 0;
10973  int i;
10974  int rc = 0;
10975  int warnInmemoryDb = 0;
10976  int readStdin = 1;
10977  int nCmd = 0;
10978  char **azCmd = 0;
10979  const char *zVfs = 0;           /* Value of -vfs command-line option */
10980#if !SQLITE_SHELL_IS_UTF8
10981  char **argvToFree = 0;
10982  int argcToFree = 0;
10983#endif
10984
10985  setBinaryMode(stdin, 0);
10986  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
10987  stdin_is_interactive = isatty(0);
10988  stdout_is_console = isatty(1);
10989
10990#ifdef SQLITE_DEBUG
10991  registerOomSimulator();
10992#endif
10993
10994#if !defined(_WIN32_WCE)
10995  if( getenv("SQLITE_DEBUG_BREAK") ){
10996    if( isatty(0) && isatty(2) ){
10997      fprintf(stderr,
10998          "attach debugger to process %d and press any key to continue.\n",
10999          GETPID());
11000      fgetc(stdin);
11001    }else{
11002#if defined(_WIN32) || defined(WIN32)
11003#if SQLITE_OS_WINRT
11004      __debugbreak();
11005#else
11006      DebugBreak();
11007#endif
11008#elif defined(SIGTRAP)
11009      raise(SIGTRAP);
11010#endif
11011    }
11012  }
11013#endif
11014
11015#if USE_SYSTEM_SQLITE+0!=1
11016  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11017    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11018            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11019    exit(1);
11020  }
11021#endif
11022  main_init(&data);
11023
11024  /* On Windows, we must translate command-line arguments into UTF-8.
11025  ** The SQLite memory allocator subsystem has to be enabled in order to
11026  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11027  ** subsequent sqlite3_config() calls will work.  So copy all results into
11028  ** memory that does not come from the SQLite memory allocator.
11029  */
11030#if !SQLITE_SHELL_IS_UTF8
11031  sqlite3_initialize();
11032  argvToFree = malloc(sizeof(argv[0])*argc*2);
11033  argcToFree = argc;
11034  argv = argvToFree + argc;
11035  if( argv==0 ) shell_out_of_memory();
11036  for(i=0; i<argc; i++){
11037    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11038    int n;
11039    if( z==0 ) shell_out_of_memory();
11040    n = (int)strlen(z);
11041    argv[i] = malloc( n+1 );
11042    if( argv[i]==0 ) shell_out_of_memory();
11043    memcpy(argv[i], z, n+1);
11044    argvToFree[i] = argv[i];
11045    sqlite3_free(z);
11046  }
11047  sqlite3_shutdown();
11048#endif
11049
11050  assert( argc>=1 && argv && argv[0] );
11051  Argv0 = argv[0];
11052
11053  /* Make sure we have a valid signal handler early, before anything
11054  ** else is done.
11055  */
11056#ifdef SIGINT
11057  signal(SIGINT, interrupt_handler);
11058#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11059  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11060#endif
11061
11062#ifdef SQLITE_SHELL_DBNAME_PROC
11063  {
11064    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11065    ** of a C-function that will provide the name of the database file.  Use
11066    ** this compile-time option to embed this shell program in larger
11067    ** applications. */
11068    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11069    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11070    warnInmemoryDb = 0;
11071  }
11072#endif
11073
11074  /* Do an initial pass through the command-line argument to locate
11075  ** the name of the database file, the name of the initialization file,
11076  ** the size of the alternative malloc heap,
11077  ** and the first command to execute.
11078  */
11079  verify_uninitialized();
11080  for(i=1; i<argc; i++){
11081    char *z;
11082    z = argv[i];
11083    if( z[0]!='-' ){
11084      if( data.aAuxDb->zDbFilename==0 ){
11085        data.aAuxDb->zDbFilename = z;
11086      }else{
11087        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11088        ** mean that nothing is read from stdin */
11089        readStdin = 0;
11090        nCmd++;
11091        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11092        if( azCmd==0 ) shell_out_of_memory();
11093        azCmd[nCmd-1] = z;
11094      }
11095    }
11096    if( z[1]=='-' ) z++;
11097    if( strcmp(z,"-separator")==0
11098     || strcmp(z,"-nullvalue")==0
11099     || strcmp(z,"-newline")==0
11100     || strcmp(z,"-cmd")==0
11101    ){
11102      (void)cmdline_option_value(argc, argv, ++i);
11103    }else if( strcmp(z,"-init")==0 ){
11104      zInitFile = cmdline_option_value(argc, argv, ++i);
11105    }else if( strcmp(z,"-batch")==0 ){
11106      /* Need to check for batch mode here to so we can avoid printing
11107      ** informational messages (like from process_sqliterc) before
11108      ** we do the actual processing of arguments later in a second pass.
11109      */
11110      stdin_is_interactive = 0;
11111    }else if( strcmp(z,"-heap")==0 ){
11112#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11113      const char *zSize;
11114      sqlite3_int64 szHeap;
11115
11116      zSize = cmdline_option_value(argc, argv, ++i);
11117      szHeap = integerValue(zSize);
11118      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11119      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11120#else
11121      (void)cmdline_option_value(argc, argv, ++i);
11122#endif
11123    }else if( strcmp(z,"-pagecache")==0 ){
11124      sqlite3_int64 n, sz;
11125      sz = integerValue(cmdline_option_value(argc,argv,++i));
11126      if( sz>70000 ) sz = 70000;
11127      if( sz<0 ) sz = 0;
11128      n = integerValue(cmdline_option_value(argc,argv,++i));
11129      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11130        n = 0xffffffffffffLL/sz;
11131      }
11132      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11133                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11134      data.shellFlgs |= SHFLG_Pagecache;
11135    }else if( strcmp(z,"-lookaside")==0 ){
11136      int n, sz;
11137      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11138      if( sz<0 ) sz = 0;
11139      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11140      if( n<0 ) n = 0;
11141      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11142      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11143#ifdef SQLITE_ENABLE_VFSTRACE
11144    }else if( strcmp(z,"-vfstrace")==0 ){
11145      extern int vfstrace_register(
11146         const char *zTraceName,
11147         const char *zOldVfsName,
11148         int (*xOut)(const char*,void*),
11149         void *pOutArg,
11150         int makeDefault
11151      );
11152      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11153#endif
11154#ifdef SQLITE_ENABLE_MULTIPLEX
11155    }else if( strcmp(z,"-multiplex")==0 ){
11156      extern int sqlite3_multiple_initialize(const char*,int);
11157      sqlite3_multiplex_initialize(0, 1);
11158#endif
11159    }else if( strcmp(z,"-mmap")==0 ){
11160      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11161      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11162#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11163    }else if( strcmp(z,"-sorterref")==0 ){
11164      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11165      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11166#endif
11167    }else if( strcmp(z,"-vfs")==0 ){
11168      zVfs = cmdline_option_value(argc, argv, ++i);
11169#ifdef SQLITE_HAVE_ZLIB
11170    }else if( strcmp(z,"-zip")==0 ){
11171      data.openMode = SHELL_OPEN_ZIPFILE;
11172#endif
11173    }else if( strcmp(z,"-append")==0 ){
11174      data.openMode = SHELL_OPEN_APPENDVFS;
11175#ifndef SQLITE_OMIT_DESERIALIZE
11176    }else if( strcmp(z,"-deserialize")==0 ){
11177      data.openMode = SHELL_OPEN_DESERIALIZE;
11178    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11179      data.szMax = integerValue(argv[++i]);
11180#endif
11181    }else if( strcmp(z,"-readonly")==0 ){
11182      data.openMode = SHELL_OPEN_READONLY;
11183    }else if( strcmp(z,"-nofollow")==0 ){
11184      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11185#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11186    }else if( strncmp(z, "-A",2)==0 ){
11187      /* All remaining command-line arguments are passed to the ".archive"
11188      ** command, so ignore them */
11189      break;
11190#endif
11191    }else if( strcmp(z, "-memtrace")==0 ){
11192      sqlite3MemTraceActivate(stderr);
11193    }else if( strcmp(z,"-bail")==0 ){
11194      bail_on_error = 1;
11195    }
11196  }
11197  verify_uninitialized();
11198
11199
11200#ifdef SQLITE_SHELL_INIT_PROC
11201  {
11202    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11203    ** of a C-function that will perform initialization actions on SQLite that
11204    ** occur just before or after sqlite3_initialize(). Use this compile-time
11205    ** option to embed this shell program in larger applications. */
11206    extern void SQLITE_SHELL_INIT_PROC(void);
11207    SQLITE_SHELL_INIT_PROC();
11208  }
11209#else
11210  /* All the sqlite3_config() calls have now been made. So it is safe
11211  ** to call sqlite3_initialize() and process any command line -vfs option. */
11212  sqlite3_initialize();
11213#endif
11214
11215  if( zVfs ){
11216    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11217    if( pVfs ){
11218      sqlite3_vfs_register(pVfs, 1);
11219    }else{
11220      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11221      exit(1);
11222    }
11223  }
11224
11225  if( data.pAuxDb->zDbFilename==0 ){
11226#ifndef SQLITE_OMIT_MEMORYDB
11227    data.pAuxDb->zDbFilename = ":memory:";
11228    warnInmemoryDb = argc==1;
11229#else
11230    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11231    return 1;
11232#endif
11233  }
11234  data.out = stdout;
11235  sqlite3_appendvfs_init(0,0,0);
11236
11237  /* Go ahead and open the database file if it already exists.  If the
11238  ** file does not exist, delay opening it.  This prevents empty database
11239  ** files from being created if a user mistypes the database name argument
11240  ** to the sqlite command-line tool.
11241  */
11242  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11243    open_db(&data, 0);
11244  }
11245
11246  /* Process the initialization file if there is one.  If no -init option
11247  ** is given on the command line, look for a file named ~/.sqliterc and
11248  ** try to process it.
11249  */
11250  process_sqliterc(&data,zInitFile);
11251
11252  /* Make a second pass through the command-line argument and set
11253  ** options.  This second pass is delayed until after the initialization
11254  ** file is processed so that the command-line arguments will override
11255  ** settings in the initialization file.
11256  */
11257  for(i=1; i<argc; i++){
11258    char *z = argv[i];
11259    if( z[0]!='-' ) continue;
11260    if( z[1]=='-' ){ z++; }
11261    if( strcmp(z,"-init")==0 ){
11262      i++;
11263    }else if( strcmp(z,"-html")==0 ){
11264      data.mode = MODE_Html;
11265    }else if( strcmp(z,"-list")==0 ){
11266      data.mode = MODE_List;
11267    }else if( strcmp(z,"-quote")==0 ){
11268      data.mode = MODE_Quote;
11269      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11270      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11271    }else if( strcmp(z,"-line")==0 ){
11272      data.mode = MODE_Line;
11273    }else if( strcmp(z,"-column")==0 ){
11274      data.mode = MODE_Column;
11275    }else if( strcmp(z,"-json")==0 ){
11276      data.mode = MODE_Json;
11277    }else if( strcmp(z,"-markdown")==0 ){
11278      data.mode = MODE_Markdown;
11279    }else if( strcmp(z,"-table")==0 ){
11280      data.mode = MODE_Table;
11281    }else if( strcmp(z,"-box")==0 ){
11282      data.mode = MODE_Box;
11283    }else if( strcmp(z,"-csv")==0 ){
11284      data.mode = MODE_Csv;
11285      memcpy(data.colSeparator,",",2);
11286#ifdef SQLITE_HAVE_ZLIB
11287    }else if( strcmp(z,"-zip")==0 ){
11288      data.openMode = SHELL_OPEN_ZIPFILE;
11289#endif
11290    }else if( strcmp(z,"-append")==0 ){
11291      data.openMode = SHELL_OPEN_APPENDVFS;
11292#ifndef SQLITE_OMIT_DESERIALIZE
11293    }else if( strcmp(z,"-deserialize")==0 ){
11294      data.openMode = SHELL_OPEN_DESERIALIZE;
11295    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
11296      data.szMax = integerValue(argv[++i]);
11297#endif
11298    }else if( strcmp(z,"-readonly")==0 ){
11299      data.openMode = SHELL_OPEN_READONLY;
11300    }else if( strcmp(z,"-nofollow")==0 ){
11301      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11302    }else if( strcmp(z,"-ascii")==0 ){
11303      data.mode = MODE_Ascii;
11304      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11305      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11306    }else if( strcmp(z,"-tabs")==0 ){
11307      data.mode = MODE_List;
11308      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11309      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11310    }else if( strcmp(z,"-separator")==0 ){
11311      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11312                       "%s",cmdline_option_value(argc,argv,++i));
11313    }else if( strcmp(z,"-newline")==0 ){
11314      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11315                       "%s",cmdline_option_value(argc,argv,++i));
11316    }else if( strcmp(z,"-nullvalue")==0 ){
11317      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11318                       "%s",cmdline_option_value(argc,argv,++i));
11319    }else if( strcmp(z,"-header")==0 ){
11320      data.showHeader = 1;
11321    }else if( strcmp(z,"-noheader")==0 ){
11322      data.showHeader = 0;
11323    }else if( strcmp(z,"-echo")==0 ){
11324      ShellSetFlag(&data, SHFLG_Echo);
11325    }else if( strcmp(z,"-eqp")==0 ){
11326      data.autoEQP = AUTOEQP_on;
11327    }else if( strcmp(z,"-eqpfull")==0 ){
11328      data.autoEQP = AUTOEQP_full;
11329    }else if( strcmp(z,"-stats")==0 ){
11330      data.statsOn = 1;
11331    }else if( strcmp(z,"-scanstats")==0 ){
11332      data.scanstatsOn = 1;
11333    }else if( strcmp(z,"-backslash")==0 ){
11334      /* Undocumented command-line option: -backslash
11335      ** Causes C-style backslash escapes to be evaluated in SQL statements
11336      ** prior to sending the SQL into SQLite.  Useful for injecting
11337      ** crazy bytes in the middle of SQL statements for testing and debugging.
11338      */
11339      ShellSetFlag(&data, SHFLG_Backslash);
11340    }else if( strcmp(z,"-bail")==0 ){
11341      /* No-op.  The bail_on_error flag should already be set. */
11342    }else if( strcmp(z,"-version")==0 ){
11343      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11344      return 0;
11345    }else if( strcmp(z,"-interactive")==0 ){
11346      stdin_is_interactive = 1;
11347    }else if( strcmp(z,"-batch")==0 ){
11348      stdin_is_interactive = 0;
11349    }else if( strcmp(z,"-heap")==0 ){
11350      i++;
11351    }else if( strcmp(z,"-pagecache")==0 ){
11352      i+=2;
11353    }else if( strcmp(z,"-lookaside")==0 ){
11354      i+=2;
11355    }else if( strcmp(z,"-mmap")==0 ){
11356      i++;
11357    }else if( strcmp(z,"-memtrace")==0 ){
11358      i++;
11359#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11360    }else if( strcmp(z,"-sorterref")==0 ){
11361      i++;
11362#endif
11363    }else if( strcmp(z,"-vfs")==0 ){
11364      i++;
11365#ifdef SQLITE_ENABLE_VFSTRACE
11366    }else if( strcmp(z,"-vfstrace")==0 ){
11367      i++;
11368#endif
11369#ifdef SQLITE_ENABLE_MULTIPLEX
11370    }else if( strcmp(z,"-multiplex")==0 ){
11371      i++;
11372#endif
11373    }else if( strcmp(z,"-help")==0 ){
11374      usage(1);
11375    }else if( strcmp(z,"-cmd")==0 ){
11376      /* Run commands that follow -cmd first and separately from commands
11377      ** that simply appear on the command-line.  This seems goofy.  It would
11378      ** be better if all commands ran in the order that they appear.  But
11379      ** we retain the goofy behavior for historical compatibility. */
11380      if( i==argc-1 ) break;
11381      z = cmdline_option_value(argc,argv,++i);
11382      if( z[0]=='.' ){
11383        rc = do_meta_command(z, &data);
11384        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11385      }else{
11386        open_db(&data, 0);
11387        rc = shell_exec(&data, z, &zErrMsg);
11388        if( zErrMsg!=0 ){
11389          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11390          if( bail_on_error ) return rc!=0 ? rc : 1;
11391        }else if( rc!=0 ){
11392          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11393          if( bail_on_error ) return rc;
11394        }
11395      }
11396#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11397    }else if( strncmp(z, "-A", 2)==0 ){
11398      if( nCmd>0 ){
11399        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11400                            " with \"%s\"\n", z);
11401        return 1;
11402      }
11403      open_db(&data, OPEN_DB_ZIPFILE);
11404      if( z[2] ){
11405        argv[i] = &z[2];
11406        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11407      }else{
11408        arDotCommand(&data, 1, argv+i, argc-i);
11409      }
11410      readStdin = 0;
11411      break;
11412#endif
11413    }else{
11414      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11415      raw_printf(stderr,"Use -help for a list of options.\n");
11416      return 1;
11417    }
11418    data.cMode = data.mode;
11419  }
11420
11421  if( !readStdin ){
11422    /* Run all arguments that do not begin with '-' as if they were separate
11423    ** command-line inputs, except for the argToSkip argument which contains
11424    ** the database filename.
11425    */
11426    for(i=0; i<nCmd; i++){
11427      if( azCmd[i][0]=='.' ){
11428        rc = do_meta_command(azCmd[i], &data);
11429        if( rc ){
11430          free(azCmd);
11431          return rc==2 ? 0 : rc;
11432        }
11433      }else{
11434        open_db(&data, 0);
11435        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11436        if( zErrMsg || rc ){
11437          if( zErrMsg!=0 ){
11438            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11439          }else{
11440            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11441          }
11442          sqlite3_free(zErrMsg);
11443          free(azCmd);
11444          return rc!=0 ? rc : 1;
11445        }
11446      }
11447    }
11448  }else{
11449    /* Run commands received from standard input
11450    */
11451    if( stdin_is_interactive ){
11452      char *zHome;
11453      char *zHistory;
11454      int nHistory;
11455      printf(
11456        "SQLite version %s %.19s\n" /*extra-version-info*/
11457        "Enter \".help\" for usage hints.\n",
11458        sqlite3_libversion(), sqlite3_sourceid()
11459      );
11460      if( warnInmemoryDb ){
11461        printf("Connected to a ");
11462        printBold("transient in-memory database");
11463        printf(".\nUse \".open FILENAME\" to reopen on a "
11464               "persistent database.\n");
11465      }
11466      zHistory = getenv("SQLITE_HISTORY");
11467      if( zHistory ){
11468        zHistory = strdup(zHistory);
11469      }else if( (zHome = find_home_dir(0))!=0 ){
11470        nHistory = strlen30(zHome) + 20;
11471        if( (zHistory = malloc(nHistory))!=0 ){
11472          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11473        }
11474      }
11475      if( zHistory ){ shell_read_history(zHistory); }
11476#if HAVE_READLINE || HAVE_EDITLINE
11477      rl_attempted_completion_function = readline_completion;
11478#elif HAVE_LINENOISE
11479      linenoiseSetCompletionCallback(linenoise_completion);
11480#endif
11481      data.in = 0;
11482      rc = process_input(&data);
11483      if( zHistory ){
11484        shell_stifle_history(2000);
11485        shell_write_history(zHistory);
11486        free(zHistory);
11487      }
11488    }else{
11489      data.in = stdin;
11490      rc = process_input(&data);
11491    }
11492  }
11493  free(azCmd);
11494  set_table_name(&data, 0);
11495  if( data.db ){
11496    session_close_all(&data, -1);
11497    close_db(data.db);
11498  }
11499  for(i=0; i<ArraySize(data.aAuxDb); i++){
11500    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
11501    if( data.aAuxDb[i].db ){
11502      session_close_all(&data, i);
11503      close_db(data.aAuxDb[i].db);
11504    }
11505  }
11506  find_home_dir(1);
11507  output_reset(&data);
11508  data.doXdgOpen = 0;
11509  clearTempFile(&data);
11510#if !SQLITE_SHELL_IS_UTF8
11511  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
11512  free(argvToFree);
11513#endif
11514  free(data.colWidth);
11515  /* Clear the global data structure so that valgrind will detect memory
11516  ** leaks */
11517  memset(&data, 0, sizeof(data));
11518  return rc;
11519}
11520