xref: /sqlite-3.40.0/src/shell.c.in (revision 4b8035e6)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE       1
53# ifndef _FILE_OFFSET_BITS
54#   define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
64#if SQLITE_USER_AUTHENTICATION
65# include "sqlite3userauth.h"
66#endif
67#include <ctype.h>
68#include <stdarg.h>
69
70#if !defined(_WIN32) && !defined(WIN32)
71# include <signal.h>
72# if !defined(__RTP__) && !defined(_WRS_KERNEL)
73#  include <pwd.h>
74# endif
75# include <unistd.h>
76# include <sys/types.h>
77#endif
78
79#if HAVE_READLINE
80# include <readline/readline.h>
81# include <readline/history.h>
82#endif
83
84#if HAVE_EDITLINE
85# include <editline/readline.h>
86#endif
87
88#if HAVE_EDITLINE || HAVE_READLINE
89
90# define shell_add_history(X) add_history(X)
91# define shell_read_history(X) read_history(X)
92# define shell_write_history(X) write_history(X)
93# define shell_stifle_history(X) stifle_history(X)
94# define shell_readline(X) readline(X)
95
96#elif HAVE_LINENOISE
97
98# include "linenoise.h"
99# define shell_add_history(X) linenoiseHistoryAdd(X)
100# define shell_read_history(X) linenoiseHistoryLoad(X)
101# define shell_write_history(X) linenoiseHistorySave(X)
102# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103# define shell_readline(X) linenoise(X)
104
105#else
106
107# define shell_read_history(X)
108# define shell_write_history(X)
109# define shell_stifle_history(X)
110
111# define SHELL_USE_LOCAL_GETLINE 1
112#endif
113
114
115#if defined(_WIN32) || defined(WIN32)
116# include <io.h>
117# include <fcntl.h>
118# define isatty(h) _isatty(h)
119# ifndef access
120#  define access(f,m) _access((f),(m))
121# endif
122# undef popen
123# define popen _popen
124# undef pclose
125# define pclose _pclose
126#else
127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
129
130# if !defined(__RTP__) && !defined(_WRS_KERNEL)
131  /* popen and pclose are not C89 functions and so are
132  ** sometimes omitted from the <stdio.h> header */
133   extern FILE *popen(const char*,const char*);
134   extern int pclose(FILE*);
135# else
136#  define SQLITE_OMIT_POPEN 1
137# endif
138#endif
139
140#if defined(_WIN32_WCE)
141/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
144 */
145#define isatty(x) 1
146#endif
147
148/* ctype macros that work with signed characters */
149#define IsSpace(X)  isspace((unsigned char)X)
150#define IsDigit(X)  isdigit((unsigned char)X)
151#define ToLower(X)  (char)tolower((unsigned char)X)
152
153#if defined(_WIN32) || defined(WIN32)
154#include <windows.h>
155
156/* string conversion routines only needed on Win32 */
157extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
158extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
160extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
161#endif
162
163/* On Windows, we normally run with output mode of TEXT so that \n characters
164** are automatically translated into \r\n.  However, this behavior needs
165** to be disabled in some cases (ex: when generating CSV output and when
166** rendering quoted strings that contain \n characters).  The following
167** routines take care of that.
168*/
169#if defined(_WIN32) || defined(WIN32)
170static void setBinaryMode(FILE *file, int isOutput){
171  if( isOutput ) fflush(file);
172  _setmode(_fileno(file), _O_BINARY);
173}
174static void setTextMode(FILE *file, int isOutput){
175  if( isOutput ) fflush(file);
176  _setmode(_fileno(file), _O_TEXT);
177}
178#else
179# define setBinaryMode(X,Y)
180# define setTextMode(X,Y)
181#endif
182
183
184/* True if the timer is enabled */
185static int enableTimer = 0;
186
187/* Return the current wall-clock time */
188static sqlite3_int64 timeOfDay(void){
189  static sqlite3_vfs *clockVfs = 0;
190  sqlite3_int64 t;
191  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
192  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
193    clockVfs->xCurrentTimeInt64(clockVfs, &t);
194  }else{
195    double r;
196    clockVfs->xCurrentTime(clockVfs, &r);
197    t = (sqlite3_int64)(r*86400000.0);
198  }
199  return t;
200}
201
202#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
203#include <sys/time.h>
204#include <sys/resource.h>
205
206/* VxWorks does not support getrusage() as far as we can determine */
207#if defined(_WRS_KERNEL) || defined(__RTP__)
208struct rusage {
209  struct timeval ru_utime; /* user CPU time used */
210  struct timeval ru_stime; /* system CPU time used */
211};
212#define getrusage(A,B) memset(B,0,sizeof(*B))
213#endif
214
215/* Saved resource information for the beginning of an operation */
216static struct rusage sBegin;  /* CPU time at start */
217static sqlite3_int64 iBegin;  /* Wall-clock time at start */
218
219/*
220** Begin timing an operation
221*/
222static void beginTimer(void){
223  if( enableTimer ){
224    getrusage(RUSAGE_SELF, &sBegin);
225    iBegin = timeOfDay();
226  }
227}
228
229/* Return the difference of two time_structs in seconds */
230static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
231  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
232         (double)(pEnd->tv_sec - pStart->tv_sec);
233}
234
235/*
236** Print the timing results.
237*/
238static void endTimer(void){
239  if( enableTimer ){
240    sqlite3_int64 iEnd = timeOfDay();
241    struct rusage sEnd;
242    getrusage(RUSAGE_SELF, &sEnd);
243    printf("Run Time: real %.3f user %f sys %f\n",
244       (iEnd - iBegin)*0.001,
245       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
246       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
247  }
248}
249
250#define BEGIN_TIMER beginTimer()
251#define END_TIMER endTimer()
252#define HAS_TIMER 1
253
254#elif (defined(_WIN32) || defined(WIN32))
255
256/* Saved resource information for the beginning of an operation */
257static HANDLE hProcess;
258static FILETIME ftKernelBegin;
259static FILETIME ftUserBegin;
260static sqlite3_int64 ftWallBegin;
261typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
262                                    LPFILETIME, LPFILETIME);
263static GETPROCTIMES getProcessTimesAddr = NULL;
264
265/*
266** Check to see if we have timer support.  Return 1 if necessary
267** support found (or found previously).
268*/
269static int hasTimer(void){
270  if( getProcessTimesAddr ){
271    return 1;
272  } else {
273    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274    ** versions. See if the version we are running on has it, and if it
275    ** does, save off a pointer to it and the current process handle.
276    */
277    hProcess = GetCurrentProcess();
278    if( hProcess ){
279      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
280      if( NULL != hinstLib ){
281        getProcessTimesAddr =
282            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
283        if( NULL != getProcessTimesAddr ){
284          return 1;
285        }
286        FreeLibrary(hinstLib);
287      }
288    }
289  }
290  return 0;
291}
292
293/*
294** Begin timing an operation
295*/
296static void beginTimer(void){
297  if( enableTimer && getProcessTimesAddr ){
298    FILETIME ftCreation, ftExit;
299    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
300                        &ftKernelBegin,&ftUserBegin);
301    ftWallBegin = timeOfDay();
302  }
303}
304
305/* Return the difference of two FILETIME structs in seconds */
306static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
307  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
308  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
309  return (double) ((i64End - i64Start) / 10000000.0);
310}
311
312/*
313** Print the timing results.
314*/
315static void endTimer(void){
316  if( enableTimer && getProcessTimesAddr){
317    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
318    sqlite3_int64 ftWallEnd = timeOfDay();
319    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
320    printf("Run Time: real %.3f user %f sys %f\n",
321       (ftWallEnd - ftWallBegin)*0.001,
322       timeDiff(&ftUserBegin, &ftUserEnd),
323       timeDiff(&ftKernelBegin, &ftKernelEnd));
324  }
325}
326
327#define BEGIN_TIMER beginTimer()
328#define END_TIMER endTimer()
329#define HAS_TIMER hasTimer()
330
331#else
332#define BEGIN_TIMER
333#define END_TIMER
334#define HAS_TIMER 0
335#endif
336
337/*
338** Used to prevent warnings about unused parameters
339*/
340#define UNUSED_PARAMETER(x) (void)(x)
341
342/*
343** If the following flag is set, then command execution stops
344** at an error if we are not interactive.
345*/
346static int bail_on_error = 0;
347
348/*
349** Threat stdin as an interactive input if the following variable
350** is true.  Otherwise, assume stdin is connected to a file or pipe.
351*/
352static int stdin_is_interactive = 1;
353
354/*
355** On Windows systems we have to know if standard output is a console
356** in order to translate UTF-8 into MBCS.  The following variable is
357** true if translation is required.
358*/
359static int stdout_is_console = 1;
360
361/*
362** The following is the open SQLite database.  We make a pointer
363** to this database a static variable so that it can be accessed
364** by the SIGINT handler to interrupt database processing.
365*/
366static sqlite3 *globalDb = 0;
367
368/*
369** True if an interrupt (Control-C) has been received.
370*/
371static volatile int seenInterrupt = 0;
372
373/*
374** This is the name of our program. It is set in main(), used
375** in a number of other places, mostly for error messages.
376*/
377static char *Argv0;
378
379/*
380** Prompt strings. Initialized in main. Settable with
381**   .prompt main continue
382*/
383static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
384static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
385
386/*
387** Render output like fprintf().  Except, if the output is going to the
388** console and if this is running on a Windows machine, translate the
389** output from UTF-8 into MBCS.
390*/
391#if defined(_WIN32) || defined(WIN32)
392void utf8_printf(FILE *out, const char *zFormat, ...){
393  va_list ap;
394  va_start(ap, zFormat);
395  if( stdout_is_console && (out==stdout || out==stderr) ){
396    char *z1 = sqlite3_vmprintf(zFormat, ap);
397    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
398    sqlite3_free(z1);
399    fputs(z2, out);
400    sqlite3_free(z2);
401  }else{
402    vfprintf(out, zFormat, ap);
403  }
404  va_end(ap);
405}
406#elif !defined(utf8_printf)
407# define utf8_printf fprintf
408#endif
409
410/*
411** Render output like fprintf().  This should not be used on anything that
412** includes string formatting (e.g. "%s").
413*/
414#if !defined(raw_printf)
415# define raw_printf fprintf
416#endif
417
418/*
419** Write I/O traces to the following stream.
420*/
421#ifdef SQLITE_ENABLE_IOTRACE
422static FILE *iotrace = 0;
423#endif
424
425/*
426** This routine works like printf in that its first argument is a
427** format string and subsequent arguments are values to be substituted
428** in place of % fields.  The result of formatting this string
429** is written to iotrace.
430*/
431#ifdef SQLITE_ENABLE_IOTRACE
432static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
433  va_list ap;
434  char *z;
435  if( iotrace==0 ) return;
436  va_start(ap, zFormat);
437  z = sqlite3_vmprintf(zFormat, ap);
438  va_end(ap);
439  utf8_printf(iotrace, "%s", z);
440  sqlite3_free(z);
441}
442#endif
443
444/*
445** Output string zUtf to stream pOut as w characters.  If w is negative,
446** then right-justify the text.  W is the width in UTF-8 characters, not
447** in bytes.  This is different from the %*.*s specification in printf
448** since with %*.*s the width is measured in bytes, not characters.
449*/
450static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
451  int i;
452  int n;
453  int aw = w<0 ? -w : w;
454  char zBuf[1000];
455  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
456  for(i=n=0; zUtf[i]; i++){
457    if( (zUtf[i]&0xc0)!=0x80 ){
458      n++;
459      if( n==aw ){
460        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
461        break;
462      }
463    }
464  }
465  if( n>=aw ){
466    utf8_printf(pOut, "%.*s", i, zUtf);
467  }else if( w<0 ){
468    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
469  }else{
470    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
471  }
472}
473
474
475/*
476** Determines if a string is a number of not.
477*/
478static int isNumber(const char *z, int *realnum){
479  if( *z=='-' || *z=='+' ) z++;
480  if( !IsDigit(*z) ){
481    return 0;
482  }
483  z++;
484  if( realnum ) *realnum = 0;
485  while( IsDigit(*z) ){ z++; }
486  if( *z=='.' ){
487    z++;
488    if( !IsDigit(*z) ) return 0;
489    while( IsDigit(*z) ){ z++; }
490    if( realnum ) *realnum = 1;
491  }
492  if( *z=='e' || *z=='E' ){
493    z++;
494    if( *z=='+' || *z=='-' ) z++;
495    if( !IsDigit(*z) ) return 0;
496    while( IsDigit(*z) ){ z++; }
497    if( realnum ) *realnum = 1;
498  }
499  return *z==0;
500}
501
502/*
503** Compute a string length that is limited to what can be stored in
504** lower 30 bits of a 32-bit signed integer.
505*/
506static int strlen30(const char *z){
507  const char *z2 = z;
508  while( *z2 ){ z2++; }
509  return 0x3fffffff & (int)(z2 - z);
510}
511
512/*
513** Return the length of a string in characters.  Multibyte UTF8 characters
514** count as a single character.
515*/
516static int strlenChar(const char *z){
517  int n = 0;
518  while( *z ){
519    if( (0xc0&*(z++))!=0x80 ) n++;
520  }
521  return n;
522}
523
524/*
525** This routine reads a line of text from FILE in, stores
526** the text in memory obtained from malloc() and returns a pointer
527** to the text.  NULL is returned at end of file, or if malloc()
528** fails.
529**
530** If zLine is not NULL then it is a malloced buffer returned from
531** a previous call to this routine that may be reused.
532*/
533static char *local_getline(char *zLine, FILE *in){
534  int nLine = zLine==0 ? 0 : 100;
535  int n = 0;
536
537  while( 1 ){
538    if( n+100>nLine ){
539      nLine = nLine*2 + 100;
540      zLine = realloc(zLine, nLine);
541      if( zLine==0 ) return 0;
542    }
543    if( fgets(&zLine[n], nLine - n, in)==0 ){
544      if( n==0 ){
545        free(zLine);
546        return 0;
547      }
548      zLine[n] = 0;
549      break;
550    }
551    while( zLine[n] ) n++;
552    if( n>0 && zLine[n-1]=='\n' ){
553      n--;
554      if( n>0 && zLine[n-1]=='\r' ) n--;
555      zLine[n] = 0;
556      break;
557    }
558  }
559#if defined(_WIN32) || defined(WIN32)
560  /* For interactive input on Windows systems, translate the
561  ** multi-byte characterset characters into UTF-8. */
562  if( stdin_is_interactive && in==stdin ){
563    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
564    if( zTrans ){
565      int nTrans = strlen30(zTrans)+1;
566      if( nTrans>nLine ){
567        zLine = realloc(zLine, nTrans);
568        if( zLine==0 ){
569          sqlite3_free(zTrans);
570          return 0;
571        }
572      }
573      memcpy(zLine, zTrans, nTrans);
574      sqlite3_free(zTrans);
575    }
576  }
577#endif /* defined(_WIN32) || defined(WIN32) */
578  return zLine;
579}
580
581/*
582** Retrieve a single line of input text.
583**
584** If in==0 then read from standard input and prompt before each line.
585** If isContinuation is true, then a continuation prompt is appropriate.
586** If isContinuation is zero, then the main prompt should be used.
587**
588** If zPrior is not NULL then it is a buffer from a prior call to this
589** routine that can be reused.
590**
591** The result is stored in space obtained from malloc() and must either
592** be freed by the caller or else passed back into this routine via the
593** zPrior argument for reuse.
594*/
595static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
596  char *zPrompt;
597  char *zResult;
598  if( in!=0 ){
599    zResult = local_getline(zPrior, in);
600  }else{
601    zPrompt = isContinuation ? continuePrompt : mainPrompt;
602#if SHELL_USE_LOCAL_GETLINE
603    printf("%s", zPrompt);
604    fflush(stdout);
605    zResult = local_getline(zPrior, stdin);
606#else
607    free(zPrior);
608    zResult = shell_readline(zPrompt);
609    if( zResult && *zResult ) shell_add_history(zResult);
610#endif
611  }
612  return zResult;
613}
614/*
615** A variable length string to which one can append text.
616*/
617typedef struct ShellText ShellText;
618struct ShellText {
619  char *z;
620  int n;
621  int nAlloc;
622};
623
624/*
625** Initialize and destroy a ShellText object
626*/
627static void initText(ShellText *p){
628  memset(p, 0, sizeof(*p));
629}
630static void freeText(ShellText *p){
631  free(p->z);
632  initText(p);
633}
634
635/* zIn is either a pointer to a NULL-terminated string in memory obtained
636** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637** added to zIn, and the result returned in memory obtained from malloc().
638** zIn, if it was not NULL, is freed.
639**
640** If the third argument, quote, is not '\0', then it is used as a
641** quote character for zAppend.
642*/
643static void appendText(ShellText *p, char const *zAppend, char quote){
644  int len;
645  int i;
646  int nAppend = strlen30(zAppend);
647
648  len = nAppend+p->n+1;
649  if( quote ){
650    len += 2;
651    for(i=0; i<nAppend; i++){
652      if( zAppend[i]==quote ) len++;
653    }
654  }
655
656  if( p->n+len>=p->nAlloc ){
657    p->nAlloc = p->nAlloc*2 + len + 20;
658    p->z = realloc(p->z, p->nAlloc);
659    if( p->z==0 ){
660      memset(p, 0, sizeof(*p));
661      return;
662    }
663  }
664
665  if( quote ){
666    char *zCsr = p->z+p->n;
667    *zCsr++ = quote;
668    for(i=0; i<nAppend; i++){
669      *zCsr++ = zAppend[i];
670      if( zAppend[i]==quote ) *zCsr++ = quote;
671    }
672    *zCsr++ = quote;
673    p->n = (int)(zCsr - p->z);
674    *zCsr = '\0';
675  }else{
676    memcpy(p->z+p->n, zAppend, nAppend);
677    p->n += nAppend;
678    p->z[p->n] = '\0';
679  }
680}
681
682/*
683** Attempt to determine if identifier zName needs to be quoted, either
684** because it contains non-alphanumeric characters, or because it is an
685** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
686** that quoting is required.
687**
688** Return '"' if quoting is required.  Return 0 if no quoting is required.
689*/
690static char quoteChar(const char *zName){
691  /* All SQLite keywords, in alphabetical order */
692  static const char *azKeywords[] = {
693    "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694    "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695    "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696    "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697    "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698    "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699    "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700    "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701    "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702    "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703    "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704    "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705    "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706    "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707    "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708    "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709    "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
710    "WITH", "WITHOUT",
711  };
712  int i, lwr, upr, mid, c;
713  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
714  for(i=0; zName[i]; i++){
715    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
716  }
717  lwr = 0;
718  upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
719  while( lwr<=upr ){
720    mid = (lwr+upr)/2;
721    c = sqlite3_stricmp(azKeywords[mid], zName);
722    if( c==0 ) return '"';
723    if( c<0 ){
724      lwr = mid+1;
725    }else{
726      upr = mid-1;
727    }
728  }
729  return 0;
730}
731
732/*
733** SQL function:  shell_add_schema(S,X)
734**
735** Add the schema name X to the CREATE statement in S and return the result.
736** Examples:
737**
738**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
739**
740** Also works on
741**
742**    CREATE INDEX
743**    CREATE UNIQUE INDEX
744**    CREATE VIEW
745**    CREATE TRIGGER
746**    CREATE VIRTUAL TABLE
747**
748** This UDF is used by the .schema command to insert the schema name of
749** attached databases into the middle of the sqlite_master.sql field.
750*/
751static void shellAddSchemaName(
752  sqlite3_context *pCtx,
753  int nVal,
754  sqlite3_value **apVal
755){
756  static const char *aPrefix[] = {
757     "TABLE",
758     "INDEX",
759     "UNIQUE INDEX",
760     "VIEW",
761     "TRIGGER",
762     "VIRTUAL TABLE"
763  };
764  int i = 0;
765  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
766  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
767  assert( nVal==2 );
768  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
769    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
770      int n = strlen30(aPrefix[i]);
771      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
772        char cQuote = quoteChar(zSchema);
773        char *z;
774        if( cQuote ){
775         z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
776        }else{
777          z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
778        }
779        sqlite3_result_text(pCtx, z, -1, sqlite3_free);
780        return;
781      }
782    }
783  }
784  sqlite3_result_value(pCtx, apVal[0]);
785}
786
787/*
788** The source code for several run-time loadable extensions is inserted
789** below by the ../tool/mkshellc.tcl script.  Before processing that included
790** code, we need to override some macros to make the included program code
791** work here in the middle of this regular program.
792*/
793#define SQLITE_EXTENSION_INIT1
794#define SQLITE_EXTENSION_INIT2(X) (void)(X)
795
796INCLUDE ../ext/misc/shathree.c
797INCLUDE ../ext/misc/fileio.c
798INCLUDE ../ext/misc/completion.c
799
800#if defined(SQLITE_ENABLE_SESSION)
801/*
802** State information for a single open session
803*/
804typedef struct OpenSession OpenSession;
805struct OpenSession {
806  char *zName;             /* Symbolic name for this session */
807  int nFilter;             /* Number of xFilter rejection GLOB patterns */
808  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
809  sqlite3_session *p;      /* The open session */
810};
811#endif
812
813/*
814** Shell output mode information from before ".explain on",
815** saved so that it can be restored by ".explain off"
816*/
817typedef struct SavedModeInfo SavedModeInfo;
818struct SavedModeInfo {
819  int valid;          /* Is there legit data in here? */
820  int mode;           /* Mode prior to ".explain on" */
821  int showHeader;     /* The ".header" setting prior to ".explain on" */
822  int colWidth[100];  /* Column widths prior to ".explain on" */
823};
824
825/*
826** State information about the database connection is contained in an
827** instance of the following structure.
828*/
829typedef struct ShellState ShellState;
830struct ShellState {
831  sqlite3 *db;           /* The database */
832  int autoExplain;       /* Automatically turn on .explain mode */
833  int autoEQP;           /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
834  int statsOn;           /* True to display memory stats before each finalize */
835  int scanstatsOn;       /* True to display scan stats before each finalize */
836  int outCount;          /* Revert to stdout when reaching zero */
837  int cnt;               /* Number of records displayed so far */
838  FILE *out;             /* Write results here */
839  FILE *traceOut;        /* Output for sqlite3_trace() */
840  int nErr;              /* Number of errors seen */
841  int mode;              /* An output mode setting */
842  int cMode;             /* temporary output mode for the current query */
843  int normalMode;        /* Output mode before ".explain on" */
844  int writableSchema;    /* True if PRAGMA writable_schema=ON */
845  int showHeader;        /* True to show column names in List or Column mode */
846  int nCheck;            /* Number of ".check" commands run */
847  unsigned shellFlgs;    /* Various flags */
848  char *zDestTable;      /* Name of destination table when MODE_Insert */
849  char zTestcase[30];    /* Name of current test case */
850  char colSeparator[20]; /* Column separator character for several modes */
851  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
852  int colWidth[100];     /* Requested width of each column when in column mode*/
853  int actualWidth[100];  /* Actual width of each column */
854  char nullValue[20];    /* The text to print when a NULL comes back from
855                         ** the database */
856  char outfile[FILENAME_MAX]; /* Filename for *out */
857  const char *zDbFilename;    /* name of the database file */
858  char *zFreeOnClose;         /* Filename to free when closing */
859  const char *zVfs;           /* Name of VFS to use */
860  sqlite3_stmt *pStmt;   /* Current statement if any. */
861  FILE *pLog;            /* Write log output here */
862  int *aiIndent;         /* Array of indents used in MODE_Explain */
863  int nIndent;           /* Size of array aiIndent[] */
864  int iIndent;           /* Index of current op in aiIndent[] */
865#if defined(SQLITE_ENABLE_SESSION)
866  int nSession;             /* Number of active sessions */
867  OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
868#endif
869};
870
871/*
872** These are the allowed shellFlgs values
873*/
874#define SHFLG_Scratch        0x00000001 /* The --scratch option is used */
875#define SHFLG_Pagecache      0x00000002 /* The --pagecache option is used */
876#define SHFLG_Lookaside      0x00000004 /* Lookaside memory is used */
877#define SHFLG_Backslash      0x00000008 /* The --backslash option is used */
878#define SHFLG_PreserveRowid  0x00000010 /* .dump preserves rowid values */
879#define SHFLG_Newlines       0x00000020 /* .dump --newline flag */
880#define SHFLG_CountChanges   0x00000040 /* .changes setting */
881#define SHFLG_Echo           0x00000080 /* .echo or --echo setting */
882
883/*
884** Macros for testing and setting shellFlgs
885*/
886#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
887#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
888#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
889
890/*
891** These are the allowed modes.
892*/
893#define MODE_Line     0  /* One column per line.  Blank line between records */
894#define MODE_Column   1  /* One record per line in neat columns */
895#define MODE_List     2  /* One record per line with a separator */
896#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
897#define MODE_Html     4  /* Generate an XHTML table */
898#define MODE_Insert   5  /* Generate SQL "insert" statements */
899#define MODE_Quote    6  /* Quote values as for SQL */
900#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
901#define MODE_Csv      8  /* Quote strings, numbers are plain */
902#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
903#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
904#define MODE_Pretty  11  /* Pretty-print schemas */
905
906static const char *modeDescr[] = {
907  "line",
908  "column",
909  "list",
910  "semi",
911  "html",
912  "insert",
913  "quote",
914  "tcl",
915  "csv",
916  "explain",
917  "ascii",
918  "prettyprint",
919};
920
921/*
922** These are the column/row/line separators used by the various
923** import/export modes.
924*/
925#define SEP_Column    "|"
926#define SEP_Row       "\n"
927#define SEP_Tab       "\t"
928#define SEP_Space     " "
929#define SEP_Comma     ","
930#define SEP_CrLf      "\r\n"
931#define SEP_Unit      "\x1F"
932#define SEP_Record    "\x1E"
933
934/*
935** Number of elements in an array
936*/
937#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
938
939/*
940** A callback for the sqlite3_log() interface.
941*/
942static void shellLog(void *pArg, int iErrCode, const char *zMsg){
943  ShellState *p = (ShellState*)pArg;
944  if( p->pLog==0 ) return;
945  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
946  fflush(p->pLog);
947}
948
949/*
950** Output the given string as a hex-encoded blob (eg. X'1234' )
951*/
952static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
953  int i;
954  char *zBlob = (char *)pBlob;
955  raw_printf(out,"X'");
956  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
957  raw_printf(out,"'");
958}
959
960/*
961** Find a string that is not found anywhere in z[].  Return a pointer
962** to that string.
963**
964** Try to use zA and zB first.  If both of those are already found in z[]
965** then make up some string and store it in the buffer zBuf.
966*/
967static const char *unused_string(
968  const char *z,                    /* Result must not appear anywhere in z */
969  const char *zA, const char *zB,   /* Try these first */
970  char *zBuf                        /* Space to store a generated string */
971){
972  unsigned i = 0;
973  if( strstr(z, zA)==0 ) return zA;
974  if( strstr(z, zB)==0 ) return zB;
975  do{
976    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
977  }while( strstr(z,zBuf)!=0 );
978  return zBuf;
979}
980
981/*
982** Output the given string as a quoted string using SQL quoting conventions.
983**
984** See also: output_quoted_escaped_string()
985*/
986static void output_quoted_string(FILE *out, const char *z){
987  int i;
988  char c;
989  setBinaryMode(out, 1);
990  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
991  if( c==0 ){
992    utf8_printf(out,"'%s'",z);
993  }else{
994    raw_printf(out, "'");
995    while( *z ){
996      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
997      if( c=='\'' ) i++;
998      if( i ){
999        utf8_printf(out, "%.*s", i, z);
1000        z += i;
1001      }
1002      if( c=='\'' ){
1003        raw_printf(out, "'");
1004        continue;
1005      }
1006      if( c==0 ){
1007        break;
1008      }
1009      z++;
1010    }
1011    raw_printf(out, "'");
1012  }
1013  setTextMode(out, 1);
1014}
1015
1016/*
1017** Output the given string as a quoted string using SQL quoting conventions.
1018** Additionallly , escape the "\n" and "\r" characters so that they do not
1019** get corrupted by end-of-line translation facilities in some operating
1020** systems.
1021**
1022** This is like output_quoted_string() but with the addition of the \r\n
1023** escape mechanism.
1024*/
1025static void output_quoted_escaped_string(FILE *out, const char *z){
1026  int i;
1027  char c;
1028  setBinaryMode(out, 1);
1029  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1030  if( c==0 ){
1031    utf8_printf(out,"'%s'",z);
1032  }else{
1033    const char *zNL = 0;
1034    const char *zCR = 0;
1035    int nNL = 0;
1036    int nCR = 0;
1037    char zBuf1[20], zBuf2[20];
1038    for(i=0; z[i]; i++){
1039      if( z[i]=='\n' ) nNL++;
1040      if( z[i]=='\r' ) nCR++;
1041    }
1042    if( nNL ){
1043      raw_printf(out, "replace(");
1044      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1045    }
1046    if( nCR ){
1047      raw_printf(out, "replace(");
1048      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1049    }
1050    raw_printf(out, "'");
1051    while( *z ){
1052      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1053      if( c=='\'' ) i++;
1054      if( i ){
1055        utf8_printf(out, "%.*s", i, z);
1056        z += i;
1057      }
1058      if( c=='\'' ){
1059        raw_printf(out, "'");
1060        continue;
1061      }
1062      if( c==0 ){
1063        break;
1064      }
1065      z++;
1066      if( c=='\n' ){
1067        raw_printf(out, "%s", zNL);
1068        continue;
1069      }
1070      raw_printf(out, "%s", zCR);
1071    }
1072    raw_printf(out, "'");
1073    if( nCR ){
1074      raw_printf(out, ",'%s',char(13))", zCR);
1075    }
1076    if( nNL ){
1077      raw_printf(out, ",'%s',char(10))", zNL);
1078    }
1079  }
1080  setTextMode(out, 1);
1081}
1082
1083/*
1084** Output the given string as a quoted according to C or TCL quoting rules.
1085*/
1086static void output_c_string(FILE *out, const char *z){
1087  unsigned int c;
1088  fputc('"', out);
1089  while( (c = *(z++))!=0 ){
1090    if( c=='\\' ){
1091      fputc(c, out);
1092      fputc(c, out);
1093    }else if( c=='"' ){
1094      fputc('\\', out);
1095      fputc('"', out);
1096    }else if( c=='\t' ){
1097      fputc('\\', out);
1098      fputc('t', out);
1099    }else if( c=='\n' ){
1100      fputc('\\', out);
1101      fputc('n', out);
1102    }else if( c=='\r' ){
1103      fputc('\\', out);
1104      fputc('r', out);
1105    }else if( !isprint(c&0xff) ){
1106      raw_printf(out, "\\%03o", c&0xff);
1107    }else{
1108      fputc(c, out);
1109    }
1110  }
1111  fputc('"', out);
1112}
1113
1114/*
1115** Output the given string with characters that are special to
1116** HTML escaped.
1117*/
1118static void output_html_string(FILE *out, const char *z){
1119  int i;
1120  if( z==0 ) z = "";
1121  while( *z ){
1122    for(i=0;   z[i]
1123            && z[i]!='<'
1124            && z[i]!='&'
1125            && z[i]!='>'
1126            && z[i]!='\"'
1127            && z[i]!='\'';
1128        i++){}
1129    if( i>0 ){
1130      utf8_printf(out,"%.*s",i,z);
1131    }
1132    if( z[i]=='<' ){
1133      raw_printf(out,"&lt;");
1134    }else if( z[i]=='&' ){
1135      raw_printf(out,"&amp;");
1136    }else if( z[i]=='>' ){
1137      raw_printf(out,"&gt;");
1138    }else if( z[i]=='\"' ){
1139      raw_printf(out,"&quot;");
1140    }else if( z[i]=='\'' ){
1141      raw_printf(out,"&#39;");
1142    }else{
1143      break;
1144    }
1145    z += i + 1;
1146  }
1147}
1148
1149/*
1150** If a field contains any character identified by a 1 in the following
1151** array, then the string must be quoted for CSV.
1152*/
1153static const char needCsvQuote[] = {
1154  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1155  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1156  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1157  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1158  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1159  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1160  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1161  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1162  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1163  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1164  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1165  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1166  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1167  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1168  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1169  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1170};
1171
1172/*
1173** Output a single term of CSV.  Actually, p->colSeparator is used for
1174** the separator, which may or may not be a comma.  p->nullValue is
1175** the null value.  Strings are quoted if necessary.  The separator
1176** is only issued if bSep is true.
1177*/
1178static void output_csv(ShellState *p, const char *z, int bSep){
1179  FILE *out = p->out;
1180  if( z==0 ){
1181    utf8_printf(out,"%s",p->nullValue);
1182  }else{
1183    int i;
1184    int nSep = strlen30(p->colSeparator);
1185    for(i=0; z[i]; i++){
1186      if( needCsvQuote[((unsigned char*)z)[i]]
1187         || (z[i]==p->colSeparator[0] &&
1188             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1189        i = 0;
1190        break;
1191      }
1192    }
1193    if( i==0 ){
1194      putc('"', out);
1195      for(i=0; z[i]; i++){
1196        if( z[i]=='"' ) putc('"', out);
1197        putc(z[i], out);
1198      }
1199      putc('"', out);
1200    }else{
1201      utf8_printf(out, "%s", z);
1202    }
1203  }
1204  if( bSep ){
1205    utf8_printf(p->out, "%s", p->colSeparator);
1206  }
1207}
1208
1209#ifdef SIGINT
1210/*
1211** This routine runs when the user presses Ctrl-C
1212*/
1213static void interrupt_handler(int NotUsed){
1214  UNUSED_PARAMETER(NotUsed);
1215  seenInterrupt++;
1216  if( seenInterrupt>2 ) exit(1);
1217  if( globalDb ) sqlite3_interrupt(globalDb);
1218}
1219#endif
1220
1221#ifndef SQLITE_OMIT_AUTHORIZATION
1222/*
1223** When the ".auth ON" is set, the following authorizer callback is
1224** invoked.  It always returns SQLITE_OK.
1225*/
1226static int shellAuth(
1227  void *pClientData,
1228  int op,
1229  const char *zA1,
1230  const char *zA2,
1231  const char *zA3,
1232  const char *zA4
1233){
1234  ShellState *p = (ShellState*)pClientData;
1235  static const char *azAction[] = { 0,
1236     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1237     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1238     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1239     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1240     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1241     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1242     "PRAGMA",               "READ",                 "SELECT",
1243     "TRANSACTION",          "UPDATE",               "ATTACH",
1244     "DETACH",               "ALTER_TABLE",          "REINDEX",
1245     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1246     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1247  };
1248  int i;
1249  const char *az[4];
1250  az[0] = zA1;
1251  az[1] = zA2;
1252  az[2] = zA3;
1253  az[3] = zA4;
1254  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1255  for(i=0; i<4; i++){
1256    raw_printf(p->out, " ");
1257    if( az[i] ){
1258      output_c_string(p->out, az[i]);
1259    }else{
1260      raw_printf(p->out, "NULL");
1261    }
1262  }
1263  raw_printf(p->out, "\n");
1264  return SQLITE_OK;
1265}
1266#endif
1267
1268/*
1269** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1270**
1271** This routine converts some CREATE TABLE statements for shadow tables
1272** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1273*/
1274static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1275  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1276    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1277  }else{
1278    utf8_printf(out, "%s%s", z, zTail);
1279  }
1280}
1281static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1282  char c = z[n];
1283  z[n] = 0;
1284  printSchemaLine(out, z, zTail);
1285  z[n] = c;
1286}
1287
1288/*
1289** This is the callback routine that the shell
1290** invokes for each row of a query result.
1291*/
1292static int shell_callback(
1293  void *pArg,
1294  int nArg,        /* Number of result columns */
1295  char **azArg,    /* Text of each result column */
1296  char **azCol,    /* Column names */
1297  int *aiType      /* Column types */
1298){
1299  int i;
1300  ShellState *p = (ShellState*)pArg;
1301
1302  switch( p->cMode ){
1303    case MODE_Line: {
1304      int w = 5;
1305      if( azArg==0 ) break;
1306      for(i=0; i<nArg; i++){
1307        int len = strlen30(azCol[i] ? azCol[i] : "");
1308        if( len>w ) w = len;
1309      }
1310      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1311      for(i=0; i<nArg; i++){
1312        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1313                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1314      }
1315      break;
1316    }
1317    case MODE_Explain:
1318    case MODE_Column: {
1319      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1320      const int *colWidth;
1321      int showHdr;
1322      char *rowSep;
1323      if( p->cMode==MODE_Column ){
1324        colWidth = p->colWidth;
1325        showHdr = p->showHeader;
1326        rowSep = p->rowSeparator;
1327      }else{
1328        colWidth = aExplainWidths;
1329        showHdr = 1;
1330        rowSep = SEP_Row;
1331      }
1332      if( p->cnt++==0 ){
1333        for(i=0; i<nArg; i++){
1334          int w, n;
1335          if( i<ArraySize(p->colWidth) ){
1336            w = colWidth[i];
1337          }else{
1338            w = 0;
1339          }
1340          if( w==0 ){
1341            w = strlenChar(azCol[i] ? azCol[i] : "");
1342            if( w<10 ) w = 10;
1343            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1344            if( w<n ) w = n;
1345          }
1346          if( i<ArraySize(p->actualWidth) ){
1347            p->actualWidth[i] = w;
1348          }
1349          if( showHdr ){
1350            utf8_width_print(p->out, w, azCol[i]);
1351            utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1352          }
1353        }
1354        if( showHdr ){
1355          for(i=0; i<nArg; i++){
1356            int w;
1357            if( i<ArraySize(p->actualWidth) ){
1358               w = p->actualWidth[i];
1359               if( w<0 ) w = -w;
1360            }else{
1361               w = 10;
1362            }
1363            utf8_printf(p->out,"%-*.*s%s",w,w,
1364                   "----------------------------------------------------------"
1365                   "----------------------------------------------------------",
1366                    i==nArg-1 ? rowSep : "  ");
1367          }
1368        }
1369      }
1370      if( azArg==0 ) break;
1371      for(i=0; i<nArg; i++){
1372        int w;
1373        if( i<ArraySize(p->actualWidth) ){
1374           w = p->actualWidth[i];
1375        }else{
1376           w = 10;
1377        }
1378        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1379          w = strlenChar(azArg[i]);
1380        }
1381        if( i==1 && p->aiIndent && p->pStmt ){
1382          if( p->iIndent<p->nIndent ){
1383            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1384          }
1385          p->iIndent++;
1386        }
1387        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1388        utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
1389      }
1390      break;
1391    }
1392    case MODE_Semi: {   /* .schema and .fullschema output */
1393      printSchemaLine(p->out, azArg[0], ";\n");
1394      break;
1395    }
1396    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
1397      char *z;
1398      int j;
1399      int nParen = 0;
1400      char cEnd = 0;
1401      char c;
1402      int nLine = 0;
1403      assert( nArg==1 );
1404      if( azArg[0]==0 ) break;
1405      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1406       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1407      ){
1408        utf8_printf(p->out, "%s;\n", azArg[0]);
1409        break;
1410      }
1411      z = sqlite3_mprintf("%s", azArg[0]);
1412      j = 0;
1413      for(i=0; IsSpace(z[i]); i++){}
1414      for(; (c = z[i])!=0; i++){
1415        if( IsSpace(c) ){
1416          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1417        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1418          j--;
1419        }
1420        z[j++] = c;
1421      }
1422      while( j>0 && IsSpace(z[j-1]) ){ j--; }
1423      z[j] = 0;
1424      if( strlen30(z)>=79 ){
1425        for(i=j=0; (c = z[i])!=0; i++){
1426          if( c==cEnd ){
1427            cEnd = 0;
1428          }else if( c=='"' || c=='\'' || c=='`' ){
1429            cEnd = c;
1430          }else if( c=='[' ){
1431            cEnd = ']';
1432          }else if( c=='(' ){
1433            nParen++;
1434          }else if( c==')' ){
1435            nParen--;
1436            if( nLine>0 && nParen==0 && j>0 ){
1437              printSchemaLineN(p->out, z, j, "\n");
1438              j = 0;
1439            }
1440          }
1441          z[j++] = c;
1442          if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1443            if( c=='\n' ) j--;
1444            printSchemaLineN(p->out, z, j, "\n  ");
1445            j = 0;
1446            nLine++;
1447            while( IsSpace(z[i+1]) ){ i++; }
1448          }
1449        }
1450        z[j] = 0;
1451      }
1452      printSchemaLine(p->out, z, ";\n");
1453      sqlite3_free(z);
1454      break;
1455    }
1456    case MODE_List: {
1457      if( p->cnt++==0 && p->showHeader ){
1458        for(i=0; i<nArg; i++){
1459          utf8_printf(p->out,"%s%s",azCol[i],
1460                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
1461        }
1462      }
1463      if( azArg==0 ) break;
1464      for(i=0; i<nArg; i++){
1465        char *z = azArg[i];
1466        if( z==0 ) z = p->nullValue;
1467        utf8_printf(p->out, "%s", z);
1468        if( i<nArg-1 ){
1469          utf8_printf(p->out, "%s", p->colSeparator);
1470        }else{
1471          utf8_printf(p->out, "%s", p->rowSeparator);
1472        }
1473      }
1474      break;
1475    }
1476    case MODE_Html: {
1477      if( p->cnt++==0 && p->showHeader ){
1478        raw_printf(p->out,"<TR>");
1479        for(i=0; i<nArg; i++){
1480          raw_printf(p->out,"<TH>");
1481          output_html_string(p->out, azCol[i]);
1482          raw_printf(p->out,"</TH>\n");
1483        }
1484        raw_printf(p->out,"</TR>\n");
1485      }
1486      if( azArg==0 ) break;
1487      raw_printf(p->out,"<TR>");
1488      for(i=0; i<nArg; i++){
1489        raw_printf(p->out,"<TD>");
1490        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1491        raw_printf(p->out,"</TD>\n");
1492      }
1493      raw_printf(p->out,"</TR>\n");
1494      break;
1495    }
1496    case MODE_Tcl: {
1497      if( p->cnt++==0 && p->showHeader ){
1498        for(i=0; i<nArg; i++){
1499          output_c_string(p->out,azCol[i] ? azCol[i] : "");
1500          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1501        }
1502        utf8_printf(p->out, "%s", p->rowSeparator);
1503      }
1504      if( azArg==0 ) break;
1505      for(i=0; i<nArg; i++){
1506        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1507        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1508      }
1509      utf8_printf(p->out, "%s", p->rowSeparator);
1510      break;
1511    }
1512    case MODE_Csv: {
1513      setBinaryMode(p->out, 1);
1514      if( p->cnt++==0 && p->showHeader ){
1515        for(i=0; i<nArg; i++){
1516          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1517        }
1518        utf8_printf(p->out, "%s", p->rowSeparator);
1519      }
1520      if( nArg>0 ){
1521        for(i=0; i<nArg; i++){
1522          output_csv(p, azArg[i], i<nArg-1);
1523        }
1524        utf8_printf(p->out, "%s", p->rowSeparator);
1525      }
1526      setTextMode(p->out, 1);
1527      break;
1528    }
1529    case MODE_Insert: {
1530      if( azArg==0 ) break;
1531      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1532      if( p->showHeader ){
1533        raw_printf(p->out,"(");
1534        for(i=0; i<nArg; i++){
1535          if( i>0 ) raw_printf(p->out, ",");
1536          if( quoteChar(azCol[i]) ){
1537            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1538            utf8_printf(p->out, "%s", z);
1539            sqlite3_free(z);
1540          }else{
1541            raw_printf(p->out, "%s", azCol[i]);
1542          }
1543        }
1544        raw_printf(p->out,")");
1545      }
1546      p->cnt++;
1547      for(i=0; i<nArg; i++){
1548        raw_printf(p->out, i>0 ? "," : " VALUES(");
1549        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1550          utf8_printf(p->out,"NULL");
1551        }else if( aiType && aiType[i]==SQLITE_TEXT ){
1552          if( ShellHasFlag(p, SHFLG_Newlines) ){
1553            output_quoted_string(p->out, azArg[i]);
1554          }else{
1555            output_quoted_escaped_string(p->out, azArg[i]);
1556          }
1557        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1558          utf8_printf(p->out,"%s", azArg[i]);
1559        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1560          char z[50];
1561          double r = sqlite3_column_double(p->pStmt, i);
1562          sqlite3_snprintf(50,z,"%!.20g", r);
1563          raw_printf(p->out, "%s", z);
1564        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1565          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1566          int nBlob = sqlite3_column_bytes(p->pStmt, i);
1567          output_hex_blob(p->out, pBlob, nBlob);
1568        }else if( isNumber(azArg[i], 0) ){
1569          utf8_printf(p->out,"%s", azArg[i]);
1570        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1571          output_quoted_string(p->out, azArg[i]);
1572        }else{
1573          output_quoted_escaped_string(p->out, azArg[i]);
1574        }
1575      }
1576      raw_printf(p->out,");\n");
1577      break;
1578    }
1579    case MODE_Quote: {
1580      if( azArg==0 ) break;
1581      if( p->cnt==0 && p->showHeader ){
1582        for(i=0; i<nArg; i++){
1583          if( i>0 ) raw_printf(p->out, ",");
1584          output_quoted_string(p->out, azCol[i]);
1585        }
1586        raw_printf(p->out,"\n");
1587      }
1588      p->cnt++;
1589      for(i=0; i<nArg; i++){
1590        if( i>0 ) raw_printf(p->out, ",");
1591        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1592          utf8_printf(p->out,"NULL");
1593        }else if( aiType && aiType[i]==SQLITE_TEXT ){
1594          output_quoted_string(p->out, azArg[i]);
1595        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1596          utf8_printf(p->out,"%s", azArg[i]);
1597        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1598          char z[50];
1599          double r = sqlite3_column_double(p->pStmt, i);
1600          sqlite3_snprintf(50,z,"%!.20g", r);
1601          raw_printf(p->out, "%s", z);
1602        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1603          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1604          int nBlob = sqlite3_column_bytes(p->pStmt, i);
1605          output_hex_blob(p->out, pBlob, nBlob);
1606        }else if( isNumber(azArg[i], 0) ){
1607          utf8_printf(p->out,"%s", azArg[i]);
1608        }else{
1609          output_quoted_string(p->out, azArg[i]);
1610        }
1611      }
1612      raw_printf(p->out,"\n");
1613      break;
1614    }
1615    case MODE_Ascii: {
1616      if( p->cnt++==0 && p->showHeader ){
1617        for(i=0; i<nArg; i++){
1618          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1619          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1620        }
1621        utf8_printf(p->out, "%s", p->rowSeparator);
1622      }
1623      if( azArg==0 ) break;
1624      for(i=0; i<nArg; i++){
1625        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1626        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1627      }
1628      utf8_printf(p->out, "%s", p->rowSeparator);
1629      break;
1630    }
1631  }
1632  return 0;
1633}
1634
1635/*
1636** This is the callback routine that the SQLite library
1637** invokes for each row of a query result.
1638*/
1639static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1640  /* since we don't have type info, call the shell_callback with a NULL value */
1641  return shell_callback(pArg, nArg, azArg, azCol, NULL);
1642}
1643
1644/*
1645** This is the callback routine from sqlite3_exec() that appends all
1646** output onto the end of a ShellText object.
1647*/
1648static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1649  ShellText *p = (ShellText*)pArg;
1650  int i;
1651  UNUSED_PARAMETER(az);
1652  if( p->n ) appendText(p, "|", 0);
1653  for(i=0; i<nArg; i++){
1654    if( i ) appendText(p, ",", 0);
1655    if( azArg[i] ) appendText(p, azArg[i], 0);
1656  }
1657  return 0;
1658}
1659
1660/*
1661** Generate an appropriate SELFTEST table in the main database.
1662*/
1663static void createSelftestTable(ShellState *p){
1664  char *zErrMsg = 0;
1665  sqlite3_exec(p->db,
1666    "SAVEPOINT selftest_init;\n"
1667    "CREATE TABLE IF NOT EXISTS selftest(\n"
1668    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
1669    "  op TEXT,\n"                   /* Operator:  memo run */
1670    "  cmd TEXT,\n"                  /* Command text */
1671    "  ans TEXT\n"                   /* Desired answer */
1672    ");"
1673    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1674    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1675    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1676    "         'memo','Tests generated by --init');\n"
1677    "INSERT INTO [_shell$self]\n"
1678    "  SELECT 'run',\n"
1679    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1680                                 "FROM sqlite_master ORDER BY 2'',224))',\n"
1681    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
1682                          "FROM sqlite_master ORDER BY 2',224));\n"
1683    "INSERT INTO [_shell$self]\n"
1684    "  SELECT 'run',"
1685    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1686    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1687    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1688    "  FROM (\n"
1689    "    SELECT name FROM sqlite_master\n"
1690    "     WHERE type='table'\n"
1691    "       AND name<>'selftest'\n"
1692    "       AND coalesce(rootpage,0)>0\n"
1693    "  )\n"
1694    " ORDER BY name;\n"
1695    "INSERT INTO [_shell$self]\n"
1696    "  VALUES('run','PRAGMA integrity_check','ok');\n"
1697    "INSERT INTO selftest(tno,op,cmd,ans)"
1698    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1699    "DROP TABLE [_shell$self];"
1700    ,0,0,&zErrMsg);
1701  if( zErrMsg ){
1702    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1703    sqlite3_free(zErrMsg);
1704  }
1705  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1706}
1707
1708
1709/*
1710** Set the destination table field of the ShellState structure to
1711** the name of the table given.  Escape any quote characters in the
1712** table name.
1713*/
1714static void set_table_name(ShellState *p, const char *zName){
1715  int i, n;
1716  int cQuote;
1717  char *z;
1718
1719  if( p->zDestTable ){
1720    free(p->zDestTable);
1721    p->zDestTable = 0;
1722  }
1723  if( zName==0 ) return;
1724  cQuote = quoteChar(zName);
1725  n = strlen30(zName);
1726  if( cQuote ) n += n+2;
1727  z = p->zDestTable = malloc( n+1 );
1728  if( z==0 ){
1729    raw_printf(stderr,"Error: out of memory\n");
1730    exit(1);
1731  }
1732  n = 0;
1733  if( cQuote ) z[n++] = cQuote;
1734  for(i=0; zName[i]; i++){
1735    z[n++] = zName[i];
1736    if( zName[i]==cQuote ) z[n++] = cQuote;
1737  }
1738  if( cQuote ) z[n++] = cQuote;
1739  z[n] = 0;
1740}
1741
1742
1743/*
1744** Execute a query statement that will generate SQL output.  Print
1745** the result columns, comma-separated, on a line and then add a
1746** semicolon terminator to the end of that line.
1747**
1748** If the number of columns is 1 and that column contains text "--"
1749** then write the semicolon on a separate line.  That way, if a
1750** "--" comment occurs at the end of the statement, the comment
1751** won't consume the semicolon terminator.
1752*/
1753static int run_table_dump_query(
1754  ShellState *p,           /* Query context */
1755  const char *zSelect,     /* SELECT statement to extract content */
1756  const char *zFirstRow    /* Print before first row, if not NULL */
1757){
1758  sqlite3_stmt *pSelect;
1759  int rc;
1760  int nResult;
1761  int i;
1762  const char *z;
1763  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1764  if( rc!=SQLITE_OK || !pSelect ){
1765    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1766                sqlite3_errmsg(p->db));
1767    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1768    return rc;
1769  }
1770  rc = sqlite3_step(pSelect);
1771  nResult = sqlite3_column_count(pSelect);
1772  while( rc==SQLITE_ROW ){
1773    if( zFirstRow ){
1774      utf8_printf(p->out, "%s", zFirstRow);
1775      zFirstRow = 0;
1776    }
1777    z = (const char*)sqlite3_column_text(pSelect, 0);
1778    utf8_printf(p->out, "%s", z);
1779    for(i=1; i<nResult; i++){
1780      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1781    }
1782    if( z==0 ) z = "";
1783    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1784    if( z[0] ){
1785      raw_printf(p->out, "\n;\n");
1786    }else{
1787      raw_printf(p->out, ";\n");
1788    }
1789    rc = sqlite3_step(pSelect);
1790  }
1791  rc = sqlite3_finalize(pSelect);
1792  if( rc!=SQLITE_OK ){
1793    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1794                sqlite3_errmsg(p->db));
1795    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1796  }
1797  return rc;
1798}
1799
1800/*
1801** Allocate space and save off current error string.
1802*/
1803static char *save_err_msg(
1804  sqlite3 *db            /* Database to query */
1805){
1806  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1807  char *zErrMsg = sqlite3_malloc64(nErrMsg);
1808  if( zErrMsg ){
1809    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1810  }
1811  return zErrMsg;
1812}
1813
1814#ifdef __linux__
1815/*
1816** Attempt to display I/O stats on Linux using /proc/PID/io
1817*/
1818static void displayLinuxIoStats(FILE *out){
1819  FILE *in;
1820  char z[200];
1821  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1822  in = fopen(z, "rb");
1823  if( in==0 ) return;
1824  while( fgets(z, sizeof(z), in)!=0 ){
1825    static const struct {
1826      const char *zPattern;
1827      const char *zDesc;
1828    } aTrans[] = {
1829      { "rchar: ",                  "Bytes received by read():" },
1830      { "wchar: ",                  "Bytes sent to write():"    },
1831      { "syscr: ",                  "Read() system calls:"      },
1832      { "syscw: ",                  "Write() system calls:"     },
1833      { "read_bytes: ",             "Bytes read from storage:"  },
1834      { "write_bytes: ",            "Bytes written to storage:" },
1835      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
1836    };
1837    int i;
1838    for(i=0; i<ArraySize(aTrans); i++){
1839      int n = (int)strlen(aTrans[i].zPattern);
1840      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1841        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1842        break;
1843      }
1844    }
1845  }
1846  fclose(in);
1847}
1848#endif
1849
1850/*
1851** Display a single line of status using 64-bit values.
1852*/
1853static void displayStatLine(
1854  ShellState *p,            /* The shell context */
1855  char *zLabel,             /* Label for this one line */
1856  char *zFormat,            /* Format for the result */
1857  int iStatusCtrl,          /* Which status to display */
1858  int bReset                /* True to reset the stats */
1859){
1860  sqlite3_int64 iCur = -1;
1861  sqlite3_int64 iHiwtr = -1;
1862  int i, nPercent;
1863  char zLine[200];
1864  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
1865  for(i=0, nPercent=0; zFormat[i]; i++){
1866    if( zFormat[i]=='%' ) nPercent++;
1867  }
1868  if( nPercent>1 ){
1869    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
1870  }else{
1871    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
1872  }
1873  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
1874}
1875
1876/*
1877** Display memory stats.
1878*/
1879static int display_stats(
1880  sqlite3 *db,                /* Database to query */
1881  ShellState *pArg,           /* Pointer to ShellState */
1882  int bReset                  /* True to reset the stats */
1883){
1884  int iCur;
1885  int iHiwtr;
1886
1887  if( pArg && pArg->out ){
1888    displayStatLine(pArg, "Memory Used:",
1889       "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
1890    displayStatLine(pArg, "Number of Outstanding Allocations:",
1891       "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
1892    if( pArg->shellFlgs & SHFLG_Pagecache ){
1893      displayStatLine(pArg, "Number of Pcache Pages Used:",
1894         "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
1895    }
1896    displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
1897       "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
1898    if( pArg->shellFlgs & SHFLG_Scratch ){
1899      displayStatLine(pArg, "Number of Scratch Allocations Used:",
1900         "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
1901    }
1902    displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
1903       "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
1904    displayStatLine(pArg, "Largest Allocation:",
1905       "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
1906    displayStatLine(pArg, "Largest Pcache Allocation:",
1907       "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
1908    displayStatLine(pArg, "Largest Scratch Allocation:",
1909       "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
1910#ifdef YYTRACKMAXSTACKDEPTH
1911    displayStatLine(pArg, "Deepest Parser Stack:",
1912       "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
1913#endif
1914  }
1915
1916  if( pArg && pArg->out && db ){
1917    if( pArg->shellFlgs & SHFLG_Lookaside ){
1918      iHiwtr = iCur = -1;
1919      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
1920                        &iCur, &iHiwtr, bReset);
1921      raw_printf(pArg->out,
1922              "Lookaside Slots Used:                %d (max %d)\n",
1923              iCur, iHiwtr);
1924      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
1925                        &iCur, &iHiwtr, bReset);
1926      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
1927              iHiwtr);
1928      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
1929                        &iCur, &iHiwtr, bReset);
1930      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
1931              iHiwtr);
1932      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
1933                        &iCur, &iHiwtr, bReset);
1934      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
1935              iHiwtr);
1936    }
1937    iHiwtr = iCur = -1;
1938    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
1939    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
1940            iCur);
1941    iHiwtr = iCur = -1;
1942    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
1943    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
1944    iHiwtr = iCur = -1;
1945    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
1946    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
1947    iHiwtr = iCur = -1;
1948    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
1949    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
1950    iHiwtr = iCur = -1;
1951    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
1952    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
1953            iCur);
1954    iHiwtr = iCur = -1;
1955    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
1956    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
1957            iCur);
1958  }
1959
1960  if( pArg && pArg->out && db && pArg->pStmt ){
1961    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
1962                               bReset);
1963    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
1964    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1965    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
1966    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
1967    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
1968    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
1969    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
1970  }
1971
1972#ifdef __linux__
1973  displayLinuxIoStats(pArg->out);
1974#endif
1975
1976  /* Do not remove this machine readable comment: extra-stats-output-here */
1977
1978  return 0;
1979}
1980
1981/*
1982** Display scan stats.
1983*/
1984static void display_scanstats(
1985  sqlite3 *db,                    /* Database to query */
1986  ShellState *pArg                /* Pointer to ShellState */
1987){
1988#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
1989  UNUSED_PARAMETER(db);
1990  UNUSED_PARAMETER(pArg);
1991#else
1992  int i, k, n, mx;
1993  raw_printf(pArg->out, "-------- scanstats --------\n");
1994  mx = 0;
1995  for(k=0; k<=mx; k++){
1996    double rEstLoop = 1.0;
1997    for(i=n=0; 1; i++){
1998      sqlite3_stmt *p = pArg->pStmt;
1999      sqlite3_int64 nLoop, nVisit;
2000      double rEst;
2001      int iSid;
2002      const char *zExplain;
2003      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2004        break;
2005      }
2006      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2007      if( iSid>mx ) mx = iSid;
2008      if( iSid!=k ) continue;
2009      if( n==0 ){
2010        rEstLoop = (double)nLoop;
2011        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2012      }
2013      n++;
2014      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2015      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2016      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2017      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2018      rEstLoop *= rEst;
2019      raw_printf(pArg->out,
2020          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2021          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2022      );
2023    }
2024  }
2025  raw_printf(pArg->out, "---------------------------\n");
2026#endif
2027}
2028
2029/*
2030** Parameter azArray points to a zero-terminated array of strings. zStr
2031** points to a single nul-terminated string. Return non-zero if zStr
2032** is equal, according to strcmp(), to any of the strings in the array.
2033** Otherwise, return zero.
2034*/
2035static int str_in_array(const char *zStr, const char **azArray){
2036  int i;
2037  for(i=0; azArray[i]; i++){
2038    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2039  }
2040  return 0;
2041}
2042
2043/*
2044** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2045** and populate the ShellState.aiIndent[] array with the number of
2046** spaces each opcode should be indented before it is output.
2047**
2048** The indenting rules are:
2049**
2050**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2051**       all opcodes that occur between the p2 jump destination and the opcode
2052**       itself by 2 spaces.
2053**
2054**     * For each "Goto", if the jump destination is earlier in the program
2055**       and ends on one of:
2056**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2057**       or if the P1 parameter is one instead of zero,
2058**       then indent all opcodes between the earlier instruction
2059**       and "Goto" by 2 spaces.
2060*/
2061static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2062  const char *zSql;               /* The text of the SQL statement */
2063  const char *z;                  /* Used to check if this is an EXPLAIN */
2064  int *abYield = 0;               /* True if op is an OP_Yield */
2065  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2066  int iOp;                        /* Index of operation in p->aiIndent[] */
2067
2068  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2069                           "NextIfOpen", "PrevIfOpen", 0 };
2070  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2071                            "Rewind", 0 };
2072  const char *azGoto[] = { "Goto", 0 };
2073
2074  /* Try to figure out if this is really an EXPLAIN statement. If this
2075  ** cannot be verified, return early.  */
2076  if( sqlite3_column_count(pSql)!=8 ){
2077    p->cMode = p->mode;
2078    return;
2079  }
2080  zSql = sqlite3_sql(pSql);
2081  if( zSql==0 ) return;
2082  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2083  if( sqlite3_strnicmp(z, "explain", 7) ){
2084    p->cMode = p->mode;
2085    return;
2086  }
2087
2088  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2089    int i;
2090    int iAddr = sqlite3_column_int(pSql, 0);
2091    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2092
2093    /* Set p2 to the P2 field of the current opcode. Then, assuming that
2094    ** p2 is an instruction address, set variable p2op to the index of that
2095    ** instruction in the aiIndent[] array. p2 and p2op may be different if
2096    ** the current instruction is part of a sub-program generated by an
2097    ** SQL trigger or foreign key.  */
2098    int p2 = sqlite3_column_int(pSql, 3);
2099    int p2op = (p2 + (iOp-iAddr));
2100
2101    /* Grow the p->aiIndent array as required */
2102    if( iOp>=nAlloc ){
2103      if( iOp==0 ){
2104        /* Do further verfication that this is explain output.  Abort if
2105        ** it is not */
2106        static const char *explainCols[] = {
2107           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2108        int jj;
2109        for(jj=0; jj<ArraySize(explainCols); jj++){
2110          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2111            p->cMode = p->mode;
2112            sqlite3_reset(pSql);
2113            return;
2114          }
2115        }
2116      }
2117      nAlloc += 100;
2118      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2119      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2120    }
2121    abYield[iOp] = str_in_array(zOp, azYield);
2122    p->aiIndent[iOp] = 0;
2123    p->nIndent = iOp+1;
2124
2125    if( str_in_array(zOp, azNext) ){
2126      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2127    }
2128    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2129     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2130    ){
2131      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2132    }
2133  }
2134
2135  p->iIndent = 0;
2136  sqlite3_free(abYield);
2137  sqlite3_reset(pSql);
2138}
2139
2140/*
2141** Free the array allocated by explain_data_prepare().
2142*/
2143static void explain_data_delete(ShellState *p){
2144  sqlite3_free(p->aiIndent);
2145  p->aiIndent = 0;
2146  p->nIndent = 0;
2147  p->iIndent = 0;
2148}
2149
2150/*
2151** Disable and restore .wheretrace and .selecttrace settings.
2152*/
2153#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2154extern int sqlite3SelectTrace;
2155static int savedSelectTrace;
2156#endif
2157#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2158extern int sqlite3WhereTrace;
2159static int savedWhereTrace;
2160#endif
2161static void disable_debug_trace_modes(void){
2162#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2163  savedSelectTrace = sqlite3SelectTrace;
2164  sqlite3SelectTrace = 0;
2165#endif
2166#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2167  savedWhereTrace = sqlite3WhereTrace;
2168  sqlite3WhereTrace = 0;
2169#endif
2170}
2171static void restore_debug_trace_modes(void){
2172#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2173  sqlite3SelectTrace = savedSelectTrace;
2174#endif
2175#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2176  sqlite3WhereTrace = savedWhereTrace;
2177#endif
2178}
2179
2180/*
2181** Run a prepared statement
2182*/
2183static void exec_prepared_stmt(
2184  ShellState *pArg,                                /* Pointer to ShellState */
2185  sqlite3_stmt *pStmt,                             /* Statment to run */
2186  int (*xCallback)(void*,int,char**,char**,int*)   /* Callback function */
2187){
2188  int rc;
2189
2190  /* perform the first step.  this will tell us if we
2191  ** have a result set or not and how wide it is.
2192  */
2193  rc = sqlite3_step(pStmt);
2194  /* if we have a result set... */
2195  if( SQLITE_ROW == rc ){
2196    /* if we have a callback... */
2197    if( xCallback ){
2198      /* allocate space for col name ptr, value ptr, and type */
2199      int nCol = sqlite3_column_count(pStmt);
2200      void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2201      if( !pData ){
2202        rc = SQLITE_NOMEM;
2203      }else{
2204        char **azCols = (char **)pData;      /* Names of result columns */
2205        char **azVals = &azCols[nCol];       /* Results */
2206        int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2207        int i, x;
2208        assert(sizeof(int) <= sizeof(char *));
2209        /* save off ptrs to column names */
2210        for(i=0; i<nCol; i++){
2211          azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2212        }
2213        do{
2214          /* extract the data and data types */
2215          for(i=0; i<nCol; i++){
2216            aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2217            if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2218              azVals[i] = "";
2219            }else{
2220              azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2221            }
2222            if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2223              rc = SQLITE_NOMEM;
2224              break; /* from for */
2225            }
2226          } /* end for */
2227
2228          /* if data and types extracted successfully... */
2229          if( SQLITE_ROW == rc ){
2230            /* call the supplied callback with the result row data */
2231            if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2232              rc = SQLITE_ABORT;
2233            }else{
2234              rc = sqlite3_step(pStmt);
2235            }
2236          }
2237        } while( SQLITE_ROW == rc );
2238        sqlite3_free(pData);
2239      }
2240    }else{
2241      do{
2242        rc = sqlite3_step(pStmt);
2243      } while( rc == SQLITE_ROW );
2244    }
2245  }
2246}
2247
2248/*
2249** Execute a statement or set of statements.  Print
2250** any result rows/columns depending on the current mode
2251** set via the supplied callback.
2252**
2253** This is very similar to SQLite's built-in sqlite3_exec()
2254** function except it takes a slightly different callback
2255** and callback data argument.
2256*/
2257static int shell_exec(
2258  sqlite3 *db,                              /* An open database */
2259  const char *zSql,                         /* SQL to be evaluated */
2260  int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
2261                                            /* (not the same as sqlite3_exec) */
2262  ShellState *pArg,                         /* Pointer to ShellState */
2263  char **pzErrMsg                           /* Error msg written here */
2264){
2265  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
2266  int rc = SQLITE_OK;             /* Return Code */
2267  int rc2;
2268  const char *zLeftover;          /* Tail of unprocessed SQL */
2269
2270  if( pzErrMsg ){
2271    *pzErrMsg = NULL;
2272  }
2273
2274  while( zSql[0] && (SQLITE_OK == rc) ){
2275    static const char *zStmtSql;
2276    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2277    if( SQLITE_OK != rc ){
2278      if( pzErrMsg ){
2279        *pzErrMsg = save_err_msg(db);
2280      }
2281    }else{
2282      if( !pStmt ){
2283        /* this happens for a comment or white-space */
2284        zSql = zLeftover;
2285        while( IsSpace(zSql[0]) ) zSql++;
2286        continue;
2287      }
2288      zStmtSql = sqlite3_sql(pStmt);
2289      if( zStmtSql==0 ) zStmtSql = "";
2290      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2291
2292      /* save off the prepared statment handle and reset row count */
2293      if( pArg ){
2294        pArg->pStmt = pStmt;
2295        pArg->cnt = 0;
2296      }
2297
2298      /* echo the sql statement if echo on */
2299      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2300        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2301      }
2302
2303      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2304      if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2305        sqlite3_stmt *pExplain;
2306        char *zEQP;
2307        disable_debug_trace_modes();
2308        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2309        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2310        if( rc==SQLITE_OK ){
2311          while( sqlite3_step(pExplain)==SQLITE_ROW ){
2312            raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2313            raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2314            raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2315            utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2316          }
2317        }
2318        sqlite3_finalize(pExplain);
2319        sqlite3_free(zEQP);
2320        if( pArg->autoEQP>=2 ){
2321          /* Also do an EXPLAIN for ".eqp full" mode */
2322          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2323          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2324          if( rc==SQLITE_OK ){
2325            pArg->cMode = MODE_Explain;
2326            explain_data_prepare(pArg, pExplain);
2327            exec_prepared_stmt(pArg, pExplain, xCallback);
2328            explain_data_delete(pArg);
2329          }
2330          sqlite3_finalize(pExplain);
2331          sqlite3_free(zEQP);
2332        }
2333        restore_debug_trace_modes();
2334      }
2335
2336      if( pArg ){
2337        pArg->cMode = pArg->mode;
2338        if( pArg->autoExplain
2339         && sqlite3_column_count(pStmt)==8
2340         && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2341        ){
2342          pArg->cMode = MODE_Explain;
2343        }
2344
2345        /* If the shell is currently in ".explain" mode, gather the extra
2346        ** data required to add indents to the output.*/
2347        if( pArg->cMode==MODE_Explain ){
2348          explain_data_prepare(pArg, pStmt);
2349        }
2350      }
2351
2352      exec_prepared_stmt(pArg, pStmt, xCallback);
2353      explain_data_delete(pArg);
2354
2355      /* print usage stats if stats on */
2356      if( pArg && pArg->statsOn ){
2357        display_stats(db, pArg, 0);
2358      }
2359
2360      /* print loop-counters if required */
2361      if( pArg && pArg->scanstatsOn ){
2362        display_scanstats(db, pArg);
2363      }
2364
2365      /* Finalize the statement just executed. If this fails, save a
2366      ** copy of the error message. Otherwise, set zSql to point to the
2367      ** next statement to execute. */
2368      rc2 = sqlite3_finalize(pStmt);
2369      if( rc!=SQLITE_NOMEM ) rc = rc2;
2370      if( rc==SQLITE_OK ){
2371        zSql = zLeftover;
2372        while( IsSpace(zSql[0]) ) zSql++;
2373      }else if( pzErrMsg ){
2374        *pzErrMsg = save_err_msg(db);
2375      }
2376
2377      /* clear saved stmt handle */
2378      if( pArg ){
2379        pArg->pStmt = NULL;
2380      }
2381    }
2382  } /* end while */
2383
2384  return rc;
2385}
2386
2387/*
2388** Release memory previously allocated by tableColumnList().
2389*/
2390static void freeColumnList(char **azCol){
2391  int i;
2392  for(i=1; azCol[i]; i++){
2393    sqlite3_free(azCol[i]);
2394  }
2395  /* azCol[0] is a static string */
2396  sqlite3_free(azCol);
2397}
2398
2399/*
2400** Return a list of pointers to strings which are the names of all
2401** columns in table zTab.   The memory to hold the names is dynamically
2402** allocated and must be released by the caller using a subsequent call
2403** to freeColumnList().
2404**
2405** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
2406** value that needs to be preserved, then azCol[0] is filled in with the
2407** name of the rowid column.
2408**
2409** The first regular column in the table is azCol[1].  The list is terminated
2410** by an entry with azCol[i]==0.
2411*/
2412static char **tableColumnList(ShellState *p, const char *zTab){
2413  char **azCol = 0;
2414  sqlite3_stmt *pStmt;
2415  char *zSql;
2416  int nCol = 0;
2417  int nAlloc = 0;
2418  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
2419  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
2420  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2421  int rc;
2422
2423  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2424  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2425  sqlite3_free(zSql);
2426  if( rc ) return 0;
2427  while( sqlite3_step(pStmt)==SQLITE_ROW ){
2428    if( nCol>=nAlloc-2 ){
2429      nAlloc = nAlloc*2 + nCol + 10;
2430      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2431      if( azCol==0 ){
2432        raw_printf(stderr, "Error: out of memory\n");
2433        exit(1);
2434      }
2435    }
2436    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2437    if( sqlite3_column_int(pStmt, 5) ){
2438      nPK++;
2439      if( nPK==1
2440       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2441                          "INTEGER")==0
2442      ){
2443        isIPK = 1;
2444      }else{
2445        isIPK = 0;
2446      }
2447    }
2448  }
2449  sqlite3_finalize(pStmt);
2450  azCol[0] = 0;
2451  azCol[nCol+1] = 0;
2452
2453  /* The decision of whether or not a rowid really needs to be preserved
2454  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
2455  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
2456  ** rowids on tables where the rowid is inaccessible because there are other
2457  ** columns in the table named "rowid", "_rowid_", and "oid".
2458  */
2459  if( preserveRowid && isIPK ){
2460    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2461    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
2462    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2463    ** ROWID aliases.  To distinguish these cases, check to see if
2464    ** there is a "pk" entry in "PRAGMA index_list".  There will be
2465    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2466    */
2467    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2468                           " WHERE origin='pk'", zTab);
2469    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2470    sqlite3_free(zSql);
2471    if( rc ){
2472      freeColumnList(azCol);
2473      return 0;
2474    }
2475    rc = sqlite3_step(pStmt);
2476    sqlite3_finalize(pStmt);
2477    preserveRowid = rc==SQLITE_ROW;
2478  }
2479  if( preserveRowid ){
2480    /* Only preserve the rowid if we can find a name to use for the
2481    ** rowid */
2482    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2483    int i, j;
2484    for(j=0; j<3; j++){
2485      for(i=1; i<=nCol; i++){
2486        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2487      }
2488      if( i>nCol ){
2489        /* At this point, we know that azRowid[j] is not the name of any
2490        ** ordinary column in the table.  Verify that azRowid[j] is a valid
2491        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
2492        ** tables will fail this last check */
2493        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2494        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2495        break;
2496      }
2497    }
2498  }
2499  return azCol;
2500}
2501
2502/*
2503** Toggle the reverse_unordered_selects setting.
2504*/
2505static void toggleSelectOrder(sqlite3 *db){
2506  sqlite3_stmt *pStmt = 0;
2507  int iSetting = 0;
2508  char zStmt[100];
2509  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2510  if( sqlite3_step(pStmt)==SQLITE_ROW ){
2511    iSetting = sqlite3_column_int(pStmt, 0);
2512  }
2513  sqlite3_finalize(pStmt);
2514  sqlite3_snprintf(sizeof(zStmt), zStmt,
2515       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2516  sqlite3_exec(db, zStmt, 0, 0, 0);
2517}
2518
2519/*
2520** This is a different callback routine used for dumping the database.
2521** Each row received by this callback consists of a table name,
2522** the table type ("index" or "table") and SQL to create the table.
2523** This routine should print text sufficient to recreate the table.
2524*/
2525static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2526  int rc;
2527  const char *zTable;
2528  const char *zType;
2529  const char *zSql;
2530  ShellState *p = (ShellState *)pArg;
2531
2532  UNUSED_PARAMETER(azNotUsed);
2533  if( nArg!=3 ) return 1;
2534  zTable = azArg[0];
2535  zType = azArg[1];
2536  zSql = azArg[2];
2537
2538  if( strcmp(zTable, "sqlite_sequence")==0 ){
2539    raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2540  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2541    raw_printf(p->out, "ANALYZE sqlite_master;\n");
2542  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2543    return 0;
2544  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2545    char *zIns;
2546    if( !p->writableSchema ){
2547      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2548      p->writableSchema = 1;
2549    }
2550    zIns = sqlite3_mprintf(
2551       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2552       "VALUES('table','%q','%q',0,'%q');",
2553       zTable, zTable, zSql);
2554    utf8_printf(p->out, "%s\n", zIns);
2555    sqlite3_free(zIns);
2556    return 0;
2557  }else{
2558    printSchemaLine(p->out, zSql, ";\n");
2559  }
2560
2561  if( strcmp(zType, "table")==0 ){
2562    ShellText sSelect;
2563    ShellText sTable;
2564    char **azCol;
2565    int i;
2566    char *savedDestTable;
2567    int savedMode;
2568
2569    azCol = tableColumnList(p, zTable);
2570    if( azCol==0 ){
2571      p->nErr++;
2572      return 0;
2573    }
2574
2575    /* Always quote the table name, even if it appears to be pure ascii,
2576    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
2577    initText(&sTable);
2578    appendText(&sTable, zTable, quoteChar(zTable));
2579    /* If preserving the rowid, add a column list after the table name.
2580    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2581    ** instead of the usual "INSERT INTO tab VALUES(...)".
2582    */
2583    if( azCol[0] ){
2584      appendText(&sTable, "(", 0);
2585      appendText(&sTable, azCol[0], 0);
2586      for(i=1; azCol[i]; i++){
2587        appendText(&sTable, ",", 0);
2588        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2589      }
2590      appendText(&sTable, ")", 0);
2591    }
2592
2593    /* Build an appropriate SELECT statement */
2594    initText(&sSelect);
2595    appendText(&sSelect, "SELECT ", 0);
2596    if( azCol[0] ){
2597      appendText(&sSelect, azCol[0], 0);
2598      appendText(&sSelect, ",", 0);
2599    }
2600    for(i=1; azCol[i]; i++){
2601      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2602      if( azCol[i+1] ){
2603        appendText(&sSelect, ",", 0);
2604      }
2605    }
2606    freeColumnList(azCol);
2607    appendText(&sSelect, " FROM ", 0);
2608    appendText(&sSelect, zTable, quoteChar(zTable));
2609
2610    savedDestTable = p->zDestTable;
2611    savedMode = p->mode;
2612    p->zDestTable = sTable.z;
2613    p->mode = p->cMode = MODE_Insert;
2614    rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2615    if( (rc&0xff)==SQLITE_CORRUPT ){
2616      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2617      toggleSelectOrder(p->db);
2618      shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2619      toggleSelectOrder(p->db);
2620    }
2621    p->zDestTable = savedDestTable;
2622    p->mode = savedMode;
2623    freeText(&sTable);
2624    freeText(&sSelect);
2625    if( rc ) p->nErr++;
2626  }
2627  return 0;
2628}
2629
2630/*
2631** Run zQuery.  Use dump_callback() as the callback routine so that
2632** the contents of the query are output as SQL statements.
2633**
2634** If we get a SQLITE_CORRUPT error, rerun the query after appending
2635** "ORDER BY rowid DESC" to the end.
2636*/
2637static int run_schema_dump_query(
2638  ShellState *p,
2639  const char *zQuery
2640){
2641  int rc;
2642  char *zErr = 0;
2643  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2644  if( rc==SQLITE_CORRUPT ){
2645    char *zQ2;
2646    int len = strlen30(zQuery);
2647    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2648    if( zErr ){
2649      utf8_printf(p->out, "/****** %s ******/\n", zErr);
2650      sqlite3_free(zErr);
2651      zErr = 0;
2652    }
2653    zQ2 = malloc( len+100 );
2654    if( zQ2==0 ) return rc;
2655    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2656    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2657    if( rc ){
2658      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2659    }else{
2660      rc = SQLITE_CORRUPT;
2661    }
2662    sqlite3_free(zErr);
2663    free(zQ2);
2664  }
2665  return rc;
2666}
2667
2668/*
2669** Text of a help message
2670*/
2671static char zHelp[] =
2672#ifndef SQLITE_OMIT_AUTHORIZATION
2673  ".auth ON|OFF           Show authorizer callbacks\n"
2674#endif
2675  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
2676  ".bail on|off           Stop after hitting an error.  Default OFF\n"
2677  ".binary on|off         Turn binary output on or off.  Default OFF\n"
2678  ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
2679  ".changes on|off        Show number of rows changed by SQL\n"
2680  ".check GLOB            Fail if output since .testcase does not match\n"
2681  ".clone NEWDB           Clone data into NEWDB from the existing database\n"
2682  ".databases             List names and files of attached databases\n"
2683  ".dbinfo ?DB?           Show status information about the database\n"
2684  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
2685  "                         If TABLE specified, only dump tables matching\n"
2686  "                         LIKE pattern TABLE.\n"
2687  ".echo on|off           Turn command echo on or off\n"
2688  ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
2689  ".exit                  Exit this program\n"
2690/* Because explain mode comes on automatically now, the ".explain" mode
2691** is removed from the help screen.  It is still supported for legacy, however */
2692/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2693  ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2694  ".headers on|off        Turn display of headers on or off\n"
2695  ".help                  Show this message\n"
2696  ".import FILE TABLE     Import data from FILE into TABLE\n"
2697#ifndef SQLITE_OMIT_TEST_CONTROL
2698  ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
2699#endif
2700  ".indexes ?TABLE?       Show names of all indexes\n"
2701  "                         If TABLE specified, only show indexes for tables\n"
2702  "                         matching LIKE pattern TABLE.\n"
2703#ifdef SQLITE_ENABLE_IOTRACE
2704  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
2705#endif
2706  ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
2707  ".lint OPTIONS          Report potential schema issues. Options:\n"
2708  "                         fkey-indexes     Find missing foreign key indexes\n"
2709#ifndef SQLITE_OMIT_LOAD_EXTENSION
2710  ".load FILE ?ENTRY?     Load an extension library\n"
2711#endif
2712  ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
2713  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
2714  "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
2715  "                         csv      Comma-separated values\n"
2716  "                         column   Left-aligned columns.  (See .width)\n"
2717  "                         html     HTML <table> code\n"
2718  "                         insert   SQL insert statements for TABLE\n"
2719  "                         line     One value per line\n"
2720  "                         list     Values delimited by \"|\"\n"
2721  "                         quote    Escape answers as for SQL\n"
2722  "                         tabs     Tab-separated values\n"
2723  "                         tcl      TCL list elements\n"
2724  ".nullvalue STRING      Use STRING in place of NULL values\n"
2725  ".once FILENAME         Output for the next SQL command only to FILENAME\n"
2726  ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2727  "                         The --new option starts with an empty file\n"
2728  ".output ?FILENAME?     Send output to FILENAME or stdout\n"
2729  ".print STRING...       Print literal STRING\n"
2730  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
2731  ".quit                  Exit this program\n"
2732  ".read FILENAME         Execute SQL in FILENAME\n"
2733  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
2734  ".save FILE             Write in-memory database into FILE\n"
2735  ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2736  ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
2737  "                          Add --indent for pretty-printing\n"
2738  ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
2739  ".separator COL ?ROW?   Change the column separator and optionally the row\n"
2740  "                         separator for both the output mode and .import\n"
2741#if defined(SQLITE_ENABLE_SESSION)
2742  ".session CMD ...       Create or control sessions\n"
2743#endif
2744  ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
2745  ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
2746  ".show                  Show the current values for various settings\n"
2747  ".stats ?on|off?        Show stats or turn stats on or off\n"
2748  ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
2749  ".tables ?TABLE?        List names of tables\n"
2750  "                         If TABLE specified, only list tables matching\n"
2751  "                         LIKE pattern TABLE.\n"
2752  ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
2753  ".timeout MS            Try opening locked tables for MS milliseconds\n"
2754  ".timer on|off          Turn SQL timer on or off\n"
2755  ".trace FILE|off        Output each SQL statement as it is run\n"
2756  ".vfsinfo ?AUX?         Information about the top-level VFS\n"
2757  ".vfslist               List all available VFSes\n"
2758  ".vfsname ?AUX?         Print the name of the VFS stack\n"
2759  ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
2760  "                         Negative values right-justify\n"
2761;
2762
2763#if defined(SQLITE_ENABLE_SESSION)
2764/*
2765** Print help information for the ".sessions" command
2766*/
2767void session_help(ShellState *p){
2768  raw_printf(p->out,
2769    ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2770    "If ?NAME? is omitted, the first defined session is used.\n"
2771    "Subcommands:\n"
2772    "   attach TABLE             Attach TABLE\n"
2773    "   changeset FILE           Write a changeset into FILE\n"
2774    "   close                    Close one session\n"
2775    "   enable ?BOOLEAN?         Set or query the enable bit\n"
2776    "   filter GLOB...           Reject tables matching GLOBs\n"
2777    "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
2778    "   isempty                  Query whether the session is empty\n"
2779    "   list                     List currently open session names\n"
2780    "   open DB NAME             Open a new session on DB\n"
2781    "   patchset FILE            Write a patchset into FILE\n"
2782  );
2783}
2784#endif
2785
2786
2787/* Forward reference */
2788static int process_input(ShellState *p, FILE *in);
2789
2790/*
2791** Read the content of file zName into memory obtained from sqlite3_malloc64()
2792** and return a pointer to the buffer. The caller is responsible for freeing
2793** the memory.
2794**
2795** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
2796** read.
2797**
2798** For convenience, a nul-terminator byte is always appended to the data read
2799** from the file before the buffer is returned. This byte is not included in
2800** the final value of (*pnByte), if applicable.
2801**
2802** NULL is returned if any error is encountered. The final value of *pnByte
2803** is undefined in this case.
2804*/
2805static char *readFile(const char *zName, int *pnByte){
2806  FILE *in = fopen(zName, "rb");
2807  long nIn;
2808  size_t nRead;
2809  char *pBuf;
2810  if( in==0 ) return 0;
2811  fseek(in, 0, SEEK_END);
2812  nIn = ftell(in);
2813  rewind(in);
2814  pBuf = sqlite3_malloc64( nIn+1 );
2815  if( pBuf==0 ) return 0;
2816  nRead = fread(pBuf, nIn, 1, in);
2817  fclose(in);
2818  if( nRead!=1 ){
2819    sqlite3_free(pBuf);
2820    return 0;
2821  }
2822  pBuf[nIn] = 0;
2823  if( pnByte ) *pnByte = nIn;
2824  return pBuf;
2825}
2826
2827#if defined(SQLITE_ENABLE_SESSION)
2828/*
2829** Close a single OpenSession object and release all of its associated
2830** resources.
2831*/
2832static void session_close(OpenSession *pSession){
2833  int i;
2834  sqlite3session_delete(pSession->p);
2835  sqlite3_free(pSession->zName);
2836  for(i=0; i<pSession->nFilter; i++){
2837    sqlite3_free(pSession->azFilter[i]);
2838  }
2839  sqlite3_free(pSession->azFilter);
2840  memset(pSession, 0, sizeof(OpenSession));
2841}
2842#endif
2843
2844/*
2845** Close all OpenSession objects and release all associated resources.
2846*/
2847#if defined(SQLITE_ENABLE_SESSION)
2848static void session_close_all(ShellState *p){
2849  int i;
2850  for(i=0; i<p->nSession; i++){
2851    session_close(&p->aSession[i]);
2852  }
2853  p->nSession = 0;
2854}
2855#else
2856# define session_close_all(X)
2857#endif
2858
2859/*
2860** Implementation of the xFilter function for an open session.  Omit
2861** any tables named by ".session filter" but let all other table through.
2862*/
2863#if defined(SQLITE_ENABLE_SESSION)
2864static int session_filter(void *pCtx, const char *zTab){
2865  OpenSession *pSession = (OpenSession*)pCtx;
2866  int i;
2867  for(i=0; i<pSession->nFilter; i++){
2868    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
2869  }
2870  return 1;
2871}
2872#endif
2873
2874/*
2875** Make sure the database is open.  If it is not, then open it.  If
2876** the database fails to open, print an error message and exit.
2877*/
2878static void open_db(ShellState *p, int keepAlive){
2879  if( p->db==0 ){
2880    sqlite3_initialize();
2881    sqlite3_open(p->zDbFilename, &p->db);
2882    globalDb = p->db;
2883    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
2884      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
2885          p->zDbFilename, sqlite3_errmsg(p->db));
2886      if( keepAlive ) return;
2887      exit(1);
2888    }
2889#ifndef SQLITE_OMIT_LOAD_EXTENSION
2890    sqlite3_enable_load_extension(p->db, 1);
2891#endif
2892    sqlite3_fileio_init(p->db, 0, 0);
2893    sqlite3_shathree_init(p->db, 0, 0);
2894    sqlite3_completion_init(p->db, 0, 0);
2895    sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
2896                            shellAddSchemaName, 0, 0);
2897  }
2898}
2899
2900#if HAVE_READLINE || HAVE_EDITLINE
2901/*
2902** Readline completion callbacks
2903*/
2904static char *readline_completion_generator(const char *text, int state){
2905  static sqlite3_stmt *pStmt = 0;
2906  char *zRet;
2907  if( state==0 ){
2908    char *zSql;
2909    sqlite3_finalize(pStmt);
2910    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2911                           "  FROM completion(%Q) ORDER BY 1", text);
2912    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
2913    sqlite3_free(zSql);
2914  }
2915  if( sqlite3_step(pStmt)==SQLITE_ROW ){
2916    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
2917  }else{
2918    sqlite3_finalize(pStmt);
2919    pStmt = 0;
2920    zRet = 0;
2921  }
2922  return zRet;
2923}
2924static char **readline_completion(const char *zText, int iStart, int iEnd){
2925  rl_attempted_completion_over = 1;
2926  return rl_completion_matches(zText, readline_completion_generator);
2927}
2928
2929#elif HAVE_LINENOISE
2930/*
2931** Linenoise completion callback
2932*/
2933static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
2934  int nLine = (int)strlen(zLine);
2935  int i, iStart;
2936  sqlite3_stmt *pStmt = 0;
2937  char *zSql;
2938  char zBuf[1000];
2939
2940  if( nLine>sizeof(zBuf)-30 ) return;
2941  if( zLine[0]=='.' ) return;
2942  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
2943  if( i==nLine-1 ) return;
2944  iStart = i+1;
2945  memcpy(zBuf, zLine, iStart);
2946  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2947                         "  FROM completion(%Q,%Q) ORDER BY 1",
2948                         &zLine[iStart], zLine);
2949  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
2950  sqlite3_free(zSql);
2951  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
2952  while( sqlite3_step(pStmt)==SQLITE_ROW ){
2953    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
2954    int nCompletion = sqlite3_column_bytes(pStmt, 0);
2955    if( iStart+nCompletion < sizeof(zBuf)-1 ){
2956      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
2957      linenoiseAddCompletion(lc, zBuf);
2958    }
2959  }
2960  sqlite3_finalize(pStmt);
2961}
2962#endif
2963
2964/*
2965** Do C-language style dequoting.
2966**
2967**    \a    -> alarm
2968**    \b    -> backspace
2969**    \t    -> tab
2970**    \n    -> newline
2971**    \v    -> vertical tab
2972**    \f    -> form feed
2973**    \r    -> carriage return
2974**    \s    -> space
2975**    \"    -> "
2976**    \'    -> '
2977**    \\    -> backslash
2978**    \NNN  -> ascii character NNN in octal
2979*/
2980static void resolve_backslashes(char *z){
2981  int i, j;
2982  char c;
2983  while( *z && *z!='\\' ) z++;
2984  for(i=j=0; (c = z[i])!=0; i++, j++){
2985    if( c=='\\' && z[i+1]!=0 ){
2986      c = z[++i];
2987      if( c=='a' ){
2988        c = '\a';
2989      }else if( c=='b' ){
2990        c = '\b';
2991      }else if( c=='t' ){
2992        c = '\t';
2993      }else if( c=='n' ){
2994        c = '\n';
2995      }else if( c=='v' ){
2996        c = '\v';
2997      }else if( c=='f' ){
2998        c = '\f';
2999      }else if( c=='r' ){
3000        c = '\r';
3001      }else if( c=='"' ){
3002        c = '"';
3003      }else if( c=='\'' ){
3004        c = '\'';
3005      }else if( c=='\\' ){
3006        c = '\\';
3007      }else if( c>='0' && c<='7' ){
3008        c -= '0';
3009        if( z[i+1]>='0' && z[i+1]<='7' ){
3010          i++;
3011          c = (c<<3) + z[i] - '0';
3012          if( z[i+1]>='0' && z[i+1]<='7' ){
3013            i++;
3014            c = (c<<3) + z[i] - '0';
3015          }
3016        }
3017      }
3018    }
3019    z[j] = c;
3020  }
3021  if( j<i ) z[j] = 0;
3022}
3023
3024/*
3025** Return the value of a hexadecimal digit.  Return -1 if the input
3026** is not a hex digit.
3027*/
3028static int hexDigitValue(char c){
3029  if( c>='0' && c<='9' ) return c - '0';
3030  if( c>='a' && c<='f' ) return c - 'a' + 10;
3031  if( c>='A' && c<='F' ) return c - 'A' + 10;
3032  return -1;
3033}
3034
3035/*
3036** Interpret zArg as an integer value, possibly with suffixes.
3037*/
3038static sqlite3_int64 integerValue(const char *zArg){
3039  sqlite3_int64 v = 0;
3040  static const struct { char *zSuffix; int iMult; } aMult[] = {
3041    { "KiB", 1024 },
3042    { "MiB", 1024*1024 },
3043    { "GiB", 1024*1024*1024 },
3044    { "KB",  1000 },
3045    { "MB",  1000000 },
3046    { "GB",  1000000000 },
3047    { "K",   1000 },
3048    { "M",   1000000 },
3049    { "G",   1000000000 },
3050  };
3051  int i;
3052  int isNeg = 0;
3053  if( zArg[0]=='-' ){
3054    isNeg = 1;
3055    zArg++;
3056  }else if( zArg[0]=='+' ){
3057    zArg++;
3058  }
3059  if( zArg[0]=='0' && zArg[1]=='x' ){
3060    int x;
3061    zArg += 2;
3062    while( (x = hexDigitValue(zArg[0]))>=0 ){
3063      v = (v<<4) + x;
3064      zArg++;
3065    }
3066  }else{
3067    while( IsDigit(zArg[0]) ){
3068      v = v*10 + zArg[0] - '0';
3069      zArg++;
3070    }
3071  }
3072  for(i=0; i<ArraySize(aMult); i++){
3073    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3074      v *= aMult[i].iMult;
3075      break;
3076    }
3077  }
3078  return isNeg? -v : v;
3079}
3080
3081/*
3082** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
3083** for TRUE and FALSE.  Return the integer value if appropriate.
3084*/
3085static int booleanValue(const char *zArg){
3086  int i;
3087  if( zArg[0]=='0' && zArg[1]=='x' ){
3088    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3089  }else{
3090    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3091  }
3092  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3093  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3094    return 1;
3095  }
3096  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3097    return 0;
3098  }
3099  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3100          zArg);
3101  return 0;
3102}
3103
3104/*
3105** Set or clear a shell flag according to a boolean value.
3106*/
3107static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3108  if( booleanValue(zArg) ){
3109    ShellSetFlag(p, mFlag);
3110  }else{
3111    ShellClearFlag(p, mFlag);
3112  }
3113}
3114
3115/*
3116** Close an output file, assuming it is not stderr or stdout
3117*/
3118static void output_file_close(FILE *f){
3119  if( f && f!=stdout && f!=stderr ) fclose(f);
3120}
3121
3122/*
3123** Try to open an output file.   The names "stdout" and "stderr" are
3124** recognized and do the right thing.  NULL is returned if the output
3125** filename is "off".
3126*/
3127static FILE *output_file_open(const char *zFile){
3128  FILE *f;
3129  if( strcmp(zFile,"stdout")==0 ){
3130    f = stdout;
3131  }else if( strcmp(zFile, "stderr")==0 ){
3132    f = stderr;
3133  }else if( strcmp(zFile, "off")==0 ){
3134    f = 0;
3135  }else{
3136    f = fopen(zFile, "wb");
3137    if( f==0 ){
3138      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3139    }
3140  }
3141  return f;
3142}
3143
3144#if !defined(SQLITE_UNTESTABLE)
3145#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3146/*
3147** A routine for handling output from sqlite3_trace().
3148*/
3149static int sql_trace_callback(
3150  unsigned mType,
3151  void *pArg,
3152  void *pP,
3153  void *pX
3154){
3155  FILE *f = (FILE*)pArg;
3156  UNUSED_PARAMETER(mType);
3157  UNUSED_PARAMETER(pP);
3158  if( f ){
3159    const char *z = (const char*)pX;
3160    int i = (int)strlen(z);
3161    while( i>0 && z[i-1]==';' ){ i--; }
3162    utf8_printf(f, "%.*s;\n", i, z);
3163  }
3164  return 0;
3165}
3166#endif
3167#endif
3168
3169/*
3170** A no-op routine that runs with the ".breakpoint" doc-command.  This is
3171** a useful spot to set a debugger breakpoint.
3172*/
3173static void test_breakpoint(void){
3174  static int nCall = 0;
3175  nCall++;
3176}
3177
3178/*
3179** An object used to read a CSV and other files for import.
3180*/
3181typedef struct ImportCtx ImportCtx;
3182struct ImportCtx {
3183  const char *zFile;  /* Name of the input file */
3184  FILE *in;           /* Read the CSV text from this input stream */
3185  char *z;            /* Accumulated text for a field */
3186  int n;              /* Number of bytes in z */
3187  int nAlloc;         /* Space allocated for z[] */
3188  int nLine;          /* Current line number */
3189  int bNotFirst;      /* True if one or more bytes already read */
3190  int cTerm;          /* Character that terminated the most recent field */
3191  int cColSep;        /* The column separator character.  (Usually ",") */
3192  int cRowSep;        /* The row separator character.  (Usually "\n") */
3193};
3194
3195/* Append a single byte to z[] */
3196static void import_append_char(ImportCtx *p, int c){
3197  if( p->n+1>=p->nAlloc ){
3198    p->nAlloc += p->nAlloc + 100;
3199    p->z = sqlite3_realloc64(p->z, p->nAlloc);
3200    if( p->z==0 ){
3201      raw_printf(stderr, "out of memory\n");
3202      exit(1);
3203    }
3204  }
3205  p->z[p->n++] = (char)c;
3206}
3207
3208/* Read a single field of CSV text.  Compatible with rfc4180 and extended
3209** with the option of having a separator other than ",".
3210**
3211**   +  Input comes from p->in.
3212**   +  Store results in p->z of length p->n.  Space to hold p->z comes
3213**      from sqlite3_malloc64().
3214**   +  Use p->cSep as the column separator.  The default is ",".
3215**   +  Use p->rSep as the row separator.  The default is "\n".
3216**   +  Keep track of the line number in p->nLine.
3217**   +  Store the character that terminates the field in p->cTerm.  Store
3218**      EOF on end-of-file.
3219**   +  Report syntax errors on stderr
3220*/
3221static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3222  int c;
3223  int cSep = p->cColSep;
3224  int rSep = p->cRowSep;
3225  p->n = 0;
3226  c = fgetc(p->in);
3227  if( c==EOF || seenInterrupt ){
3228    p->cTerm = EOF;
3229    return 0;
3230  }
3231  if( c=='"' ){
3232    int pc, ppc;
3233    int startLine = p->nLine;
3234    int cQuote = c;
3235    pc = ppc = 0;
3236    while( 1 ){
3237      c = fgetc(p->in);
3238      if( c==rSep ) p->nLine++;
3239      if( c==cQuote ){
3240        if( pc==cQuote ){
3241          pc = 0;
3242          continue;
3243        }
3244      }
3245      if( (c==cSep && pc==cQuote)
3246       || (c==rSep && pc==cQuote)
3247       || (c==rSep && pc=='\r' && ppc==cQuote)
3248       || (c==EOF && pc==cQuote)
3249      ){
3250        do{ p->n--; }while( p->z[p->n]!=cQuote );
3251        p->cTerm = c;
3252        break;
3253      }
3254      if( pc==cQuote && c!='\r' ){
3255        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3256                p->zFile, p->nLine, cQuote);
3257      }
3258      if( c==EOF ){
3259        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3260                p->zFile, startLine, cQuote);
3261        p->cTerm = c;
3262        break;
3263      }
3264      import_append_char(p, c);
3265      ppc = pc;
3266      pc = c;
3267    }
3268  }else{
3269    /* If this is the first field being parsed and it begins with the
3270    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
3271    if( (c&0xff)==0xef && p->bNotFirst==0 ){
3272      import_append_char(p, c);
3273      c = fgetc(p->in);
3274      if( (c&0xff)==0xbb ){
3275        import_append_char(p, c);
3276        c = fgetc(p->in);
3277        if( (c&0xff)==0xbf ){
3278          p->bNotFirst = 1;
3279          p->n = 0;
3280          return csv_read_one_field(p);
3281        }
3282      }
3283    }
3284    while( c!=EOF && c!=cSep && c!=rSep ){
3285      import_append_char(p, c);
3286      c = fgetc(p->in);
3287    }
3288    if( c==rSep ){
3289      p->nLine++;
3290      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3291    }
3292    p->cTerm = c;
3293  }
3294  if( p->z ) p->z[p->n] = 0;
3295  p->bNotFirst = 1;
3296  return p->z;
3297}
3298
3299/* Read a single field of ASCII delimited text.
3300**
3301**   +  Input comes from p->in.
3302**   +  Store results in p->z of length p->n.  Space to hold p->z comes
3303**      from sqlite3_malloc64().
3304**   +  Use p->cSep as the column separator.  The default is "\x1F".
3305**   +  Use p->rSep as the row separator.  The default is "\x1E".
3306**   +  Keep track of the row number in p->nLine.
3307**   +  Store the character that terminates the field in p->cTerm.  Store
3308**      EOF on end-of-file.
3309**   +  Report syntax errors on stderr
3310*/
3311static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3312  int c;
3313  int cSep = p->cColSep;
3314  int rSep = p->cRowSep;
3315  p->n = 0;
3316  c = fgetc(p->in);
3317  if( c==EOF || seenInterrupt ){
3318    p->cTerm = EOF;
3319    return 0;
3320  }
3321  while( c!=EOF && c!=cSep && c!=rSep ){
3322    import_append_char(p, c);
3323    c = fgetc(p->in);
3324  }
3325  if( c==rSep ){
3326    p->nLine++;
3327  }
3328  p->cTerm = c;
3329  if( p->z ) p->z[p->n] = 0;
3330  return p->z;
3331}
3332
3333/*
3334** Try to transfer data for table zTable.  If an error is seen while
3335** moving forward, try to go backwards.  The backwards movement won't
3336** work for WITHOUT ROWID tables.
3337*/
3338static void tryToCloneData(
3339  ShellState *p,
3340  sqlite3 *newDb,
3341  const char *zTable
3342){
3343  sqlite3_stmt *pQuery = 0;
3344  sqlite3_stmt *pInsert = 0;
3345  char *zQuery = 0;
3346  char *zInsert = 0;
3347  int rc;
3348  int i, j, n;
3349  int nTable = (int)strlen(zTable);
3350  int k = 0;
3351  int cnt = 0;
3352  const int spinRate = 10000;
3353
3354  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3355  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3356  if( rc ){
3357    utf8_printf(stderr, "Error %d: %s on [%s]\n",
3358            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3359            zQuery);
3360    goto end_data_xfer;
3361  }
3362  n = sqlite3_column_count(pQuery);
3363  zInsert = sqlite3_malloc64(200 + nTable + n*3);
3364  if( zInsert==0 ){
3365    raw_printf(stderr, "out of memory\n");
3366    goto end_data_xfer;
3367  }
3368  sqlite3_snprintf(200+nTable,zInsert,
3369                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3370  i = (int)strlen(zInsert);
3371  for(j=1; j<n; j++){
3372    memcpy(zInsert+i, ",?", 2);
3373    i += 2;
3374  }
3375  memcpy(zInsert+i, ");", 3);
3376  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3377  if( rc ){
3378    utf8_printf(stderr, "Error %d: %s on [%s]\n",
3379            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3380            zQuery);
3381    goto end_data_xfer;
3382  }
3383  for(k=0; k<2; k++){
3384    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3385      for(i=0; i<n; i++){
3386        switch( sqlite3_column_type(pQuery, i) ){
3387          case SQLITE_NULL: {
3388            sqlite3_bind_null(pInsert, i+1);
3389            break;
3390          }
3391          case SQLITE_INTEGER: {
3392            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3393            break;
3394          }
3395          case SQLITE_FLOAT: {
3396            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3397            break;
3398          }
3399          case SQLITE_TEXT: {
3400            sqlite3_bind_text(pInsert, i+1,
3401                             (const char*)sqlite3_column_text(pQuery,i),
3402                             -1, SQLITE_STATIC);
3403            break;
3404          }
3405          case SQLITE_BLOB: {
3406            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3407                                            sqlite3_column_bytes(pQuery,i),
3408                                            SQLITE_STATIC);
3409            break;
3410          }
3411        }
3412      } /* End for */
3413      rc = sqlite3_step(pInsert);
3414      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3415        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3416                        sqlite3_errmsg(newDb));
3417      }
3418      sqlite3_reset(pInsert);
3419      cnt++;
3420      if( (cnt%spinRate)==0 ){
3421        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3422        fflush(stdout);
3423      }
3424    } /* End while */
3425    if( rc==SQLITE_DONE ) break;
3426    sqlite3_finalize(pQuery);
3427    sqlite3_free(zQuery);
3428    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3429                             zTable);
3430    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3431    if( rc ){
3432      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3433      break;
3434    }
3435  } /* End for(k=0...) */
3436
3437end_data_xfer:
3438  sqlite3_finalize(pQuery);
3439  sqlite3_finalize(pInsert);
3440  sqlite3_free(zQuery);
3441  sqlite3_free(zInsert);
3442}
3443
3444
3445/*
3446** Try to transfer all rows of the schema that match zWhere.  For
3447** each row, invoke xForEach() on the object defined by that row.
3448** If an error is encountered while moving forward through the
3449** sqlite_master table, try again moving backwards.
3450*/
3451static void tryToCloneSchema(
3452  ShellState *p,
3453  sqlite3 *newDb,
3454  const char *zWhere,
3455  void (*xForEach)(ShellState*,sqlite3*,const char*)
3456){
3457  sqlite3_stmt *pQuery = 0;
3458  char *zQuery = 0;
3459  int rc;
3460  const unsigned char *zName;
3461  const unsigned char *zSql;
3462  char *zErrMsg = 0;
3463
3464  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3465                           " WHERE %s", zWhere);
3466  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3467  if( rc ){
3468    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3469                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3470                    zQuery);
3471    goto end_schema_xfer;
3472  }
3473  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3474    zName = sqlite3_column_text(pQuery, 0);
3475    zSql = sqlite3_column_text(pQuery, 1);
3476    printf("%s... ", zName); fflush(stdout);
3477    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3478    if( zErrMsg ){
3479      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3480      sqlite3_free(zErrMsg);
3481      zErrMsg = 0;
3482    }
3483    if( xForEach ){
3484      xForEach(p, newDb, (const char*)zName);
3485    }
3486    printf("done\n");
3487  }
3488  if( rc!=SQLITE_DONE ){
3489    sqlite3_finalize(pQuery);
3490    sqlite3_free(zQuery);
3491    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3492                             " WHERE %s ORDER BY rowid DESC", zWhere);
3493    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3494    if( rc ){
3495      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3496                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3497                      zQuery);
3498      goto end_schema_xfer;
3499    }
3500    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3501      zName = sqlite3_column_text(pQuery, 0);
3502      zSql = sqlite3_column_text(pQuery, 1);
3503      printf("%s... ", zName); fflush(stdout);
3504      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3505      if( zErrMsg ){
3506        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3507        sqlite3_free(zErrMsg);
3508        zErrMsg = 0;
3509      }
3510      if( xForEach ){
3511        xForEach(p, newDb, (const char*)zName);
3512      }
3513      printf("done\n");
3514    }
3515  }
3516end_schema_xfer:
3517  sqlite3_finalize(pQuery);
3518  sqlite3_free(zQuery);
3519}
3520
3521/*
3522** Open a new database file named "zNewDb".  Try to recover as much information
3523** as possible out of the main database (which might be corrupt) and write it
3524** into zNewDb.
3525*/
3526static void tryToClone(ShellState *p, const char *zNewDb){
3527  int rc;
3528  sqlite3 *newDb = 0;
3529  if( access(zNewDb,0)==0 ){
3530    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3531    return;
3532  }
3533  rc = sqlite3_open(zNewDb, &newDb);
3534  if( rc ){
3535    utf8_printf(stderr, "Cannot create output database: %s\n",
3536            sqlite3_errmsg(newDb));
3537  }else{
3538    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3539    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3540    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3541    tryToCloneSchema(p, newDb, "type!='table'", 0);
3542    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3543    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3544  }
3545  sqlite3_close(newDb);
3546}
3547
3548/*
3549** Change the output file back to stdout
3550*/
3551static void output_reset(ShellState *p){
3552  if( p->outfile[0]=='|' ){
3553#ifndef SQLITE_OMIT_POPEN
3554    pclose(p->out);
3555#endif
3556  }else{
3557    output_file_close(p->out);
3558  }
3559  p->outfile[0] = 0;
3560  p->out = stdout;
3561}
3562
3563/*
3564** Run an SQL command and return the single integer result.
3565*/
3566static int db_int(ShellState *p, const char *zSql){
3567  sqlite3_stmt *pStmt;
3568  int res = 0;
3569  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3570  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3571    res = sqlite3_column_int(pStmt,0);
3572  }
3573  sqlite3_finalize(pStmt);
3574  return res;
3575}
3576
3577/*
3578** Convert a 2-byte or 4-byte big-endian integer into a native integer
3579*/
3580static unsigned int get2byteInt(unsigned char *a){
3581  return (a[0]<<8) + a[1];
3582}
3583static unsigned int get4byteInt(unsigned char *a){
3584  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3585}
3586
3587/*
3588** Implementation of the ".info" command.
3589**
3590** Return 1 on error, 2 to exit, and 0 otherwise.
3591*/
3592static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3593  static const struct { const char *zName; int ofst; } aField[] = {
3594     { "file change counter:",  24  },
3595     { "database page count:",  28  },
3596     { "freelist page count:",  36  },
3597     { "schema cookie:",        40  },
3598     { "schema format:",        44  },
3599     { "default cache size:",   48  },
3600     { "autovacuum top root:",  52  },
3601     { "incremental vacuum:",   64  },
3602     { "text encoding:",        56  },
3603     { "user version:",         60  },
3604     { "application id:",       68  },
3605     { "software version:",     96  },
3606  };
3607  static const struct { const char *zName; const char *zSql; } aQuery[] = {
3608     { "number of tables:",
3609       "SELECT count(*) FROM %s WHERE type='table'" },
3610     { "number of indexes:",
3611       "SELECT count(*) FROM %s WHERE type='index'" },
3612     { "number of triggers:",
3613       "SELECT count(*) FROM %s WHERE type='trigger'" },
3614     { "number of views:",
3615       "SELECT count(*) FROM %s WHERE type='view'" },
3616     { "schema size:",
3617       "SELECT total(length(sql)) FROM %s" },
3618  };
3619  sqlite3_file *pFile = 0;
3620  int i;
3621  char *zSchemaTab;
3622  char *zDb = nArg>=2 ? azArg[1] : "main";
3623  unsigned char aHdr[100];
3624  open_db(p, 0);
3625  if( p->db==0 ) return 1;
3626  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
3627  if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
3628    return 1;
3629  }
3630  i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
3631  if( i!=SQLITE_OK ){
3632    raw_printf(stderr, "unable to read database header\n");
3633    return 1;
3634  }
3635  i = get2byteInt(aHdr+16);
3636  if( i==1 ) i = 65536;
3637  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3638  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3639  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3640  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3641  for(i=0; i<ArraySize(aField); i++){
3642    int ofst = aField[i].ofst;
3643    unsigned int val = get4byteInt(aHdr + ofst);
3644    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3645    switch( ofst ){
3646      case 56: {
3647        if( val==1 ) raw_printf(p->out, " (utf8)");
3648        if( val==2 ) raw_printf(p->out, " (utf16le)");
3649        if( val==3 ) raw_printf(p->out, " (utf16be)");
3650      }
3651    }
3652    raw_printf(p->out, "\n");
3653  }
3654  if( zDb==0 ){
3655    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3656  }else if( strcmp(zDb,"temp")==0 ){
3657    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3658  }else{
3659    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3660  }
3661  for(i=0; i<ArraySize(aQuery); i++){
3662    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3663    int val = db_int(p, zSql);
3664    sqlite3_free(zSql);
3665    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3666  }
3667  sqlite3_free(zSchemaTab);
3668  return 0;
3669}
3670
3671/*
3672** Print the current sqlite3_errmsg() value to stderr and return 1.
3673*/
3674static int shellDatabaseError(sqlite3 *db){
3675  const char *zErr = sqlite3_errmsg(db);
3676  utf8_printf(stderr, "Error: %s\n", zErr);
3677  return 1;
3678}
3679
3680/*
3681** Print an out-of-memory message to stderr and return 1.
3682*/
3683static int shellNomemError(void){
3684  raw_printf(stderr, "Error: out of memory\n");
3685  return 1;
3686}
3687
3688/*
3689** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
3690** if they match and FALSE (0) if they do not match.
3691**
3692** Globbing rules:
3693**
3694**      '*'       Matches any sequence of zero or more characters.
3695**
3696**      '?'       Matches exactly one character.
3697**
3698**     [...]      Matches one character from the enclosed list of
3699**                characters.
3700**
3701**     [^...]     Matches one character not in the enclosed list.
3702**
3703**      '#'       Matches any sequence of one or more digits with an
3704**                optional + or - sign in front
3705**
3706**      ' '       Any span of whitespace matches any other span of
3707**                whitespace.
3708**
3709** Extra whitespace at the end of z[] is ignored.
3710*/
3711static int testcase_glob(const char *zGlob, const char *z){
3712  int c, c2;
3713  int invert;
3714  int seen;
3715
3716  while( (c = (*(zGlob++)))!=0 ){
3717    if( IsSpace(c) ){
3718      if( !IsSpace(*z) ) return 0;
3719      while( IsSpace(*zGlob) ) zGlob++;
3720      while( IsSpace(*z) ) z++;
3721    }else if( c=='*' ){
3722      while( (c=(*(zGlob++))) == '*' || c=='?' ){
3723        if( c=='?' && (*(z++))==0 ) return 0;
3724      }
3725      if( c==0 ){
3726        return 1;
3727      }else if( c=='[' ){
3728        while( *z && testcase_glob(zGlob-1,z)==0 ){
3729          z++;
3730        }
3731        return (*z)!=0;
3732      }
3733      while( (c2 = (*(z++)))!=0 ){
3734        while( c2!=c ){
3735          c2 = *(z++);
3736          if( c2==0 ) return 0;
3737        }
3738        if( testcase_glob(zGlob,z) ) return 1;
3739      }
3740      return 0;
3741    }else if( c=='?' ){
3742      if( (*(z++))==0 ) return 0;
3743    }else if( c=='[' ){
3744      int prior_c = 0;
3745      seen = 0;
3746      invert = 0;
3747      c = *(z++);
3748      if( c==0 ) return 0;
3749      c2 = *(zGlob++);
3750      if( c2=='^' ){
3751        invert = 1;
3752        c2 = *(zGlob++);
3753      }
3754      if( c2==']' ){
3755        if( c==']' ) seen = 1;
3756        c2 = *(zGlob++);
3757      }
3758      while( c2 && c2!=']' ){
3759        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3760          c2 = *(zGlob++);
3761          if( c>=prior_c && c<=c2 ) seen = 1;
3762          prior_c = 0;
3763        }else{
3764          if( c==c2 ){
3765            seen = 1;
3766          }
3767          prior_c = c2;
3768        }
3769        c2 = *(zGlob++);
3770      }
3771      if( c2==0 || (seen ^ invert)==0 ) return 0;
3772    }else if( c=='#' ){
3773      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3774      if( !IsDigit(z[0]) ) return 0;
3775      z++;
3776      while( IsDigit(z[0]) ){ z++; }
3777    }else{
3778      if( c!=(*(z++)) ) return 0;
3779    }
3780  }
3781  while( IsSpace(*z) ){ z++; }
3782  return *z==0;
3783}
3784
3785
3786/*
3787** Compare the string as a command-line option with either one or two
3788** initial "-" characters.
3789*/
3790static int optionMatch(const char *zStr, const char *zOpt){
3791  if( zStr[0]!='-' ) return 0;
3792  zStr++;
3793  if( zStr[0]=='-' ) zStr++;
3794  return strcmp(zStr, zOpt)==0;
3795}
3796
3797/*
3798** Delete a file.
3799*/
3800int shellDeleteFile(const char *zFilename){
3801  int rc;
3802#ifdef _WIN32
3803  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
3804  rc = _wunlink(z);
3805  sqlite3_free(z);
3806#else
3807  rc = unlink(zFilename);
3808#endif
3809  return rc;
3810}
3811
3812
3813/*
3814** The implementation of SQL scalar function fkey_collate_clause(), used
3815** by the ".lint fkey-indexes" command. This scalar function is always
3816** called with four arguments - the parent table name, the parent column name,
3817** the child table name and the child column name.
3818**
3819**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
3820**
3821** If either of the named tables or columns do not exist, this function
3822** returns an empty string. An empty string is also returned if both tables
3823** and columns exist but have the same default collation sequence. Or,
3824** if both exist but the default collation sequences are different, this
3825** function returns the string " COLLATE <parent-collation>", where
3826** <parent-collation> is the default collation sequence of the parent column.
3827*/
3828static void shellFkeyCollateClause(
3829  sqlite3_context *pCtx,
3830  int nVal,
3831  sqlite3_value **apVal
3832){
3833  sqlite3 *db = sqlite3_context_db_handle(pCtx);
3834  const char *zParent;
3835  const char *zParentCol;
3836  const char *zParentSeq;
3837  const char *zChild;
3838  const char *zChildCol;
3839  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
3840  int rc;
3841
3842  assert( nVal==4 );
3843  zParent = (const char*)sqlite3_value_text(apVal[0]);
3844  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
3845  zChild = (const char*)sqlite3_value_text(apVal[2]);
3846  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
3847
3848  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
3849  rc = sqlite3_table_column_metadata(
3850      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
3851  );
3852  if( rc==SQLITE_OK ){
3853    rc = sqlite3_table_column_metadata(
3854        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
3855    );
3856  }
3857
3858  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
3859    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
3860    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
3861    sqlite3_free(z);
3862  }
3863}
3864
3865
3866/*
3867** The implementation of dot-command ".lint fkey-indexes".
3868*/
3869static int lintFkeyIndexes(
3870  ShellState *pState,             /* Current shell tool state */
3871  char **azArg,                   /* Array of arguments passed to dot command */
3872  int nArg                        /* Number of entries in azArg[] */
3873){
3874  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
3875  FILE *out = pState->out;        /* Stream to write non-error output to */
3876  int bVerbose = 0;               /* If -verbose is present */
3877  int bGroupByParent = 0;         /* If -groupbyparent is present */
3878  int i;                          /* To iterate through azArg[] */
3879  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
3880  int rc;                         /* Return code */
3881  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
3882
3883  /*
3884  ** This SELECT statement returns one row for each foreign key constraint
3885  ** in the schema of the main database. The column values are:
3886  **
3887  ** 0. The text of an SQL statement similar to:
3888  **
3889  **      "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
3890  **
3891  **    This is the same SELECT that the foreign keys implementation needs
3892  **    to run internally on child tables. If there is an index that can
3893  **    be used to optimize this query, then it can also be used by the FK
3894  **    implementation to optimize DELETE or UPDATE statements on the parent
3895  **    table.
3896  **
3897  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
3898  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
3899  **    contains an index that can be used to optimize the query.
3900  **
3901  ** 2. Human readable text that describes the child table and columns. e.g.
3902  **
3903  **       "child_table(child_key1, child_key2)"
3904  **
3905  ** 3. Human readable text that describes the parent table and columns. e.g.
3906  **
3907  **       "parent_table(parent_key1, parent_key2)"
3908  **
3909  ** 4. A full CREATE INDEX statement for an index that could be used to
3910  **    optimize DELETE or UPDATE statements on the parent table. e.g.
3911  **
3912  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
3913  **
3914  ** 5. The name of the parent table.
3915  **
3916  ** These six values are used by the C logic below to generate the report.
3917  */
3918  const char *zSql =
3919  "SELECT "
3920    "     'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
3921    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
3922    "  || fkey_collate_clause("
3923    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
3924    ", "
3925    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
3926    "  || group_concat('*=?', ' AND ') || ')'"
3927    ", "
3928    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
3929    ", "
3930    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
3931    ", "
3932    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
3933    "  || ' ON ' || quote(s.name) || '('"
3934    "  || group_concat(quote(f.[from]) ||"
3935    "        fkey_collate_clause("
3936    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
3937    "  || ');'"
3938    ", "
3939    "     f.[table] "
3940    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
3941    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
3942    "GROUP BY s.name, f.id "
3943    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
3944  ;
3945  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
3946
3947  for(i=2; i<nArg; i++){
3948    int n = (int)strlen(azArg[i]);
3949    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
3950      bVerbose = 1;
3951    }
3952    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
3953      bGroupByParent = 1;
3954      zIndent = "    ";
3955    }
3956    else{
3957      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
3958          azArg[0], azArg[1]
3959      );
3960      return SQLITE_ERROR;
3961    }
3962  }
3963
3964  /* Register the fkey_collate_clause() SQL function */
3965  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
3966      0, shellFkeyCollateClause, 0, 0
3967  );
3968
3969
3970  if( rc==SQLITE_OK ){
3971    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
3972  }
3973  if( rc==SQLITE_OK ){
3974    sqlite3_bind_int(pSql, 1, bGroupByParent);
3975  }
3976
3977  if( rc==SQLITE_OK ){
3978    int rc2;
3979    char *zPrev = 0;
3980    while( SQLITE_ROW==sqlite3_step(pSql) ){
3981      int res = -1;
3982      sqlite3_stmt *pExplain = 0;
3983      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
3984      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
3985      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
3986      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
3987      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
3988      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
3989
3990      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3991      if( rc!=SQLITE_OK ) break;
3992      if( SQLITE_ROW==sqlite3_step(pExplain) ){
3993        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
3994        res = (
3995              0==sqlite3_strglob(zGlob, zPlan)
3996           || 0==sqlite3_strglob(zGlobIPK, zPlan)
3997        );
3998      }
3999      rc = sqlite3_finalize(pExplain);
4000      if( rc!=SQLITE_OK ) break;
4001
4002      if( res<0 ){
4003        raw_printf(stderr, "Error: internal error");
4004        break;
4005      }else{
4006        if( bGroupByParent
4007        && (bVerbose || res==0)
4008        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4009        ){
4010          raw_printf(out, "-- Parent table %s\n", zParent);
4011          sqlite3_free(zPrev);
4012          zPrev = sqlite3_mprintf("%s", zParent);
4013        }
4014
4015        if( res==0 ){
4016          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4017        }else if( bVerbose ){
4018          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4019              zIndent, zFrom, zTarget
4020          );
4021        }
4022      }
4023    }
4024    sqlite3_free(zPrev);
4025
4026    if( rc!=SQLITE_OK ){
4027      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4028    }
4029
4030    rc2 = sqlite3_finalize(pSql);
4031    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4032      rc = rc2;
4033      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4034    }
4035  }else{
4036    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4037  }
4038
4039  return rc;
4040}
4041
4042/*
4043** Implementation of ".lint" dot command.
4044*/
4045static int lintDotCommand(
4046  ShellState *pState,             /* Current shell tool state */
4047  char **azArg,                   /* Array of arguments passed to dot command */
4048  int nArg                        /* Number of entries in azArg[] */
4049){
4050  int n;
4051  n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
4052  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4053  return lintFkeyIndexes(pState, azArg, nArg);
4054
4055 usage:
4056  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4057  raw_printf(stderr, "Where sub-commands are:\n");
4058  raw_printf(stderr, "    fkey-indexes\n");
4059  return SQLITE_ERROR;
4060}
4061
4062
4063/*
4064** If an input line begins with "." then invoke this routine to
4065** process that line.
4066**
4067** Return 1 on error, 2 to exit, and 0 otherwise.
4068*/
4069static int do_meta_command(char *zLine, ShellState *p){
4070  int h = 1;
4071  int nArg = 0;
4072  int n, c;
4073  int rc = 0;
4074  char *azArg[50];
4075
4076  /* Parse the input line into tokens.
4077  */
4078  while( zLine[h] && nArg<ArraySize(azArg) ){
4079    while( IsSpace(zLine[h]) ){ h++; }
4080    if( zLine[h]==0 ) break;
4081    if( zLine[h]=='\'' || zLine[h]=='"' ){
4082      int delim = zLine[h++];
4083      azArg[nArg++] = &zLine[h];
4084      while( zLine[h] && zLine[h]!=delim ){
4085        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
4086        h++;
4087      }
4088      if( zLine[h]==delim ){
4089        zLine[h++] = 0;
4090      }
4091      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
4092    }else{
4093      azArg[nArg++] = &zLine[h];
4094      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4095      if( zLine[h] ) zLine[h++] = 0;
4096      resolve_backslashes(azArg[nArg-1]);
4097    }
4098  }
4099
4100  /* Process the input line.
4101  */
4102  if( nArg==0 ) return 0; /* no tokens, no error */
4103  n = strlen30(azArg[0]);
4104  c = azArg[0][0];
4105
4106#ifndef SQLITE_OMIT_AUTHORIZATION
4107  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4108    if( nArg!=2 ){
4109      raw_printf(stderr, "Usage: .auth ON|OFF\n");
4110      rc = 1;
4111      goto meta_command_exit;
4112    }
4113    open_db(p, 0);
4114    if( booleanValue(azArg[1]) ){
4115      sqlite3_set_authorizer(p->db, shellAuth, p);
4116    }else{
4117      sqlite3_set_authorizer(p->db, 0, 0);
4118    }
4119  }else
4120#endif
4121
4122  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4123   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4124  ){
4125    const char *zDestFile = 0;
4126    const char *zDb = 0;
4127    sqlite3 *pDest;
4128    sqlite3_backup *pBackup;
4129    int j;
4130    for(j=1; j<nArg; j++){
4131      const char *z = azArg[j];
4132      if( z[0]=='-' ){
4133        while( z[0]=='-' ) z++;
4134        /* No options to process at this time */
4135        {
4136          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
4137          return 1;
4138        }
4139      }else if( zDestFile==0 ){
4140        zDestFile = azArg[j];
4141      }else if( zDb==0 ){
4142        zDb = zDestFile;
4143        zDestFile = azArg[j];
4144      }else{
4145        raw_printf(stderr, "too many arguments to .backup\n");
4146        return 1;
4147      }
4148    }
4149    if( zDestFile==0 ){
4150      raw_printf(stderr, "missing FILENAME argument on .backup\n");
4151      return 1;
4152    }
4153    if( zDb==0 ) zDb = "main";
4154    rc = sqlite3_open(zDestFile, &pDest);
4155    if( rc!=SQLITE_OK ){
4156      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
4157      sqlite3_close(pDest);
4158      return 1;
4159    }
4160    open_db(p, 0);
4161    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4162    if( pBackup==0 ){
4163      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4164      sqlite3_close(pDest);
4165      return 1;
4166    }
4167    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4168    sqlite3_backup_finish(pBackup);
4169    if( rc==SQLITE_DONE ){
4170      rc = 0;
4171    }else{
4172      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4173      rc = 1;
4174    }
4175    sqlite3_close(pDest);
4176  }else
4177
4178  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4179    if( nArg==2 ){
4180      bail_on_error = booleanValue(azArg[1]);
4181    }else{
4182      raw_printf(stderr, "Usage: .bail on|off\n");
4183      rc = 1;
4184    }
4185  }else
4186
4187  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4188    if( nArg==2 ){
4189      if( booleanValue(azArg[1]) ){
4190        setBinaryMode(p->out, 1);
4191      }else{
4192        setTextMode(p->out, 1);
4193      }
4194    }else{
4195      raw_printf(stderr, "Usage: .binary on|off\n");
4196      rc = 1;
4197    }
4198  }else
4199
4200  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4201    if( nArg==2 ){
4202#if defined(_WIN32) || defined(WIN32)
4203      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4204      rc = !SetCurrentDirectoryW(z);
4205      sqlite3_free(z);
4206#else
4207      rc = chdir(azArg[1]);
4208#endif
4209      if( rc ){
4210        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4211        rc = 1;
4212      }
4213    }else{
4214      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4215      rc = 1;
4216    }
4217  }else
4218
4219  /* The undocumented ".breakpoint" command causes a call to the no-op
4220  ** routine named test_breakpoint().
4221  */
4222  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4223    test_breakpoint();
4224  }else
4225
4226  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4227    if( nArg==2 ){
4228      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
4229    }else{
4230      raw_printf(stderr, "Usage: .changes on|off\n");
4231      rc = 1;
4232    }
4233  }else
4234
4235  /* Cancel output redirection, if it is currently set (by .testcase)
4236  ** Then read the content of the testcase-out.txt file and compare against
4237  ** azArg[1].  If there are differences, report an error and exit.
4238  */
4239  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4240    char *zRes = 0;
4241    output_reset(p);
4242    if( nArg!=2 ){
4243      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
4244      rc = 2;
4245    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
4246      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4247      rc = 2;
4248    }else if( testcase_glob(azArg[1],zRes)==0 ){
4249      utf8_printf(stderr,
4250                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
4251                 p->zTestcase, azArg[1], zRes);
4252      rc = 2;
4253    }else{
4254      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
4255      p->nCheck++;
4256    }
4257    sqlite3_free(zRes);
4258  }else
4259
4260  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4261    if( nArg==2 ){
4262      tryToClone(p, azArg[1]);
4263    }else{
4264      raw_printf(stderr, "Usage: .clone FILENAME\n");
4265      rc = 1;
4266    }
4267  }else
4268
4269  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
4270    ShellState data;
4271    char *zErrMsg = 0;
4272    open_db(p, 0);
4273    memcpy(&data, p, sizeof(data));
4274    data.showHeader = 0;
4275    data.cMode = data.mode = MODE_List;
4276    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
4277    data.cnt = 0;
4278    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4279                 callback, &data, &zErrMsg);
4280    if( zErrMsg ){
4281      utf8_printf(stderr,"Error: %s\n", zErrMsg);
4282      sqlite3_free(zErrMsg);
4283      rc = 1;
4284    }
4285  }else
4286
4287  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4288    rc = shell_dbinfo_command(p, nArg, azArg);
4289  }else
4290
4291  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
4292    const char *zLike = 0;
4293    int i;
4294    int savedShowHeader = p->showHeader;
4295    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
4296    for(i=1; i<nArg; i++){
4297      if( azArg[i][0]=='-' ){
4298        const char *z = azArg[i]+1;
4299        if( z[0]=='-' ) z++;
4300        if( strcmp(z,"preserve-rowids")==0 ){
4301#ifdef SQLITE_OMIT_VIRTUALTABLE
4302          raw_printf(stderr, "The --preserve-rowids option is not compatible"
4303                             " with SQLITE_OMIT_VIRTUALTABLE\n");
4304          rc = 1;
4305          goto meta_command_exit;
4306#else
4307          ShellSetFlag(p, SHFLG_PreserveRowid);
4308#endif
4309        }else
4310        if( strcmp(z,"newlines")==0 ){
4311          ShellSetFlag(p, SHFLG_Newlines);
4312        }else
4313        {
4314          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4315          rc = 1;
4316          goto meta_command_exit;
4317        }
4318      }else if( zLike ){
4319        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
4320                           "?--newlines? ?LIKE-PATTERN?\n");
4321        rc = 1;
4322        goto meta_command_exit;
4323      }else{
4324        zLike = azArg[i];
4325      }
4326    }
4327    open_db(p, 0);
4328    /* When playing back a "dump", the content might appear in an order
4329    ** which causes immediate foreign key constraints to be violated.
4330    ** So disable foreign-key constraint enforcement to prevent problems. */
4331    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4332    raw_printf(p->out, "BEGIN TRANSACTION;\n");
4333    p->writableSchema = 0;
4334    p->showHeader = 0;
4335    /* Set writable_schema=ON since doing so forces SQLite to initialize
4336    ** as much of the schema as it can even if the sqlite_master table is
4337    ** corrupt. */
4338    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4339    p->nErr = 0;
4340    if( zLike==0 ){
4341      run_schema_dump_query(p,
4342        "SELECT name, type, sql FROM sqlite_master "
4343        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4344      );
4345      run_schema_dump_query(p,
4346        "SELECT name, type, sql FROM sqlite_master "
4347        "WHERE name=='sqlite_sequence'"
4348      );
4349      run_table_dump_query(p,
4350        "SELECT sql FROM sqlite_master "
4351        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4352      );
4353    }else{
4354      char *zSql;
4355      zSql = sqlite3_mprintf(
4356        "SELECT name, type, sql FROM sqlite_master "
4357        "WHERE tbl_name LIKE %Q AND type=='table'"
4358        "  AND sql NOT NULL", zLike);
4359      run_schema_dump_query(p,zSql);
4360      sqlite3_free(zSql);
4361      zSql = sqlite3_mprintf(
4362        "SELECT sql FROM sqlite_master "
4363        "WHERE sql NOT NULL"
4364        "  AND type IN ('index','trigger','view')"
4365        "  AND tbl_name LIKE %Q", zLike);
4366      run_table_dump_query(p, zSql, 0);
4367      sqlite3_free(zSql);
4368    }
4369    if( p->writableSchema ){
4370      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
4371      p->writableSchema = 0;
4372    }
4373    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4374    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
4375    raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4376    p->showHeader = savedShowHeader;
4377  }else
4378
4379  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4380    if( nArg==2 ){
4381      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
4382    }else{
4383      raw_printf(stderr, "Usage: .echo on|off\n");
4384      rc = 1;
4385    }
4386  }else
4387
4388  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4389    if( nArg==2 ){
4390      if( strcmp(azArg[1],"full")==0 ){
4391        p->autoEQP = 2;
4392      }else{
4393        p->autoEQP = booleanValue(azArg[1]);
4394      }
4395    }else{
4396      raw_printf(stderr, "Usage: .eqp on|off|full\n");
4397      rc = 1;
4398    }
4399  }else
4400
4401  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
4402    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
4403    rc = 2;
4404  }else
4405
4406  /* The ".explain" command is automatic now.  It is largely pointless.  It
4407  ** retained purely for backwards compatibility */
4408  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
4409    int val = 1;
4410    if( nArg>=2 ){
4411      if( strcmp(azArg[1],"auto")==0 ){
4412        val = 99;
4413      }else{
4414        val =  booleanValue(azArg[1]);
4415      }
4416    }
4417    if( val==1 && p->mode!=MODE_Explain ){
4418      p->normalMode = p->mode;
4419      p->mode = MODE_Explain;
4420      p->autoExplain = 0;
4421    }else if( val==0 ){
4422      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4423      p->autoExplain = 0;
4424    }else if( val==99 ){
4425      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4426      p->autoExplain = 1;
4427    }
4428  }else
4429
4430  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
4431    ShellState data;
4432    char *zErrMsg = 0;
4433    int doStats = 0;
4434    memcpy(&data, p, sizeof(data));
4435    data.showHeader = 0;
4436    data.cMode = data.mode = MODE_Semi;
4437    if( nArg==2 && optionMatch(azArg[1], "indent") ){
4438      data.cMode = data.mode = MODE_Pretty;
4439      nArg = 1;
4440    }
4441    if( nArg!=1 ){
4442      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
4443      rc = 1;
4444      goto meta_command_exit;
4445    }
4446    open_db(p, 0);
4447    rc = sqlite3_exec(p->db,
4448       "SELECT sql FROM"
4449       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4450       "     FROM sqlite_master UNION ALL"
4451       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4452       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4453       "ORDER BY rowid",
4454       callback, &data, &zErrMsg
4455    );
4456    if( rc==SQLITE_OK ){
4457      sqlite3_stmt *pStmt;
4458      rc = sqlite3_prepare_v2(p->db,
4459               "SELECT rowid FROM sqlite_master"
4460               " WHERE name GLOB 'sqlite_stat[134]'",
4461               -1, &pStmt, 0);
4462      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4463      sqlite3_finalize(pStmt);
4464    }
4465    if( doStats==0 ){
4466      raw_printf(p->out, "/* No STAT tables available */\n");
4467    }else{
4468      raw_printf(p->out, "ANALYZE sqlite_master;\n");
4469      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4470                   callback, &data, &zErrMsg);
4471      data.cMode = data.mode = MODE_Insert;
4472      data.zDestTable = "sqlite_stat1";
4473      shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4474                 shell_callback, &data,&zErrMsg);
4475      data.zDestTable = "sqlite_stat3";
4476      shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4477                 shell_callback, &data,&zErrMsg);
4478      data.zDestTable = "sqlite_stat4";
4479      shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4480                 shell_callback, &data, &zErrMsg);
4481      raw_printf(p->out, "ANALYZE sqlite_master;\n");
4482    }
4483  }else
4484
4485  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4486    if( nArg==2 ){
4487      p->showHeader = booleanValue(azArg[1]);
4488    }else{
4489      raw_printf(stderr, "Usage: .headers on|off\n");
4490      rc = 1;
4491    }
4492  }else
4493
4494  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
4495    utf8_printf(p->out, "%s", zHelp);
4496  }else
4497
4498  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
4499    char *zTable;               /* Insert data into this table */
4500    char *zFile;                /* Name of file to extra content from */
4501    sqlite3_stmt *pStmt = NULL; /* A statement */
4502    int nCol;                   /* Number of columns in the table */
4503    int nByte;                  /* Number of bytes in an SQL string */
4504    int i, j;                   /* Loop counters */
4505    int needCommit;             /* True to COMMIT or ROLLBACK at end */
4506    int nSep;                   /* Number of bytes in p->colSeparator[] */
4507    char *zSql;                 /* An SQL statement */
4508    ImportCtx sCtx;             /* Reader context */
4509    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4510    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
4511
4512    if( nArg!=3 ){
4513      raw_printf(stderr, "Usage: .import FILE TABLE\n");
4514      goto meta_command_exit;
4515    }
4516    zFile = azArg[1];
4517    zTable = azArg[2];
4518    seenInterrupt = 0;
4519    memset(&sCtx, 0, sizeof(sCtx));
4520    open_db(p, 0);
4521    nSep = strlen30(p->colSeparator);
4522    if( nSep==0 ){
4523      raw_printf(stderr,
4524                 "Error: non-null column separator required for import\n");
4525      return 1;
4526    }
4527    if( nSep>1 ){
4528      raw_printf(stderr, "Error: multi-character column separators not allowed"
4529                      " for import\n");
4530      return 1;
4531    }
4532    nSep = strlen30(p->rowSeparator);
4533    if( nSep==0 ){
4534      raw_printf(stderr, "Error: non-null row separator required for import\n");
4535      return 1;
4536    }
4537    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4538      /* When importing CSV (only), if the row separator is set to the
4539      ** default output row separator, change it to the default input
4540      ** row separator.  This avoids having to maintain different input
4541      ** and output row separators. */
4542      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4543      nSep = strlen30(p->rowSeparator);
4544    }
4545    if( nSep>1 ){
4546      raw_printf(stderr, "Error: multi-character row separators not allowed"
4547                      " for import\n");
4548      return 1;
4549    }
4550    sCtx.zFile = zFile;
4551    sCtx.nLine = 1;
4552    if( sCtx.zFile[0]=='|' ){
4553#ifdef SQLITE_OMIT_POPEN
4554      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4555      return 1;
4556#else
4557      sCtx.in = popen(sCtx.zFile+1, "r");
4558      sCtx.zFile = "<pipe>";
4559      xCloser = pclose;
4560#endif
4561    }else{
4562      sCtx.in = fopen(sCtx.zFile, "rb");
4563      xCloser = fclose;
4564    }
4565    if( p->mode==MODE_Ascii ){
4566      xRead = ascii_read_one_field;
4567    }else{
4568      xRead = csv_read_one_field;
4569    }
4570    if( sCtx.in==0 ){
4571      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4572      return 1;
4573    }
4574    sCtx.cColSep = p->colSeparator[0];
4575    sCtx.cRowSep = p->rowSeparator[0];
4576    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
4577    if( zSql==0 ){
4578      raw_printf(stderr, "Error: out of memory\n");
4579      xCloser(sCtx.in);
4580      return 1;
4581    }
4582    nByte = strlen30(zSql);
4583    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4584    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
4585    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
4586      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4587      char cSep = '(';
4588      while( xRead(&sCtx) ){
4589        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
4590        cSep = ',';
4591        if( sCtx.cTerm!=sCtx.cColSep ) break;
4592      }
4593      if( cSep=='(' ){
4594        sqlite3_free(zCreate);
4595        sqlite3_free(sCtx.z);
4596        xCloser(sCtx.in);
4597        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
4598        return 1;
4599      }
4600      zCreate = sqlite3_mprintf("%z\n)", zCreate);
4601      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4602      sqlite3_free(zCreate);
4603      if( rc ){
4604        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
4605                sqlite3_errmsg(p->db));
4606        sqlite3_free(sCtx.z);
4607        xCloser(sCtx.in);
4608        return 1;
4609      }
4610      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4611    }
4612    sqlite3_free(zSql);
4613    if( rc ){
4614      if (pStmt) sqlite3_finalize(pStmt);
4615      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
4616      xCloser(sCtx.in);
4617      return 1;
4618    }
4619    nCol = sqlite3_column_count(pStmt);
4620    sqlite3_finalize(pStmt);
4621    pStmt = 0;
4622    if( nCol==0 ) return 0; /* no columns, no error */
4623    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
4624    if( zSql==0 ){
4625      raw_printf(stderr, "Error: out of memory\n");
4626      xCloser(sCtx.in);
4627      return 1;
4628    }
4629    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
4630    j = strlen30(zSql);
4631    for(i=1; i<nCol; i++){
4632      zSql[j++] = ',';
4633      zSql[j++] = '?';
4634    }
4635    zSql[j++] = ')';
4636    zSql[j] = 0;
4637    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4638    sqlite3_free(zSql);
4639    if( rc ){
4640      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
4641      if (pStmt) sqlite3_finalize(pStmt);
4642      xCloser(sCtx.in);
4643      return 1;
4644    }
4645    needCommit = sqlite3_get_autocommit(p->db);
4646    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
4647    do{
4648      int startLine = sCtx.nLine;
4649      for(i=0; i<nCol; i++){
4650        char *z = xRead(&sCtx);
4651        /*
4652        ** Did we reach end-of-file before finding any columns?
4653        ** If so, stop instead of NULL filling the remaining columns.
4654        */
4655        if( z==0 && i==0 ) break;
4656        /*
4657        ** Did we reach end-of-file OR end-of-line before finding any
4658        ** columns in ASCII mode?  If so, stop instead of NULL filling
4659        ** the remaining columns.
4660        */
4661        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
4662        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
4663        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
4664          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4665                          "filling the rest with NULL\n",
4666                          sCtx.zFile, startLine, nCol, i+1);
4667          i += 2;
4668          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
4669        }
4670      }
4671      if( sCtx.cTerm==sCtx.cColSep ){
4672        do{
4673          xRead(&sCtx);
4674          i++;
4675        }while( sCtx.cTerm==sCtx.cColSep );
4676        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4677                        "extras ignored\n",
4678                        sCtx.zFile, startLine, nCol, i);
4679      }
4680      if( i>=nCol ){
4681        sqlite3_step(pStmt);
4682        rc = sqlite3_reset(pStmt);
4683        if( rc!=SQLITE_OK ){
4684          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
4685                      startLine, sqlite3_errmsg(p->db));
4686        }
4687      }
4688    }while( sCtx.cTerm!=EOF );
4689
4690    xCloser(sCtx.in);
4691    sqlite3_free(sCtx.z);
4692    sqlite3_finalize(pStmt);
4693    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
4694  }else
4695
4696#ifndef SQLITE_UNTESTABLE
4697  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
4698    char *zSql;
4699    char *zCollist = 0;
4700    sqlite3_stmt *pStmt;
4701    int tnum = 0;
4702    int i;
4703    if( nArg!=3 ){
4704      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
4705      rc = 1;
4706      goto meta_command_exit;
4707    }
4708    open_db(p, 0);
4709    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
4710                           " WHERE name='%q' AND type='index'", azArg[1]);
4711    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4712    sqlite3_free(zSql);
4713    if( sqlite3_step(pStmt)==SQLITE_ROW ){
4714      tnum = sqlite3_column_int(pStmt, 0);
4715    }
4716    sqlite3_finalize(pStmt);
4717    if( tnum==0 ){
4718      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
4719      rc = 1;
4720      goto meta_command_exit;
4721    }
4722    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
4723    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4724    sqlite3_free(zSql);
4725    i = 0;
4726    while( sqlite3_step(pStmt)==SQLITE_ROW ){
4727      char zLabel[20];
4728      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
4729      i++;
4730      if( zCol==0 ){
4731        if( sqlite3_column_int(pStmt,1)==-1 ){
4732          zCol = "_ROWID_";
4733        }else{
4734          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
4735          zCol = zLabel;
4736        }
4737      }
4738      if( zCollist==0 ){
4739        zCollist = sqlite3_mprintf("\"%w\"", zCol);
4740      }else{
4741        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
4742      }
4743    }
4744    sqlite3_finalize(pStmt);
4745    zSql = sqlite3_mprintf(
4746          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
4747          azArg[2], zCollist, zCollist);
4748    sqlite3_free(zCollist);
4749    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
4750    if( rc==SQLITE_OK ){
4751      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
4752      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
4753      if( rc ){
4754        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
4755      }else{
4756        utf8_printf(stdout, "%s;\n", zSql);
4757        raw_printf(stdout,
4758           "WARNING: writing to an imposter table will corrupt the index!\n"
4759        );
4760      }
4761    }else{
4762      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
4763      rc = 1;
4764    }
4765    sqlite3_free(zSql);
4766  }else
4767#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
4768
4769#ifdef SQLITE_ENABLE_IOTRACE
4770  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
4771    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
4772    if( iotrace && iotrace!=stdout ) fclose(iotrace);
4773    iotrace = 0;
4774    if( nArg<2 ){
4775      sqlite3IoTrace = 0;
4776    }else if( strcmp(azArg[1], "-")==0 ){
4777      sqlite3IoTrace = iotracePrintf;
4778      iotrace = stdout;
4779    }else{
4780      iotrace = fopen(azArg[1], "w");
4781      if( iotrace==0 ){
4782        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
4783        sqlite3IoTrace = 0;
4784        rc = 1;
4785      }else{
4786        sqlite3IoTrace = iotracePrintf;
4787      }
4788    }
4789  }else
4790#endif
4791
4792  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
4793    static const struct {
4794       const char *zLimitName;   /* Name of a limit */
4795       int limitCode;            /* Integer code for that limit */
4796    } aLimit[] = {
4797      { "length",                SQLITE_LIMIT_LENGTH                    },
4798      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
4799      { "column",                SQLITE_LIMIT_COLUMN                    },
4800      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
4801      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
4802      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
4803      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
4804      { "attached",              SQLITE_LIMIT_ATTACHED                  },
4805      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
4806      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
4807      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
4808      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
4809    };
4810    int i, n2;
4811    open_db(p, 0);
4812    if( nArg==1 ){
4813      for(i=0; i<ArraySize(aLimit); i++){
4814        printf("%20s %d\n", aLimit[i].zLimitName,
4815               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
4816      }
4817    }else if( nArg>3 ){
4818      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
4819      rc = 1;
4820      goto meta_command_exit;
4821    }else{
4822      int iLimit = -1;
4823      n2 = strlen30(azArg[1]);
4824      for(i=0; i<ArraySize(aLimit); i++){
4825        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
4826          if( iLimit<0 ){
4827            iLimit = i;
4828          }else{
4829            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
4830            rc = 1;
4831            goto meta_command_exit;
4832          }
4833        }
4834      }
4835      if( iLimit<0 ){
4836        utf8_printf(stderr, "unknown limit: \"%s\"\n"
4837                        "enter \".limits\" with no arguments for a list.\n",
4838                         azArg[1]);
4839        rc = 1;
4840        goto meta_command_exit;
4841      }
4842      if( nArg==3 ){
4843        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
4844                      (int)integerValue(azArg[2]));
4845      }
4846      printf("%20s %d\n", aLimit[iLimit].zLimitName,
4847             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
4848    }
4849  }else
4850
4851  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
4852    open_db(p, 0);
4853    lintDotCommand(p, azArg, nArg);
4854  }else
4855
4856#ifndef SQLITE_OMIT_LOAD_EXTENSION
4857  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
4858    const char *zFile, *zProc;
4859    char *zErrMsg = 0;
4860    if( nArg<2 ){
4861      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
4862      rc = 1;
4863      goto meta_command_exit;
4864    }
4865    zFile = azArg[1];
4866    zProc = nArg>=3 ? azArg[2] : 0;
4867    open_db(p, 0);
4868    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
4869    if( rc!=SQLITE_OK ){
4870      utf8_printf(stderr, "Error: %s\n", zErrMsg);
4871      sqlite3_free(zErrMsg);
4872      rc = 1;
4873    }
4874  }else
4875#endif
4876
4877  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
4878    if( nArg!=2 ){
4879      raw_printf(stderr, "Usage: .log FILENAME\n");
4880      rc = 1;
4881    }else{
4882      const char *zFile = azArg[1];
4883      output_file_close(p->pLog);
4884      p->pLog = output_file_open(zFile);
4885    }
4886  }else
4887
4888  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
4889    const char *zMode = nArg>=2 ? azArg[1] : "";
4890    int n2 = (int)strlen(zMode);
4891    int c2 = zMode[0];
4892    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
4893      p->mode = MODE_Line;
4894      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4895    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
4896      p->mode = MODE_Column;
4897      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4898    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
4899      p->mode = MODE_List;
4900      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
4901      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4902    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
4903      p->mode = MODE_Html;
4904    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
4905      p->mode = MODE_Tcl;
4906      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
4907      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4908    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
4909      p->mode = MODE_Csv;
4910      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
4911      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
4912    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
4913      p->mode = MODE_List;
4914      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
4915    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
4916      p->mode = MODE_Insert;
4917      set_table_name(p, nArg>=3 ? azArg[2] : "table");
4918    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
4919      p->mode = MODE_Quote;
4920    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
4921      p->mode = MODE_Ascii;
4922      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
4923      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
4924    }else if( nArg==1 ){
4925      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
4926    }else{
4927      raw_printf(stderr, "Error: mode should be one of: "
4928         "ascii column csv html insert line list quote tabs tcl\n");
4929      rc = 1;
4930    }
4931    p->cMode = p->mode;
4932  }else
4933
4934  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
4935    if( nArg==2 ){
4936      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
4937                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
4938    }else{
4939      raw_printf(stderr, "Usage: .nullvalue STRING\n");
4940      rc = 1;
4941    }
4942  }else
4943
4944  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
4945    char *zNewFilename;  /* Name of the database file to open */
4946    int iName = 1;       /* Index in azArg[] of the filename */
4947    int newFlag = 0;     /* True to delete file before opening */
4948    /* Close the existing database */
4949    session_close_all(p);
4950    sqlite3_close(p->db);
4951    p->db = 0;
4952    p->zDbFilename = 0;
4953    sqlite3_free(p->zFreeOnClose);
4954    p->zFreeOnClose = 0;
4955    /* Check for command-line arguments */
4956    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
4957      const char *z = azArg[iName];
4958      if( optionMatch(z,"new") ){
4959        newFlag = 1;
4960      }else if( z[0]=='-' ){
4961        utf8_printf(stderr, "unknown option: %s\n", z);
4962        rc = 1;
4963        goto meta_command_exit;
4964      }
4965    }
4966    /* If a filename is specified, try to open it first */
4967    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
4968    if( zNewFilename ){
4969      if( newFlag ) shellDeleteFile(zNewFilename);
4970      p->zDbFilename = zNewFilename;
4971      open_db(p, 1);
4972      if( p->db==0 ){
4973        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
4974        sqlite3_free(zNewFilename);
4975      }else{
4976        p->zFreeOnClose = zNewFilename;
4977      }
4978    }
4979    if( p->db==0 ){
4980      /* As a fall-back open a TEMP database */
4981      p->zDbFilename = 0;
4982      open_db(p, 0);
4983    }
4984  }else
4985
4986  if( c=='o'
4987   && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
4988  ){
4989    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
4990    if( nArg>2 ){
4991      utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
4992      rc = 1;
4993      goto meta_command_exit;
4994    }
4995    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
4996      if( nArg<2 ){
4997        raw_printf(stderr, "Usage: .once FILE\n");
4998        rc = 1;
4999        goto meta_command_exit;
5000      }
5001      p->outCount = 2;
5002    }else{
5003      p->outCount = 0;
5004    }
5005    output_reset(p);
5006    if( zFile[0]=='|' ){
5007#ifdef SQLITE_OMIT_POPEN
5008      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5009      rc = 1;
5010      p->out = stdout;
5011#else
5012      p->out = popen(zFile + 1, "w");
5013      if( p->out==0 ){
5014        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
5015        p->out = stdout;
5016        rc = 1;
5017      }else{
5018        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5019      }
5020#endif
5021    }else{
5022      p->out = output_file_open(zFile);
5023      if( p->out==0 ){
5024        if( strcmp(zFile,"off")!=0 ){
5025          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
5026        }
5027        p->out = stdout;
5028        rc = 1;
5029      } else {
5030        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5031      }
5032    }
5033  }else
5034
5035  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5036    int i;
5037    for(i=1; i<nArg; i++){
5038      if( i>1 ) raw_printf(p->out, " ");
5039      utf8_printf(p->out, "%s", azArg[i]);
5040    }
5041    raw_printf(p->out, "\n");
5042  }else
5043
5044  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
5045    if( nArg >= 2) {
5046      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5047    }
5048    if( nArg >= 3) {
5049      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5050    }
5051  }else
5052
5053  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
5054    rc = 2;
5055  }else
5056
5057  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5058    FILE *alt;
5059    if( nArg!=2 ){
5060      raw_printf(stderr, "Usage: .read FILE\n");
5061      rc = 1;
5062      goto meta_command_exit;
5063    }
5064    alt = fopen(azArg[1], "rb");
5065    if( alt==0 ){
5066      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5067      rc = 1;
5068    }else{
5069      rc = process_input(p, alt);
5070      fclose(alt);
5071    }
5072  }else
5073
5074  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
5075    const char *zSrcFile;
5076    const char *zDb;
5077    sqlite3 *pSrc;
5078    sqlite3_backup *pBackup;
5079    int nTimeout = 0;
5080
5081    if( nArg==2 ){
5082      zSrcFile = azArg[1];
5083      zDb = "main";
5084    }else if( nArg==3 ){
5085      zSrcFile = azArg[2];
5086      zDb = azArg[1];
5087    }else{
5088      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
5089      rc = 1;
5090      goto meta_command_exit;
5091    }
5092    rc = sqlite3_open(zSrcFile, &pSrc);
5093    if( rc!=SQLITE_OK ){
5094      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
5095      sqlite3_close(pSrc);
5096      return 1;
5097    }
5098    open_db(p, 0);
5099    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5100    if( pBackup==0 ){
5101      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5102      sqlite3_close(pSrc);
5103      return 1;
5104    }
5105    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5106          || rc==SQLITE_BUSY  ){
5107      if( rc==SQLITE_BUSY ){
5108        if( nTimeout++ >= 3 ) break;
5109        sqlite3_sleep(100);
5110      }
5111    }
5112    sqlite3_backup_finish(pBackup);
5113    if( rc==SQLITE_DONE ){
5114      rc = 0;
5115    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
5116      raw_printf(stderr, "Error: source database is busy\n");
5117      rc = 1;
5118    }else{
5119      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5120      rc = 1;
5121    }
5122    sqlite3_close(pSrc);
5123  }else
5124
5125
5126  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5127    if( nArg==2 ){
5128      p->scanstatsOn = booleanValue(azArg[1]);
5129#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5130      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
5131#endif
5132    }else{
5133      raw_printf(stderr, "Usage: .scanstats on|off\n");
5134      rc = 1;
5135    }
5136  }else
5137
5138  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
5139    ShellText sSelect;
5140    ShellState data;
5141    char *zErrMsg = 0;
5142    const char *zDiv = 0;
5143    int iSchema = 0;
5144
5145    open_db(p, 0);
5146    memcpy(&data, p, sizeof(data));
5147    data.showHeader = 0;
5148    data.cMode = data.mode = MODE_Semi;
5149    initText(&sSelect);
5150    if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5151      data.cMode = data.mode = MODE_Pretty;
5152      nArg--;
5153      if( nArg==2 ) azArg[1] = azArg[2];
5154    }
5155    if( nArg==2 && azArg[1][0]!='-' ){
5156      int i;
5157      for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
5158      if( strcmp(azArg[1],"sqlite_master")==0 ){
5159        char *new_argv[2], *new_colv[2];
5160        new_argv[0] = "CREATE TABLE sqlite_master (\n"
5161                      "  type text,\n"
5162                      "  name text,\n"
5163                      "  tbl_name text,\n"
5164                      "  rootpage integer,\n"
5165                      "  sql text\n"
5166                      ")";
5167        new_argv[1] = 0;
5168        new_colv[0] = "sql";
5169        new_colv[1] = 0;
5170        callback(&data, 1, new_argv, new_colv);
5171        rc = SQLITE_OK;
5172      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
5173        char *new_argv[2], *new_colv[2];
5174        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5175                      "  type text,\n"
5176                      "  name text,\n"
5177                      "  tbl_name text,\n"
5178                      "  rootpage integer,\n"
5179                      "  sql text\n"
5180                      ")";
5181        new_argv[1] = 0;
5182        new_colv[0] = "sql";
5183        new_colv[1] = 0;
5184        callback(&data, 1, new_argv, new_colv);
5185        rc = SQLITE_OK;
5186      }else{
5187        zDiv = "(";
5188      }
5189    }else if( nArg==1 ){
5190      zDiv = "(";
5191    }else{
5192      raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5193      rc = 1;
5194      goto meta_command_exit;
5195    }
5196    if( zDiv ){
5197      sqlite3_stmt *pStmt = 0;
5198      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5199                              -1, &pStmt, 0);
5200      if( rc ){
5201        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5202        sqlite3_finalize(pStmt);
5203        rc = 1;
5204        goto meta_command_exit;
5205      }
5206      appendText(&sSelect, "SELECT sql FROM", 0);
5207      iSchema = 0;
5208      while( sqlite3_step(pStmt)==SQLITE_ROW ){
5209        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5210        char zScNum[30];
5211        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5212        appendText(&sSelect, zDiv, 0);
5213        zDiv = " UNION ALL ";
5214        if( strcmp(zDb, "main")!=0 ){
5215          appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
5216          appendText(&sSelect, zDb, '"');
5217          appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5218          appendText(&sSelect, zScNum, 0);
5219          appendText(&sSelect, " AS snum, ", 0);
5220          appendText(&sSelect, zDb, '\'');
5221          appendText(&sSelect, " AS sname FROM ", 0);
5222          appendText(&sSelect, zDb, '"');
5223          appendText(&sSelect, ".sqlite_master", 0);
5224        }else{
5225          appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5226          appendText(&sSelect, zScNum, 0);
5227          appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5228        }
5229      }
5230      sqlite3_finalize(pStmt);
5231      appendText(&sSelect, ") WHERE ", 0);
5232      if( nArg>1 ){
5233        char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5234        if( strchr(azArg[1], '.') ){
5235          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5236        }else{
5237          appendText(&sSelect, "lower(tbl_name)", 0);
5238        }
5239        appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5240        appendText(&sSelect, zQarg, 0);
5241        appendText(&sSelect, " AND ", 0);
5242        sqlite3_free(zQarg);
5243      }
5244      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5245                           " ORDER BY snum, rowid", 0);
5246      rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5247      freeText(&sSelect);
5248    }
5249    if( zErrMsg ){
5250      utf8_printf(stderr,"Error: %s\n", zErrMsg);
5251      sqlite3_free(zErrMsg);
5252      rc = 1;
5253    }else if( rc != SQLITE_OK ){
5254      raw_printf(stderr,"Error: querying schema information\n");
5255      rc = 1;
5256    }else{
5257      rc = 0;
5258    }
5259  }else
5260
5261#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5262  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
5263    sqlite3SelectTrace = (int)integerValue(azArg[1]);
5264  }else
5265#endif
5266
5267#if defined(SQLITE_ENABLE_SESSION)
5268  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5269    OpenSession *pSession = &p->aSession[0];
5270    char **azCmd = &azArg[1];
5271    int iSes = 0;
5272    int nCmd = nArg - 1;
5273    int i;
5274    if( nArg<=1 ) goto session_syntax_error;
5275    open_db(p, 0);
5276    if( nArg>=3 ){
5277      for(iSes=0; iSes<p->nSession; iSes++){
5278        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5279      }
5280      if( iSes<p->nSession ){
5281        pSession = &p->aSession[iSes];
5282        azCmd++;
5283        nCmd--;
5284      }else{
5285        pSession = &p->aSession[0];
5286        iSes = 0;
5287      }
5288    }
5289
5290    /* .session attach TABLE
5291    ** Invoke the sqlite3session_attach() interface to attach a particular
5292    ** table so that it is never filtered.
5293    */
5294    if( strcmp(azCmd[0],"attach")==0 ){
5295      if( nCmd!=2 ) goto session_syntax_error;
5296      if( pSession->p==0 ){
5297        session_not_open:
5298        raw_printf(stderr, "ERROR: No sessions are open\n");
5299      }else{
5300        rc = sqlite3session_attach(pSession->p, azCmd[1]);
5301        if( rc ){
5302          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
5303          rc = 0;
5304        }
5305      }
5306    }else
5307
5308    /* .session changeset FILE
5309    ** .session patchset FILE
5310    ** Write a changeset or patchset into a file.  The file is overwritten.
5311    */
5312    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5313      FILE *out = 0;
5314      if( nCmd!=2 ) goto session_syntax_error;
5315      if( pSession->p==0 ) goto session_not_open;
5316      out = fopen(azCmd[1], "wb");
5317      if( out==0 ){
5318        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
5319      }else{
5320        int szChng;
5321        void *pChng;
5322        if( azCmd[0][0]=='c' ){
5323          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
5324        }else{
5325          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5326        }
5327        if( rc ){
5328          printf("Error: error code %d\n", rc);
5329          rc = 0;
5330        }
5331        if( pChng
5332          && fwrite(pChng, szChng, 1, out)!=1 ){
5333          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
5334                  szChng);
5335        }
5336        sqlite3_free(pChng);
5337        fclose(out);
5338      }
5339    }else
5340
5341    /* .session close
5342    ** Close the identified session
5343    */
5344    if( strcmp(azCmd[0], "close")==0 ){
5345      if( nCmd!=1 ) goto session_syntax_error;
5346      if( p->nSession ){
5347        session_close(pSession);
5348        p->aSession[iSes] = p->aSession[--p->nSession];
5349      }
5350    }else
5351
5352    /* .session enable ?BOOLEAN?
5353    ** Query or set the enable flag
5354    */
5355    if( strcmp(azCmd[0], "enable")==0 ){
5356      int ii;
5357      if( nCmd>2 ) goto session_syntax_error;
5358      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5359      if( p->nSession ){
5360        ii = sqlite3session_enable(pSession->p, ii);
5361        utf8_printf(p->out, "session %s enable flag = %d\n",
5362                    pSession->zName, ii);
5363      }
5364    }else
5365
5366    /* .session filter GLOB ....
5367    ** Set a list of GLOB patterns of table names to be excluded.
5368    */
5369    if( strcmp(azCmd[0], "filter")==0 ){
5370      int ii, nByte;
5371      if( nCmd<2 ) goto session_syntax_error;
5372      if( p->nSession ){
5373        for(ii=0; ii<pSession->nFilter; ii++){
5374          sqlite3_free(pSession->azFilter[ii]);
5375        }
5376        sqlite3_free(pSession->azFilter);
5377        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5378        pSession->azFilter = sqlite3_malloc( nByte );
5379        if( pSession->azFilter==0 ){
5380          raw_printf(stderr, "Error: out or memory\n");
5381          exit(1);
5382        }
5383        for(ii=1; ii<nCmd; ii++){
5384          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
5385        }
5386        pSession->nFilter = ii-1;
5387      }
5388    }else
5389
5390    /* .session indirect ?BOOLEAN?
5391    ** Query or set the indirect flag
5392    */
5393    if( strcmp(azCmd[0], "indirect")==0 ){
5394      int ii;
5395      if( nCmd>2 ) goto session_syntax_error;
5396      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5397      if( p->nSession ){
5398        ii = sqlite3session_indirect(pSession->p, ii);
5399        utf8_printf(p->out, "session %s indirect flag = %d\n",
5400                    pSession->zName, ii);
5401      }
5402    }else
5403
5404    /* .session isempty
5405    ** Determine if the session is empty
5406    */
5407    if( strcmp(azCmd[0], "isempty")==0 ){
5408      int ii;
5409      if( nCmd!=1 ) goto session_syntax_error;
5410      if( p->nSession ){
5411        ii = sqlite3session_isempty(pSession->p);
5412        utf8_printf(p->out, "session %s isempty flag = %d\n",
5413                    pSession->zName, ii);
5414      }
5415    }else
5416
5417    /* .session list
5418    ** List all currently open sessions
5419    */
5420    if( strcmp(azCmd[0],"list")==0 ){
5421      for(i=0; i<p->nSession; i++){
5422        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
5423      }
5424    }else
5425
5426    /* .session open DB NAME
5427    ** Open a new session called NAME on the attached database DB.
5428    ** DB is normally "main".
5429    */
5430    if( strcmp(azCmd[0],"open")==0 ){
5431      char *zName;
5432      if( nCmd!=3 ) goto session_syntax_error;
5433      zName = azCmd[2];
5434      if( zName[0]==0 ) goto session_syntax_error;
5435      for(i=0; i<p->nSession; i++){
5436        if( strcmp(p->aSession[i].zName,zName)==0 ){
5437          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
5438          goto meta_command_exit;
5439        }
5440      }
5441      if( p->nSession>=ArraySize(p->aSession) ){
5442        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
5443        goto meta_command_exit;
5444      }
5445      pSession = &p->aSession[p->nSession];
5446      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5447      if( rc ){
5448        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
5449        rc = 0;
5450        goto meta_command_exit;
5451      }
5452      pSession->nFilter = 0;
5453      sqlite3session_table_filter(pSession->p, session_filter, pSession);
5454      p->nSession++;
5455      pSession->zName = sqlite3_mprintf("%s", zName);
5456    }else
5457    /* If no command name matches, show a syntax error */
5458    session_syntax_error:
5459    session_help(p);
5460  }else
5461#endif
5462
5463#ifdef SQLITE_DEBUG
5464  /* Undocumented commands for internal testing.  Subject to change
5465  ** without notice. */
5466  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5467    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5468      int i, v;
5469      for(i=1; i<nArg; i++){
5470        v = booleanValue(azArg[i]);
5471        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
5472      }
5473    }
5474    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5475      int i; sqlite3_int64 v;
5476      for(i=1; i<nArg; i++){
5477        char zBuf[200];
5478        v = integerValue(azArg[i]);
5479        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
5480        utf8_printf(p->out, "%s", zBuf);
5481      }
5482    }
5483  }else
5484#endif
5485
5486  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5487    int bIsInit = 0;         /* True to initialize the SELFTEST table */
5488    int bVerbose = 0;        /* Verbose output */
5489    int bSelftestExists;     /* True if SELFTEST already exists */
5490    int i, k;                /* Loop counters */
5491    int nTest = 0;           /* Number of tests runs */
5492    int nErr = 0;            /* Number of errors seen */
5493    ShellText str;           /* Answer for a query */
5494    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
5495
5496    open_db(p,0);
5497    for(i=1; i<nArg; i++){
5498      const char *z = azArg[i];
5499      if( z[0]=='-' && z[1]=='-' ) z++;
5500      if( strcmp(z,"-init")==0 ){
5501        bIsInit = 1;
5502      }else
5503      if( strcmp(z,"-v")==0 ){
5504        bVerbose++;
5505      }else
5506      {
5507        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5508                    azArg[i], azArg[0]);
5509        raw_printf(stderr, "Should be one of: --init -v\n");
5510        rc = 1;
5511        goto meta_command_exit;
5512      }
5513    }
5514    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5515           != SQLITE_OK ){
5516      bSelftestExists = 0;
5517    }else{
5518      bSelftestExists = 1;
5519    }
5520    if( bIsInit ){
5521      createSelftestTable(p);
5522      bSelftestExists = 1;
5523    }
5524    initText(&str);
5525    appendText(&str, "x", 0);
5526    for(k=bSelftestExists; k>=0; k--){
5527      if( k==1 ){
5528        rc = sqlite3_prepare_v2(p->db,
5529            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5530            -1, &pStmt, 0);
5531      }else{
5532        rc = sqlite3_prepare_v2(p->db,
5533          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
5534          "      (1,'run','PRAGMA integrity_check','ok')",
5535          -1, &pStmt, 0);
5536      }
5537      if( rc ){
5538        raw_printf(stderr, "Error querying the selftest table\n");
5539        rc = 1;
5540        sqlite3_finalize(pStmt);
5541        goto meta_command_exit;
5542      }
5543      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
5544        int tno = sqlite3_column_int(pStmt, 0);
5545        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
5546        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
5547        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
5548
5549        k = 0;
5550        if( bVerbose>0 ){
5551          char *zQuote = sqlite3_mprintf("%q", zSql);
5552          printf("%d: %s %s\n", tno, zOp, zSql);
5553          sqlite3_free(zQuote);
5554        }
5555        if( strcmp(zOp,"memo")==0 ){
5556          utf8_printf(p->out, "%s\n", zSql);
5557        }else
5558        if( strcmp(zOp,"run")==0 ){
5559          char *zErrMsg = 0;
5560          str.n = 0;
5561          str.z[0] = 0;
5562          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5563          nTest++;
5564          if( bVerbose ){
5565            utf8_printf(p->out, "Result: %s\n", str.z);
5566          }
5567          if( rc || zErrMsg ){
5568            nErr++;
5569            rc = 1;
5570            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5571            sqlite3_free(zErrMsg);
5572          }else if( strcmp(zAns,str.z)!=0 ){
5573            nErr++;
5574            rc = 1;
5575            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5576            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
5577          }
5578        }else
5579        {
5580          utf8_printf(stderr,
5581            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5582          rc = 1;
5583          break;
5584        }
5585      } /* End loop over rows of content from SELFTEST */
5586      sqlite3_finalize(pStmt);
5587    } /* End loop over k */
5588    freeText(&str);
5589    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5590  }else
5591
5592  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
5593    if( nArg<2 || nArg>3 ){
5594      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
5595      rc = 1;
5596    }
5597    if( nArg>=2 ){
5598      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
5599                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
5600    }
5601    if( nArg>=3 ){
5602      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5603                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
5604    }
5605  }else
5606
5607  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5608    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
5609    int i;                   /* Loop counter */
5610    int bSchema = 0;         /* Also hash the schema */
5611    int bSeparate = 0;       /* Hash each table separately */
5612    int iSize = 224;         /* Hash algorithm to use */
5613    int bDebug = 0;          /* Only show the query that would have run */
5614    sqlite3_stmt *pStmt;     /* For querying tables names */
5615    char *zSql;              /* SQL to be run */
5616    char *zSep;              /* Separator */
5617    ShellText sSql;          /* Complete SQL for the query to run the hash */
5618    ShellText sQuery;        /* Set of queries used to read all content */
5619    open_db(p, 0);
5620    for(i=1; i<nArg; i++){
5621      const char *z = azArg[i];
5622      if( z[0]=='-' ){
5623        z++;
5624        if( z[0]=='-' ) z++;
5625        if( strcmp(z,"schema")==0 ){
5626          bSchema = 1;
5627        }else
5628        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
5629         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
5630        ){
5631          iSize = atoi(&z[5]);
5632        }else
5633        if( strcmp(z,"debug")==0 ){
5634          bDebug = 1;
5635        }else
5636        {
5637          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5638                      azArg[i], azArg[0]);
5639          raw_printf(stderr, "Should be one of: --schema"
5640                             " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5641          rc = 1;
5642          goto meta_command_exit;
5643        }
5644      }else if( zLike ){
5645        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5646        rc = 1;
5647        goto meta_command_exit;
5648      }else{
5649        zLike = z;
5650        bSeparate = 1;
5651        if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
5652      }
5653    }
5654    if( bSchema ){
5655      zSql = "SELECT lower(name) FROM sqlite_master"
5656             " WHERE type='table' AND coalesce(rootpage,0)>1"
5657             " UNION ALL SELECT 'sqlite_master'"
5658             " ORDER BY 1 collate nocase";
5659    }else{
5660      zSql = "SELECT lower(name) FROM sqlite_master"
5661             " WHERE type='table' AND coalesce(rootpage,0)>1"
5662             " AND name NOT LIKE 'sqlite_%'"
5663             " ORDER BY 1 collate nocase";
5664    }
5665    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5666    initText(&sQuery);
5667    initText(&sSql);
5668    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
5669    zSep = "VALUES(";
5670    while( SQLITE_ROW==sqlite3_step(pStmt) ){
5671      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
5672      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
5673      if( strncmp(zTab, "sqlite_",7)!=0 ){
5674        appendText(&sQuery,"SELECT * FROM ", 0);
5675        appendText(&sQuery,zTab,'"');
5676        appendText(&sQuery," NOT INDEXED;", 0);
5677      }else if( strcmp(zTab, "sqlite_master")==0 ){
5678        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5679                           " ORDER BY name;", 0);
5680      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
5681        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
5682                           " ORDER BY name;", 0);
5683      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
5684        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
5685                           " ORDER BY tbl,idx;", 0);
5686      }else if( strcmp(zTab, "sqlite_stat3")==0
5687             || strcmp(zTab, "sqlite_stat4")==0 ){
5688        appendText(&sQuery, "SELECT * FROM ", 0);
5689        appendText(&sQuery, zTab, 0);
5690        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
5691      }
5692      appendText(&sSql, zSep, 0);
5693      appendText(&sSql, sQuery.z, '\'');
5694      sQuery.n = 0;
5695      appendText(&sSql, ",", 0);
5696      appendText(&sSql, zTab, '\'');
5697      zSep = "),(";
5698    }
5699    sqlite3_finalize(pStmt);
5700    if( bSeparate ){
5701      zSql = sqlite3_mprintf(
5702          "%s))"
5703          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
5704          "   FROM [sha3sum$query]",
5705          sSql.z, iSize);
5706    }else{
5707      zSql = sqlite3_mprintf(
5708          "%s))"
5709          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
5710          "   FROM [sha3sum$query]",
5711          sSql.z, iSize);
5712    }
5713    freeText(&sQuery);
5714    freeText(&sSql);
5715    if( bDebug ){
5716      utf8_printf(p->out, "%s\n", zSql);
5717    }else{
5718      shell_exec(p->db, zSql, shell_callback, p, 0);
5719    }
5720    sqlite3_free(zSql);
5721  }else
5722
5723  if( c=='s'
5724   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
5725  ){
5726    char *zCmd;
5727    int i, x;
5728    if( nArg<2 ){
5729      raw_printf(stderr, "Usage: .system COMMAND\n");
5730      rc = 1;
5731      goto meta_command_exit;
5732    }
5733    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
5734    for(i=2; i<nArg; i++){
5735      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
5736                             zCmd, azArg[i]);
5737    }
5738    x = system(zCmd);
5739    sqlite3_free(zCmd);
5740    if( x ) raw_printf(stderr, "System command returns %d\n", x);
5741  }else
5742
5743  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
5744    static const char *azBool[] = { "off", "on", "full", "unk" };
5745    int i;
5746    if( nArg!=1 ){
5747      raw_printf(stderr, "Usage: .show\n");
5748      rc = 1;
5749      goto meta_command_exit;
5750    }
5751    utf8_printf(p->out, "%12.12s: %s\n","echo",
5752                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
5753    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
5754    utf8_printf(p->out, "%12.12s: %s\n","explain",
5755         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
5756    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
5757    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
5758    utf8_printf(p->out, "%12.12s: ", "nullvalue");
5759      output_c_string(p->out, p->nullValue);
5760      raw_printf(p->out, "\n");
5761    utf8_printf(p->out,"%12.12s: %s\n","output",
5762            strlen30(p->outfile) ? p->outfile : "stdout");
5763    utf8_printf(p->out,"%12.12s: ", "colseparator");
5764      output_c_string(p->out, p->colSeparator);
5765      raw_printf(p->out, "\n");
5766    utf8_printf(p->out,"%12.12s: ", "rowseparator");
5767      output_c_string(p->out, p->rowSeparator);
5768      raw_printf(p->out, "\n");
5769    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
5770    utf8_printf(p->out, "%12.12s: ", "width");
5771    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
5772      raw_printf(p->out, "%d ", p->colWidth[i]);
5773    }
5774    raw_printf(p->out, "\n");
5775    utf8_printf(p->out, "%12.12s: %s\n", "filename",
5776                p->zDbFilename ? p->zDbFilename : "");
5777  }else
5778
5779  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
5780    if( nArg==2 ){
5781      p->statsOn = booleanValue(azArg[1]);
5782    }else if( nArg==1 ){
5783      display_stats(p->db, p, 0);
5784    }else{
5785      raw_printf(stderr, "Usage: .stats ?on|off?\n");
5786      rc = 1;
5787    }
5788  }else
5789
5790  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
5791   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
5792                 || strncmp(azArg[0], "indexes", n)==0) )
5793  ){
5794    sqlite3_stmt *pStmt;
5795    char **azResult;
5796    int nRow, nAlloc;
5797    int ii;
5798    ShellText s;
5799    initText(&s);
5800    open_db(p, 0);
5801    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
5802    if( rc ) return shellDatabaseError(p->db);
5803
5804    if( nArg>2 && c=='i' ){
5805      /* It is an historical accident that the .indexes command shows an error
5806      ** when called with the wrong number of arguments whereas the .tables
5807      ** command does not. */
5808      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
5809      rc = 1;
5810      goto meta_command_exit;
5811    }
5812    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
5813      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
5814      if( zDbName==0 ) continue;
5815      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
5816      if( sqlite3_stricmp(zDbName, "main")==0 ){
5817        appendText(&s, "SELECT name FROM ", 0);
5818      }else{
5819        appendText(&s, "SELECT ", 0);
5820        appendText(&s, zDbName, '\'');
5821        appendText(&s, "||'.'||name FROM ", 0);
5822      }
5823      appendText(&s, zDbName, '"');
5824      appendText(&s, ".sqlite_master ", 0);
5825      if( c=='t' ){
5826        appendText(&s," WHERE type IN ('table','view')"
5827                      "   AND name NOT LIKE 'sqlite_%'"
5828                      "   AND name LIKE ?1", 0);
5829      }else{
5830        appendText(&s," WHERE type='index'"
5831                      "   AND tbl_name LIKE ?1", 0);
5832      }
5833    }
5834    rc = sqlite3_finalize(pStmt);
5835    appendText(&s, " ORDER BY 1", 0);
5836    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
5837    freeText(&s);
5838    if( rc ) return shellDatabaseError(p->db);
5839
5840    /* Run the SQL statement prepared by the above block. Store the results
5841    ** as an array of nul-terminated strings in azResult[].  */
5842    nRow = nAlloc = 0;
5843    azResult = 0;
5844    if( nArg>1 ){
5845      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
5846    }else{
5847      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
5848    }
5849    while( sqlite3_step(pStmt)==SQLITE_ROW ){
5850      if( nRow>=nAlloc ){
5851        char **azNew;
5852        int n2 = nAlloc*2 + 10;
5853        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
5854        if( azNew==0 ){
5855          rc = shellNomemError();
5856          break;
5857        }
5858        nAlloc = n2;
5859        azResult = azNew;
5860      }
5861      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
5862      if( 0==azResult[nRow] ){
5863        rc = shellNomemError();
5864        break;
5865      }
5866      nRow++;
5867    }
5868    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
5869      rc = shellDatabaseError(p->db);
5870    }
5871
5872    /* Pretty-print the contents of array azResult[] to the output */
5873    if( rc==0 && nRow>0 ){
5874      int len, maxlen = 0;
5875      int i, j;
5876      int nPrintCol, nPrintRow;
5877      for(i=0; i<nRow; i++){
5878        len = strlen30(azResult[i]);
5879        if( len>maxlen ) maxlen = len;
5880      }
5881      nPrintCol = 80/(maxlen+2);
5882      if( nPrintCol<1 ) nPrintCol = 1;
5883      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
5884      for(i=0; i<nPrintRow; i++){
5885        for(j=i; j<nRow; j+=nPrintRow){
5886          char *zSp = j<nPrintRow ? "" : "  ";
5887          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
5888                      azResult[j] ? azResult[j]:"");
5889        }
5890        raw_printf(p->out, "\n");
5891      }
5892    }
5893
5894    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
5895    sqlite3_free(azResult);
5896  }else
5897
5898  /* Begin redirecting output to the file "testcase-out.txt" */
5899  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
5900    output_reset(p);
5901    p->out = output_file_open("testcase-out.txt");
5902    if( p->out==0 ){
5903      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
5904    }
5905    if( nArg>=2 ){
5906      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
5907    }else{
5908      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
5909    }
5910  }else
5911
5912#ifndef SQLITE_UNTESTABLE
5913  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
5914    static const struct {
5915       const char *zCtrlName;   /* Name of a test-control option */
5916       int ctrlCode;            /* Integer code for that option */
5917    } aCtrl[] = {
5918      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
5919      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
5920      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
5921      { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
5922      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
5923      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
5924      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
5925      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
5926      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
5927      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
5928      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
5929      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
5930      { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
5931      { "byteorder",             SQLITE_TESTCTRL_BYTEORDER              },
5932      { "never_corrupt",         SQLITE_TESTCTRL_NEVER_CORRUPT          },
5933      { "imposter",              SQLITE_TESTCTRL_IMPOSTER               },
5934    };
5935    int testctrl = -1;
5936    int rc2 = 0;
5937    int i, n2;
5938    open_db(p, 0);
5939
5940    /* convert testctrl text option to value. allow any unique prefix
5941    ** of the option name, or a numerical value. */
5942    n2 = strlen30(azArg[1]);
5943    for(i=0; i<ArraySize(aCtrl); i++){
5944      if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
5945        if( testctrl<0 ){
5946          testctrl = aCtrl[i].ctrlCode;
5947        }else{
5948          utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
5949          testctrl = -1;
5950          break;
5951        }
5952      }
5953    }
5954    if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
5955    if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
5956      utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
5957    }else{
5958      switch(testctrl){
5959
5960        /* sqlite3_test_control(int, db, int) */
5961        case SQLITE_TESTCTRL_OPTIMIZATIONS:
5962        case SQLITE_TESTCTRL_RESERVE:
5963          if( nArg==3 ){
5964            int opt = (int)strtol(azArg[2], 0, 0);
5965            rc2 = sqlite3_test_control(testctrl, p->db, opt);
5966            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5967          } else {
5968            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
5969                    azArg[1]);
5970          }
5971          break;
5972
5973        /* sqlite3_test_control(int) */
5974        case SQLITE_TESTCTRL_PRNG_SAVE:
5975        case SQLITE_TESTCTRL_PRNG_RESTORE:
5976        case SQLITE_TESTCTRL_PRNG_RESET:
5977        case SQLITE_TESTCTRL_BYTEORDER:
5978          if( nArg==2 ){
5979            rc2 = sqlite3_test_control(testctrl);
5980            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5981          } else {
5982            utf8_printf(stderr,"Error: testctrl %s takes no options\n",
5983                        azArg[1]);
5984          }
5985          break;
5986
5987        /* sqlite3_test_control(int, uint) */
5988        case SQLITE_TESTCTRL_PENDING_BYTE:
5989          if( nArg==3 ){
5990            unsigned int opt = (unsigned int)integerValue(azArg[2]);
5991            rc2 = sqlite3_test_control(testctrl, opt);
5992            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5993          } else {
5994            utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
5995                           " int option\n", azArg[1]);
5996          }
5997          break;
5998
5999        /* sqlite3_test_control(int, int) */
6000        case SQLITE_TESTCTRL_ASSERT:
6001        case SQLITE_TESTCTRL_ALWAYS:
6002        case SQLITE_TESTCTRL_NEVER_CORRUPT:
6003          if( nArg==3 ){
6004            int opt = booleanValue(azArg[2]);
6005            rc2 = sqlite3_test_control(testctrl, opt);
6006            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6007          } else {
6008            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6009                            azArg[1]);
6010          }
6011          break;
6012
6013        /* sqlite3_test_control(int, char *) */
6014#ifdef SQLITE_N_KEYWORD
6015        case SQLITE_TESTCTRL_ISKEYWORD:
6016          if( nArg==3 ){
6017            const char *opt = azArg[2];
6018            rc2 = sqlite3_test_control(testctrl, opt);
6019            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6020          } else {
6021            utf8_printf(stderr,
6022                        "Error: testctrl %s takes a single char * option\n",
6023                        azArg[1]);
6024          }
6025          break;
6026#endif
6027
6028        case SQLITE_TESTCTRL_IMPOSTER:
6029          if( nArg==5 ){
6030            rc2 = sqlite3_test_control(testctrl, p->db,
6031                          azArg[2],
6032                          integerValue(azArg[3]),
6033                          integerValue(azArg[4]));
6034            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6035          }else{
6036            raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
6037          }
6038          break;
6039
6040        case SQLITE_TESTCTRL_BITVEC_TEST:
6041        case SQLITE_TESTCTRL_FAULT_INSTALL:
6042        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6043        case SQLITE_TESTCTRL_SCRATCHMALLOC:
6044        default:
6045          utf8_printf(stderr,
6046                      "Error: CLI support for testctrl %s not implemented\n",
6047                      azArg[1]);
6048          break;
6049      }
6050    }
6051  }else
6052#endif /* !defined(SQLITE_UNTESTABLE) */
6053
6054  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
6055    open_db(p, 0);
6056    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
6057  }else
6058
6059  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6060    if( nArg==2 ){
6061      enableTimer = booleanValue(azArg[1]);
6062      if( enableTimer && !HAS_TIMER ){
6063        raw_printf(stderr, "Error: timer not available on this system.\n");
6064        enableTimer = 0;
6065      }
6066    }else{
6067      raw_printf(stderr, "Usage: .timer on|off\n");
6068      rc = 1;
6069    }
6070  }else
6071
6072  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
6073    open_db(p, 0);
6074    if( nArg!=2 ){
6075      raw_printf(stderr, "Usage: .trace FILE|off\n");
6076      rc = 1;
6077      goto meta_command_exit;
6078    }
6079    output_file_close(p->traceOut);
6080    p->traceOut = output_file_open(azArg[1]);
6081#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6082    if( p->traceOut==0 ){
6083      sqlite3_trace_v2(p->db, 0, 0, 0);
6084    }else{
6085      sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
6086    }
6087#endif
6088  }else
6089
6090#if SQLITE_USER_AUTHENTICATION
6091  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6092    if( nArg<2 ){
6093      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
6094      rc = 1;
6095      goto meta_command_exit;
6096    }
6097    open_db(p, 0);
6098    if( strcmp(azArg[1],"login")==0 ){
6099      if( nArg!=4 ){
6100        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
6101        rc = 1;
6102        goto meta_command_exit;
6103      }
6104      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6105                                    (int)strlen(azArg[3]));
6106      if( rc ){
6107        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
6108        rc = 1;
6109      }
6110    }else if( strcmp(azArg[1],"add")==0 ){
6111      if( nArg!=5 ){
6112        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
6113        rc = 1;
6114        goto meta_command_exit;
6115      }
6116      rc = sqlite3_user_add(p->db, azArg[2],
6117                            azArg[3], (int)strlen(azArg[3]),
6118                            booleanValue(azArg[4]));
6119      if( rc ){
6120        raw_printf(stderr, "User-Add failed: %d\n", rc);
6121        rc = 1;
6122      }
6123    }else if( strcmp(azArg[1],"edit")==0 ){
6124      if( nArg!=5 ){
6125        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
6126        rc = 1;
6127        goto meta_command_exit;
6128      }
6129      rc = sqlite3_user_change(p->db, azArg[2],
6130                              azArg[3], (int)strlen(azArg[3]),
6131                              booleanValue(azArg[4]));
6132      if( rc ){
6133        raw_printf(stderr, "User-Edit failed: %d\n", rc);
6134        rc = 1;
6135      }
6136    }else if( strcmp(azArg[1],"delete")==0 ){
6137      if( nArg!=3 ){
6138        raw_printf(stderr, "Usage: .user delete USER\n");
6139        rc = 1;
6140        goto meta_command_exit;
6141      }
6142      rc = sqlite3_user_delete(p->db, azArg[2]);
6143      if( rc ){
6144        raw_printf(stderr, "User-Delete failed: %d\n", rc);
6145        rc = 1;
6146      }
6147    }else{
6148      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
6149      rc = 1;
6150      goto meta_command_exit;
6151    }
6152  }else
6153#endif /* SQLITE_USER_AUTHENTICATION */
6154
6155  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
6156    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
6157        sqlite3_libversion(), sqlite3_sourceid());
6158  }else
6159
6160  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6161    const char *zDbName = nArg==2 ? azArg[1] : "main";
6162    sqlite3_vfs *pVfs = 0;
6163    if( p->db ){
6164      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6165      if( pVfs ){
6166        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
6167        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6168        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6169        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6170      }
6171    }
6172  }else
6173
6174  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6175    sqlite3_vfs *pVfs;
6176    sqlite3_vfs *pCurrent = 0;
6177    if( p->db ){
6178      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6179    }
6180    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6181      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
6182           pVfs==pCurrent ? "  <--- CURRENT" : "");
6183      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6184      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6185      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6186      if( pVfs->pNext ){
6187        raw_printf(p->out, "-----------------------------------\n");
6188      }
6189    }
6190  }else
6191
6192  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6193    const char *zDbName = nArg==2 ? azArg[1] : "main";
6194    char *zVfsName = 0;
6195    if( p->db ){
6196      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6197      if( zVfsName ){
6198        utf8_printf(p->out, "%s\n", zVfsName);
6199        sqlite3_free(zVfsName);
6200      }
6201    }
6202  }else
6203
6204#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6205  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
6206    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
6207  }else
6208#endif
6209
6210  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
6211    int j;
6212    assert( nArg<=ArraySize(azArg) );
6213    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
6214      p->colWidth[j-1] = (int)integerValue(azArg[j]);
6215    }
6216  }else
6217
6218  {
6219    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
6220      " \"%s\". Enter \".help\" for help\n", azArg[0]);
6221    rc = 1;
6222  }
6223
6224meta_command_exit:
6225  if( p->outCount ){
6226    p->outCount--;
6227    if( p->outCount==0 ) output_reset(p);
6228  }
6229  return rc;
6230}
6231
6232/*
6233** Return TRUE if a semicolon occurs anywhere in the first N characters
6234** of string z[].
6235*/
6236static int line_contains_semicolon(const char *z, int N){
6237  int i;
6238  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
6239  return 0;
6240}
6241
6242/*
6243** Test to see if a line consists entirely of whitespace.
6244*/
6245static int _all_whitespace(const char *z){
6246  for(; *z; z++){
6247    if( IsSpace(z[0]) ) continue;
6248    if( *z=='/' && z[1]=='*' ){
6249      z += 2;
6250      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6251      if( *z==0 ) return 0;
6252      z++;
6253      continue;
6254    }
6255    if( *z=='-' && z[1]=='-' ){
6256      z += 2;
6257      while( *z && *z!='\n' ){ z++; }
6258      if( *z==0 ) return 1;
6259      continue;
6260    }
6261    return 0;
6262  }
6263  return 1;
6264}
6265
6266/*
6267** Return TRUE if the line typed in is an SQL command terminator other
6268** than a semi-colon.  The SQL Server style "go" command is understood
6269** as is the Oracle "/".
6270*/
6271static int line_is_command_terminator(const char *zLine){
6272  while( IsSpace(zLine[0]) ){ zLine++; };
6273  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6274    return 1;  /* Oracle */
6275  }
6276  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
6277         && _all_whitespace(&zLine[2]) ){
6278    return 1;  /* SQL Server */
6279  }
6280  return 0;
6281}
6282
6283/*
6284** Return true if zSql is a complete SQL statement.  Return false if it
6285** ends in the middle of a string literal or C-style comment.
6286*/
6287static int line_is_complete(char *zSql, int nSql){
6288  int rc;
6289  if( zSql==0 ) return 1;
6290  zSql[nSql] = ';';
6291  zSql[nSql+1] = 0;
6292  rc = sqlite3_complete(zSql);
6293  zSql[nSql] = 0;
6294  return rc;
6295}
6296
6297/*
6298** Run a single line of SQL
6299*/
6300static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6301  int rc;
6302  char *zErrMsg = 0;
6303
6304  open_db(p, 0);
6305  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
6306  BEGIN_TIMER;
6307  rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6308  END_TIMER;
6309  if( rc || zErrMsg ){
6310    char zPrefix[100];
6311    if( in!=0 || !stdin_is_interactive ){
6312      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6313                       "Error: near line %d:", startline);
6314    }else{
6315      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6316    }
6317    if( zErrMsg!=0 ){
6318      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6319      sqlite3_free(zErrMsg);
6320      zErrMsg = 0;
6321    }else{
6322      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6323    }
6324    return 1;
6325  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
6326    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
6327            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6328  }
6329  return 0;
6330}
6331
6332
6333/*
6334** Read input from *in and process it.  If *in==0 then input
6335** is interactive - the user is typing it it.  Otherwise, input
6336** is coming from a file or device.  A prompt is issued and history
6337** is saved only if input is interactive.  An interrupt signal will
6338** cause this routine to exit immediately, unless input is interactive.
6339**
6340** Return the number of errors.
6341*/
6342static int process_input(ShellState *p, FILE *in){
6343  char *zLine = 0;          /* A single input line */
6344  char *zSql = 0;           /* Accumulated SQL text */
6345  int nLine;                /* Length of current line */
6346  int nSql = 0;             /* Bytes of zSql[] used */
6347  int nAlloc = 0;           /* Allocated zSql[] space */
6348  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
6349  int rc;                   /* Error code */
6350  int errCnt = 0;           /* Number of errors seen */
6351  int lineno = 0;           /* Current line number */
6352  int startline = 0;        /* Line number for start of current input */
6353
6354  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6355    fflush(p->out);
6356    zLine = one_input_line(in, zLine, nSql>0);
6357    if( zLine==0 ){
6358      /* End of input */
6359      if( in==0 && stdin_is_interactive ) printf("\n");
6360      break;
6361    }
6362    if( seenInterrupt ){
6363      if( in!=0 ) break;
6364      seenInterrupt = 0;
6365    }
6366    lineno++;
6367    if( nSql==0 && _all_whitespace(zLine) ){
6368      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6369      continue;
6370    }
6371    if( zLine && zLine[0]=='.' && nSql==0 ){
6372      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6373      rc = do_meta_command(zLine, p);
6374      if( rc==2 ){ /* exit requested */
6375        break;
6376      }else if( rc ){
6377        errCnt++;
6378      }
6379      continue;
6380    }
6381    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
6382      memcpy(zLine,";",2);
6383    }
6384    nLine = strlen30(zLine);
6385    if( nSql+nLine+2>=nAlloc ){
6386      nAlloc = nSql+nLine+100;
6387      zSql = realloc(zSql, nAlloc);
6388      if( zSql==0 ){
6389        raw_printf(stderr, "Error: out of memory\n");
6390        exit(1);
6391      }
6392    }
6393    nSqlPrior = nSql;
6394    if( nSql==0 ){
6395      int i;
6396      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
6397      assert( nAlloc>0 && zSql!=0 );
6398      memcpy(zSql, zLine+i, nLine+1-i);
6399      startline = lineno;
6400      nSql = nLine-i;
6401    }else{
6402      zSql[nSql++] = '\n';
6403      memcpy(zSql+nSql, zLine, nLine+1);
6404      nSql += nLine;
6405    }
6406    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
6407                && sqlite3_complete(zSql) ){
6408      errCnt += runOneSqlLine(p, zSql, in, startline);
6409      nSql = 0;
6410      if( p->outCount ){
6411        output_reset(p);
6412        p->outCount = 0;
6413      }
6414    }else if( nSql && _all_whitespace(zSql) ){
6415      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
6416      nSql = 0;
6417    }
6418  }
6419  if( nSql && !_all_whitespace(zSql) ){
6420    runOneSqlLine(p, zSql, in, startline);
6421  }
6422  free(zSql);
6423  free(zLine);
6424  return errCnt>0;
6425}
6426
6427/*
6428** Return a pathname which is the user's home directory.  A
6429** 0 return indicates an error of some kind.
6430*/
6431static char *find_home_dir(int clearFlag){
6432  static char *home_dir = NULL;
6433  if( clearFlag ){
6434    free(home_dir);
6435    home_dir = 0;
6436    return 0;
6437  }
6438  if( home_dir ) return home_dir;
6439
6440#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6441     && !defined(__RTP__) && !defined(_WRS_KERNEL)
6442  {
6443    struct passwd *pwent;
6444    uid_t uid = getuid();
6445    if( (pwent=getpwuid(uid)) != NULL) {
6446      home_dir = pwent->pw_dir;
6447    }
6448  }
6449#endif
6450
6451#if defined(_WIN32_WCE)
6452  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6453   */
6454  home_dir = "/";
6455#else
6456
6457#if defined(_WIN32) || defined(WIN32)
6458  if (!home_dir) {
6459    home_dir = getenv("USERPROFILE");
6460  }
6461#endif
6462
6463  if (!home_dir) {
6464    home_dir = getenv("HOME");
6465  }
6466
6467#if defined(_WIN32) || defined(WIN32)
6468  if (!home_dir) {
6469    char *zDrive, *zPath;
6470    int n;
6471    zDrive = getenv("HOMEDRIVE");
6472    zPath = getenv("HOMEPATH");
6473    if( zDrive && zPath ){
6474      n = strlen30(zDrive) + strlen30(zPath) + 1;
6475      home_dir = malloc( n );
6476      if( home_dir==0 ) return 0;
6477      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6478      return home_dir;
6479    }
6480    home_dir = "c:\\";
6481  }
6482#endif
6483
6484#endif /* !_WIN32_WCE */
6485
6486  if( home_dir ){
6487    int n = strlen30(home_dir) + 1;
6488    char *z = malloc( n );
6489    if( z ) memcpy(z, home_dir, n);
6490    home_dir = z;
6491  }
6492
6493  return home_dir;
6494}
6495
6496/*
6497** Read input from the file given by sqliterc_override.  Or if that
6498** parameter is NULL, take input from ~/.sqliterc
6499**
6500** Returns the number of errors.
6501*/
6502static void process_sqliterc(
6503  ShellState *p,                  /* Configuration data */
6504  const char *sqliterc_override   /* Name of config file. NULL to use default */
6505){
6506  char *home_dir = NULL;
6507  const char *sqliterc = sqliterc_override;
6508  char *zBuf = 0;
6509  FILE *in = NULL;
6510
6511  if (sqliterc == NULL) {
6512    home_dir = find_home_dir(0);
6513    if( home_dir==0 ){
6514      raw_printf(stderr, "-- warning: cannot find home directory;"
6515                      " cannot read ~/.sqliterc\n");
6516      return;
6517    }
6518    sqlite3_initialize();
6519    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6520    sqliterc = zBuf;
6521  }
6522  in = fopen(sqliterc,"rb");
6523  if( in ){
6524    if( stdin_is_interactive ){
6525      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
6526    }
6527    process_input(p,in);
6528    fclose(in);
6529  }
6530  sqlite3_free(zBuf);
6531}
6532
6533/*
6534** Show available command line options
6535*/
6536static const char zOptions[] =
6537  "   -ascii               set output mode to 'ascii'\n"
6538  "   -bail                stop after hitting an error\n"
6539  "   -batch               force batch I/O\n"
6540  "   -column              set output mode to 'column'\n"
6541  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
6542  "   -csv                 set output mode to 'csv'\n"
6543  "   -echo                print commands before execution\n"
6544  "   -init FILENAME       read/process named file\n"
6545  "   -[no]header          turn headers on or off\n"
6546#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6547  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
6548#endif
6549  "   -help                show this message\n"
6550  "   -html                set output mode to HTML\n"
6551  "   -interactive         force interactive I/O\n"
6552  "   -line                set output mode to 'line'\n"
6553  "   -list                set output mode to 'list'\n"
6554  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
6555  "   -mmap N              default mmap size set to N\n"
6556#ifdef SQLITE_ENABLE_MULTIPLEX
6557  "   -multiplex           enable the multiplexor VFS\n"
6558#endif
6559  "   -newline SEP         set output row separator. Default: '\\n'\n"
6560  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
6561  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
6562  "   -quote               set output mode to 'quote'\n"
6563  "   -scratch SIZE N      use N slots of SZ bytes each for scratch memory\n"
6564  "   -separator SEP       set output column separator. Default: '|'\n"
6565  "   -stats               print memory stats before each finalize\n"
6566  "   -version             show SQLite version\n"
6567  "   -vfs NAME            use NAME as the default VFS\n"
6568#ifdef SQLITE_ENABLE_VFSTRACE
6569  "   -vfstrace            enable tracing of all VFS calls\n"
6570#endif
6571;
6572static void usage(int showDetail){
6573  utf8_printf(stderr,
6574      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6575      "FILENAME is the name of an SQLite database. A new database is created\n"
6576      "if the file does not previously exist.\n", Argv0);
6577  if( showDetail ){
6578    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
6579  }else{
6580    raw_printf(stderr, "Use the -help option for additional information\n");
6581  }
6582  exit(1);
6583}
6584
6585/*
6586** Initialize the state information in data
6587*/
6588static void main_init(ShellState *data) {
6589  memset(data, 0, sizeof(*data));
6590  data->normalMode = data->cMode = data->mode = MODE_List;
6591  data->autoExplain = 1;
6592  memcpy(data->colSeparator,SEP_Column, 2);
6593  memcpy(data->rowSeparator,SEP_Row, 2);
6594  data->showHeader = 0;
6595  data->shellFlgs = SHFLG_Lookaside;
6596  sqlite3_config(SQLITE_CONFIG_URI, 1);
6597  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
6598  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
6599  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6600  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
6601}
6602
6603/*
6604** Output text to the console in a font that attracts extra attention.
6605*/
6606#ifdef _WIN32
6607static void printBold(const char *zText){
6608  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6609  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6610  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6611  SetConsoleTextAttribute(out,
6612         FOREGROUND_RED|FOREGROUND_INTENSITY
6613  );
6614  printf("%s", zText);
6615  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
6616}
6617#else
6618static void printBold(const char *zText){
6619  printf("\033[1m%s\033[0m", zText);
6620}
6621#endif
6622
6623/*
6624** Get the argument to an --option.  Throw an error and die if no argument
6625** is available.
6626*/
6627static char *cmdline_option_value(int argc, char **argv, int i){
6628  if( i==argc ){
6629    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
6630            argv[0], argv[argc-1]);
6631    exit(1);
6632  }
6633  return argv[i];
6634}
6635
6636#ifndef SQLITE_SHELL_IS_UTF8
6637#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6638#    define SQLITE_SHELL_IS_UTF8          (0)
6639#  else
6640#    define SQLITE_SHELL_IS_UTF8          (1)
6641#  endif
6642#endif
6643
6644#if SQLITE_SHELL_IS_UTF8
6645int SQLITE_CDECL main(int argc, char **argv){
6646#else
6647int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
6648  char **argv;
6649#endif
6650  char *zErrMsg = 0;
6651  ShellState data;
6652  const char *zInitFile = 0;
6653  int i;
6654  int rc = 0;
6655  int warnInmemoryDb = 0;
6656  int readStdin = 1;
6657  int nCmd = 0;
6658  char **azCmd = 0;
6659
6660  setBinaryMode(stdin, 0);
6661  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
6662  stdin_is_interactive = isatty(0);
6663  stdout_is_console = isatty(1);
6664
6665#if USE_SYSTEM_SQLITE+0!=1
6666  if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
6667    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
6668            sqlite3_sourceid(), SQLITE_SOURCE_ID);
6669    exit(1);
6670  }
6671#endif
6672  main_init(&data);
6673#if !SQLITE_SHELL_IS_UTF8
6674  sqlite3_initialize();
6675  argv = sqlite3_malloc64(sizeof(argv[0])*argc);
6676  if( argv==0 ){
6677    raw_printf(stderr, "out of memory\n");
6678    exit(1);
6679  }
6680  for(i=0; i<argc; i++){
6681    argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
6682    if( argv[i]==0 ){
6683      raw_printf(stderr, "out of memory\n");
6684      exit(1);
6685    }
6686  }
6687#endif
6688  assert( argc>=1 && argv && argv[0] );
6689  Argv0 = argv[0];
6690
6691  /* Make sure we have a valid signal handler early, before anything
6692  ** else is done.
6693  */
6694#ifdef SIGINT
6695  signal(SIGINT, interrupt_handler);
6696#endif
6697
6698#ifdef SQLITE_SHELL_DBNAME_PROC
6699  {
6700    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
6701    ** of a C-function that will provide the name of the database file.  Use
6702    ** this compile-time option to embed this shell program in larger
6703    ** applications. */
6704    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
6705    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
6706    warnInmemoryDb = 0;
6707  }
6708#endif
6709
6710  /* Do an initial pass through the command-line argument to locate
6711  ** the name of the database file, the name of the initialization file,
6712  ** the size of the alternative malloc heap,
6713  ** and the first command to execute.
6714  */
6715  for(i=1; i<argc; i++){
6716    char *z;
6717    z = argv[i];
6718    if( z[0]!='-' ){
6719      if( data.zDbFilename==0 ){
6720        data.zDbFilename = z;
6721      }else{
6722        /* Excesss arguments are interpreted as SQL (or dot-commands) and
6723        ** mean that nothing is read from stdin */
6724        readStdin = 0;
6725        nCmd++;
6726        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
6727        if( azCmd==0 ){
6728          raw_printf(stderr, "out of memory\n");
6729          exit(1);
6730        }
6731        azCmd[nCmd-1] = z;
6732      }
6733    }
6734    if( z[1]=='-' ) z++;
6735    if( strcmp(z,"-separator")==0
6736     || strcmp(z,"-nullvalue")==0
6737     || strcmp(z,"-newline")==0
6738     || strcmp(z,"-cmd")==0
6739    ){
6740      (void)cmdline_option_value(argc, argv, ++i);
6741    }else if( strcmp(z,"-init")==0 ){
6742      zInitFile = cmdline_option_value(argc, argv, ++i);
6743    }else if( strcmp(z,"-batch")==0 ){
6744      /* Need to check for batch mode here to so we can avoid printing
6745      ** informational messages (like from process_sqliterc) before
6746      ** we do the actual processing of arguments later in a second pass.
6747      */
6748      stdin_is_interactive = 0;
6749    }else if( strcmp(z,"-heap")==0 ){
6750#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6751      const char *zSize;
6752      sqlite3_int64 szHeap;
6753
6754      zSize = cmdline_option_value(argc, argv, ++i);
6755      szHeap = integerValue(zSize);
6756      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
6757      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
6758#else
6759      (void)cmdline_option_value(argc, argv, ++i);
6760#endif
6761    }else if( strcmp(z,"-scratch")==0 ){
6762      int n, sz;
6763      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6764      if( sz>400000 ) sz = 400000;
6765      if( sz<2500 ) sz = 2500;
6766      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6767      if( n>10 ) n = 10;
6768      if( n<1 ) n = 1;
6769      sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
6770      data.shellFlgs |= SHFLG_Scratch;
6771    }else if( strcmp(z,"-pagecache")==0 ){
6772      int n, sz;
6773      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6774      if( sz>70000 ) sz = 70000;
6775      if( sz<0 ) sz = 0;
6776      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6777      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
6778                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
6779      data.shellFlgs |= SHFLG_Pagecache;
6780    }else if( strcmp(z,"-lookaside")==0 ){
6781      int n, sz;
6782      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6783      if( sz<0 ) sz = 0;
6784      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6785      if( n<0 ) n = 0;
6786      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
6787      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
6788#ifdef SQLITE_ENABLE_VFSTRACE
6789    }else if( strcmp(z,"-vfstrace")==0 ){
6790      extern int vfstrace_register(
6791         const char *zTraceName,
6792         const char *zOldVfsName,
6793         int (*xOut)(const char*,void*),
6794         void *pOutArg,
6795         int makeDefault
6796      );
6797      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
6798#endif
6799#ifdef SQLITE_ENABLE_MULTIPLEX
6800    }else if( strcmp(z,"-multiplex")==0 ){
6801      extern int sqlite3_multiple_initialize(const char*,int);
6802      sqlite3_multiplex_initialize(0, 1);
6803#endif
6804    }else if( strcmp(z,"-mmap")==0 ){
6805      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
6806      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
6807    }else if( strcmp(z,"-vfs")==0 ){
6808      sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
6809      if( pVfs ){
6810        sqlite3_vfs_register(pVfs, 1);
6811      }else{
6812        utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
6813        exit(1);
6814      }
6815    }
6816  }
6817  if( data.zDbFilename==0 ){
6818#ifndef SQLITE_OMIT_MEMORYDB
6819    data.zDbFilename = ":memory:";
6820    warnInmemoryDb = argc==1;
6821#else
6822    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
6823    return 1;
6824#endif
6825  }
6826  data.out = stdout;
6827
6828  /* Go ahead and open the database file if it already exists.  If the
6829  ** file does not exist, delay opening it.  This prevents empty database
6830  ** files from being created if a user mistypes the database name argument
6831  ** to the sqlite command-line tool.
6832  */
6833  if( access(data.zDbFilename, 0)==0 ){
6834    open_db(&data, 0);
6835  }
6836
6837  /* Process the initialization file if there is one.  If no -init option
6838  ** is given on the command line, look for a file named ~/.sqliterc and
6839  ** try to process it.
6840  */
6841  process_sqliterc(&data,zInitFile);
6842
6843  /* Make a second pass through the command-line argument and set
6844  ** options.  This second pass is delayed until after the initialization
6845  ** file is processed so that the command-line arguments will override
6846  ** settings in the initialization file.
6847  */
6848  for(i=1; i<argc; i++){
6849    char *z = argv[i];
6850    if( z[0]!='-' ) continue;
6851    if( z[1]=='-' ){ z++; }
6852    if( strcmp(z,"-init")==0 ){
6853      i++;
6854    }else if( strcmp(z,"-html")==0 ){
6855      data.mode = MODE_Html;
6856    }else if( strcmp(z,"-list")==0 ){
6857      data.mode = MODE_List;
6858    }else if( strcmp(z,"-quote")==0 ){
6859      data.mode = MODE_Quote;
6860    }else if( strcmp(z,"-line")==0 ){
6861      data.mode = MODE_Line;
6862    }else if( strcmp(z,"-column")==0 ){
6863      data.mode = MODE_Column;
6864    }else if( strcmp(z,"-csv")==0 ){
6865      data.mode = MODE_Csv;
6866      memcpy(data.colSeparator,",",2);
6867    }else if( strcmp(z,"-ascii")==0 ){
6868      data.mode = MODE_Ascii;
6869      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6870                       SEP_Unit);
6871      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6872                       SEP_Record);
6873    }else if( strcmp(z,"-separator")==0 ){
6874      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6875                       "%s",cmdline_option_value(argc,argv,++i));
6876    }else if( strcmp(z,"-newline")==0 ){
6877      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6878                       "%s",cmdline_option_value(argc,argv,++i));
6879    }else if( strcmp(z,"-nullvalue")==0 ){
6880      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
6881                       "%s",cmdline_option_value(argc,argv,++i));
6882    }else if( strcmp(z,"-header")==0 ){
6883      data.showHeader = 1;
6884    }else if( strcmp(z,"-noheader")==0 ){
6885      data.showHeader = 0;
6886    }else if( strcmp(z,"-echo")==0 ){
6887      ShellSetFlag(&data, SHFLG_Echo);
6888    }else if( strcmp(z,"-eqp")==0 ){
6889      data.autoEQP = 1;
6890    }else if( strcmp(z,"-eqpfull")==0 ){
6891      data.autoEQP = 2;
6892    }else if( strcmp(z,"-stats")==0 ){
6893      data.statsOn = 1;
6894    }else if( strcmp(z,"-scanstats")==0 ){
6895      data.scanstatsOn = 1;
6896    }else if( strcmp(z,"-backslash")==0 ){
6897      /* Undocumented command-line option: -backslash
6898      ** Causes C-style backslash escapes to be evaluated in SQL statements
6899      ** prior to sending the SQL into SQLite.  Useful for injecting
6900      ** crazy bytes in the middle of SQL statements for testing and debugging.
6901      */
6902      ShellSetFlag(&data, SHFLG_Backslash);
6903    }else if( strcmp(z,"-bail")==0 ){
6904      bail_on_error = 1;
6905    }else if( strcmp(z,"-version")==0 ){
6906      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
6907      return 0;
6908    }else if( strcmp(z,"-interactive")==0 ){
6909      stdin_is_interactive = 1;
6910    }else if( strcmp(z,"-batch")==0 ){
6911      stdin_is_interactive = 0;
6912    }else if( strcmp(z,"-heap")==0 ){
6913      i++;
6914    }else if( strcmp(z,"-scratch")==0 ){
6915      i+=2;
6916    }else if( strcmp(z,"-pagecache")==0 ){
6917      i+=2;
6918    }else if( strcmp(z,"-lookaside")==0 ){
6919      i+=2;
6920    }else if( strcmp(z,"-mmap")==0 ){
6921      i++;
6922    }else if( strcmp(z,"-vfs")==0 ){
6923      i++;
6924#ifdef SQLITE_ENABLE_VFSTRACE
6925    }else if( strcmp(z,"-vfstrace")==0 ){
6926      i++;
6927#endif
6928#ifdef SQLITE_ENABLE_MULTIPLEX
6929    }else if( strcmp(z,"-multiplex")==0 ){
6930      i++;
6931#endif
6932    }else if( strcmp(z,"-help")==0 ){
6933      usage(1);
6934    }else if( strcmp(z,"-cmd")==0 ){
6935      /* Run commands that follow -cmd first and separately from commands
6936      ** that simply appear on the command-line.  This seems goofy.  It would
6937      ** be better if all commands ran in the order that they appear.  But
6938      ** we retain the goofy behavior for historical compatibility. */
6939      if( i==argc-1 ) break;
6940      z = cmdline_option_value(argc,argv,++i);
6941      if( z[0]=='.' ){
6942        rc = do_meta_command(z, &data);
6943        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
6944      }else{
6945        open_db(&data, 0);
6946        rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
6947        if( zErrMsg!=0 ){
6948          utf8_printf(stderr,"Error: %s\n", zErrMsg);
6949          if( bail_on_error ) return rc!=0 ? rc : 1;
6950        }else if( rc!=0 ){
6951          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
6952          if( bail_on_error ) return rc;
6953        }
6954      }
6955    }else{
6956      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
6957      raw_printf(stderr,"Use -help for a list of options.\n");
6958      return 1;
6959    }
6960    data.cMode = data.mode;
6961  }
6962
6963  if( !readStdin ){
6964    /* Run all arguments that do not begin with '-' as if they were separate
6965    ** command-line inputs, except for the argToSkip argument which contains
6966    ** the database filename.
6967    */
6968    for(i=0; i<nCmd; i++){
6969      if( azCmd[i][0]=='.' ){
6970        rc = do_meta_command(azCmd[i], &data);
6971        if( rc ) return rc==2 ? 0 : rc;
6972      }else{
6973        open_db(&data, 0);
6974        rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
6975        if( zErrMsg!=0 ){
6976          utf8_printf(stderr,"Error: %s\n", zErrMsg);
6977          return rc!=0 ? rc : 1;
6978        }else if( rc!=0 ){
6979          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
6980          return rc;
6981        }
6982      }
6983    }
6984    free(azCmd);
6985  }else{
6986    /* Run commands received from standard input
6987    */
6988    if( stdin_is_interactive ){
6989      char *zHome;
6990      char *zHistory = 0;
6991      int nHistory;
6992      printf(
6993        "SQLite version %s %.19s\n" /*extra-version-info*/
6994        "Enter \".help\" for usage hints.\n",
6995        sqlite3_libversion(), sqlite3_sourceid()
6996      );
6997      if( warnInmemoryDb ){
6998        printf("Connected to a ");
6999        printBold("transient in-memory database");
7000        printf(".\nUse \".open FILENAME\" to reopen on a "
7001               "persistent database.\n");
7002      }
7003      zHome = find_home_dir(0);
7004      if( zHome ){
7005        nHistory = strlen30(zHome) + 20;
7006        if( (zHistory = malloc(nHistory))!=0 ){
7007          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7008        }
7009      }
7010      if( zHistory ){ shell_read_history(zHistory); }
7011#if HAVE_READLINE || HAVE_EDITLINE
7012      rl_attempted_completion_function = readline_completion;
7013#elif HAVE_LINENOISE
7014      linenoiseSetCompletionCallback(linenoise_completion);
7015#endif
7016      rc = process_input(&data, 0);
7017      if( zHistory ){
7018        shell_stifle_history(100);
7019        shell_write_history(zHistory);
7020        free(zHistory);
7021      }
7022    }else{
7023      rc = process_input(&data, stdin);
7024    }
7025  }
7026  set_table_name(&data, 0);
7027  if( data.db ){
7028    session_close_all(&data);
7029    sqlite3_close(data.db);
7030  }
7031  sqlite3_free(data.zFreeOnClose);
7032  find_home_dir(1);
7033#if !SQLITE_SHELL_IS_UTF8
7034  for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7035  sqlite3_free(argv);
7036#endif
7037  return rc;
7038}
7039