xref: /sqlite-3.40.0/src/shell.c.in (revision ba334bb2)
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<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)
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    int rc;
2910    sqlite3_finalize(pStmt);
2911    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2912                           "  FROM completion(%Q) ORDER BY 1", text);
2913    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
2914    sqlite3_free(zSql);
2915  }
2916  if( sqlite3_step(pStmt)==SQLITE_ROW ){
2917    zRet = strdup(sqlite3_column_text(pStmt, 0));
2918  }else{
2919    sqlite3_finalize(pStmt);
2920    pStmt = 0;
2921    zRet = 0;
2922  }
2923  return zRet;
2924}
2925static char **readline_completion(const char *zText, int iStart, int iEnd){
2926  rl_attempted_completion_over = 1;
2927  return rl_completion_matches(zText, readline_completion_generator);
2928}
2929
2930#elif HAVE_LINENOISE
2931/*
2932** Linenoise completion callback
2933*/
2934static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
2935  int nLine = (int)strlen(zLine);
2936  int i, iStart;
2937  sqlite3_stmt *pStmt = 0;
2938  char *zSql;
2939  char zBuf[1000];
2940
2941  if( nLine>sizeof(zBuf)-30 ) return;
2942  if( zLine[0]=='.' ) return;
2943  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
2944  if( i==nLine-1 ) return;
2945  iStart = i+1;
2946  memcpy(zBuf, zLine, iStart);
2947  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
2948                         "  FROM completion(%Q,%Q) ORDER BY 1",
2949                         &zLine[iStart], zLine);
2950  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
2951  sqlite3_free(zSql);
2952  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
2953  while( sqlite3_step(pStmt)==SQLITE_ROW ){
2954    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
2955    int nCompletion = sqlite3_column_bytes(pStmt, 0);
2956    if( iStart+nCompletion < sizeof(zBuf)-1 ){
2957      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
2958      linenoiseAddCompletion(lc, zBuf);
2959    }
2960  }
2961  sqlite3_finalize(pStmt);
2962}
2963#endif
2964
2965/*
2966** Do C-language style dequoting.
2967**
2968**    \a    -> alarm
2969**    \b    -> backspace
2970**    \t    -> tab
2971**    \n    -> newline
2972**    \v    -> vertical tab
2973**    \f    -> form feed
2974**    \r    -> carriage return
2975**    \s    -> space
2976**    \"    -> "
2977**    \'    -> '
2978**    \\    -> backslash
2979**    \NNN  -> ascii character NNN in octal
2980*/
2981static void resolve_backslashes(char *z){
2982  int i, j;
2983  char c;
2984  while( *z && *z!='\\' ) z++;
2985  for(i=j=0; (c = z[i])!=0; i++, j++){
2986    if( c=='\\' && z[i+1]!=0 ){
2987      c = z[++i];
2988      if( c=='a' ){
2989        c = '\a';
2990      }else if( c=='b' ){
2991        c = '\b';
2992      }else if( c=='t' ){
2993        c = '\t';
2994      }else if( c=='n' ){
2995        c = '\n';
2996      }else if( c=='v' ){
2997        c = '\v';
2998      }else if( c=='f' ){
2999        c = '\f';
3000      }else if( c=='r' ){
3001        c = '\r';
3002      }else if( c=='"' ){
3003        c = '"';
3004      }else if( c=='\'' ){
3005        c = '\'';
3006      }else if( c=='\\' ){
3007        c = '\\';
3008      }else if( c>='0' && c<='7' ){
3009        c -= '0';
3010        if( z[i+1]>='0' && z[i+1]<='7' ){
3011          i++;
3012          c = (c<<3) + z[i] - '0';
3013          if( z[i+1]>='0' && z[i+1]<='7' ){
3014            i++;
3015            c = (c<<3) + z[i] - '0';
3016          }
3017        }
3018      }
3019    }
3020    z[j] = c;
3021  }
3022  if( j<i ) z[j] = 0;
3023}
3024
3025/*
3026** Return the value of a hexadecimal digit.  Return -1 if the input
3027** is not a hex digit.
3028*/
3029static int hexDigitValue(char c){
3030  if( c>='0' && c<='9' ) return c - '0';
3031  if( c>='a' && c<='f' ) return c - 'a' + 10;
3032  if( c>='A' && c<='F' ) return c - 'A' + 10;
3033  return -1;
3034}
3035
3036/*
3037** Interpret zArg as an integer value, possibly with suffixes.
3038*/
3039static sqlite3_int64 integerValue(const char *zArg){
3040  sqlite3_int64 v = 0;
3041  static const struct { char *zSuffix; int iMult; } aMult[] = {
3042    { "KiB", 1024 },
3043    { "MiB", 1024*1024 },
3044    { "GiB", 1024*1024*1024 },
3045    { "KB",  1000 },
3046    { "MB",  1000000 },
3047    { "GB",  1000000000 },
3048    { "K",   1000 },
3049    { "M",   1000000 },
3050    { "G",   1000000000 },
3051  };
3052  int i;
3053  int isNeg = 0;
3054  if( zArg[0]=='-' ){
3055    isNeg = 1;
3056    zArg++;
3057  }else if( zArg[0]=='+' ){
3058    zArg++;
3059  }
3060  if( zArg[0]=='0' && zArg[1]=='x' ){
3061    int x;
3062    zArg += 2;
3063    while( (x = hexDigitValue(zArg[0]))>=0 ){
3064      v = (v<<4) + x;
3065      zArg++;
3066    }
3067  }else{
3068    while( IsDigit(zArg[0]) ){
3069      v = v*10 + zArg[0] - '0';
3070      zArg++;
3071    }
3072  }
3073  for(i=0; i<ArraySize(aMult); i++){
3074    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3075      v *= aMult[i].iMult;
3076      break;
3077    }
3078  }
3079  return isNeg? -v : v;
3080}
3081
3082/*
3083** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
3084** for TRUE and FALSE.  Return the integer value if appropriate.
3085*/
3086static int booleanValue(const char *zArg){
3087  int i;
3088  if( zArg[0]=='0' && zArg[1]=='x' ){
3089    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3090  }else{
3091    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3092  }
3093  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3094  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3095    return 1;
3096  }
3097  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3098    return 0;
3099  }
3100  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3101          zArg);
3102  return 0;
3103}
3104
3105/*
3106** Set or clear a shell flag according to a boolean value.
3107*/
3108static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3109  if( booleanValue(zArg) ){
3110    ShellSetFlag(p, mFlag);
3111  }else{
3112    ShellClearFlag(p, mFlag);
3113  }
3114}
3115
3116/*
3117** Close an output file, assuming it is not stderr or stdout
3118*/
3119static void output_file_close(FILE *f){
3120  if( f && f!=stdout && f!=stderr ) fclose(f);
3121}
3122
3123/*
3124** Try to open an output file.   The names "stdout" and "stderr" are
3125** recognized and do the right thing.  NULL is returned if the output
3126** filename is "off".
3127*/
3128static FILE *output_file_open(const char *zFile){
3129  FILE *f;
3130  if( strcmp(zFile,"stdout")==0 ){
3131    f = stdout;
3132  }else if( strcmp(zFile, "stderr")==0 ){
3133    f = stderr;
3134  }else if( strcmp(zFile, "off")==0 ){
3135    f = 0;
3136  }else{
3137    f = fopen(zFile, "wb");
3138    if( f==0 ){
3139      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3140    }
3141  }
3142  return f;
3143}
3144
3145#if !defined(SQLITE_UNTESTABLE)
3146#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3147/*
3148** A routine for handling output from sqlite3_trace().
3149*/
3150static int sql_trace_callback(
3151  unsigned mType,
3152  void *pArg,
3153  void *pP,
3154  void *pX
3155){
3156  FILE *f = (FILE*)pArg;
3157  UNUSED_PARAMETER(mType);
3158  UNUSED_PARAMETER(pP);
3159  if( f ){
3160    const char *z = (const char*)pX;
3161    int i = (int)strlen(z);
3162    while( i>0 && z[i-1]==';' ){ i--; }
3163    utf8_printf(f, "%.*s;\n", i, z);
3164  }
3165  return 0;
3166}
3167#endif
3168#endif
3169
3170/*
3171** A no-op routine that runs with the ".breakpoint" doc-command.  This is
3172** a useful spot to set a debugger breakpoint.
3173*/
3174static void test_breakpoint(void){
3175  static int nCall = 0;
3176  nCall++;
3177}
3178
3179/*
3180** An object used to read a CSV and other files for import.
3181*/
3182typedef struct ImportCtx ImportCtx;
3183struct ImportCtx {
3184  const char *zFile;  /* Name of the input file */
3185  FILE *in;           /* Read the CSV text from this input stream */
3186  char *z;            /* Accumulated text for a field */
3187  int n;              /* Number of bytes in z */
3188  int nAlloc;         /* Space allocated for z[] */
3189  int nLine;          /* Current line number */
3190  int bNotFirst;      /* True if one or more bytes already read */
3191  int cTerm;          /* Character that terminated the most recent field */
3192  int cColSep;        /* The column separator character.  (Usually ",") */
3193  int cRowSep;        /* The row separator character.  (Usually "\n") */
3194};
3195
3196/* Append a single byte to z[] */
3197static void import_append_char(ImportCtx *p, int c){
3198  if( p->n+1>=p->nAlloc ){
3199    p->nAlloc += p->nAlloc + 100;
3200    p->z = sqlite3_realloc64(p->z, p->nAlloc);
3201    if( p->z==0 ){
3202      raw_printf(stderr, "out of memory\n");
3203      exit(1);
3204    }
3205  }
3206  p->z[p->n++] = (char)c;
3207}
3208
3209/* Read a single field of CSV text.  Compatible with rfc4180 and extended
3210** with the option of having a separator other than ",".
3211**
3212**   +  Input comes from p->in.
3213**   +  Store results in p->z of length p->n.  Space to hold p->z comes
3214**      from sqlite3_malloc64().
3215**   +  Use p->cSep as the column separator.  The default is ",".
3216**   +  Use p->rSep as the row separator.  The default is "\n".
3217**   +  Keep track of the line number in p->nLine.
3218**   +  Store the character that terminates the field in p->cTerm.  Store
3219**      EOF on end-of-file.
3220**   +  Report syntax errors on stderr
3221*/
3222static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3223  int c;
3224  int cSep = p->cColSep;
3225  int rSep = p->cRowSep;
3226  p->n = 0;
3227  c = fgetc(p->in);
3228  if( c==EOF || seenInterrupt ){
3229    p->cTerm = EOF;
3230    return 0;
3231  }
3232  if( c=='"' ){
3233    int pc, ppc;
3234    int startLine = p->nLine;
3235    int cQuote = c;
3236    pc = ppc = 0;
3237    while( 1 ){
3238      c = fgetc(p->in);
3239      if( c==rSep ) p->nLine++;
3240      if( c==cQuote ){
3241        if( pc==cQuote ){
3242          pc = 0;
3243          continue;
3244        }
3245      }
3246      if( (c==cSep && pc==cQuote)
3247       || (c==rSep && pc==cQuote)
3248       || (c==rSep && pc=='\r' && ppc==cQuote)
3249       || (c==EOF && pc==cQuote)
3250      ){
3251        do{ p->n--; }while( p->z[p->n]!=cQuote );
3252        p->cTerm = c;
3253        break;
3254      }
3255      if( pc==cQuote && c!='\r' ){
3256        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3257                p->zFile, p->nLine, cQuote);
3258      }
3259      if( c==EOF ){
3260        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3261                p->zFile, startLine, cQuote);
3262        p->cTerm = c;
3263        break;
3264      }
3265      import_append_char(p, c);
3266      ppc = pc;
3267      pc = c;
3268    }
3269  }else{
3270    /* If this is the first field being parsed and it begins with the
3271    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
3272    if( (c&0xff)==0xef && p->bNotFirst==0 ){
3273      import_append_char(p, c);
3274      c = fgetc(p->in);
3275      if( (c&0xff)==0xbb ){
3276        import_append_char(p, c);
3277        c = fgetc(p->in);
3278        if( (c&0xff)==0xbf ){
3279          p->bNotFirst = 1;
3280          p->n = 0;
3281          return csv_read_one_field(p);
3282        }
3283      }
3284    }
3285    while( c!=EOF && c!=cSep && c!=rSep ){
3286      import_append_char(p, c);
3287      c = fgetc(p->in);
3288    }
3289    if( c==rSep ){
3290      p->nLine++;
3291      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3292    }
3293    p->cTerm = c;
3294  }
3295  if( p->z ) p->z[p->n] = 0;
3296  p->bNotFirst = 1;
3297  return p->z;
3298}
3299
3300/* Read a single field of ASCII delimited text.
3301**
3302**   +  Input comes from p->in.
3303**   +  Store results in p->z of length p->n.  Space to hold p->z comes
3304**      from sqlite3_malloc64().
3305**   +  Use p->cSep as the column separator.  The default is "\x1F".
3306**   +  Use p->rSep as the row separator.  The default is "\x1E".
3307**   +  Keep track of the row number in p->nLine.
3308**   +  Store the character that terminates the field in p->cTerm.  Store
3309**      EOF on end-of-file.
3310**   +  Report syntax errors on stderr
3311*/
3312static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3313  int c;
3314  int cSep = p->cColSep;
3315  int rSep = p->cRowSep;
3316  p->n = 0;
3317  c = fgetc(p->in);
3318  if( c==EOF || seenInterrupt ){
3319    p->cTerm = EOF;
3320    return 0;
3321  }
3322  while( c!=EOF && c!=cSep && c!=rSep ){
3323    import_append_char(p, c);
3324    c = fgetc(p->in);
3325  }
3326  if( c==rSep ){
3327    p->nLine++;
3328  }
3329  p->cTerm = c;
3330  if( p->z ) p->z[p->n] = 0;
3331  return p->z;
3332}
3333
3334/*
3335** Try to transfer data for table zTable.  If an error is seen while
3336** moving forward, try to go backwards.  The backwards movement won't
3337** work for WITHOUT ROWID tables.
3338*/
3339static void tryToCloneData(
3340  ShellState *p,
3341  sqlite3 *newDb,
3342  const char *zTable
3343){
3344  sqlite3_stmt *pQuery = 0;
3345  sqlite3_stmt *pInsert = 0;
3346  char *zQuery = 0;
3347  char *zInsert = 0;
3348  int rc;
3349  int i, j, n;
3350  int nTable = (int)strlen(zTable);
3351  int k = 0;
3352  int cnt = 0;
3353  const int spinRate = 10000;
3354
3355  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3356  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3357  if( rc ){
3358    utf8_printf(stderr, "Error %d: %s on [%s]\n",
3359            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3360            zQuery);
3361    goto end_data_xfer;
3362  }
3363  n = sqlite3_column_count(pQuery);
3364  zInsert = sqlite3_malloc64(200 + nTable + n*3);
3365  if( zInsert==0 ){
3366    raw_printf(stderr, "out of memory\n");
3367    goto end_data_xfer;
3368  }
3369  sqlite3_snprintf(200+nTable,zInsert,
3370                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3371  i = (int)strlen(zInsert);
3372  for(j=1; j<n; j++){
3373    memcpy(zInsert+i, ",?", 2);
3374    i += 2;
3375  }
3376  memcpy(zInsert+i, ");", 3);
3377  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3378  if( rc ){
3379    utf8_printf(stderr, "Error %d: %s on [%s]\n",
3380            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3381            zQuery);
3382    goto end_data_xfer;
3383  }
3384  for(k=0; k<2; k++){
3385    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3386      for(i=0; i<n; i++){
3387        switch( sqlite3_column_type(pQuery, i) ){
3388          case SQLITE_NULL: {
3389            sqlite3_bind_null(pInsert, i+1);
3390            break;
3391          }
3392          case SQLITE_INTEGER: {
3393            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3394            break;
3395          }
3396          case SQLITE_FLOAT: {
3397            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3398            break;
3399          }
3400          case SQLITE_TEXT: {
3401            sqlite3_bind_text(pInsert, i+1,
3402                             (const char*)sqlite3_column_text(pQuery,i),
3403                             -1, SQLITE_STATIC);
3404            break;
3405          }
3406          case SQLITE_BLOB: {
3407            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3408                                            sqlite3_column_bytes(pQuery,i),
3409                                            SQLITE_STATIC);
3410            break;
3411          }
3412        }
3413      } /* End for */
3414      rc = sqlite3_step(pInsert);
3415      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3416        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3417                        sqlite3_errmsg(newDb));
3418      }
3419      sqlite3_reset(pInsert);
3420      cnt++;
3421      if( (cnt%spinRate)==0 ){
3422        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3423        fflush(stdout);
3424      }
3425    } /* End while */
3426    if( rc==SQLITE_DONE ) break;
3427    sqlite3_finalize(pQuery);
3428    sqlite3_free(zQuery);
3429    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3430                             zTable);
3431    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3432    if( rc ){
3433      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3434      break;
3435    }
3436  } /* End for(k=0...) */
3437
3438end_data_xfer:
3439  sqlite3_finalize(pQuery);
3440  sqlite3_finalize(pInsert);
3441  sqlite3_free(zQuery);
3442  sqlite3_free(zInsert);
3443}
3444
3445
3446/*
3447** Try to transfer all rows of the schema that match zWhere.  For
3448** each row, invoke xForEach() on the object defined by that row.
3449** If an error is encountered while moving forward through the
3450** sqlite_master table, try again moving backwards.
3451*/
3452static void tryToCloneSchema(
3453  ShellState *p,
3454  sqlite3 *newDb,
3455  const char *zWhere,
3456  void (*xForEach)(ShellState*,sqlite3*,const char*)
3457){
3458  sqlite3_stmt *pQuery = 0;
3459  char *zQuery = 0;
3460  int rc;
3461  const unsigned char *zName;
3462  const unsigned char *zSql;
3463  char *zErrMsg = 0;
3464
3465  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3466                           " WHERE %s", zWhere);
3467  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3468  if( rc ){
3469    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3470                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3471                    zQuery);
3472    goto end_schema_xfer;
3473  }
3474  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3475    zName = sqlite3_column_text(pQuery, 0);
3476    zSql = sqlite3_column_text(pQuery, 1);
3477    printf("%s... ", zName); fflush(stdout);
3478    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3479    if( zErrMsg ){
3480      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3481      sqlite3_free(zErrMsg);
3482      zErrMsg = 0;
3483    }
3484    if( xForEach ){
3485      xForEach(p, newDb, (const char*)zName);
3486    }
3487    printf("done\n");
3488  }
3489  if( rc!=SQLITE_DONE ){
3490    sqlite3_finalize(pQuery);
3491    sqlite3_free(zQuery);
3492    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3493                             " WHERE %s ORDER BY rowid DESC", zWhere);
3494    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3495    if( rc ){
3496      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3497                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3498                      zQuery);
3499      goto end_schema_xfer;
3500    }
3501    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3502      zName = sqlite3_column_text(pQuery, 0);
3503      zSql = sqlite3_column_text(pQuery, 1);
3504      printf("%s... ", zName); fflush(stdout);
3505      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3506      if( zErrMsg ){
3507        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3508        sqlite3_free(zErrMsg);
3509        zErrMsg = 0;
3510      }
3511      if( xForEach ){
3512        xForEach(p, newDb, (const char*)zName);
3513      }
3514      printf("done\n");
3515    }
3516  }
3517end_schema_xfer:
3518  sqlite3_finalize(pQuery);
3519  sqlite3_free(zQuery);
3520}
3521
3522/*
3523** Open a new database file named "zNewDb".  Try to recover as much information
3524** as possible out of the main database (which might be corrupt) and write it
3525** into zNewDb.
3526*/
3527static void tryToClone(ShellState *p, const char *zNewDb){
3528  int rc;
3529  sqlite3 *newDb = 0;
3530  if( access(zNewDb,0)==0 ){
3531    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3532    return;
3533  }
3534  rc = sqlite3_open(zNewDb, &newDb);
3535  if( rc ){
3536    utf8_printf(stderr, "Cannot create output database: %s\n",
3537            sqlite3_errmsg(newDb));
3538  }else{
3539    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3540    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3541    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3542    tryToCloneSchema(p, newDb, "type!='table'", 0);
3543    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3544    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3545  }
3546  sqlite3_close(newDb);
3547}
3548
3549/*
3550** Change the output file back to stdout
3551*/
3552static void output_reset(ShellState *p){
3553  if( p->outfile[0]=='|' ){
3554#ifndef SQLITE_OMIT_POPEN
3555    pclose(p->out);
3556#endif
3557  }else{
3558    output_file_close(p->out);
3559  }
3560  p->outfile[0] = 0;
3561  p->out = stdout;
3562}
3563
3564/*
3565** Run an SQL command and return the single integer result.
3566*/
3567static int db_int(ShellState *p, const char *zSql){
3568  sqlite3_stmt *pStmt;
3569  int res = 0;
3570  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3571  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3572    res = sqlite3_column_int(pStmt,0);
3573  }
3574  sqlite3_finalize(pStmt);
3575  return res;
3576}
3577
3578/*
3579** Convert a 2-byte or 4-byte big-endian integer into a native integer
3580*/
3581static unsigned int get2byteInt(unsigned char *a){
3582  return (a[0]<<8) + a[1];
3583}
3584static unsigned int get4byteInt(unsigned char *a){
3585  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3586}
3587
3588/*
3589** Implementation of the ".info" command.
3590**
3591** Return 1 on error, 2 to exit, and 0 otherwise.
3592*/
3593static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3594  static const struct { const char *zName; int ofst; } aField[] = {
3595     { "file change counter:",  24  },
3596     { "database page count:",  28  },
3597     { "freelist page count:",  36  },
3598     { "schema cookie:",        40  },
3599     { "schema format:",        44  },
3600     { "default cache size:",   48  },
3601     { "autovacuum top root:",  52  },
3602     { "incremental vacuum:",   64  },
3603     { "text encoding:",        56  },
3604     { "user version:",         60  },
3605     { "application id:",       68  },
3606     { "software version:",     96  },
3607  };
3608  static const struct { const char *zName; const char *zSql; } aQuery[] = {
3609     { "number of tables:",
3610       "SELECT count(*) FROM %s WHERE type='table'" },
3611     { "number of indexes:",
3612       "SELECT count(*) FROM %s WHERE type='index'" },
3613     { "number of triggers:",
3614       "SELECT count(*) FROM %s WHERE type='trigger'" },
3615     { "number of views:",
3616       "SELECT count(*) FROM %s WHERE type='view'" },
3617     { "schema size:",
3618       "SELECT total(length(sql)) FROM %s" },
3619  };
3620  sqlite3_file *pFile = 0;
3621  int i;
3622  char *zSchemaTab;
3623  char *zDb = nArg>=2 ? azArg[1] : "main";
3624  unsigned char aHdr[100];
3625  open_db(p, 0);
3626  if( p->db==0 ) return 1;
3627  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
3628  if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
3629    return 1;
3630  }
3631  i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
3632  if( i!=SQLITE_OK ){
3633    raw_printf(stderr, "unable to read database header\n");
3634    return 1;
3635  }
3636  i = get2byteInt(aHdr+16);
3637  if( i==1 ) i = 65536;
3638  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3639  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3640  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3641  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3642  for(i=0; i<ArraySize(aField); i++){
3643    int ofst = aField[i].ofst;
3644    unsigned int val = get4byteInt(aHdr + ofst);
3645    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3646    switch( ofst ){
3647      case 56: {
3648        if( val==1 ) raw_printf(p->out, " (utf8)");
3649        if( val==2 ) raw_printf(p->out, " (utf16le)");
3650        if( val==3 ) raw_printf(p->out, " (utf16be)");
3651      }
3652    }
3653    raw_printf(p->out, "\n");
3654  }
3655  if( zDb==0 ){
3656    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3657  }else if( strcmp(zDb,"temp")==0 ){
3658    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3659  }else{
3660    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3661  }
3662  for(i=0; i<ArraySize(aQuery); i++){
3663    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3664    int val = db_int(p, zSql);
3665    sqlite3_free(zSql);
3666    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3667  }
3668  sqlite3_free(zSchemaTab);
3669  return 0;
3670}
3671
3672/*
3673** Print the current sqlite3_errmsg() value to stderr and return 1.
3674*/
3675static int shellDatabaseError(sqlite3 *db){
3676  const char *zErr = sqlite3_errmsg(db);
3677  utf8_printf(stderr, "Error: %s\n", zErr);
3678  return 1;
3679}
3680
3681/*
3682** Print an out-of-memory message to stderr and return 1.
3683*/
3684static int shellNomemError(void){
3685  raw_printf(stderr, "Error: out of memory\n");
3686  return 1;
3687}
3688
3689/*
3690** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
3691** if they match and FALSE (0) if they do not match.
3692**
3693** Globbing rules:
3694**
3695**      '*'       Matches any sequence of zero or more characters.
3696**
3697**      '?'       Matches exactly one character.
3698**
3699**     [...]      Matches one character from the enclosed list of
3700**                characters.
3701**
3702**     [^...]     Matches one character not in the enclosed list.
3703**
3704**      '#'       Matches any sequence of one or more digits with an
3705**                optional + or - sign in front
3706**
3707**      ' '       Any span of whitespace matches any other span of
3708**                whitespace.
3709**
3710** Extra whitespace at the end of z[] is ignored.
3711*/
3712static int testcase_glob(const char *zGlob, const char *z){
3713  int c, c2;
3714  int invert;
3715  int seen;
3716
3717  while( (c = (*(zGlob++)))!=0 ){
3718    if( IsSpace(c) ){
3719      if( !IsSpace(*z) ) return 0;
3720      while( IsSpace(*zGlob) ) zGlob++;
3721      while( IsSpace(*z) ) z++;
3722    }else if( c=='*' ){
3723      while( (c=(*(zGlob++))) == '*' || c=='?' ){
3724        if( c=='?' && (*(z++))==0 ) return 0;
3725      }
3726      if( c==0 ){
3727        return 1;
3728      }else if( c=='[' ){
3729        while( *z && testcase_glob(zGlob-1,z)==0 ){
3730          z++;
3731        }
3732        return (*z)!=0;
3733      }
3734      while( (c2 = (*(z++)))!=0 ){
3735        while( c2!=c ){
3736          c2 = *(z++);
3737          if( c2==0 ) return 0;
3738        }
3739        if( testcase_glob(zGlob,z) ) return 1;
3740      }
3741      return 0;
3742    }else if( c=='?' ){
3743      if( (*(z++))==0 ) return 0;
3744    }else if( c=='[' ){
3745      int prior_c = 0;
3746      seen = 0;
3747      invert = 0;
3748      c = *(z++);
3749      if( c==0 ) return 0;
3750      c2 = *(zGlob++);
3751      if( c2=='^' ){
3752        invert = 1;
3753        c2 = *(zGlob++);
3754      }
3755      if( c2==']' ){
3756        if( c==']' ) seen = 1;
3757        c2 = *(zGlob++);
3758      }
3759      while( c2 && c2!=']' ){
3760        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3761          c2 = *(zGlob++);
3762          if( c>=prior_c && c<=c2 ) seen = 1;
3763          prior_c = 0;
3764        }else{
3765          if( c==c2 ){
3766            seen = 1;
3767          }
3768          prior_c = c2;
3769        }
3770        c2 = *(zGlob++);
3771      }
3772      if( c2==0 || (seen ^ invert)==0 ) return 0;
3773    }else if( c=='#' ){
3774      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3775      if( !IsDigit(z[0]) ) return 0;
3776      z++;
3777      while( IsDigit(z[0]) ){ z++; }
3778    }else{
3779      if( c!=(*(z++)) ) return 0;
3780    }
3781  }
3782  while( IsSpace(*z) ){ z++; }
3783  return *z==0;
3784}
3785
3786
3787/*
3788** Compare the string as a command-line option with either one or two
3789** initial "-" characters.
3790*/
3791static int optionMatch(const char *zStr, const char *zOpt){
3792  if( zStr[0]!='-' ) return 0;
3793  zStr++;
3794  if( zStr[0]=='-' ) zStr++;
3795  return strcmp(zStr, zOpt)==0;
3796}
3797
3798/*
3799** Delete a file.
3800*/
3801int shellDeleteFile(const char *zFilename){
3802  int rc;
3803#ifdef _WIN32
3804  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
3805  rc = _wunlink(z);
3806  sqlite3_free(z);
3807#else
3808  rc = unlink(zFilename);
3809#endif
3810  return rc;
3811}
3812
3813
3814/*
3815** The implementation of SQL scalar function fkey_collate_clause(), used
3816** by the ".lint fkey-indexes" command. This scalar function is always
3817** called with four arguments - the parent table name, the parent column name,
3818** the child table name and the child column name.
3819**
3820**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
3821**
3822** If either of the named tables or columns do not exist, this function
3823** returns an empty string. An empty string is also returned if both tables
3824** and columns exist but have the same default collation sequence. Or,
3825** if both exist but the default collation sequences are different, this
3826** function returns the string " COLLATE <parent-collation>", where
3827** <parent-collation> is the default collation sequence of the parent column.
3828*/
3829static void shellFkeyCollateClause(
3830  sqlite3_context *pCtx,
3831  int nVal,
3832  sqlite3_value **apVal
3833){
3834  sqlite3 *db = sqlite3_context_db_handle(pCtx);
3835  const char *zParent;
3836  const char *zParentCol;
3837  const char *zParentSeq;
3838  const char *zChild;
3839  const char *zChildCol;
3840  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
3841  int rc;
3842
3843  assert( nVal==4 );
3844  zParent = (const char*)sqlite3_value_text(apVal[0]);
3845  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
3846  zChild = (const char*)sqlite3_value_text(apVal[2]);
3847  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
3848
3849  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
3850  rc = sqlite3_table_column_metadata(
3851      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
3852  );
3853  if( rc==SQLITE_OK ){
3854    rc = sqlite3_table_column_metadata(
3855        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
3856    );
3857  }
3858
3859  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
3860    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
3861    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
3862    sqlite3_free(z);
3863  }
3864}
3865
3866
3867/*
3868** The implementation of dot-command ".lint fkey-indexes".
3869*/
3870static int lintFkeyIndexes(
3871  ShellState *pState,             /* Current shell tool state */
3872  char **azArg,                   /* Array of arguments passed to dot command */
3873  int nArg                        /* Number of entries in azArg[] */
3874){
3875  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
3876  FILE *out = pState->out;        /* Stream to write non-error output to */
3877  int bVerbose = 0;               /* If -verbose is present */
3878  int bGroupByParent = 0;         /* If -groupbyparent is present */
3879  int i;                          /* To iterate through azArg[] */
3880  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
3881  int rc;                         /* Return code */
3882  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
3883
3884  /*
3885  ** This SELECT statement returns one row for each foreign key constraint
3886  ** in the schema of the main database. The column values are:
3887  **
3888  ** 0. The text of an SQL statement similar to:
3889  **
3890  **      "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
3891  **
3892  **    This is the same SELECT that the foreign keys implementation needs
3893  **    to run internally on child tables. If there is an index that can
3894  **    be used to optimize this query, then it can also be used by the FK
3895  **    implementation to optimize DELETE or UPDATE statements on the parent
3896  **    table.
3897  **
3898  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
3899  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
3900  **    contains an index that can be used to optimize the query.
3901  **
3902  ** 2. Human readable text that describes the child table and columns. e.g.
3903  **
3904  **       "child_table(child_key1, child_key2)"
3905  **
3906  ** 3. Human readable text that describes the parent table and columns. e.g.
3907  **
3908  **       "parent_table(parent_key1, parent_key2)"
3909  **
3910  ** 4. A full CREATE INDEX statement for an index that could be used to
3911  **    optimize DELETE or UPDATE statements on the parent table. e.g.
3912  **
3913  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
3914  **
3915  ** 5. The name of the parent table.
3916  **
3917  ** These six values are used by the C logic below to generate the report.
3918  */
3919  const char *zSql =
3920  "SELECT "
3921    "     'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
3922    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
3923    "  || fkey_collate_clause("
3924    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
3925    ", "
3926    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
3927    "  || group_concat('*=?', ' AND ') || ')'"
3928    ", "
3929    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
3930    ", "
3931    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
3932    ", "
3933    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
3934    "  || ' ON ' || quote(s.name) || '('"
3935    "  || group_concat(quote(f.[from]) ||"
3936    "        fkey_collate_clause("
3937    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
3938    "  || ');'"
3939    ", "
3940    "     f.[table] "
3941    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
3942    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
3943    "GROUP BY s.name, f.id "
3944    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
3945  ;
3946  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
3947
3948  for(i=2; i<nArg; i++){
3949    int n = (int)strlen(azArg[i]);
3950    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
3951      bVerbose = 1;
3952    }
3953    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
3954      bGroupByParent = 1;
3955      zIndent = "    ";
3956    }
3957    else{
3958      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
3959          azArg[0], azArg[1]
3960      );
3961      return SQLITE_ERROR;
3962    }
3963  }
3964
3965  /* Register the fkey_collate_clause() SQL function */
3966  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
3967      0, shellFkeyCollateClause, 0, 0
3968  );
3969
3970
3971  if( rc==SQLITE_OK ){
3972    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
3973  }
3974  if( rc==SQLITE_OK ){
3975    sqlite3_bind_int(pSql, 1, bGroupByParent);
3976  }
3977
3978  if( rc==SQLITE_OK ){
3979    int rc2;
3980    char *zPrev = 0;
3981    while( SQLITE_ROW==sqlite3_step(pSql) ){
3982      int res = -1;
3983      sqlite3_stmt *pExplain = 0;
3984      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
3985      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
3986      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
3987      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
3988      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
3989      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
3990
3991      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3992      if( rc!=SQLITE_OK ) break;
3993      if( SQLITE_ROW==sqlite3_step(pExplain) ){
3994        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
3995        res = (
3996              0==sqlite3_strglob(zGlob, zPlan)
3997           || 0==sqlite3_strglob(zGlobIPK, zPlan)
3998        );
3999      }
4000      rc = sqlite3_finalize(pExplain);
4001      if( rc!=SQLITE_OK ) break;
4002
4003      if( res<0 ){
4004        raw_printf(stderr, "Error: internal error");
4005        break;
4006      }else{
4007        if( bGroupByParent
4008        && (bVerbose || res==0)
4009        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4010        ){
4011          raw_printf(out, "-- Parent table %s\n", zParent);
4012          sqlite3_free(zPrev);
4013          zPrev = sqlite3_mprintf("%s", zParent);
4014        }
4015
4016        if( res==0 ){
4017          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4018        }else if( bVerbose ){
4019          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4020              zIndent, zFrom, zTarget
4021          );
4022        }
4023      }
4024    }
4025    sqlite3_free(zPrev);
4026
4027    if( rc!=SQLITE_OK ){
4028      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4029    }
4030
4031    rc2 = sqlite3_finalize(pSql);
4032    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4033      rc = rc2;
4034      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4035    }
4036  }else{
4037    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4038  }
4039
4040  return rc;
4041}
4042
4043/*
4044** Implementation of ".lint" dot command.
4045*/
4046static int lintDotCommand(
4047  ShellState *pState,             /* Current shell tool state */
4048  char **azArg,                   /* Array of arguments passed to dot command */
4049  int nArg                        /* Number of entries in azArg[] */
4050){
4051  int n;
4052  n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
4053  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4054  return lintFkeyIndexes(pState, azArg, nArg);
4055
4056 usage:
4057  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4058  raw_printf(stderr, "Where sub-commands are:\n");
4059  raw_printf(stderr, "    fkey-indexes\n");
4060  return SQLITE_ERROR;
4061}
4062
4063
4064/*
4065** If an input line begins with "." then invoke this routine to
4066** process that line.
4067**
4068** Return 1 on error, 2 to exit, and 0 otherwise.
4069*/
4070static int do_meta_command(char *zLine, ShellState *p){
4071  int h = 1;
4072  int nArg = 0;
4073  int n, c;
4074  int rc = 0;
4075  char *azArg[50];
4076
4077  /* Parse the input line into tokens.
4078  */
4079  while( zLine[h] && nArg<ArraySize(azArg) ){
4080    while( IsSpace(zLine[h]) ){ h++; }
4081    if( zLine[h]==0 ) break;
4082    if( zLine[h]=='\'' || zLine[h]=='"' ){
4083      int delim = zLine[h++];
4084      azArg[nArg++] = &zLine[h];
4085      while( zLine[h] && zLine[h]!=delim ){
4086        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
4087        h++;
4088      }
4089      if( zLine[h]==delim ){
4090        zLine[h++] = 0;
4091      }
4092      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
4093    }else{
4094      azArg[nArg++] = &zLine[h];
4095      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4096      if( zLine[h] ) zLine[h++] = 0;
4097      resolve_backslashes(azArg[nArg-1]);
4098    }
4099  }
4100
4101  /* Process the input line.
4102  */
4103  if( nArg==0 ) return 0; /* no tokens, no error */
4104  n = strlen30(azArg[0]);
4105  c = azArg[0][0];
4106
4107#ifndef SQLITE_OMIT_AUTHORIZATION
4108  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4109    if( nArg!=2 ){
4110      raw_printf(stderr, "Usage: .auth ON|OFF\n");
4111      rc = 1;
4112      goto meta_command_exit;
4113    }
4114    open_db(p, 0);
4115    if( booleanValue(azArg[1]) ){
4116      sqlite3_set_authorizer(p->db, shellAuth, p);
4117    }else{
4118      sqlite3_set_authorizer(p->db, 0, 0);
4119    }
4120  }else
4121#endif
4122
4123  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4124   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4125  ){
4126    const char *zDestFile = 0;
4127    const char *zDb = 0;
4128    sqlite3 *pDest;
4129    sqlite3_backup *pBackup;
4130    int j;
4131    for(j=1; j<nArg; j++){
4132      const char *z = azArg[j];
4133      if( z[0]=='-' ){
4134        while( z[0]=='-' ) z++;
4135        /* No options to process at this time */
4136        {
4137          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
4138          return 1;
4139        }
4140      }else if( zDestFile==0 ){
4141        zDestFile = azArg[j];
4142      }else if( zDb==0 ){
4143        zDb = zDestFile;
4144        zDestFile = azArg[j];
4145      }else{
4146        raw_printf(stderr, "too many arguments to .backup\n");
4147        return 1;
4148      }
4149    }
4150    if( zDestFile==0 ){
4151      raw_printf(stderr, "missing FILENAME argument on .backup\n");
4152      return 1;
4153    }
4154    if( zDb==0 ) zDb = "main";
4155    rc = sqlite3_open(zDestFile, &pDest);
4156    if( rc!=SQLITE_OK ){
4157      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
4158      sqlite3_close(pDest);
4159      return 1;
4160    }
4161    open_db(p, 0);
4162    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4163    if( pBackup==0 ){
4164      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4165      sqlite3_close(pDest);
4166      return 1;
4167    }
4168    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4169    sqlite3_backup_finish(pBackup);
4170    if( rc==SQLITE_DONE ){
4171      rc = 0;
4172    }else{
4173      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
4174      rc = 1;
4175    }
4176    sqlite3_close(pDest);
4177  }else
4178
4179  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4180    if( nArg==2 ){
4181      bail_on_error = booleanValue(azArg[1]);
4182    }else{
4183      raw_printf(stderr, "Usage: .bail on|off\n");
4184      rc = 1;
4185    }
4186  }else
4187
4188  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4189    if( nArg==2 ){
4190      if( booleanValue(azArg[1]) ){
4191        setBinaryMode(p->out, 1);
4192      }else{
4193        setTextMode(p->out, 1);
4194      }
4195    }else{
4196      raw_printf(stderr, "Usage: .binary on|off\n");
4197      rc = 1;
4198    }
4199  }else
4200
4201  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4202    if( nArg==2 ){
4203#if defined(_WIN32) || defined(WIN32)
4204      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4205      rc = !SetCurrentDirectoryW(z);
4206      sqlite3_free(z);
4207#else
4208      rc = chdir(azArg[1]);
4209#endif
4210      if( rc ){
4211        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4212        rc = 1;
4213      }
4214    }else{
4215      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4216      rc = 1;
4217    }
4218  }else
4219
4220  /* The undocumented ".breakpoint" command causes a call to the no-op
4221  ** routine named test_breakpoint().
4222  */
4223  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4224    test_breakpoint();
4225  }else
4226
4227  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4228    if( nArg==2 ){
4229      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
4230    }else{
4231      raw_printf(stderr, "Usage: .changes on|off\n");
4232      rc = 1;
4233    }
4234  }else
4235
4236  /* Cancel output redirection, if it is currently set (by .testcase)
4237  ** Then read the content of the testcase-out.txt file and compare against
4238  ** azArg[1].  If there are differences, report an error and exit.
4239  */
4240  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4241    char *zRes = 0;
4242    output_reset(p);
4243    if( nArg!=2 ){
4244      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
4245      rc = 2;
4246    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
4247      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4248      rc = 2;
4249    }else if( testcase_glob(azArg[1],zRes)==0 ){
4250      utf8_printf(stderr,
4251                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
4252                 p->zTestcase, azArg[1], zRes);
4253      rc = 2;
4254    }else{
4255      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
4256      p->nCheck++;
4257    }
4258    sqlite3_free(zRes);
4259  }else
4260
4261  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4262    if( nArg==2 ){
4263      tryToClone(p, azArg[1]);
4264    }else{
4265      raw_printf(stderr, "Usage: .clone FILENAME\n");
4266      rc = 1;
4267    }
4268  }else
4269
4270  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
4271    ShellState data;
4272    char *zErrMsg = 0;
4273    open_db(p, 0);
4274    memcpy(&data, p, sizeof(data));
4275    data.showHeader = 0;
4276    data.cMode = data.mode = MODE_List;
4277    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
4278    data.cnt = 0;
4279    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4280                 callback, &data, &zErrMsg);
4281    if( zErrMsg ){
4282      utf8_printf(stderr,"Error: %s\n", zErrMsg);
4283      sqlite3_free(zErrMsg);
4284      rc = 1;
4285    }
4286  }else
4287
4288  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4289    rc = shell_dbinfo_command(p, nArg, azArg);
4290  }else
4291
4292  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
4293    const char *zLike = 0;
4294    int i;
4295    int savedShowHeader = p->showHeader;
4296    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
4297    for(i=1; i<nArg; i++){
4298      if( azArg[i][0]=='-' ){
4299        const char *z = azArg[i]+1;
4300        if( z[0]=='-' ) z++;
4301        if( strcmp(z,"preserve-rowids")==0 ){
4302#ifdef SQLITE_OMIT_VIRTUALTABLE
4303          raw_printf(stderr, "The --preserve-rowids option is not compatible"
4304                             " with SQLITE_OMIT_VIRTUALTABLE\n");
4305          rc = 1;
4306          goto meta_command_exit;
4307#else
4308          ShellSetFlag(p, SHFLG_PreserveRowid);
4309#endif
4310        }else
4311        if( strcmp(z,"newlines")==0 ){
4312          ShellSetFlag(p, SHFLG_Newlines);
4313        }else
4314        {
4315          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4316          rc = 1;
4317          goto meta_command_exit;
4318        }
4319      }else if( zLike ){
4320        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
4321                           "?--newlines? ?LIKE-PATTERN?\n");
4322        rc = 1;
4323        goto meta_command_exit;
4324      }else{
4325        zLike = azArg[i];
4326      }
4327    }
4328    open_db(p, 0);
4329    /* When playing back a "dump", the content might appear in an order
4330    ** which causes immediate foreign key constraints to be violated.
4331    ** So disable foreign-key constraint enforcement to prevent problems. */
4332    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4333    raw_printf(p->out, "BEGIN TRANSACTION;\n");
4334    p->writableSchema = 0;
4335    p->showHeader = 0;
4336    /* Set writable_schema=ON since doing so forces SQLite to initialize
4337    ** as much of the schema as it can even if the sqlite_master table is
4338    ** corrupt. */
4339    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4340    p->nErr = 0;
4341    if( zLike==0 ){
4342      run_schema_dump_query(p,
4343        "SELECT name, type, sql FROM sqlite_master "
4344        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4345      );
4346      run_schema_dump_query(p,
4347        "SELECT name, type, sql FROM sqlite_master "
4348        "WHERE name=='sqlite_sequence'"
4349      );
4350      run_table_dump_query(p,
4351        "SELECT sql FROM sqlite_master "
4352        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4353      );
4354    }else{
4355      char *zSql;
4356      zSql = sqlite3_mprintf(
4357        "SELECT name, type, sql FROM sqlite_master "
4358        "WHERE tbl_name LIKE %Q AND type=='table'"
4359        "  AND sql NOT NULL", zLike);
4360      run_schema_dump_query(p,zSql);
4361      sqlite3_free(zSql);
4362      zSql = sqlite3_mprintf(
4363        "SELECT sql FROM sqlite_master "
4364        "WHERE sql NOT NULL"
4365        "  AND type IN ('index','trigger','view')"
4366        "  AND tbl_name LIKE %Q", zLike);
4367      run_table_dump_query(p, zSql, 0);
4368      sqlite3_free(zSql);
4369    }
4370    if( p->writableSchema ){
4371      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
4372      p->writableSchema = 0;
4373    }
4374    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4375    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
4376    raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4377    p->showHeader = savedShowHeader;
4378  }else
4379
4380  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4381    if( nArg==2 ){
4382      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
4383    }else{
4384      raw_printf(stderr, "Usage: .echo on|off\n");
4385      rc = 1;
4386    }
4387  }else
4388
4389  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4390    if( nArg==2 ){
4391      if( strcmp(azArg[1],"full")==0 ){
4392        p->autoEQP = 2;
4393      }else{
4394        p->autoEQP = booleanValue(azArg[1]);
4395      }
4396    }else{
4397      raw_printf(stderr, "Usage: .eqp on|off|full\n");
4398      rc = 1;
4399    }
4400  }else
4401
4402  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
4403    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
4404    rc = 2;
4405  }else
4406
4407  /* The ".explain" command is automatic now.  It is largely pointless.  It
4408  ** retained purely for backwards compatibility */
4409  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
4410    int val = 1;
4411    if( nArg>=2 ){
4412      if( strcmp(azArg[1],"auto")==0 ){
4413        val = 99;
4414      }else{
4415        val =  booleanValue(azArg[1]);
4416      }
4417    }
4418    if( val==1 && p->mode!=MODE_Explain ){
4419      p->normalMode = p->mode;
4420      p->mode = MODE_Explain;
4421      p->autoExplain = 0;
4422    }else if( val==0 ){
4423      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4424      p->autoExplain = 0;
4425    }else if( val==99 ){
4426      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4427      p->autoExplain = 1;
4428    }
4429  }else
4430
4431  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
4432    ShellState data;
4433    char *zErrMsg = 0;
4434    int doStats = 0;
4435    memcpy(&data, p, sizeof(data));
4436    data.showHeader = 0;
4437    data.cMode = data.mode = MODE_Semi;
4438    if( nArg==2 && optionMatch(azArg[1], "indent") ){
4439      data.cMode = data.mode = MODE_Pretty;
4440      nArg = 1;
4441    }
4442    if( nArg!=1 ){
4443      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
4444      rc = 1;
4445      goto meta_command_exit;
4446    }
4447    open_db(p, 0);
4448    rc = sqlite3_exec(p->db,
4449       "SELECT sql FROM"
4450       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4451       "     FROM sqlite_master UNION ALL"
4452       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4453       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4454       "ORDER BY rowid",
4455       callback, &data, &zErrMsg
4456    );
4457    if( rc==SQLITE_OK ){
4458      sqlite3_stmt *pStmt;
4459      rc = sqlite3_prepare_v2(p->db,
4460               "SELECT rowid FROM sqlite_master"
4461               " WHERE name GLOB 'sqlite_stat[134]'",
4462               -1, &pStmt, 0);
4463      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4464      sqlite3_finalize(pStmt);
4465    }
4466    if( doStats==0 ){
4467      raw_printf(p->out, "/* No STAT tables available */\n");
4468    }else{
4469      raw_printf(p->out, "ANALYZE sqlite_master;\n");
4470      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4471                   callback, &data, &zErrMsg);
4472      data.cMode = data.mode = MODE_Insert;
4473      data.zDestTable = "sqlite_stat1";
4474      shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4475                 shell_callback, &data,&zErrMsg);
4476      data.zDestTable = "sqlite_stat3";
4477      shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4478                 shell_callback, &data,&zErrMsg);
4479      data.zDestTable = "sqlite_stat4";
4480      shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4481                 shell_callback, &data, &zErrMsg);
4482      raw_printf(p->out, "ANALYZE sqlite_master;\n");
4483    }
4484  }else
4485
4486  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4487    if( nArg==2 ){
4488      p->showHeader = booleanValue(azArg[1]);
4489    }else{
4490      raw_printf(stderr, "Usage: .headers on|off\n");
4491      rc = 1;
4492    }
4493  }else
4494
4495  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
4496    utf8_printf(p->out, "%s", zHelp);
4497  }else
4498
4499  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
4500    char *zTable;               /* Insert data into this table */
4501    char *zFile;                /* Name of file to extra content from */
4502    sqlite3_stmt *pStmt = NULL; /* A statement */
4503    int nCol;                   /* Number of columns in the table */
4504    int nByte;                  /* Number of bytes in an SQL string */
4505    int i, j;                   /* Loop counters */
4506    int needCommit;             /* True to COMMIT or ROLLBACK at end */
4507    int nSep;                   /* Number of bytes in p->colSeparator[] */
4508    char *zSql;                 /* An SQL statement */
4509    ImportCtx sCtx;             /* Reader context */
4510    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4511    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
4512
4513    if( nArg!=3 ){
4514      raw_printf(stderr, "Usage: .import FILE TABLE\n");
4515      goto meta_command_exit;
4516    }
4517    zFile = azArg[1];
4518    zTable = azArg[2];
4519    seenInterrupt = 0;
4520    memset(&sCtx, 0, sizeof(sCtx));
4521    open_db(p, 0);
4522    nSep = strlen30(p->colSeparator);
4523    if( nSep==0 ){
4524      raw_printf(stderr,
4525                 "Error: non-null column separator required for import\n");
4526      return 1;
4527    }
4528    if( nSep>1 ){
4529      raw_printf(stderr, "Error: multi-character column separators not allowed"
4530                      " for import\n");
4531      return 1;
4532    }
4533    nSep = strlen30(p->rowSeparator);
4534    if( nSep==0 ){
4535      raw_printf(stderr, "Error: non-null row separator required for import\n");
4536      return 1;
4537    }
4538    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4539      /* When importing CSV (only), if the row separator is set to the
4540      ** default output row separator, change it to the default input
4541      ** row separator.  This avoids having to maintain different input
4542      ** and output row separators. */
4543      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4544      nSep = strlen30(p->rowSeparator);
4545    }
4546    if( nSep>1 ){
4547      raw_printf(stderr, "Error: multi-character row separators not allowed"
4548                      " for import\n");
4549      return 1;
4550    }
4551    sCtx.zFile = zFile;
4552    sCtx.nLine = 1;
4553    if( sCtx.zFile[0]=='|' ){
4554#ifdef SQLITE_OMIT_POPEN
4555      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4556      return 1;
4557#else
4558      sCtx.in = popen(sCtx.zFile+1, "r");
4559      sCtx.zFile = "<pipe>";
4560      xCloser = pclose;
4561#endif
4562    }else{
4563      sCtx.in = fopen(sCtx.zFile, "rb");
4564      xCloser = fclose;
4565    }
4566    if( p->mode==MODE_Ascii ){
4567      xRead = ascii_read_one_field;
4568    }else{
4569      xRead = csv_read_one_field;
4570    }
4571    if( sCtx.in==0 ){
4572      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4573      return 1;
4574    }
4575    sCtx.cColSep = p->colSeparator[0];
4576    sCtx.cRowSep = p->rowSeparator[0];
4577    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
4578    if( zSql==0 ){
4579      raw_printf(stderr, "Error: out of memory\n");
4580      xCloser(sCtx.in);
4581      return 1;
4582    }
4583    nByte = strlen30(zSql);
4584    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4585    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
4586    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
4587      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4588      char cSep = '(';
4589      while( xRead(&sCtx) ){
4590        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
4591        cSep = ',';
4592        if( sCtx.cTerm!=sCtx.cColSep ) break;
4593      }
4594      if( cSep=='(' ){
4595        sqlite3_free(zCreate);
4596        sqlite3_free(sCtx.z);
4597        xCloser(sCtx.in);
4598        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
4599        return 1;
4600      }
4601      zCreate = sqlite3_mprintf("%z\n)", zCreate);
4602      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4603      sqlite3_free(zCreate);
4604      if( rc ){
4605        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
4606                sqlite3_errmsg(p->db));
4607        sqlite3_free(sCtx.z);
4608        xCloser(sCtx.in);
4609        return 1;
4610      }
4611      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4612    }
4613    sqlite3_free(zSql);
4614    if( rc ){
4615      if (pStmt) sqlite3_finalize(pStmt);
4616      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
4617      xCloser(sCtx.in);
4618      return 1;
4619    }
4620    nCol = sqlite3_column_count(pStmt);
4621    sqlite3_finalize(pStmt);
4622    pStmt = 0;
4623    if( nCol==0 ) return 0; /* no columns, no error */
4624    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
4625    if( zSql==0 ){
4626      raw_printf(stderr, "Error: out of memory\n");
4627      xCloser(sCtx.in);
4628      return 1;
4629    }
4630    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
4631    j = strlen30(zSql);
4632    for(i=1; i<nCol; i++){
4633      zSql[j++] = ',';
4634      zSql[j++] = '?';
4635    }
4636    zSql[j++] = ')';
4637    zSql[j] = 0;
4638    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4639    sqlite3_free(zSql);
4640    if( rc ){
4641      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
4642      if (pStmt) sqlite3_finalize(pStmt);
4643      xCloser(sCtx.in);
4644      return 1;
4645    }
4646    needCommit = sqlite3_get_autocommit(p->db);
4647    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
4648    do{
4649      int startLine = sCtx.nLine;
4650      for(i=0; i<nCol; i++){
4651        char *z = xRead(&sCtx);
4652        /*
4653        ** Did we reach end-of-file before finding any columns?
4654        ** If so, stop instead of NULL filling the remaining columns.
4655        */
4656        if( z==0 && i==0 ) break;
4657        /*
4658        ** Did we reach end-of-file OR end-of-line before finding any
4659        ** columns in ASCII mode?  If so, stop instead of NULL filling
4660        ** the remaining columns.
4661        */
4662        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
4663        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
4664        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
4665          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4666                          "filling the rest with NULL\n",
4667                          sCtx.zFile, startLine, nCol, i+1);
4668          i += 2;
4669          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
4670        }
4671      }
4672      if( sCtx.cTerm==sCtx.cColSep ){
4673        do{
4674          xRead(&sCtx);
4675          i++;
4676        }while( sCtx.cTerm==sCtx.cColSep );
4677        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
4678                        "extras ignored\n",
4679                        sCtx.zFile, startLine, nCol, i);
4680      }
4681      if( i>=nCol ){
4682        sqlite3_step(pStmt);
4683        rc = sqlite3_reset(pStmt);
4684        if( rc!=SQLITE_OK ){
4685          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
4686                      startLine, sqlite3_errmsg(p->db));
4687        }
4688      }
4689    }while( sCtx.cTerm!=EOF );
4690
4691    xCloser(sCtx.in);
4692    sqlite3_free(sCtx.z);
4693    sqlite3_finalize(pStmt);
4694    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
4695  }else
4696
4697#ifndef SQLITE_UNTESTABLE
4698  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
4699    char *zSql;
4700    char *zCollist = 0;
4701    sqlite3_stmt *pStmt;
4702    int tnum = 0;
4703    int i;
4704    if( nArg!=3 ){
4705      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
4706      rc = 1;
4707      goto meta_command_exit;
4708    }
4709    open_db(p, 0);
4710    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
4711                           " WHERE name='%q' AND type='index'", azArg[1]);
4712    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4713    sqlite3_free(zSql);
4714    if( sqlite3_step(pStmt)==SQLITE_ROW ){
4715      tnum = sqlite3_column_int(pStmt, 0);
4716    }
4717    sqlite3_finalize(pStmt);
4718    if( tnum==0 ){
4719      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
4720      rc = 1;
4721      goto meta_command_exit;
4722    }
4723    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
4724    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4725    sqlite3_free(zSql);
4726    i = 0;
4727    while( sqlite3_step(pStmt)==SQLITE_ROW ){
4728      char zLabel[20];
4729      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
4730      i++;
4731      if( zCol==0 ){
4732        if( sqlite3_column_int(pStmt,1)==-1 ){
4733          zCol = "_ROWID_";
4734        }else{
4735          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
4736          zCol = zLabel;
4737        }
4738      }
4739      if( zCollist==0 ){
4740        zCollist = sqlite3_mprintf("\"%w\"", zCol);
4741      }else{
4742        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
4743      }
4744    }
4745    sqlite3_finalize(pStmt);
4746    zSql = sqlite3_mprintf(
4747          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
4748          azArg[2], zCollist, zCollist);
4749    sqlite3_free(zCollist);
4750    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
4751    if( rc==SQLITE_OK ){
4752      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
4753      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
4754      if( rc ){
4755        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
4756      }else{
4757        utf8_printf(stdout, "%s;\n", zSql);
4758        raw_printf(stdout,
4759           "WARNING: writing to an imposter table will corrupt the index!\n"
4760        );
4761      }
4762    }else{
4763      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
4764      rc = 1;
4765    }
4766    sqlite3_free(zSql);
4767  }else
4768#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
4769
4770#ifdef SQLITE_ENABLE_IOTRACE
4771  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
4772    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
4773    if( iotrace && iotrace!=stdout ) fclose(iotrace);
4774    iotrace = 0;
4775    if( nArg<2 ){
4776      sqlite3IoTrace = 0;
4777    }else if( strcmp(azArg[1], "-")==0 ){
4778      sqlite3IoTrace = iotracePrintf;
4779      iotrace = stdout;
4780    }else{
4781      iotrace = fopen(azArg[1], "w");
4782      if( iotrace==0 ){
4783        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
4784        sqlite3IoTrace = 0;
4785        rc = 1;
4786      }else{
4787        sqlite3IoTrace = iotracePrintf;
4788      }
4789    }
4790  }else
4791#endif
4792
4793  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
4794    static const struct {
4795       const char *zLimitName;   /* Name of a limit */
4796       int limitCode;            /* Integer code for that limit */
4797    } aLimit[] = {
4798      { "length",                SQLITE_LIMIT_LENGTH                    },
4799      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
4800      { "column",                SQLITE_LIMIT_COLUMN                    },
4801      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
4802      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
4803      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
4804      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
4805      { "attached",              SQLITE_LIMIT_ATTACHED                  },
4806      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
4807      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
4808      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
4809      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
4810    };
4811    int i, n2;
4812    open_db(p, 0);
4813    if( nArg==1 ){
4814      for(i=0; i<ArraySize(aLimit); i++){
4815        printf("%20s %d\n", aLimit[i].zLimitName,
4816               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
4817      }
4818    }else if( nArg>3 ){
4819      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
4820      rc = 1;
4821      goto meta_command_exit;
4822    }else{
4823      int iLimit = -1;
4824      n2 = strlen30(azArg[1]);
4825      for(i=0; i<ArraySize(aLimit); i++){
4826        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
4827          if( iLimit<0 ){
4828            iLimit = i;
4829          }else{
4830            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
4831            rc = 1;
4832            goto meta_command_exit;
4833          }
4834        }
4835      }
4836      if( iLimit<0 ){
4837        utf8_printf(stderr, "unknown limit: \"%s\"\n"
4838                        "enter \".limits\" with no arguments for a list.\n",
4839                         azArg[1]);
4840        rc = 1;
4841        goto meta_command_exit;
4842      }
4843      if( nArg==3 ){
4844        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
4845                      (int)integerValue(azArg[2]));
4846      }
4847      printf("%20s %d\n", aLimit[iLimit].zLimitName,
4848             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
4849    }
4850  }else
4851
4852  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
4853    open_db(p, 0);
4854    lintDotCommand(p, azArg, nArg);
4855  }else
4856
4857#ifndef SQLITE_OMIT_LOAD_EXTENSION
4858  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
4859    const char *zFile, *zProc;
4860    char *zErrMsg = 0;
4861    if( nArg<2 ){
4862      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
4863      rc = 1;
4864      goto meta_command_exit;
4865    }
4866    zFile = azArg[1];
4867    zProc = nArg>=3 ? azArg[2] : 0;
4868    open_db(p, 0);
4869    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
4870    if( rc!=SQLITE_OK ){
4871      utf8_printf(stderr, "Error: %s\n", zErrMsg);
4872      sqlite3_free(zErrMsg);
4873      rc = 1;
4874    }
4875  }else
4876#endif
4877
4878  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
4879    if( nArg!=2 ){
4880      raw_printf(stderr, "Usage: .log FILENAME\n");
4881      rc = 1;
4882    }else{
4883      const char *zFile = azArg[1];
4884      output_file_close(p->pLog);
4885      p->pLog = output_file_open(zFile);
4886    }
4887  }else
4888
4889  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
4890    const char *zMode = nArg>=2 ? azArg[1] : "";
4891    int n2 = (int)strlen(zMode);
4892    int c2 = zMode[0];
4893    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
4894      p->mode = MODE_Line;
4895      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4896    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
4897      p->mode = MODE_Column;
4898      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4899    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
4900      p->mode = MODE_List;
4901      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
4902      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4903    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
4904      p->mode = MODE_Html;
4905    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
4906      p->mode = MODE_Tcl;
4907      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
4908      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4909    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
4910      p->mode = MODE_Csv;
4911      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
4912      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
4913    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
4914      p->mode = MODE_List;
4915      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
4916    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
4917      p->mode = MODE_Insert;
4918      set_table_name(p, nArg>=3 ? azArg[2] : "table");
4919    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
4920      p->mode = MODE_Quote;
4921    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
4922      p->mode = MODE_Ascii;
4923      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
4924      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
4925    }else if( nArg==1 ){
4926      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
4927    }else{
4928      raw_printf(stderr, "Error: mode should be one of: "
4929         "ascii column csv html insert line list quote tabs tcl\n");
4930      rc = 1;
4931    }
4932    p->cMode = p->mode;
4933  }else
4934
4935  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
4936    if( nArg==2 ){
4937      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
4938                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
4939    }else{
4940      raw_printf(stderr, "Usage: .nullvalue STRING\n");
4941      rc = 1;
4942    }
4943  }else
4944
4945  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
4946    char *zNewFilename;  /* Name of the database file to open */
4947    int iName = 1;       /* Index in azArg[] of the filename */
4948    int newFlag = 0;     /* True to delete file before opening */
4949    /* Close the existing database */
4950    session_close_all(p);
4951    sqlite3_close(p->db);
4952    p->db = 0;
4953    p->zDbFilename = 0;
4954    sqlite3_free(p->zFreeOnClose);
4955    p->zFreeOnClose = 0;
4956    /* Check for command-line arguments */
4957    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
4958      const char *z = azArg[iName];
4959      if( optionMatch(z,"new") ){
4960        newFlag = 1;
4961      }else if( z[0]=='-' ){
4962        utf8_printf(stderr, "unknown option: %s\n", z);
4963        rc = 1;
4964        goto meta_command_exit;
4965      }
4966    }
4967    /* If a filename is specified, try to open it first */
4968    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
4969    if( zNewFilename ){
4970      if( newFlag ) shellDeleteFile(zNewFilename);
4971      p->zDbFilename = zNewFilename;
4972      open_db(p, 1);
4973      if( p->db==0 ){
4974        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
4975        sqlite3_free(zNewFilename);
4976      }else{
4977        p->zFreeOnClose = zNewFilename;
4978      }
4979    }
4980    if( p->db==0 ){
4981      /* As a fall-back open a TEMP database */
4982      p->zDbFilename = 0;
4983      open_db(p, 0);
4984    }
4985  }else
4986
4987  if( c=='o'
4988   && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
4989  ){
4990    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
4991    if( nArg>2 ){
4992      utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
4993      rc = 1;
4994      goto meta_command_exit;
4995    }
4996    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
4997      if( nArg<2 ){
4998        raw_printf(stderr, "Usage: .once FILE\n");
4999        rc = 1;
5000        goto meta_command_exit;
5001      }
5002      p->outCount = 2;
5003    }else{
5004      p->outCount = 0;
5005    }
5006    output_reset(p);
5007    if( zFile[0]=='|' ){
5008#ifdef SQLITE_OMIT_POPEN
5009      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5010      rc = 1;
5011      p->out = stdout;
5012#else
5013      p->out = popen(zFile + 1, "w");
5014      if( p->out==0 ){
5015        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
5016        p->out = stdout;
5017        rc = 1;
5018      }else{
5019        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5020      }
5021#endif
5022    }else{
5023      p->out = output_file_open(zFile);
5024      if( p->out==0 ){
5025        if( strcmp(zFile,"off")!=0 ){
5026          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
5027        }
5028        p->out = stdout;
5029        rc = 1;
5030      } else {
5031        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
5032      }
5033    }
5034  }else
5035
5036  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5037    int i;
5038    for(i=1; i<nArg; i++){
5039      if( i>1 ) raw_printf(p->out, " ");
5040      utf8_printf(p->out, "%s", azArg[i]);
5041    }
5042    raw_printf(p->out, "\n");
5043  }else
5044
5045  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
5046    if( nArg >= 2) {
5047      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5048    }
5049    if( nArg >= 3) {
5050      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5051    }
5052  }else
5053
5054  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
5055    rc = 2;
5056  }else
5057
5058  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5059    FILE *alt;
5060    if( nArg!=2 ){
5061      raw_printf(stderr, "Usage: .read FILE\n");
5062      rc = 1;
5063      goto meta_command_exit;
5064    }
5065    alt = fopen(azArg[1], "rb");
5066    if( alt==0 ){
5067      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5068      rc = 1;
5069    }else{
5070      rc = process_input(p, alt);
5071      fclose(alt);
5072    }
5073  }else
5074
5075  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
5076    const char *zSrcFile;
5077    const char *zDb;
5078    sqlite3 *pSrc;
5079    sqlite3_backup *pBackup;
5080    int nTimeout = 0;
5081
5082    if( nArg==2 ){
5083      zSrcFile = azArg[1];
5084      zDb = "main";
5085    }else if( nArg==3 ){
5086      zSrcFile = azArg[2];
5087      zDb = azArg[1];
5088    }else{
5089      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
5090      rc = 1;
5091      goto meta_command_exit;
5092    }
5093    rc = sqlite3_open(zSrcFile, &pSrc);
5094    if( rc!=SQLITE_OK ){
5095      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
5096      sqlite3_close(pSrc);
5097      return 1;
5098    }
5099    open_db(p, 0);
5100    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5101    if( pBackup==0 ){
5102      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5103      sqlite3_close(pSrc);
5104      return 1;
5105    }
5106    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5107          || rc==SQLITE_BUSY  ){
5108      if( rc==SQLITE_BUSY ){
5109        if( nTimeout++ >= 3 ) break;
5110        sqlite3_sleep(100);
5111      }
5112    }
5113    sqlite3_backup_finish(pBackup);
5114    if( rc==SQLITE_DONE ){
5115      rc = 0;
5116    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
5117      raw_printf(stderr, "Error: source database is busy\n");
5118      rc = 1;
5119    }else{
5120      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5121      rc = 1;
5122    }
5123    sqlite3_close(pSrc);
5124  }else
5125
5126
5127  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5128    if( nArg==2 ){
5129      p->scanstatsOn = booleanValue(azArg[1]);
5130#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5131      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
5132#endif
5133    }else{
5134      raw_printf(stderr, "Usage: .scanstats on|off\n");
5135      rc = 1;
5136    }
5137  }else
5138
5139  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
5140    ShellText sSelect;
5141    ShellState data;
5142    char *zErrMsg = 0;
5143    const char *zDiv = 0;
5144    int iSchema = 0;
5145
5146    open_db(p, 0);
5147    memcpy(&data, p, sizeof(data));
5148    data.showHeader = 0;
5149    data.cMode = data.mode = MODE_Semi;
5150    initText(&sSelect);
5151    if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5152      data.cMode = data.mode = MODE_Pretty;
5153      nArg--;
5154      if( nArg==2 ) azArg[1] = azArg[2];
5155    }
5156    if( nArg==2 && azArg[1][0]!='-' ){
5157      int i;
5158      for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
5159      if( strcmp(azArg[1],"sqlite_master")==0 ){
5160        char *new_argv[2], *new_colv[2];
5161        new_argv[0] = "CREATE TABLE sqlite_master (\n"
5162                      "  type text,\n"
5163                      "  name text,\n"
5164                      "  tbl_name text,\n"
5165                      "  rootpage integer,\n"
5166                      "  sql text\n"
5167                      ")";
5168        new_argv[1] = 0;
5169        new_colv[0] = "sql";
5170        new_colv[1] = 0;
5171        callback(&data, 1, new_argv, new_colv);
5172        rc = SQLITE_OK;
5173      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
5174        char *new_argv[2], *new_colv[2];
5175        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5176                      "  type text,\n"
5177                      "  name text,\n"
5178                      "  tbl_name text,\n"
5179                      "  rootpage integer,\n"
5180                      "  sql text\n"
5181                      ")";
5182        new_argv[1] = 0;
5183        new_colv[0] = "sql";
5184        new_colv[1] = 0;
5185        callback(&data, 1, new_argv, new_colv);
5186        rc = SQLITE_OK;
5187      }else{
5188        zDiv = "(";
5189      }
5190    }else if( nArg==1 ){
5191      zDiv = "(";
5192    }else{
5193      raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5194      rc = 1;
5195      goto meta_command_exit;
5196    }
5197    if( zDiv ){
5198      sqlite3_stmt *pStmt = 0;
5199      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5200                              -1, &pStmt, 0);
5201      if( rc ){
5202        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5203        sqlite3_finalize(pStmt);
5204        rc = 1;
5205        goto meta_command_exit;
5206      }
5207      appendText(&sSelect, "SELECT sql FROM", 0);
5208      iSchema = 0;
5209      while( sqlite3_step(pStmt)==SQLITE_ROW ){
5210        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5211        char zScNum[30];
5212        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5213        appendText(&sSelect, zDiv, 0);
5214        zDiv = " UNION ALL ";
5215        if( strcmp(zDb, "main")!=0 ){
5216          appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
5217          appendText(&sSelect, zDb, '"');
5218          appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5219          appendText(&sSelect, zScNum, 0);
5220          appendText(&sSelect, " AS snum, ", 0);
5221          appendText(&sSelect, zDb, '\'');
5222          appendText(&sSelect, " AS sname FROM ", 0);
5223          appendText(&sSelect, zDb, '"');
5224          appendText(&sSelect, ".sqlite_master", 0);
5225        }else{
5226          appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5227          appendText(&sSelect, zScNum, 0);
5228          appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5229        }
5230      }
5231      sqlite3_finalize(pStmt);
5232      appendText(&sSelect, ") WHERE ", 0);
5233      if( nArg>1 ){
5234        char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5235        if( strchr(azArg[1], '.') ){
5236          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5237        }else{
5238          appendText(&sSelect, "lower(tbl_name)", 0);
5239        }
5240        appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5241        appendText(&sSelect, zQarg, 0);
5242        appendText(&sSelect, " AND ", 0);
5243        sqlite3_free(zQarg);
5244      }
5245      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5246                           " ORDER BY snum, rowid", 0);
5247      rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5248      freeText(&sSelect);
5249    }
5250    if( zErrMsg ){
5251      utf8_printf(stderr,"Error: %s\n", zErrMsg);
5252      sqlite3_free(zErrMsg);
5253      rc = 1;
5254    }else if( rc != SQLITE_OK ){
5255      raw_printf(stderr,"Error: querying schema information\n");
5256      rc = 1;
5257    }else{
5258      rc = 0;
5259    }
5260  }else
5261
5262#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5263  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
5264    sqlite3SelectTrace = (int)integerValue(azArg[1]);
5265  }else
5266#endif
5267
5268#if defined(SQLITE_ENABLE_SESSION)
5269  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5270    OpenSession *pSession = &p->aSession[0];
5271    char **azCmd = &azArg[1];
5272    int iSes = 0;
5273    int nCmd = nArg - 1;
5274    int i;
5275    if( nArg<=1 ) goto session_syntax_error;
5276    open_db(p, 0);
5277    if( nArg>=3 ){
5278      for(iSes=0; iSes<p->nSession; iSes++){
5279        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5280      }
5281      if( iSes<p->nSession ){
5282        pSession = &p->aSession[iSes];
5283        azCmd++;
5284        nCmd--;
5285      }else{
5286        pSession = &p->aSession[0];
5287        iSes = 0;
5288      }
5289    }
5290
5291    /* .session attach TABLE
5292    ** Invoke the sqlite3session_attach() interface to attach a particular
5293    ** table so that it is never filtered.
5294    */
5295    if( strcmp(azCmd[0],"attach")==0 ){
5296      if( nCmd!=2 ) goto session_syntax_error;
5297      if( pSession->p==0 ){
5298        session_not_open:
5299        raw_printf(stderr, "ERROR: No sessions are open\n");
5300      }else{
5301        rc = sqlite3session_attach(pSession->p, azCmd[1]);
5302        if( rc ){
5303          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
5304          rc = 0;
5305        }
5306      }
5307    }else
5308
5309    /* .session changeset FILE
5310    ** .session patchset FILE
5311    ** Write a changeset or patchset into a file.  The file is overwritten.
5312    */
5313    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5314      FILE *out = 0;
5315      if( nCmd!=2 ) goto session_syntax_error;
5316      if( pSession->p==0 ) goto session_not_open;
5317      out = fopen(azCmd[1], "wb");
5318      if( out==0 ){
5319        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
5320      }else{
5321        int szChng;
5322        void *pChng;
5323        if( azCmd[0][0]=='c' ){
5324          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
5325        }else{
5326          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5327        }
5328        if( rc ){
5329          printf("Error: error code %d\n", rc);
5330          rc = 0;
5331        }
5332        if( pChng
5333          && fwrite(pChng, szChng, 1, out)!=1 ){
5334          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
5335                  szChng);
5336        }
5337        sqlite3_free(pChng);
5338        fclose(out);
5339      }
5340    }else
5341
5342    /* .session close
5343    ** Close the identified session
5344    */
5345    if( strcmp(azCmd[0], "close")==0 ){
5346      if( nCmd!=1 ) goto session_syntax_error;
5347      if( p->nSession ){
5348        session_close(pSession);
5349        p->aSession[iSes] = p->aSession[--p->nSession];
5350      }
5351    }else
5352
5353    /* .session enable ?BOOLEAN?
5354    ** Query or set the enable flag
5355    */
5356    if( strcmp(azCmd[0], "enable")==0 ){
5357      int ii;
5358      if( nCmd>2 ) goto session_syntax_error;
5359      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5360      if( p->nSession ){
5361        ii = sqlite3session_enable(pSession->p, ii);
5362        utf8_printf(p->out, "session %s enable flag = %d\n",
5363                    pSession->zName, ii);
5364      }
5365    }else
5366
5367    /* .session filter GLOB ....
5368    ** Set a list of GLOB patterns of table names to be excluded.
5369    */
5370    if( strcmp(azCmd[0], "filter")==0 ){
5371      int ii, nByte;
5372      if( nCmd<2 ) goto session_syntax_error;
5373      if( p->nSession ){
5374        for(ii=0; ii<pSession->nFilter; ii++){
5375          sqlite3_free(pSession->azFilter[ii]);
5376        }
5377        sqlite3_free(pSession->azFilter);
5378        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5379        pSession->azFilter = sqlite3_malloc( nByte );
5380        if( pSession->azFilter==0 ){
5381          raw_printf(stderr, "Error: out or memory\n");
5382          exit(1);
5383        }
5384        for(ii=1; ii<nCmd; ii++){
5385          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
5386        }
5387        pSession->nFilter = ii-1;
5388      }
5389    }else
5390
5391    /* .session indirect ?BOOLEAN?
5392    ** Query or set the indirect flag
5393    */
5394    if( strcmp(azCmd[0], "indirect")==0 ){
5395      int ii;
5396      if( nCmd>2 ) goto session_syntax_error;
5397      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5398      if( p->nSession ){
5399        ii = sqlite3session_indirect(pSession->p, ii);
5400        utf8_printf(p->out, "session %s indirect flag = %d\n",
5401                    pSession->zName, ii);
5402      }
5403    }else
5404
5405    /* .session isempty
5406    ** Determine if the session is empty
5407    */
5408    if( strcmp(azCmd[0], "isempty")==0 ){
5409      int ii;
5410      if( nCmd!=1 ) goto session_syntax_error;
5411      if( p->nSession ){
5412        ii = sqlite3session_isempty(pSession->p);
5413        utf8_printf(p->out, "session %s isempty flag = %d\n",
5414                    pSession->zName, ii);
5415      }
5416    }else
5417
5418    /* .session list
5419    ** List all currently open sessions
5420    */
5421    if( strcmp(azCmd[0],"list")==0 ){
5422      for(i=0; i<p->nSession; i++){
5423        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
5424      }
5425    }else
5426
5427    /* .session open DB NAME
5428    ** Open a new session called NAME on the attached database DB.
5429    ** DB is normally "main".
5430    */
5431    if( strcmp(azCmd[0],"open")==0 ){
5432      char *zName;
5433      if( nCmd!=3 ) goto session_syntax_error;
5434      zName = azCmd[2];
5435      if( zName[0]==0 ) goto session_syntax_error;
5436      for(i=0; i<p->nSession; i++){
5437        if( strcmp(p->aSession[i].zName,zName)==0 ){
5438          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
5439          goto meta_command_exit;
5440        }
5441      }
5442      if( p->nSession>=ArraySize(p->aSession) ){
5443        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
5444        goto meta_command_exit;
5445      }
5446      pSession = &p->aSession[p->nSession];
5447      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5448      if( rc ){
5449        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
5450        rc = 0;
5451        goto meta_command_exit;
5452      }
5453      pSession->nFilter = 0;
5454      sqlite3session_table_filter(pSession->p, session_filter, pSession);
5455      p->nSession++;
5456      pSession->zName = sqlite3_mprintf("%s", zName);
5457    }else
5458    /* If no command name matches, show a syntax error */
5459    session_syntax_error:
5460    session_help(p);
5461  }else
5462#endif
5463
5464#ifdef SQLITE_DEBUG
5465  /* Undocumented commands for internal testing.  Subject to change
5466  ** without notice. */
5467  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5468    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5469      int i, v;
5470      for(i=1; i<nArg; i++){
5471        v = booleanValue(azArg[i]);
5472        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
5473      }
5474    }
5475    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5476      int i; sqlite3_int64 v;
5477      for(i=1; i<nArg; i++){
5478        char zBuf[200];
5479        v = integerValue(azArg[i]);
5480        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
5481        utf8_printf(p->out, "%s", zBuf);
5482      }
5483    }
5484  }else
5485#endif
5486
5487  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5488    int bIsInit = 0;         /* True to initialize the SELFTEST table */
5489    int bVerbose = 0;        /* Verbose output */
5490    int bSelftestExists;     /* True if SELFTEST already exists */
5491    int i, k;                /* Loop counters */
5492    int nTest = 0;           /* Number of tests runs */
5493    int nErr = 0;            /* Number of errors seen */
5494    ShellText str;           /* Answer for a query */
5495    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
5496
5497    open_db(p,0);
5498    for(i=1; i<nArg; i++){
5499      const char *z = azArg[i];
5500      if( z[0]=='-' && z[1]=='-' ) z++;
5501      if( strcmp(z,"-init")==0 ){
5502        bIsInit = 1;
5503      }else
5504      if( strcmp(z,"-v")==0 ){
5505        bVerbose++;
5506      }else
5507      {
5508        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5509                    azArg[i], azArg[0]);
5510        raw_printf(stderr, "Should be one of: --init -v\n");
5511        rc = 1;
5512        goto meta_command_exit;
5513      }
5514    }
5515    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5516           != SQLITE_OK ){
5517      bSelftestExists = 0;
5518    }else{
5519      bSelftestExists = 1;
5520    }
5521    if( bIsInit ){
5522      createSelftestTable(p);
5523      bSelftestExists = 1;
5524    }
5525    initText(&str);
5526    appendText(&str, "x", 0);
5527    for(k=bSelftestExists; k>=0; k--){
5528      if( k==1 ){
5529        rc = sqlite3_prepare_v2(p->db,
5530            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5531            -1, &pStmt, 0);
5532      }else{
5533        rc = sqlite3_prepare_v2(p->db,
5534          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
5535          "      (1,'run','PRAGMA integrity_check','ok')",
5536          -1, &pStmt, 0);
5537      }
5538      if( rc ){
5539        raw_printf(stderr, "Error querying the selftest table\n");
5540        rc = 1;
5541        sqlite3_finalize(pStmt);
5542        goto meta_command_exit;
5543      }
5544      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
5545        int tno = sqlite3_column_int(pStmt, 0);
5546        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
5547        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
5548        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
5549
5550        k = 0;
5551        if( bVerbose>0 ){
5552          char *zQuote = sqlite3_mprintf("%q", zSql);
5553          printf("%d: %s %s\n", tno, zOp, zSql);
5554          sqlite3_free(zQuote);
5555        }
5556        if( strcmp(zOp,"memo")==0 ){
5557          utf8_printf(p->out, "%s\n", zSql);
5558        }else
5559        if( strcmp(zOp,"run")==0 ){
5560          char *zErrMsg = 0;
5561          str.n = 0;
5562          str.z[0] = 0;
5563          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5564          nTest++;
5565          if( bVerbose ){
5566            utf8_printf(p->out, "Result: %s\n", str.z);
5567          }
5568          if( rc || zErrMsg ){
5569            nErr++;
5570            rc = 1;
5571            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5572            sqlite3_free(zErrMsg);
5573          }else if( strcmp(zAns,str.z)!=0 ){
5574            nErr++;
5575            rc = 1;
5576            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5577            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
5578          }
5579        }else
5580        {
5581          utf8_printf(stderr,
5582            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5583          rc = 1;
5584          break;
5585        }
5586      } /* End loop over rows of content from SELFTEST */
5587      sqlite3_finalize(pStmt);
5588    } /* End loop over k */
5589    freeText(&str);
5590    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5591  }else
5592
5593  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
5594    if( nArg<2 || nArg>3 ){
5595      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
5596      rc = 1;
5597    }
5598    if( nArg>=2 ){
5599      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
5600                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
5601    }
5602    if( nArg>=3 ){
5603      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5604                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
5605    }
5606  }else
5607
5608  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5609    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
5610    int i;                   /* Loop counter */
5611    int bSchema = 0;         /* Also hash the schema */
5612    int bSeparate = 0;       /* Hash each table separately */
5613    int iSize = 224;         /* Hash algorithm to use */
5614    int bDebug = 0;          /* Only show the query that would have run */
5615    sqlite3_stmt *pStmt;     /* For querying tables names */
5616    char *zSql;              /* SQL to be run */
5617    char *zSep;              /* Separator */
5618    ShellText sSql;          /* Complete SQL for the query to run the hash */
5619    ShellText sQuery;        /* Set of queries used to read all content */
5620    open_db(p, 0);
5621    for(i=1; i<nArg; i++){
5622      const char *z = azArg[i];
5623      if( z[0]=='-' ){
5624        z++;
5625        if( z[0]=='-' ) z++;
5626        if( strcmp(z,"schema")==0 ){
5627          bSchema = 1;
5628        }else
5629        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
5630         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
5631        ){
5632          iSize = atoi(&z[5]);
5633        }else
5634        if( strcmp(z,"debug")==0 ){
5635          bDebug = 1;
5636        }else
5637        {
5638          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5639                      azArg[i], azArg[0]);
5640          raw_printf(stderr, "Should be one of: --schema"
5641                             " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5642          rc = 1;
5643          goto meta_command_exit;
5644        }
5645      }else if( zLike ){
5646        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5647        rc = 1;
5648        goto meta_command_exit;
5649      }else{
5650        zLike = z;
5651        bSeparate = 1;
5652        if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
5653      }
5654    }
5655    if( bSchema ){
5656      zSql = "SELECT lower(name) FROM sqlite_master"
5657             " WHERE type='table' AND coalesce(rootpage,0)>1"
5658             " UNION ALL SELECT 'sqlite_master'"
5659             " ORDER BY 1 collate nocase";
5660    }else{
5661      zSql = "SELECT lower(name) FROM sqlite_master"
5662             " WHERE type='table' AND coalesce(rootpage,0)>1"
5663             " AND name NOT LIKE 'sqlite_%'"
5664             " ORDER BY 1 collate nocase";
5665    }
5666    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5667    initText(&sQuery);
5668    initText(&sSql);
5669    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
5670    zSep = "VALUES(";
5671    while( SQLITE_ROW==sqlite3_step(pStmt) ){
5672      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
5673      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
5674      if( strncmp(zTab, "sqlite_",7)!=0 ){
5675        appendText(&sQuery,"SELECT * FROM ", 0);
5676        appendText(&sQuery,zTab,'"');
5677        appendText(&sQuery," NOT INDEXED;", 0);
5678      }else if( strcmp(zTab, "sqlite_master")==0 ){
5679        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5680                           " ORDER BY name;", 0);
5681      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
5682        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
5683                           " ORDER BY name;", 0);
5684      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
5685        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
5686                           " ORDER BY tbl,idx;", 0);
5687      }else if( strcmp(zTab, "sqlite_stat3")==0
5688             || strcmp(zTab, "sqlite_stat4")==0 ){
5689        appendText(&sQuery, "SELECT * FROM ", 0);
5690        appendText(&sQuery, zTab, 0);
5691        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
5692      }
5693      appendText(&sSql, zSep, 0);
5694      appendText(&sSql, sQuery.z, '\'');
5695      sQuery.n = 0;
5696      appendText(&sSql, ",", 0);
5697      appendText(&sSql, zTab, '\'');
5698      zSep = "),(";
5699    }
5700    sqlite3_finalize(pStmt);
5701    if( bSeparate ){
5702      zSql = sqlite3_mprintf(
5703          "%s))"
5704          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
5705          "   FROM [sha3sum$query]",
5706          sSql.z, iSize);
5707    }else{
5708      zSql = sqlite3_mprintf(
5709          "%s))"
5710          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
5711          "   FROM [sha3sum$query]",
5712          sSql.z, iSize);
5713    }
5714    freeText(&sQuery);
5715    freeText(&sSql);
5716    if( bDebug ){
5717      utf8_printf(p->out, "%s\n", zSql);
5718    }else{
5719      shell_exec(p->db, zSql, shell_callback, p, 0);
5720    }
5721    sqlite3_free(zSql);
5722  }else
5723
5724  if( c=='s'
5725   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
5726  ){
5727    char *zCmd;
5728    int i, x;
5729    if( nArg<2 ){
5730      raw_printf(stderr, "Usage: .system COMMAND\n");
5731      rc = 1;
5732      goto meta_command_exit;
5733    }
5734    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
5735    for(i=2; i<nArg; i++){
5736      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
5737                             zCmd, azArg[i]);
5738    }
5739    x = system(zCmd);
5740    sqlite3_free(zCmd);
5741    if( x ) raw_printf(stderr, "System command returns %d\n", x);
5742  }else
5743
5744  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
5745    static const char *azBool[] = { "off", "on", "full", "unk" };
5746    int i;
5747    if( nArg!=1 ){
5748      raw_printf(stderr, "Usage: .show\n");
5749      rc = 1;
5750      goto meta_command_exit;
5751    }
5752    utf8_printf(p->out, "%12.12s: %s\n","echo",
5753                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
5754    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
5755    utf8_printf(p->out, "%12.12s: %s\n","explain",
5756         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
5757    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
5758    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
5759    utf8_printf(p->out, "%12.12s: ", "nullvalue");
5760      output_c_string(p->out, p->nullValue);
5761      raw_printf(p->out, "\n");
5762    utf8_printf(p->out,"%12.12s: %s\n","output",
5763            strlen30(p->outfile) ? p->outfile : "stdout");
5764    utf8_printf(p->out,"%12.12s: ", "colseparator");
5765      output_c_string(p->out, p->colSeparator);
5766      raw_printf(p->out, "\n");
5767    utf8_printf(p->out,"%12.12s: ", "rowseparator");
5768      output_c_string(p->out, p->rowSeparator);
5769      raw_printf(p->out, "\n");
5770    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
5771    utf8_printf(p->out, "%12.12s: ", "width");
5772    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
5773      raw_printf(p->out, "%d ", p->colWidth[i]);
5774    }
5775    raw_printf(p->out, "\n");
5776    utf8_printf(p->out, "%12.12s: %s\n", "filename",
5777                p->zDbFilename ? p->zDbFilename : "");
5778  }else
5779
5780  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
5781    if( nArg==2 ){
5782      p->statsOn = booleanValue(azArg[1]);
5783    }else if( nArg==1 ){
5784      display_stats(p->db, p, 0);
5785    }else{
5786      raw_printf(stderr, "Usage: .stats ?on|off?\n");
5787      rc = 1;
5788    }
5789  }else
5790
5791  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
5792   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
5793                 || strncmp(azArg[0], "indexes", n)==0) )
5794  ){
5795    sqlite3_stmt *pStmt;
5796    char **azResult;
5797    int nRow, nAlloc;
5798    int ii;
5799    ShellText s;
5800    initText(&s);
5801    open_db(p, 0);
5802    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
5803    if( rc ) return shellDatabaseError(p->db);
5804
5805    if( nArg>2 && c=='i' ){
5806      /* It is an historical accident that the .indexes command shows an error
5807      ** when called with the wrong number of arguments whereas the .tables
5808      ** command does not. */
5809      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
5810      rc = 1;
5811      goto meta_command_exit;
5812    }
5813    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
5814      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
5815      if( zDbName==0 ) continue;
5816      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
5817      if( sqlite3_stricmp(zDbName, "main")==0 ){
5818        appendText(&s, "SELECT name FROM ", 0);
5819      }else{
5820        appendText(&s, "SELECT ", 0);
5821        appendText(&s, zDbName, '\'');
5822        appendText(&s, "||'.'||name FROM ", 0);
5823      }
5824      appendText(&s, zDbName, '"');
5825      appendText(&s, ".sqlite_master ", 0);
5826      if( c=='t' ){
5827        appendText(&s," WHERE type IN ('table','view')"
5828                      "   AND name NOT LIKE 'sqlite_%'"
5829                      "   AND name LIKE ?1", 0);
5830      }else{
5831        appendText(&s," WHERE type='index'"
5832                      "   AND tbl_name LIKE ?1", 0);
5833      }
5834    }
5835    rc = sqlite3_finalize(pStmt);
5836    appendText(&s, " ORDER BY 1", 0);
5837    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
5838    freeText(&s);
5839    if( rc ) return shellDatabaseError(p->db);
5840
5841    /* Run the SQL statement prepared by the above block. Store the results
5842    ** as an array of nul-terminated strings in azResult[].  */
5843    nRow = nAlloc = 0;
5844    azResult = 0;
5845    if( nArg>1 ){
5846      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
5847    }else{
5848      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
5849    }
5850    while( sqlite3_step(pStmt)==SQLITE_ROW ){
5851      if( nRow>=nAlloc ){
5852        char **azNew;
5853        int n2 = nAlloc*2 + 10;
5854        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
5855        if( azNew==0 ){
5856          rc = shellNomemError();
5857          break;
5858        }
5859        nAlloc = n2;
5860        azResult = azNew;
5861      }
5862      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
5863      if( 0==azResult[nRow] ){
5864        rc = shellNomemError();
5865        break;
5866      }
5867      nRow++;
5868    }
5869    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
5870      rc = shellDatabaseError(p->db);
5871    }
5872
5873    /* Pretty-print the contents of array azResult[] to the output */
5874    if( rc==0 && nRow>0 ){
5875      int len, maxlen = 0;
5876      int i, j;
5877      int nPrintCol, nPrintRow;
5878      for(i=0; i<nRow; i++){
5879        len = strlen30(azResult[i]);
5880        if( len>maxlen ) maxlen = len;
5881      }
5882      nPrintCol = 80/(maxlen+2);
5883      if( nPrintCol<1 ) nPrintCol = 1;
5884      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
5885      for(i=0; i<nPrintRow; i++){
5886        for(j=i; j<nRow; j+=nPrintRow){
5887          char *zSp = j<nPrintRow ? "" : "  ";
5888          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
5889                      azResult[j] ? azResult[j]:"");
5890        }
5891        raw_printf(p->out, "\n");
5892      }
5893    }
5894
5895    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
5896    sqlite3_free(azResult);
5897  }else
5898
5899  /* Begin redirecting output to the file "testcase-out.txt" */
5900  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
5901    output_reset(p);
5902    p->out = output_file_open("testcase-out.txt");
5903    if( p->out==0 ){
5904      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
5905    }
5906    if( nArg>=2 ){
5907      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
5908    }else{
5909      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
5910    }
5911  }else
5912
5913#ifndef SQLITE_UNTESTABLE
5914  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
5915    static const struct {
5916       const char *zCtrlName;   /* Name of a test-control option */
5917       int ctrlCode;            /* Integer code for that option */
5918    } aCtrl[] = {
5919      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
5920      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
5921      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
5922      { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
5923      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
5924      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
5925      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
5926      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
5927      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
5928      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
5929      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
5930      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
5931      { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
5932      { "byteorder",             SQLITE_TESTCTRL_BYTEORDER              },
5933      { "never_corrupt",         SQLITE_TESTCTRL_NEVER_CORRUPT          },
5934      { "imposter",              SQLITE_TESTCTRL_IMPOSTER               },
5935    };
5936    int testctrl = -1;
5937    int rc2 = 0;
5938    int i, n2;
5939    open_db(p, 0);
5940
5941    /* convert testctrl text option to value. allow any unique prefix
5942    ** of the option name, or a numerical value. */
5943    n2 = strlen30(azArg[1]);
5944    for(i=0; i<ArraySize(aCtrl); i++){
5945      if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
5946        if( testctrl<0 ){
5947          testctrl = aCtrl[i].ctrlCode;
5948        }else{
5949          utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
5950          testctrl = -1;
5951          break;
5952        }
5953      }
5954    }
5955    if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
5956    if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
5957      utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
5958    }else{
5959      switch(testctrl){
5960
5961        /* sqlite3_test_control(int, db, int) */
5962        case SQLITE_TESTCTRL_OPTIMIZATIONS:
5963        case SQLITE_TESTCTRL_RESERVE:
5964          if( nArg==3 ){
5965            int opt = (int)strtol(azArg[2], 0, 0);
5966            rc2 = sqlite3_test_control(testctrl, p->db, opt);
5967            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5968          } else {
5969            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
5970                    azArg[1]);
5971          }
5972          break;
5973
5974        /* sqlite3_test_control(int) */
5975        case SQLITE_TESTCTRL_PRNG_SAVE:
5976        case SQLITE_TESTCTRL_PRNG_RESTORE:
5977        case SQLITE_TESTCTRL_PRNG_RESET:
5978        case SQLITE_TESTCTRL_BYTEORDER:
5979          if( nArg==2 ){
5980            rc2 = sqlite3_test_control(testctrl);
5981            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5982          } else {
5983            utf8_printf(stderr,"Error: testctrl %s takes no options\n",
5984                        azArg[1]);
5985          }
5986          break;
5987
5988        /* sqlite3_test_control(int, uint) */
5989        case SQLITE_TESTCTRL_PENDING_BYTE:
5990          if( nArg==3 ){
5991            unsigned int opt = (unsigned int)integerValue(azArg[2]);
5992            rc2 = sqlite3_test_control(testctrl, opt);
5993            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
5994          } else {
5995            utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
5996                           " int option\n", azArg[1]);
5997          }
5998          break;
5999
6000        /* sqlite3_test_control(int, int) */
6001        case SQLITE_TESTCTRL_ASSERT:
6002        case SQLITE_TESTCTRL_ALWAYS:
6003        case SQLITE_TESTCTRL_NEVER_CORRUPT:
6004          if( nArg==3 ){
6005            int opt = booleanValue(azArg[2]);
6006            rc2 = sqlite3_test_control(testctrl, opt);
6007            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6008          } else {
6009            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
6010                            azArg[1]);
6011          }
6012          break;
6013
6014        /* sqlite3_test_control(int, char *) */
6015#ifdef SQLITE_N_KEYWORD
6016        case SQLITE_TESTCTRL_ISKEYWORD:
6017          if( nArg==3 ){
6018            const char *opt = azArg[2];
6019            rc2 = sqlite3_test_control(testctrl, opt);
6020            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6021          } else {
6022            utf8_printf(stderr,
6023                        "Error: testctrl %s takes a single char * option\n",
6024                        azArg[1]);
6025          }
6026          break;
6027#endif
6028
6029        case SQLITE_TESTCTRL_IMPOSTER:
6030          if( nArg==5 ){
6031            rc2 = sqlite3_test_control(testctrl, p->db,
6032                          azArg[2],
6033                          integerValue(azArg[3]),
6034                          integerValue(azArg[4]));
6035            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
6036          }else{
6037            raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
6038          }
6039          break;
6040
6041        case SQLITE_TESTCTRL_BITVEC_TEST:
6042        case SQLITE_TESTCTRL_FAULT_INSTALL:
6043        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6044        case SQLITE_TESTCTRL_SCRATCHMALLOC:
6045        default:
6046          utf8_printf(stderr,
6047                      "Error: CLI support for testctrl %s not implemented\n",
6048                      azArg[1]);
6049          break;
6050      }
6051    }
6052  }else
6053#endif /* !defined(SQLITE_UNTESTABLE) */
6054
6055  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
6056    open_db(p, 0);
6057    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
6058  }else
6059
6060  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6061    if( nArg==2 ){
6062      enableTimer = booleanValue(azArg[1]);
6063      if( enableTimer && !HAS_TIMER ){
6064        raw_printf(stderr, "Error: timer not available on this system.\n");
6065        enableTimer = 0;
6066      }
6067    }else{
6068      raw_printf(stderr, "Usage: .timer on|off\n");
6069      rc = 1;
6070    }
6071  }else
6072
6073  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
6074    open_db(p, 0);
6075    if( nArg!=2 ){
6076      raw_printf(stderr, "Usage: .trace FILE|off\n");
6077      rc = 1;
6078      goto meta_command_exit;
6079    }
6080    output_file_close(p->traceOut);
6081    p->traceOut = output_file_open(azArg[1]);
6082#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6083    if( p->traceOut==0 ){
6084      sqlite3_trace_v2(p->db, 0, 0, 0);
6085    }else{
6086      sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
6087    }
6088#endif
6089  }else
6090
6091#if SQLITE_USER_AUTHENTICATION
6092  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6093    if( nArg<2 ){
6094      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
6095      rc = 1;
6096      goto meta_command_exit;
6097    }
6098    open_db(p, 0);
6099    if( strcmp(azArg[1],"login")==0 ){
6100      if( nArg!=4 ){
6101        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
6102        rc = 1;
6103        goto meta_command_exit;
6104      }
6105      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6106                                    (int)strlen(azArg[3]));
6107      if( rc ){
6108        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
6109        rc = 1;
6110      }
6111    }else if( strcmp(azArg[1],"add")==0 ){
6112      if( nArg!=5 ){
6113        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
6114        rc = 1;
6115        goto meta_command_exit;
6116      }
6117      rc = sqlite3_user_add(p->db, azArg[2],
6118                            azArg[3], (int)strlen(azArg[3]),
6119                            booleanValue(azArg[4]));
6120      if( rc ){
6121        raw_printf(stderr, "User-Add failed: %d\n", rc);
6122        rc = 1;
6123      }
6124    }else if( strcmp(azArg[1],"edit")==0 ){
6125      if( nArg!=5 ){
6126        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
6127        rc = 1;
6128        goto meta_command_exit;
6129      }
6130      rc = sqlite3_user_change(p->db, azArg[2],
6131                              azArg[3], (int)strlen(azArg[3]),
6132                              booleanValue(azArg[4]));
6133      if( rc ){
6134        raw_printf(stderr, "User-Edit failed: %d\n", rc);
6135        rc = 1;
6136      }
6137    }else if( strcmp(azArg[1],"delete")==0 ){
6138      if( nArg!=3 ){
6139        raw_printf(stderr, "Usage: .user delete USER\n");
6140        rc = 1;
6141        goto meta_command_exit;
6142      }
6143      rc = sqlite3_user_delete(p->db, azArg[2]);
6144      if( rc ){
6145        raw_printf(stderr, "User-Delete failed: %d\n", rc);
6146        rc = 1;
6147      }
6148    }else{
6149      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
6150      rc = 1;
6151      goto meta_command_exit;
6152    }
6153  }else
6154#endif /* SQLITE_USER_AUTHENTICATION */
6155
6156  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
6157    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
6158        sqlite3_libversion(), sqlite3_sourceid());
6159  }else
6160
6161  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6162    const char *zDbName = nArg==2 ? azArg[1] : "main";
6163    sqlite3_vfs *pVfs = 0;
6164    if( p->db ){
6165      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6166      if( pVfs ){
6167        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
6168        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6169        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6170        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6171      }
6172    }
6173  }else
6174
6175  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6176    sqlite3_vfs *pVfs;
6177    sqlite3_vfs *pCurrent = 0;
6178    if( p->db ){
6179      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6180    }
6181    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6182      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
6183           pVfs==pCurrent ? "  <--- CURRENT" : "");
6184      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
6185      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
6186      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6187      if( pVfs->pNext ){
6188        raw_printf(p->out, "-----------------------------------\n");
6189      }
6190    }
6191  }else
6192
6193  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6194    const char *zDbName = nArg==2 ? azArg[1] : "main";
6195    char *zVfsName = 0;
6196    if( p->db ){
6197      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6198      if( zVfsName ){
6199        utf8_printf(p->out, "%s\n", zVfsName);
6200        sqlite3_free(zVfsName);
6201      }
6202    }
6203  }else
6204
6205#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6206  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
6207    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
6208  }else
6209#endif
6210
6211  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
6212    int j;
6213    assert( nArg<=ArraySize(azArg) );
6214    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
6215      p->colWidth[j-1] = (int)integerValue(azArg[j]);
6216    }
6217  }else
6218
6219  {
6220    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
6221      " \"%s\". Enter \".help\" for help\n", azArg[0]);
6222    rc = 1;
6223  }
6224
6225meta_command_exit:
6226  if( p->outCount ){
6227    p->outCount--;
6228    if( p->outCount==0 ) output_reset(p);
6229  }
6230  return rc;
6231}
6232
6233/*
6234** Return TRUE if a semicolon occurs anywhere in the first N characters
6235** of string z[].
6236*/
6237static int line_contains_semicolon(const char *z, int N){
6238  int i;
6239  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
6240  return 0;
6241}
6242
6243/*
6244** Test to see if a line consists entirely of whitespace.
6245*/
6246static int _all_whitespace(const char *z){
6247  for(; *z; z++){
6248    if( IsSpace(z[0]) ) continue;
6249    if( *z=='/' && z[1]=='*' ){
6250      z += 2;
6251      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6252      if( *z==0 ) return 0;
6253      z++;
6254      continue;
6255    }
6256    if( *z=='-' && z[1]=='-' ){
6257      z += 2;
6258      while( *z && *z!='\n' ){ z++; }
6259      if( *z==0 ) return 1;
6260      continue;
6261    }
6262    return 0;
6263  }
6264  return 1;
6265}
6266
6267/*
6268** Return TRUE if the line typed in is an SQL command terminator other
6269** than a semi-colon.  The SQL Server style "go" command is understood
6270** as is the Oracle "/".
6271*/
6272static int line_is_command_terminator(const char *zLine){
6273  while( IsSpace(zLine[0]) ){ zLine++; };
6274  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6275    return 1;  /* Oracle */
6276  }
6277  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
6278         && _all_whitespace(&zLine[2]) ){
6279    return 1;  /* SQL Server */
6280  }
6281  return 0;
6282}
6283
6284/*
6285** Return true if zSql is a complete SQL statement.  Return false if it
6286** ends in the middle of a string literal or C-style comment.
6287*/
6288static int line_is_complete(char *zSql, int nSql){
6289  int rc;
6290  if( zSql==0 ) return 1;
6291  zSql[nSql] = ';';
6292  zSql[nSql+1] = 0;
6293  rc = sqlite3_complete(zSql);
6294  zSql[nSql] = 0;
6295  return rc;
6296}
6297
6298/*
6299** Run a single line of SQL
6300*/
6301static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6302  int rc;
6303  char *zErrMsg = 0;
6304
6305  open_db(p, 0);
6306  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
6307  BEGIN_TIMER;
6308  rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6309  END_TIMER;
6310  if( rc || zErrMsg ){
6311    char zPrefix[100];
6312    if( in!=0 || !stdin_is_interactive ){
6313      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6314                       "Error: near line %d:", startline);
6315    }else{
6316      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6317    }
6318    if( zErrMsg!=0 ){
6319      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6320      sqlite3_free(zErrMsg);
6321      zErrMsg = 0;
6322    }else{
6323      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6324    }
6325    return 1;
6326  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
6327    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
6328            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6329  }
6330  return 0;
6331}
6332
6333
6334/*
6335** Read input from *in and process it.  If *in==0 then input
6336** is interactive - the user is typing it it.  Otherwise, input
6337** is coming from a file or device.  A prompt is issued and history
6338** is saved only if input is interactive.  An interrupt signal will
6339** cause this routine to exit immediately, unless input is interactive.
6340**
6341** Return the number of errors.
6342*/
6343static int process_input(ShellState *p, FILE *in){
6344  char *zLine = 0;          /* A single input line */
6345  char *zSql = 0;           /* Accumulated SQL text */
6346  int nLine;                /* Length of current line */
6347  int nSql = 0;             /* Bytes of zSql[] used */
6348  int nAlloc = 0;           /* Allocated zSql[] space */
6349  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
6350  int rc;                   /* Error code */
6351  int errCnt = 0;           /* Number of errors seen */
6352  int lineno = 0;           /* Current line number */
6353  int startline = 0;        /* Line number for start of current input */
6354
6355  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6356    fflush(p->out);
6357    zLine = one_input_line(in, zLine, nSql>0);
6358    if( zLine==0 ){
6359      /* End of input */
6360      if( in==0 && stdin_is_interactive ) printf("\n");
6361      break;
6362    }
6363    if( seenInterrupt ){
6364      if( in!=0 ) break;
6365      seenInterrupt = 0;
6366    }
6367    lineno++;
6368    if( nSql==0 && _all_whitespace(zLine) ){
6369      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6370      continue;
6371    }
6372    if( zLine && zLine[0]=='.' && nSql==0 ){
6373      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
6374      rc = do_meta_command(zLine, p);
6375      if( rc==2 ){ /* exit requested */
6376        break;
6377      }else if( rc ){
6378        errCnt++;
6379      }
6380      continue;
6381    }
6382    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
6383      memcpy(zLine,";",2);
6384    }
6385    nLine = strlen30(zLine);
6386    if( nSql+nLine+2>=nAlloc ){
6387      nAlloc = nSql+nLine+100;
6388      zSql = realloc(zSql, nAlloc);
6389      if( zSql==0 ){
6390        raw_printf(stderr, "Error: out of memory\n");
6391        exit(1);
6392      }
6393    }
6394    nSqlPrior = nSql;
6395    if( nSql==0 ){
6396      int i;
6397      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
6398      assert( nAlloc>0 && zSql!=0 );
6399      memcpy(zSql, zLine+i, nLine+1-i);
6400      startline = lineno;
6401      nSql = nLine-i;
6402    }else{
6403      zSql[nSql++] = '\n';
6404      memcpy(zSql+nSql, zLine, nLine+1);
6405      nSql += nLine;
6406    }
6407    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
6408                && sqlite3_complete(zSql) ){
6409      errCnt += runOneSqlLine(p, zSql, in, startline);
6410      nSql = 0;
6411      if( p->outCount ){
6412        output_reset(p);
6413        p->outCount = 0;
6414      }
6415    }else if( nSql && _all_whitespace(zSql) ){
6416      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
6417      nSql = 0;
6418    }
6419  }
6420  if( nSql && !_all_whitespace(zSql) ){
6421    runOneSqlLine(p, zSql, in, startline);
6422  }
6423  free(zSql);
6424  free(zLine);
6425  return errCnt>0;
6426}
6427
6428/*
6429** Return a pathname which is the user's home directory.  A
6430** 0 return indicates an error of some kind.
6431*/
6432static char *find_home_dir(int clearFlag){
6433  static char *home_dir = NULL;
6434  if( clearFlag ){
6435    free(home_dir);
6436    home_dir = 0;
6437    return 0;
6438  }
6439  if( home_dir ) return home_dir;
6440
6441#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6442     && !defined(__RTP__) && !defined(_WRS_KERNEL)
6443  {
6444    struct passwd *pwent;
6445    uid_t uid = getuid();
6446    if( (pwent=getpwuid(uid)) != NULL) {
6447      home_dir = pwent->pw_dir;
6448    }
6449  }
6450#endif
6451
6452#if defined(_WIN32_WCE)
6453  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6454   */
6455  home_dir = "/";
6456#else
6457
6458#if defined(_WIN32) || defined(WIN32)
6459  if (!home_dir) {
6460    home_dir = getenv("USERPROFILE");
6461  }
6462#endif
6463
6464  if (!home_dir) {
6465    home_dir = getenv("HOME");
6466  }
6467
6468#if defined(_WIN32) || defined(WIN32)
6469  if (!home_dir) {
6470    char *zDrive, *zPath;
6471    int n;
6472    zDrive = getenv("HOMEDRIVE");
6473    zPath = getenv("HOMEPATH");
6474    if( zDrive && zPath ){
6475      n = strlen30(zDrive) + strlen30(zPath) + 1;
6476      home_dir = malloc( n );
6477      if( home_dir==0 ) return 0;
6478      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6479      return home_dir;
6480    }
6481    home_dir = "c:\\";
6482  }
6483#endif
6484
6485#endif /* !_WIN32_WCE */
6486
6487  if( home_dir ){
6488    int n = strlen30(home_dir) + 1;
6489    char *z = malloc( n );
6490    if( z ) memcpy(z, home_dir, n);
6491    home_dir = z;
6492  }
6493
6494  return home_dir;
6495}
6496
6497/*
6498** Read input from the file given by sqliterc_override.  Or if that
6499** parameter is NULL, take input from ~/.sqliterc
6500**
6501** Returns the number of errors.
6502*/
6503static void process_sqliterc(
6504  ShellState *p,                  /* Configuration data */
6505  const char *sqliterc_override   /* Name of config file. NULL to use default */
6506){
6507  char *home_dir = NULL;
6508  const char *sqliterc = sqliterc_override;
6509  char *zBuf = 0;
6510  FILE *in = NULL;
6511
6512  if (sqliterc == NULL) {
6513    home_dir = find_home_dir(0);
6514    if( home_dir==0 ){
6515      raw_printf(stderr, "-- warning: cannot find home directory;"
6516                      " cannot read ~/.sqliterc\n");
6517      return;
6518    }
6519    sqlite3_initialize();
6520    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6521    sqliterc = zBuf;
6522  }
6523  in = fopen(sqliterc,"rb");
6524  if( in ){
6525    if( stdin_is_interactive ){
6526      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
6527    }
6528    process_input(p,in);
6529    fclose(in);
6530  }
6531  sqlite3_free(zBuf);
6532}
6533
6534/*
6535** Show available command line options
6536*/
6537static const char zOptions[] =
6538  "   -ascii               set output mode to 'ascii'\n"
6539  "   -bail                stop after hitting an error\n"
6540  "   -batch               force batch I/O\n"
6541  "   -column              set output mode to 'column'\n"
6542  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
6543  "   -csv                 set output mode to 'csv'\n"
6544  "   -echo                print commands before execution\n"
6545  "   -init FILENAME       read/process named file\n"
6546  "   -[no]header          turn headers on or off\n"
6547#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6548  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
6549#endif
6550  "   -help                show this message\n"
6551  "   -html                set output mode to HTML\n"
6552  "   -interactive         force interactive I/O\n"
6553  "   -line                set output mode to 'line'\n"
6554  "   -list                set output mode to 'list'\n"
6555  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
6556  "   -mmap N              default mmap size set to N\n"
6557#ifdef SQLITE_ENABLE_MULTIPLEX
6558  "   -multiplex           enable the multiplexor VFS\n"
6559#endif
6560  "   -newline SEP         set output row separator. Default: '\\n'\n"
6561  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
6562  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
6563  "   -quote               set output mode to 'quote'\n"
6564  "   -scratch SIZE N      use N slots of SZ bytes each for scratch memory\n"
6565  "   -separator SEP       set output column separator. Default: '|'\n"
6566  "   -stats               print memory stats before each finalize\n"
6567  "   -version             show SQLite version\n"
6568  "   -vfs NAME            use NAME as the default VFS\n"
6569#ifdef SQLITE_ENABLE_VFSTRACE
6570  "   -vfstrace            enable tracing of all VFS calls\n"
6571#endif
6572;
6573static void usage(int showDetail){
6574  utf8_printf(stderr,
6575      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6576      "FILENAME is the name of an SQLite database. A new database is created\n"
6577      "if the file does not previously exist.\n", Argv0);
6578  if( showDetail ){
6579    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
6580  }else{
6581    raw_printf(stderr, "Use the -help option for additional information\n");
6582  }
6583  exit(1);
6584}
6585
6586/*
6587** Initialize the state information in data
6588*/
6589static void main_init(ShellState *data) {
6590  memset(data, 0, sizeof(*data));
6591  data->normalMode = data->cMode = data->mode = MODE_List;
6592  data->autoExplain = 1;
6593  memcpy(data->colSeparator,SEP_Column, 2);
6594  memcpy(data->rowSeparator,SEP_Row, 2);
6595  data->showHeader = 0;
6596  data->shellFlgs = SHFLG_Lookaside;
6597  sqlite3_config(SQLITE_CONFIG_URI, 1);
6598  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
6599  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
6600  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6601  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
6602}
6603
6604/*
6605** Output text to the console in a font that attracts extra attention.
6606*/
6607#ifdef _WIN32
6608static void printBold(const char *zText){
6609  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6610  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6611  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6612  SetConsoleTextAttribute(out,
6613         FOREGROUND_RED|FOREGROUND_INTENSITY
6614  );
6615  printf("%s", zText);
6616  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
6617}
6618#else
6619static void printBold(const char *zText){
6620  printf("\033[1m%s\033[0m", zText);
6621}
6622#endif
6623
6624/*
6625** Get the argument to an --option.  Throw an error and die if no argument
6626** is available.
6627*/
6628static char *cmdline_option_value(int argc, char **argv, int i){
6629  if( i==argc ){
6630    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
6631            argv[0], argv[argc-1]);
6632    exit(1);
6633  }
6634  return argv[i];
6635}
6636
6637#ifndef SQLITE_SHELL_IS_UTF8
6638#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6639#    define SQLITE_SHELL_IS_UTF8          (0)
6640#  else
6641#    define SQLITE_SHELL_IS_UTF8          (1)
6642#  endif
6643#endif
6644
6645#if SQLITE_SHELL_IS_UTF8
6646int SQLITE_CDECL main(int argc, char **argv){
6647#else
6648int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
6649  char **argv;
6650#endif
6651  char *zErrMsg = 0;
6652  ShellState data;
6653  const char *zInitFile = 0;
6654  int i;
6655  int rc = 0;
6656  int warnInmemoryDb = 0;
6657  int readStdin = 1;
6658  int nCmd = 0;
6659  char **azCmd = 0;
6660
6661  setBinaryMode(stdin, 0);
6662  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
6663  stdin_is_interactive = isatty(0);
6664  stdout_is_console = isatty(1);
6665
6666#if USE_SYSTEM_SQLITE+0!=1
6667  if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
6668    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
6669            sqlite3_sourceid(), SQLITE_SOURCE_ID);
6670    exit(1);
6671  }
6672#endif
6673  main_init(&data);
6674#if !SQLITE_SHELL_IS_UTF8
6675  sqlite3_initialize();
6676  argv = sqlite3_malloc64(sizeof(argv[0])*argc);
6677  if( argv==0 ){
6678    raw_printf(stderr, "out of memory\n");
6679    exit(1);
6680  }
6681  for(i=0; i<argc; i++){
6682    argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
6683    if( argv[i]==0 ){
6684      raw_printf(stderr, "out of memory\n");
6685      exit(1);
6686    }
6687  }
6688#endif
6689  assert( argc>=1 && argv && argv[0] );
6690  Argv0 = argv[0];
6691
6692  /* Make sure we have a valid signal handler early, before anything
6693  ** else is done.
6694  */
6695#ifdef SIGINT
6696  signal(SIGINT, interrupt_handler);
6697#endif
6698
6699#ifdef SQLITE_SHELL_DBNAME_PROC
6700  {
6701    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
6702    ** of a C-function that will provide the name of the database file.  Use
6703    ** this compile-time option to embed this shell program in larger
6704    ** applications. */
6705    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
6706    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
6707    warnInmemoryDb = 0;
6708  }
6709#endif
6710
6711  /* Do an initial pass through the command-line argument to locate
6712  ** the name of the database file, the name of the initialization file,
6713  ** the size of the alternative malloc heap,
6714  ** and the first command to execute.
6715  */
6716  for(i=1; i<argc; i++){
6717    char *z;
6718    z = argv[i];
6719    if( z[0]!='-' ){
6720      if( data.zDbFilename==0 ){
6721        data.zDbFilename = z;
6722      }else{
6723        /* Excesss arguments are interpreted as SQL (or dot-commands) and
6724        ** mean that nothing is read from stdin */
6725        readStdin = 0;
6726        nCmd++;
6727        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
6728        if( azCmd==0 ){
6729          raw_printf(stderr, "out of memory\n");
6730          exit(1);
6731        }
6732        azCmd[nCmd-1] = z;
6733      }
6734    }
6735    if( z[1]=='-' ) z++;
6736    if( strcmp(z,"-separator")==0
6737     || strcmp(z,"-nullvalue")==0
6738     || strcmp(z,"-newline")==0
6739     || strcmp(z,"-cmd")==0
6740    ){
6741      (void)cmdline_option_value(argc, argv, ++i);
6742    }else if( strcmp(z,"-init")==0 ){
6743      zInitFile = cmdline_option_value(argc, argv, ++i);
6744    }else if( strcmp(z,"-batch")==0 ){
6745      /* Need to check for batch mode here to so we can avoid printing
6746      ** informational messages (like from process_sqliterc) before
6747      ** we do the actual processing of arguments later in a second pass.
6748      */
6749      stdin_is_interactive = 0;
6750    }else if( strcmp(z,"-heap")==0 ){
6751#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6752      const char *zSize;
6753      sqlite3_int64 szHeap;
6754
6755      zSize = cmdline_option_value(argc, argv, ++i);
6756      szHeap = integerValue(zSize);
6757      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
6758      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
6759#else
6760      (void)cmdline_option_value(argc, argv, ++i);
6761#endif
6762    }else if( strcmp(z,"-scratch")==0 ){
6763      int n, sz;
6764      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6765      if( sz>400000 ) sz = 400000;
6766      if( sz<2500 ) sz = 2500;
6767      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6768      if( n>10 ) n = 10;
6769      if( n<1 ) n = 1;
6770      sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
6771      data.shellFlgs |= SHFLG_Scratch;
6772    }else if( strcmp(z,"-pagecache")==0 ){
6773      int n, sz;
6774      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6775      if( sz>70000 ) sz = 70000;
6776      if( sz<0 ) sz = 0;
6777      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6778      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
6779                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
6780      data.shellFlgs |= SHFLG_Pagecache;
6781    }else if( strcmp(z,"-lookaside")==0 ){
6782      int n, sz;
6783      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
6784      if( sz<0 ) sz = 0;
6785      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
6786      if( n<0 ) n = 0;
6787      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
6788      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
6789#ifdef SQLITE_ENABLE_VFSTRACE
6790    }else if( strcmp(z,"-vfstrace")==0 ){
6791      extern int vfstrace_register(
6792         const char *zTraceName,
6793         const char *zOldVfsName,
6794         int (*xOut)(const char*,void*),
6795         void *pOutArg,
6796         int makeDefault
6797      );
6798      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
6799#endif
6800#ifdef SQLITE_ENABLE_MULTIPLEX
6801    }else if( strcmp(z,"-multiplex")==0 ){
6802      extern int sqlite3_multiple_initialize(const char*,int);
6803      sqlite3_multiplex_initialize(0, 1);
6804#endif
6805    }else if( strcmp(z,"-mmap")==0 ){
6806      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
6807      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
6808    }else if( strcmp(z,"-vfs")==0 ){
6809      sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
6810      if( pVfs ){
6811        sqlite3_vfs_register(pVfs, 1);
6812      }else{
6813        utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
6814        exit(1);
6815      }
6816    }
6817  }
6818  if( data.zDbFilename==0 ){
6819#ifndef SQLITE_OMIT_MEMORYDB
6820    data.zDbFilename = ":memory:";
6821    warnInmemoryDb = argc==1;
6822#else
6823    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
6824    return 1;
6825#endif
6826  }
6827  data.out = stdout;
6828
6829  /* Go ahead and open the database file if it already exists.  If the
6830  ** file does not exist, delay opening it.  This prevents empty database
6831  ** files from being created if a user mistypes the database name argument
6832  ** to the sqlite command-line tool.
6833  */
6834  if( access(data.zDbFilename, 0)==0 ){
6835    open_db(&data, 0);
6836  }
6837
6838  /* Process the initialization file if there is one.  If no -init option
6839  ** is given on the command line, look for a file named ~/.sqliterc and
6840  ** try to process it.
6841  */
6842  process_sqliterc(&data,zInitFile);
6843
6844  /* Make a second pass through the command-line argument and set
6845  ** options.  This second pass is delayed until after the initialization
6846  ** file is processed so that the command-line arguments will override
6847  ** settings in the initialization file.
6848  */
6849  for(i=1; i<argc; i++){
6850    char *z = argv[i];
6851    if( z[0]!='-' ) continue;
6852    if( z[1]=='-' ){ z++; }
6853    if( strcmp(z,"-init")==0 ){
6854      i++;
6855    }else if( strcmp(z,"-html")==0 ){
6856      data.mode = MODE_Html;
6857    }else if( strcmp(z,"-list")==0 ){
6858      data.mode = MODE_List;
6859    }else if( strcmp(z,"-quote")==0 ){
6860      data.mode = MODE_Quote;
6861    }else if( strcmp(z,"-line")==0 ){
6862      data.mode = MODE_Line;
6863    }else if( strcmp(z,"-column")==0 ){
6864      data.mode = MODE_Column;
6865    }else if( strcmp(z,"-csv")==0 ){
6866      data.mode = MODE_Csv;
6867      memcpy(data.colSeparator,",",2);
6868    }else if( strcmp(z,"-ascii")==0 ){
6869      data.mode = MODE_Ascii;
6870      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6871                       SEP_Unit);
6872      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6873                       SEP_Record);
6874    }else if( strcmp(z,"-separator")==0 ){
6875      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
6876                       "%s",cmdline_option_value(argc,argv,++i));
6877    }else if( strcmp(z,"-newline")==0 ){
6878      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
6879                       "%s",cmdline_option_value(argc,argv,++i));
6880    }else if( strcmp(z,"-nullvalue")==0 ){
6881      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
6882                       "%s",cmdline_option_value(argc,argv,++i));
6883    }else if( strcmp(z,"-header")==0 ){
6884      data.showHeader = 1;
6885    }else if( strcmp(z,"-noheader")==0 ){
6886      data.showHeader = 0;
6887    }else if( strcmp(z,"-echo")==0 ){
6888      ShellSetFlag(&data, SHFLG_Echo);
6889    }else if( strcmp(z,"-eqp")==0 ){
6890      data.autoEQP = 1;
6891    }else if( strcmp(z,"-eqpfull")==0 ){
6892      data.autoEQP = 2;
6893    }else if( strcmp(z,"-stats")==0 ){
6894      data.statsOn = 1;
6895    }else if( strcmp(z,"-scanstats")==0 ){
6896      data.scanstatsOn = 1;
6897    }else if( strcmp(z,"-backslash")==0 ){
6898      /* Undocumented command-line option: -backslash
6899      ** Causes C-style backslash escapes to be evaluated in SQL statements
6900      ** prior to sending the SQL into SQLite.  Useful for injecting
6901      ** crazy bytes in the middle of SQL statements for testing and debugging.
6902      */
6903      ShellSetFlag(&data, SHFLG_Backslash);
6904    }else if( strcmp(z,"-bail")==0 ){
6905      bail_on_error = 1;
6906    }else if( strcmp(z,"-version")==0 ){
6907      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
6908      return 0;
6909    }else if( strcmp(z,"-interactive")==0 ){
6910      stdin_is_interactive = 1;
6911    }else if( strcmp(z,"-batch")==0 ){
6912      stdin_is_interactive = 0;
6913    }else if( strcmp(z,"-heap")==0 ){
6914      i++;
6915    }else if( strcmp(z,"-scratch")==0 ){
6916      i+=2;
6917    }else if( strcmp(z,"-pagecache")==0 ){
6918      i+=2;
6919    }else if( strcmp(z,"-lookaside")==0 ){
6920      i+=2;
6921    }else if( strcmp(z,"-mmap")==0 ){
6922      i++;
6923    }else if( strcmp(z,"-vfs")==0 ){
6924      i++;
6925#ifdef SQLITE_ENABLE_VFSTRACE
6926    }else if( strcmp(z,"-vfstrace")==0 ){
6927      i++;
6928#endif
6929#ifdef SQLITE_ENABLE_MULTIPLEX
6930    }else if( strcmp(z,"-multiplex")==0 ){
6931      i++;
6932#endif
6933    }else if( strcmp(z,"-help")==0 ){
6934      usage(1);
6935    }else if( strcmp(z,"-cmd")==0 ){
6936      /* Run commands that follow -cmd first and separately from commands
6937      ** that simply appear on the command-line.  This seems goofy.  It would
6938      ** be better if all commands ran in the order that they appear.  But
6939      ** we retain the goofy behavior for historical compatibility. */
6940      if( i==argc-1 ) break;
6941      z = cmdline_option_value(argc,argv,++i);
6942      if( z[0]=='.' ){
6943        rc = do_meta_command(z, &data);
6944        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
6945      }else{
6946        open_db(&data, 0);
6947        rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
6948        if( zErrMsg!=0 ){
6949          utf8_printf(stderr,"Error: %s\n", zErrMsg);
6950          if( bail_on_error ) return rc!=0 ? rc : 1;
6951        }else if( rc!=0 ){
6952          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
6953          if( bail_on_error ) return rc;
6954        }
6955      }
6956    }else{
6957      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
6958      raw_printf(stderr,"Use -help for a list of options.\n");
6959      return 1;
6960    }
6961    data.cMode = data.mode;
6962  }
6963
6964  if( !readStdin ){
6965    /* Run all arguments that do not begin with '-' as if they were separate
6966    ** command-line inputs, except for the argToSkip argument which contains
6967    ** the database filename.
6968    */
6969    for(i=0; i<nCmd; i++){
6970      if( azCmd[i][0]=='.' ){
6971        rc = do_meta_command(azCmd[i], &data);
6972        if( rc ) return rc==2 ? 0 : rc;
6973      }else{
6974        open_db(&data, 0);
6975        rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
6976        if( zErrMsg!=0 ){
6977          utf8_printf(stderr,"Error: %s\n", zErrMsg);
6978          return rc!=0 ? rc : 1;
6979        }else if( rc!=0 ){
6980          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
6981          return rc;
6982        }
6983      }
6984    }
6985    free(azCmd);
6986  }else{
6987    /* Run commands received from standard input
6988    */
6989    if( stdin_is_interactive ){
6990      char *zHome;
6991      char *zHistory = 0;
6992      int nHistory;
6993      printf(
6994        "SQLite version %s %.19s\n" /*extra-version-info*/
6995        "Enter \".help\" for usage hints.\n",
6996        sqlite3_libversion(), sqlite3_sourceid()
6997      );
6998      if( warnInmemoryDb ){
6999        printf("Connected to a ");
7000        printBold("transient in-memory database");
7001        printf(".\nUse \".open FILENAME\" to reopen on a "
7002               "persistent database.\n");
7003      }
7004      zHome = find_home_dir(0);
7005      if( zHome ){
7006        nHistory = strlen30(zHome) + 20;
7007        if( (zHistory = malloc(nHistory))!=0 ){
7008          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7009        }
7010      }
7011      if( zHistory ){ shell_read_history(zHistory); }
7012#if HAVE_READLINE || HAVE_EDITLINE
7013      rl_attempted_completion_function = readline_completion;
7014#elif HAVE_LINENOISE
7015      linenoiseSetCompletionCallback(linenoise_completion);
7016#endif
7017      rc = process_input(&data, 0);
7018      if( zHistory ){
7019        shell_stifle_history(100);
7020        shell_write_history(zHistory);
7021        free(zHistory);
7022      }
7023    }else{
7024      rc = process_input(&data, stdin);
7025    }
7026  }
7027  set_table_name(&data, 0);
7028  if( data.db ){
7029    session_close_all(&data);
7030    sqlite3_close(data.db);
7031  }
7032  sqlite3_free(data.zFreeOnClose);
7033  find_home_dir(1);
7034#if !SQLITE_SHELL_IS_UTF8
7035  for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7036  sqlite3_free(argv);
7037#endif
7038  return rc;
7039}
7040