xref: /sqlite-3.40.0/src/shell.c.in (revision 49507d2a)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
42** somewhat for use as a WASM module in a web browser. This flag
43** should only be used when building the "fiddle" web application, as
44** the browser-mode build has much different user input requirements
45** and this build mode rewires the user input subsystem to account for
46** that.
47*/
48
49/*
50** Warning pragmas copied from msvc.h in the core.
51*/
52#if defined(_MSC_VER)
53#pragma warning(disable : 4054)
54#pragma warning(disable : 4055)
55#pragma warning(disable : 4100)
56#pragma warning(disable : 4127)
57#pragma warning(disable : 4130)
58#pragma warning(disable : 4152)
59#pragma warning(disable : 4189)
60#pragma warning(disable : 4206)
61#pragma warning(disable : 4210)
62#pragma warning(disable : 4232)
63#pragma warning(disable : 4244)
64#pragma warning(disable : 4305)
65#pragma warning(disable : 4306)
66#pragma warning(disable : 4702)
67#pragma warning(disable : 4706)
68#endif /* defined(_MSC_VER) */
69
70/*
71** No support for loadable extensions in VxWorks.
72*/
73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
74# define SQLITE_OMIT_LOAD_EXTENSION 1
75#endif
76
77/*
78** Enable large-file support for fopen() and friends on unix.
79*/
80#ifndef SQLITE_DISABLE_LFS
81# define _LARGE_FILE       1
82# ifndef _FILE_OFFSET_BITS
83#   define _FILE_OFFSET_BITS 64
84# endif
85# define _LARGEFILE_SOURCE 1
86#endif
87
88#if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE)
89/*
90** emcc requires _POSIX_SOURCE (or one of several similar defines)
91** to expose strdup().
92*/
93# define _POSIX_SOURCE
94#endif
95
96#include <stdlib.h>
97#include <string.h>
98#include <stdio.h>
99#include <assert.h>
100#include "sqlite3.h"
101typedef sqlite3_int64 i64;
102typedef sqlite3_uint64 u64;
103typedef unsigned char u8;
104#if SQLITE_USER_AUTHENTICATION
105# include "sqlite3userauth.h"
106#endif
107#include <ctype.h>
108#include <stdarg.h>
109
110#if !defined(_WIN32) && !defined(WIN32)
111# include <signal.h>
112# if !defined(__RTP__) && !defined(_WRS_KERNEL)
113#  include <pwd.h>
114# endif
115#endif
116#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
117# include <unistd.h>
118# include <dirent.h>
119# define GETPID getpid
120# if defined(__MINGW32__)
121#  define DIRENT dirent
122#  ifndef S_ISLNK
123#   define S_ISLNK(mode) (0)
124#  endif
125# endif
126#else
127# define GETPID (int)GetCurrentProcessId
128#endif
129#include <sys/types.h>
130#include <sys/stat.h>
131
132#if HAVE_READLINE
133# include <readline/readline.h>
134# include <readline/history.h>
135#endif
136
137#if HAVE_EDITLINE
138# include <editline/readline.h>
139#endif
140
141#if HAVE_EDITLINE || HAVE_READLINE
142
143# define shell_add_history(X) add_history(X)
144# define shell_read_history(X) read_history(X)
145# define shell_write_history(X) write_history(X)
146# define shell_stifle_history(X) stifle_history(X)
147# define shell_readline(X) readline(X)
148
149#elif HAVE_LINENOISE
150
151# include "linenoise.h"
152# define shell_add_history(X) linenoiseHistoryAdd(X)
153# define shell_read_history(X) linenoiseHistoryLoad(X)
154# define shell_write_history(X) linenoiseHistorySave(X)
155# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
156# define shell_readline(X) linenoise(X)
157
158#else
159
160# define shell_read_history(X)
161# define shell_write_history(X)
162# define shell_stifle_history(X)
163
164# define SHELL_USE_LOCAL_GETLINE 1
165#endif
166
167
168#if defined(_WIN32) || defined(WIN32)
169# if SQLITE_OS_WINRT
170#  define SQLITE_OMIT_POPEN 1
171# else
172#  include <io.h>
173#  include <fcntl.h>
174#  define isatty(h) _isatty(h)
175#  ifndef access
176#   define access(f,m) _access((f),(m))
177#  endif
178#  ifndef unlink
179#   define unlink _unlink
180#  endif
181#  ifndef strdup
182#   define strdup _strdup
183#  endif
184#  undef popen
185#  define popen _popen
186#  undef pclose
187#  define pclose _pclose
188# endif
189#else
190 /* Make sure isatty() has a prototype. */
191 extern int isatty(int);
192
193# if !defined(__RTP__) && !defined(_WRS_KERNEL)
194  /* popen and pclose are not C89 functions and so are
195  ** sometimes omitted from the <stdio.h> header */
196   extern FILE *popen(const char*,const char*);
197   extern int pclose(FILE*);
198# else
199#  define SQLITE_OMIT_POPEN 1
200# endif
201#endif
202
203#if defined(_WIN32_WCE)
204/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
205 * thus we always assume that we have a console. That can be
206 * overridden with the -batch command line option.
207 */
208#define isatty(x) 1
209#endif
210
211/* ctype macros that work with signed characters */
212#define IsSpace(X)  isspace((unsigned char)X)
213#define IsDigit(X)  isdigit((unsigned char)X)
214#define ToLower(X)  (char)tolower((unsigned char)X)
215
216#if defined(_WIN32) || defined(WIN32)
217#if SQLITE_OS_WINRT
218#include <intrin.h>
219#endif
220#include <windows.h>
221
222/* string conversion routines only needed on Win32 */
223extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
224extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
225extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
226extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
227#endif
228
229/* On Windows, we normally run with output mode of TEXT so that \n characters
230** are automatically translated into \r\n.  However, this behavior needs
231** to be disabled in some cases (ex: when generating CSV output and when
232** rendering quoted strings that contain \n characters).  The following
233** routines take care of that.
234*/
235#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
236static void setBinaryMode(FILE *file, int isOutput){
237  if( isOutput ) fflush(file);
238  _setmode(_fileno(file), _O_BINARY);
239}
240static void setTextMode(FILE *file, int isOutput){
241  if( isOutput ) fflush(file);
242  _setmode(_fileno(file), _O_TEXT);
243}
244#else
245# define setBinaryMode(X,Y)
246# define setTextMode(X,Y)
247#endif
248
249/* True if the timer is enabled */
250static int enableTimer = 0;
251
252/* A version of strcmp() that works with NULL values */
253static int cli_strcmp(const char *a, const char *b){
254  if( a==0 ) a = "";
255  if( b==0 ) b = "";
256  return strcmp(a,b);
257}
258static int cli_strncmp(const char *a, const char *b, size_t n){
259  if( a==0 ) a = "";
260  if( b==0 ) b = "";
261  return strncmp(a,b,n);
262}
263
264/* Return the current wall-clock time */
265static sqlite3_int64 timeOfDay(void){
266  static sqlite3_vfs *clockVfs = 0;
267  sqlite3_int64 t;
268  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
269  if( clockVfs==0 ) return 0;  /* Never actually happens */
270  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
271    clockVfs->xCurrentTimeInt64(clockVfs, &t);
272  }else{
273    double r;
274    clockVfs->xCurrentTime(clockVfs, &r);
275    t = (sqlite3_int64)(r*86400000.0);
276  }
277  return t;
278}
279
280#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
281#include <sys/time.h>
282#include <sys/resource.h>
283
284/* VxWorks does not support getrusage() as far as we can determine */
285#if defined(_WRS_KERNEL) || defined(__RTP__)
286struct rusage {
287  struct timeval ru_utime; /* user CPU time used */
288  struct timeval ru_stime; /* system CPU time used */
289};
290#define getrusage(A,B) memset(B,0,sizeof(*B))
291#endif
292
293/* Saved resource information for the beginning of an operation */
294static struct rusage sBegin;  /* CPU time at start */
295static sqlite3_int64 iBegin;  /* Wall-clock time at start */
296
297/*
298** Begin timing an operation
299*/
300static void beginTimer(void){
301  if( enableTimer ){
302    getrusage(RUSAGE_SELF, &sBegin);
303    iBegin = timeOfDay();
304  }
305}
306
307/* Return the difference of two time_structs in seconds */
308static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
309  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
310         (double)(pEnd->tv_sec - pStart->tv_sec);
311}
312
313/*
314** Print the timing results.
315*/
316static void endTimer(void){
317  if( enableTimer ){
318    sqlite3_int64 iEnd = timeOfDay();
319    struct rusage sEnd;
320    getrusage(RUSAGE_SELF, &sEnd);
321    printf("Run Time: real %.3f user %f sys %f\n",
322       (iEnd - iBegin)*0.001,
323       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
324       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
325  }
326}
327
328#define BEGIN_TIMER beginTimer()
329#define END_TIMER endTimer()
330#define HAS_TIMER 1
331
332#elif (defined(_WIN32) || defined(WIN32))
333
334/* Saved resource information for the beginning of an operation */
335static HANDLE hProcess;
336static FILETIME ftKernelBegin;
337static FILETIME ftUserBegin;
338static sqlite3_int64 ftWallBegin;
339typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
340                                    LPFILETIME, LPFILETIME);
341static GETPROCTIMES getProcessTimesAddr = NULL;
342
343/*
344** Check to see if we have timer support.  Return 1 if necessary
345** support found (or found previously).
346*/
347static int hasTimer(void){
348  if( getProcessTimesAddr ){
349    return 1;
350  } else {
351#if !SQLITE_OS_WINRT
352    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
353    ** versions. See if the version we are running on has it, and if it
354    ** does, save off a pointer to it and the current process handle.
355    */
356    hProcess = GetCurrentProcess();
357    if( hProcess ){
358      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
359      if( NULL != hinstLib ){
360        getProcessTimesAddr =
361            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
362        if( NULL != getProcessTimesAddr ){
363          return 1;
364        }
365        FreeLibrary(hinstLib);
366      }
367    }
368#endif
369  }
370  return 0;
371}
372
373/*
374** Begin timing an operation
375*/
376static void beginTimer(void){
377  if( enableTimer && getProcessTimesAddr ){
378    FILETIME ftCreation, ftExit;
379    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
380                        &ftKernelBegin,&ftUserBegin);
381    ftWallBegin = timeOfDay();
382  }
383}
384
385/* Return the difference of two FILETIME structs in seconds */
386static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
387  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
388  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
389  return (double) ((i64End - i64Start) / 10000000.0);
390}
391
392/*
393** Print the timing results.
394*/
395static void endTimer(void){
396  if( enableTimer && getProcessTimesAddr){
397    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
398    sqlite3_int64 ftWallEnd = timeOfDay();
399    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
400    printf("Run Time: real %.3f user %f sys %f\n",
401       (ftWallEnd - ftWallBegin)*0.001,
402       timeDiff(&ftUserBegin, &ftUserEnd),
403       timeDiff(&ftKernelBegin, &ftKernelEnd));
404  }
405}
406
407#define BEGIN_TIMER beginTimer()
408#define END_TIMER endTimer()
409#define HAS_TIMER hasTimer()
410
411#else
412#define BEGIN_TIMER
413#define END_TIMER
414#define HAS_TIMER 0
415#endif
416
417/*
418** Used to prevent warnings about unused parameters
419*/
420#define UNUSED_PARAMETER(x) (void)(x)
421
422/*
423** Number of elements in an array
424*/
425#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
426
427/*
428** If the following flag is set, then command execution stops
429** at an error if we are not interactive.
430*/
431static int bail_on_error = 0;
432
433/*
434** Threat stdin as an interactive input if the following variable
435** is true.  Otherwise, assume stdin is connected to a file or pipe.
436*/
437static int stdin_is_interactive = 1;
438
439/*
440** On Windows systems we have to know if standard output is a console
441** in order to translate UTF-8 into MBCS.  The following variable is
442** true if translation is required.
443*/
444static int stdout_is_console = 1;
445
446/*
447** The following is the open SQLite database.  We make a pointer
448** to this database a static variable so that it can be accessed
449** by the SIGINT handler to interrupt database processing.
450*/
451static sqlite3 *globalDb = 0;
452
453/*
454** True if an interrupt (Control-C) has been received.
455*/
456static volatile int seenInterrupt = 0;
457
458/*
459** This is the name of our program. It is set in main(), used
460** in a number of other places, mostly for error messages.
461*/
462static char *Argv0;
463
464/*
465** Prompt strings. Initialized in main. Settable with
466**   .prompt main continue
467*/
468static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
469static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
470
471/*
472** Render output like fprintf().  Except, if the output is going to the
473** console and if this is running on a Windows machine, translate the
474** output from UTF-8 into MBCS.
475*/
476#if defined(_WIN32) || defined(WIN32)
477void utf8_printf(FILE *out, const char *zFormat, ...){
478  va_list ap;
479  va_start(ap, zFormat);
480  if( stdout_is_console && (out==stdout || out==stderr) ){
481    char *z1 = sqlite3_vmprintf(zFormat, ap);
482    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
483    sqlite3_free(z1);
484    fputs(z2, out);
485    sqlite3_free(z2);
486  }else{
487    vfprintf(out, zFormat, ap);
488  }
489  va_end(ap);
490}
491#elif !defined(utf8_printf)
492# define utf8_printf fprintf
493#endif
494
495/*
496** Render output like fprintf().  This should not be used on anything that
497** includes string formatting (e.g. "%s").
498*/
499#if !defined(raw_printf)
500# define raw_printf fprintf
501#endif
502
503/* Indicate out-of-memory and exit. */
504static void shell_out_of_memory(void){
505  raw_printf(stderr,"Error: out of memory\n");
506  exit(1);
507}
508
509/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
510** out-of-memory error.
511*/
512static void shell_check_oom(void *p){
513  if( p==0 ) shell_out_of_memory();
514}
515
516/*
517** Write I/O traces to the following stream.
518*/
519#ifdef SQLITE_ENABLE_IOTRACE
520static FILE *iotrace = 0;
521#endif
522
523/*
524** This routine works like printf in that its first argument is a
525** format string and subsequent arguments are values to be substituted
526** in place of % fields.  The result of formatting this string
527** is written to iotrace.
528*/
529#ifdef SQLITE_ENABLE_IOTRACE
530static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
531  va_list ap;
532  char *z;
533  if( iotrace==0 ) return;
534  va_start(ap, zFormat);
535  z = sqlite3_vmprintf(zFormat, ap);
536  va_end(ap);
537  utf8_printf(iotrace, "%s", z);
538  sqlite3_free(z);
539}
540#endif
541
542/*
543** Output string zUtf to stream pOut as w characters.  If w is negative,
544** then right-justify the text.  W is the width in UTF-8 characters, not
545** in bytes.  This is different from the %*.*s specification in printf
546** since with %*.*s the width is measured in bytes, not characters.
547*/
548static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
549  int i;
550  int n;
551  int aw = w<0 ? -w : w;
552  if( zUtf==0 ) zUtf = "";
553  for(i=n=0; zUtf[i]; i++){
554    if( (zUtf[i]&0xc0)!=0x80 ){
555      n++;
556      if( n==aw ){
557        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
558        break;
559      }
560    }
561  }
562  if( n>=aw ){
563    utf8_printf(pOut, "%.*s", i, zUtf);
564  }else if( w<0 ){
565    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
566  }else{
567    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
568  }
569}
570
571
572/*
573** Determines if a string is a number of not.
574*/
575static int isNumber(const char *z, int *realnum){
576  if( *z=='-' || *z=='+' ) z++;
577  if( !IsDigit(*z) ){
578    return 0;
579  }
580  z++;
581  if( realnum ) *realnum = 0;
582  while( IsDigit(*z) ){ z++; }
583  if( *z=='.' ){
584    z++;
585    if( !IsDigit(*z) ) return 0;
586    while( IsDigit(*z) ){ z++; }
587    if( realnum ) *realnum = 1;
588  }
589  if( *z=='e' || *z=='E' ){
590    z++;
591    if( *z=='+' || *z=='-' ) z++;
592    if( !IsDigit(*z) ) return 0;
593    while( IsDigit(*z) ){ z++; }
594    if( realnum ) *realnum = 1;
595  }
596  return *z==0;
597}
598
599/*
600** Compute a string length that is limited to what can be stored in
601** lower 30 bits of a 32-bit signed integer.
602*/
603static int strlen30(const char *z){
604  const char *z2 = z;
605  while( *z2 ){ z2++; }
606  return 0x3fffffff & (int)(z2 - z);
607}
608
609/*
610** Return the length of a string in characters.  Multibyte UTF8 characters
611** count as a single character.
612*/
613static int strlenChar(const char *z){
614  int n = 0;
615  while( *z ){
616    if( (0xc0&*(z++))!=0x80 ) n++;
617  }
618  return n;
619}
620
621/*
622** Return open FILE * if zFile exists, can be opened for read
623** and is an ordinary file or a character stream source.
624** Otherwise return 0.
625*/
626static FILE * openChrSource(const char *zFile){
627#ifdef _WIN32
628  struct _stat x = {0};
629# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
630  /* On Windows, open first, then check the stream nature. This order
631  ** is necessary because _stat() and sibs, when checking a named pipe,
632  ** effectively break the pipe as its supplier sees it. */
633  FILE *rv = fopen(zFile, "rb");
634  if( rv==0 ) return 0;
635  if( _fstat(_fileno(rv), &x) != 0
636      || !STAT_CHR_SRC(x.st_mode)){
637    fclose(rv);
638    rv = 0;
639  }
640  return rv;
641#else
642  struct stat x = {0};
643  int rc = stat(zFile, &x);
644# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
645  if( rc!=0 ) return 0;
646  if( STAT_CHR_SRC(x.st_mode) ){
647    return fopen(zFile, "rb");
648  }else{
649    return 0;
650  }
651#endif
652#undef STAT_CHR_SRC
653}
654
655/*
656** This routine reads a line of text from FILE in, stores
657** the text in memory obtained from malloc() and returns a pointer
658** to the text.  NULL is returned at end of file, or if malloc()
659** fails.
660**
661** If zLine is not NULL then it is a malloced buffer returned from
662** a previous call to this routine that may be reused.
663*/
664static char *local_getline(char *zLine, FILE *in){
665  int nLine = zLine==0 ? 0 : 100;
666  int n = 0;
667
668  while( 1 ){
669    if( n+100>nLine ){
670      nLine = nLine*2 + 100;
671      zLine = realloc(zLine, nLine);
672      shell_check_oom(zLine);
673    }
674    if( fgets(&zLine[n], nLine - n, in)==0 ){
675      if( n==0 ){
676        free(zLine);
677        return 0;
678      }
679      zLine[n] = 0;
680      break;
681    }
682    while( zLine[n] ) n++;
683    if( n>0 && zLine[n-1]=='\n' ){
684      n--;
685      if( n>0 && zLine[n-1]=='\r' ) n--;
686      zLine[n] = 0;
687      break;
688    }
689  }
690#if defined(_WIN32) || defined(WIN32)
691  /* For interactive input on Windows systems, translate the
692  ** multi-byte characterset characters into UTF-8. */
693  if( stdin_is_interactive && in==stdin ){
694    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
695    if( zTrans ){
696      i64 nTrans = strlen(zTrans)+1;
697      if( nTrans>nLine ){
698        zLine = realloc(zLine, nTrans);
699        shell_check_oom(zLine);
700      }
701      memcpy(zLine, zTrans, nTrans);
702      sqlite3_free(zTrans);
703    }
704  }
705#endif /* defined(_WIN32) || defined(WIN32) */
706  return zLine;
707}
708
709/*
710** Retrieve a single line of input text.
711**
712** If in==0 then read from standard input and prompt before each line.
713** If isContinuation is true, then a continuation prompt is appropriate.
714** If isContinuation is zero, then the main prompt should be used.
715**
716** If zPrior is not NULL then it is a buffer from a prior call to this
717** routine that can be reused.
718**
719** The result is stored in space obtained from malloc() and must either
720** be freed by the caller or else passed back into this routine via the
721** zPrior argument for reuse.
722*/
723#ifndef SQLITE_SHELL_FIDDLE
724static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
725  char *zPrompt;
726  char *zResult;
727  if( in!=0 ){
728    zResult = local_getline(zPrior, in);
729  }else{
730    zPrompt = isContinuation ? continuePrompt : mainPrompt;
731#if SHELL_USE_LOCAL_GETLINE
732    printf("%s", zPrompt);
733    fflush(stdout);
734    zResult = local_getline(zPrior, stdin);
735#else
736    free(zPrior);
737    zResult = shell_readline(zPrompt);
738    if( zResult && *zResult ) shell_add_history(zResult);
739#endif
740  }
741  return zResult;
742}
743#endif /* !SQLITE_SHELL_FIDDLE */
744
745/*
746** Return the value of a hexadecimal digit.  Return -1 if the input
747** is not a hex digit.
748*/
749static int hexDigitValue(char c){
750  if( c>='0' && c<='9' ) return c - '0';
751  if( c>='a' && c<='f' ) return c - 'a' + 10;
752  if( c>='A' && c<='F' ) return c - 'A' + 10;
753  return -1;
754}
755
756/*
757** Interpret zArg as an integer value, possibly with suffixes.
758*/
759static sqlite3_int64 integerValue(const char *zArg){
760  sqlite3_int64 v = 0;
761  static const struct { char *zSuffix; int iMult; } aMult[] = {
762    { "KiB", 1024 },
763    { "MiB", 1024*1024 },
764    { "GiB", 1024*1024*1024 },
765    { "KB",  1000 },
766    { "MB",  1000000 },
767    { "GB",  1000000000 },
768    { "K",   1000 },
769    { "M",   1000000 },
770    { "G",   1000000000 },
771  };
772  int i;
773  int isNeg = 0;
774  if( zArg[0]=='-' ){
775    isNeg = 1;
776    zArg++;
777  }else if( zArg[0]=='+' ){
778    zArg++;
779  }
780  if( zArg[0]=='0' && zArg[1]=='x' ){
781    int x;
782    zArg += 2;
783    while( (x = hexDigitValue(zArg[0]))>=0 ){
784      v = (v<<4) + x;
785      zArg++;
786    }
787  }else{
788    while( IsDigit(zArg[0]) ){
789      v = v*10 + zArg[0] - '0';
790      zArg++;
791    }
792  }
793  for(i=0; i<ArraySize(aMult); i++){
794    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
795      v *= aMult[i].iMult;
796      break;
797    }
798  }
799  return isNeg? -v : v;
800}
801
802/*
803** A variable length string to which one can append text.
804*/
805typedef struct ShellText ShellText;
806struct ShellText {
807  char *z;
808  int n;
809  int nAlloc;
810};
811
812/*
813** Initialize and destroy a ShellText object
814*/
815static void initText(ShellText *p){
816  memset(p, 0, sizeof(*p));
817}
818static void freeText(ShellText *p){
819  free(p->z);
820  initText(p);
821}
822
823/* zIn is either a pointer to a NULL-terminated string in memory obtained
824** from malloc(), or a NULL pointer. The string pointed to by zAppend is
825** added to zIn, and the result returned in memory obtained from malloc().
826** zIn, if it was not NULL, is freed.
827**
828** If the third argument, quote, is not '\0', then it is used as a
829** quote character for zAppend.
830*/
831static void appendText(ShellText *p, const char *zAppend, char quote){
832  i64 len;
833  i64 i;
834  i64 nAppend = strlen30(zAppend);
835
836  len = nAppend+p->n+1;
837  if( quote ){
838    len += 2;
839    for(i=0; i<nAppend; i++){
840      if( zAppend[i]==quote ) len++;
841    }
842  }
843
844  if( p->z==0 || p->n+len>=p->nAlloc ){
845    p->nAlloc = p->nAlloc*2 + len + 20;
846    p->z = realloc(p->z, p->nAlloc);
847    shell_check_oom(p->z);
848  }
849
850  if( quote ){
851    char *zCsr = p->z+p->n;
852    *zCsr++ = quote;
853    for(i=0; i<nAppend; i++){
854      *zCsr++ = zAppend[i];
855      if( zAppend[i]==quote ) *zCsr++ = quote;
856    }
857    *zCsr++ = quote;
858    p->n = (int)(zCsr - p->z);
859    *zCsr = '\0';
860  }else{
861    memcpy(p->z+p->n, zAppend, nAppend);
862    p->n += nAppend;
863    p->z[p->n] = '\0';
864  }
865}
866
867/*
868** Attempt to determine if identifier zName needs to be quoted, either
869** because it contains non-alphanumeric characters, or because it is an
870** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
871** that quoting is required.
872**
873** Return '"' if quoting is required.  Return 0 if no quoting is required.
874*/
875static char quoteChar(const char *zName){
876  int i;
877  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
878  for(i=0; zName[i]; i++){
879    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
880  }
881  return sqlite3_keyword_check(zName, i) ? '"' : 0;
882}
883
884/*
885** Construct a fake object name and column list to describe the structure
886** of the view, virtual table, or table valued function zSchema.zName.
887*/
888static char *shellFakeSchema(
889  sqlite3 *db,            /* The database connection containing the vtab */
890  const char *zSchema,    /* Schema of the database holding the vtab */
891  const char *zName       /* The name of the virtual table */
892){
893  sqlite3_stmt *pStmt = 0;
894  char *zSql;
895  ShellText s;
896  char cQuote;
897  char *zDiv = "(";
898  int nRow = 0;
899
900  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
901                         zSchema ? zSchema : "main", zName);
902  shell_check_oom(zSql);
903  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
904  sqlite3_free(zSql);
905  initText(&s);
906  if( zSchema ){
907    cQuote = quoteChar(zSchema);
908    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
909    appendText(&s, zSchema, cQuote);
910    appendText(&s, ".", 0);
911  }
912  cQuote = quoteChar(zName);
913  appendText(&s, zName, cQuote);
914  while( sqlite3_step(pStmt)==SQLITE_ROW ){
915    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
916    nRow++;
917    appendText(&s, zDiv, 0);
918    zDiv = ",";
919    if( zCol==0 ) zCol = "";
920    cQuote = quoteChar(zCol);
921    appendText(&s, zCol, cQuote);
922  }
923  appendText(&s, ")", 0);
924  sqlite3_finalize(pStmt);
925  if( nRow==0 ){
926    freeText(&s);
927    s.z = 0;
928  }
929  return s.z;
930}
931
932/*
933** SQL function:  shell_module_schema(X)
934**
935** Return a fake schema for the table-valued function or eponymous virtual
936** table X.
937*/
938static void shellModuleSchema(
939  sqlite3_context *pCtx,
940  int nVal,
941  sqlite3_value **apVal
942){
943  const char *zName;
944  char *zFake;
945  UNUSED_PARAMETER(nVal);
946  zName = (const char*)sqlite3_value_text(apVal[0]);
947  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
948  if( zFake ){
949    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
950                        -1, sqlite3_free);
951    free(zFake);
952  }
953}
954
955/*
956** SQL function:  shell_add_schema(S,X)
957**
958** Add the schema name X to the CREATE statement in S and return the result.
959** Examples:
960**
961**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
962**
963** Also works on
964**
965**    CREATE INDEX
966**    CREATE UNIQUE INDEX
967**    CREATE VIEW
968**    CREATE TRIGGER
969**    CREATE VIRTUAL TABLE
970**
971** This UDF is used by the .schema command to insert the schema name of
972** attached databases into the middle of the sqlite_schema.sql field.
973*/
974static void shellAddSchemaName(
975  sqlite3_context *pCtx,
976  int nVal,
977  sqlite3_value **apVal
978){
979  static const char *aPrefix[] = {
980     "TABLE",
981     "INDEX",
982     "UNIQUE INDEX",
983     "VIEW",
984     "TRIGGER",
985     "VIRTUAL TABLE"
986  };
987  int i = 0;
988  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
989  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
990  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
991  sqlite3 *db = sqlite3_context_db_handle(pCtx);
992  UNUSED_PARAMETER(nVal);
993  if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){
994    for(i=0; i<ArraySize(aPrefix); i++){
995      int n = strlen30(aPrefix[i]);
996      if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
997        char *z = 0;
998        char *zFake = 0;
999        if( zSchema ){
1000          char cQuote = quoteChar(zSchema);
1001          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
1002            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
1003          }else{
1004            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
1005          }
1006        }
1007        if( zName
1008         && aPrefix[i][0]=='V'
1009         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
1010        ){
1011          if( z==0 ){
1012            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1013          }else{
1014            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1015          }
1016          free(zFake);
1017        }
1018        if( z ){
1019          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1020          return;
1021        }
1022      }
1023    }
1024  }
1025  sqlite3_result_value(pCtx, apVal[0]);
1026}
1027
1028/*
1029** The source code for several run-time loadable extensions is inserted
1030** below by the ../tool/mkshellc.tcl script.  Before processing that included
1031** code, we need to override some macros to make the included program code
1032** work here in the middle of this regular program.
1033*/
1034#define SQLITE_EXTENSION_INIT1
1035#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1036
1037#if defined(_WIN32) && defined(_MSC_VER)
1038INCLUDE test_windirent.h
1039INCLUDE test_windirent.c
1040#define dirent DIRENT
1041#endif
1042INCLUDE ../ext/misc/memtrace.c
1043INCLUDE ../ext/misc/shathree.c
1044INCLUDE ../ext/misc/uint.c
1045INCLUDE ../ext/misc/decimal.c
1046INCLUDE ../ext/misc/ieee754.c
1047INCLUDE ../ext/misc/series.c
1048INCLUDE ../ext/misc/regexp.c
1049#ifndef SQLITE_SHELL_FIDDLE
1050INCLUDE ../ext/misc/fileio.c
1051INCLUDE ../ext/misc/completion.c
1052INCLUDE ../ext/misc/appendvfs.c
1053#endif
1054#ifdef SQLITE_HAVE_ZLIB
1055INCLUDE ../ext/misc/zipfile.c
1056INCLUDE ../ext/misc/sqlar.c
1057#endif
1058INCLUDE ../ext/expert/sqlite3expert.h
1059INCLUDE ../ext/expert/sqlite3expert.c
1060
1061#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1062#define SQLITE_SHELL_HAVE_RECOVER 1
1063#else
1064#define SQLITE_SHELL_HAVE_RECOVER 0
1065#endif
1066#if SQLITE_SHELL_HAVE_RECOVER
1067INCLUDE ../ext/recover/dbdata.c
1068INCLUDE ../ext/recover/sqlite3recover.h
1069INCLUDE ../ext/recover/sqlite3recover.c
1070#endif
1071
1072#if defined(SQLITE_ENABLE_SESSION)
1073/*
1074** State information for a single open session
1075*/
1076typedef struct OpenSession OpenSession;
1077struct OpenSession {
1078  char *zName;             /* Symbolic name for this session */
1079  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1080  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1081  sqlite3_session *p;      /* The open session */
1082};
1083#endif
1084
1085typedef struct ExpertInfo ExpertInfo;
1086struct ExpertInfo {
1087  sqlite3expert *pExpert;
1088  int bVerbose;
1089};
1090
1091/* A single line in the EQP output */
1092typedef struct EQPGraphRow EQPGraphRow;
1093struct EQPGraphRow {
1094  int iEqpId;           /* ID for this row */
1095  int iParentId;        /* ID of the parent row */
1096  EQPGraphRow *pNext;   /* Next row in sequence */
1097  char zText[1];        /* Text to display for this row */
1098};
1099
1100/* All EQP output is collected into an instance of the following */
1101typedef struct EQPGraph EQPGraph;
1102struct EQPGraph {
1103  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1104  EQPGraphRow *pLast;   /* Last element of the pRow list */
1105  char zPrefix[100];    /* Graph prefix */
1106};
1107
1108/* Parameters affecting columnar mode result display (defaulting together) */
1109typedef struct ColModeOpts {
1110  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1111  u8 bQuote;            /* Quote results for .mode box and table */
1112  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1113} ColModeOpts;
1114#define ColModeOpts_default { 60, 0, 0 }
1115#define ColModeOpts_default_qbox { 60, 1, 0 }
1116
1117/*
1118** State information about the database connection is contained in an
1119** instance of the following structure.
1120*/
1121typedef struct ShellState ShellState;
1122struct ShellState {
1123  sqlite3 *db;           /* The database */
1124  u8 autoExplain;        /* Automatically turn on .explain mode */
1125  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1126  u8 autoEQPtest;        /* autoEQP is in test mode */
1127  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1128  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1129  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1130  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1131  u8 nEqpLevel;          /* Depth of the EQP output graph */
1132  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1133  u8 bSafeMode;          /* True to prohibit unsafe operations */
1134  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1135  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1136  unsigned statsOn;      /* True to display memory stats before each finalize */
1137  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1138  int inputNesting;      /* Track nesting level of .read and other redirects */
1139  int outCount;          /* Revert to stdout when reaching zero */
1140  int cnt;               /* Number of records displayed so far */
1141  int lineno;            /* Line number of last line read from in */
1142  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1143  FILE *in;              /* Read commands from this stream */
1144  FILE *out;             /* Write results here */
1145  FILE *traceOut;        /* Output for sqlite3_trace() */
1146  int nErr;              /* Number of errors seen */
1147  int mode;              /* An output mode setting */
1148  int modePrior;         /* Saved mode */
1149  int cMode;             /* temporary output mode for the current query */
1150  int normalMode;        /* Output mode before ".explain on" */
1151  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1152  int showHeader;        /* True to show column names in List or Column mode */
1153  int nCheck;            /* Number of ".check" commands run */
1154  unsigned nProgress;    /* Number of progress callbacks encountered */
1155  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1156  unsigned flgProgress;  /* Flags for the progress callback */
1157  unsigned shellFlgs;    /* Various flags */
1158  unsigned priorShFlgs;  /* Saved copy of flags */
1159  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1160  char *zDestTable;      /* Name of destination table when MODE_Insert */
1161  char *zTempFile;       /* Temporary file that might need deleting */
1162  char zTestcase[30];    /* Name of current test case */
1163  char colSeparator[20]; /* Column separator character for several modes */
1164  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1165  char colSepPrior[20];  /* Saved column separator */
1166  char rowSepPrior[20];  /* Saved row separator */
1167  int *colWidth;         /* Requested width of each column in columnar modes */
1168  int *actualWidth;      /* Actual width of each column */
1169  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1170  char nullValue[20];    /* The text to print when a NULL comes back from
1171                         ** the database */
1172  char outfile[FILENAME_MAX]; /* Filename for *out */
1173  sqlite3_stmt *pStmt;   /* Current statement if any. */
1174  FILE *pLog;            /* Write log output here */
1175  struct AuxDb {         /* Storage space for auxiliary database connections */
1176    sqlite3 *db;               /* Connection pointer */
1177    const char *zDbFilename;   /* Filename used to open the connection */
1178    char *zFreeOnClose;        /* Free this memory allocation on close */
1179#if defined(SQLITE_ENABLE_SESSION)
1180    int nSession;              /* Number of active sessions */
1181    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1182#endif
1183  } aAuxDb[5],           /* Array of all database connections */
1184    *pAuxDb;             /* Currently active database connection */
1185  int *aiIndent;         /* Array of indents used in MODE_Explain */
1186  int nIndent;           /* Size of array aiIndent[] */
1187  int iIndent;           /* Index of current op in aiIndent[] */
1188  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1189  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1190  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1191#ifdef SQLITE_SHELL_FIDDLE
1192  struct {
1193    const char * zInput; /* Input string from wasm/JS proxy */
1194    const char * zPos;   /* Cursor pos into zInput */
1195    const char * zDefaultDbName; /* Default name for db file */
1196  } wasm;
1197#endif
1198};
1199
1200#ifdef SQLITE_SHELL_FIDDLE
1201static ShellState shellState;
1202#endif
1203
1204
1205/* Allowed values for ShellState.autoEQP
1206*/
1207#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1208#define AUTOEQP_on       1           /* Automatic EQP is on */
1209#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1210#define AUTOEQP_full     3           /* Show full EXPLAIN */
1211
1212/* Allowed values for ShellState.openMode
1213*/
1214#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1215#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1216#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1217#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1218#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1219#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1220#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1221
1222/* Allowed values for ShellState.eTraceType
1223*/
1224#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1225#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1226#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1227
1228/* Bits in the ShellState.flgProgress variable */
1229#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1230#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1231                                   ** callback limit is reached, and for each
1232                                   ** top-level SQL statement */
1233#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1234
1235/*
1236** These are the allowed shellFlgs values
1237*/
1238#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1239#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1240#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1241#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1242#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1243#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1244#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1245#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1246#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1247#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1248
1249/*
1250** Macros for testing and setting shellFlgs
1251*/
1252#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1253#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1254#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1255
1256/*
1257** These are the allowed modes.
1258*/
1259#define MODE_Line     0  /* One column per line.  Blank line between records */
1260#define MODE_Column   1  /* One record per line in neat columns */
1261#define MODE_List     2  /* One record per line with a separator */
1262#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1263#define MODE_Html     4  /* Generate an XHTML table */
1264#define MODE_Insert   5  /* Generate SQL "insert" statements */
1265#define MODE_Quote    6  /* Quote values as for SQL */
1266#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1267#define MODE_Csv      8  /* Quote strings, numbers are plain */
1268#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1269#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1270#define MODE_Pretty  11  /* Pretty-print schemas */
1271#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1272#define MODE_Json    13  /* Output JSON */
1273#define MODE_Markdown 14 /* Markdown formatting */
1274#define MODE_Table   15  /* MySQL-style table formatting */
1275#define MODE_Box     16  /* Unicode box-drawing characters */
1276#define MODE_Count   17  /* Output only a count of the rows of output */
1277#define MODE_Off     18  /* No query output shown */
1278
1279static const char *modeDescr[] = {
1280  "line",
1281  "column",
1282  "list",
1283  "semi",
1284  "html",
1285  "insert",
1286  "quote",
1287  "tcl",
1288  "csv",
1289  "explain",
1290  "ascii",
1291  "prettyprint",
1292  "eqp",
1293  "json",
1294  "markdown",
1295  "table",
1296  "box",
1297  "count",
1298  "off"
1299};
1300
1301/*
1302** These are the column/row/line separators used by the various
1303** import/export modes.
1304*/
1305#define SEP_Column    "|"
1306#define SEP_Row       "\n"
1307#define SEP_Tab       "\t"
1308#define SEP_Space     " "
1309#define SEP_Comma     ","
1310#define SEP_CrLf      "\r\n"
1311#define SEP_Unit      "\x1F"
1312#define SEP_Record    "\x1E"
1313
1314/*
1315** Limit input nesting via .read or any other input redirect.
1316** It's not too expensive, so a generous allowance can be made.
1317*/
1318#define MAX_INPUT_NESTING 25
1319
1320/*
1321** A callback for the sqlite3_log() interface.
1322*/
1323static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1324  ShellState *p = (ShellState*)pArg;
1325  if( p->pLog==0 ) return;
1326  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1327  fflush(p->pLog);
1328}
1329
1330/*
1331** SQL function:  shell_putsnl(X)
1332**
1333** Write the text X to the screen (or whatever output is being directed)
1334** adding a newline at the end, and then return X.
1335*/
1336static void shellPutsFunc(
1337  sqlite3_context *pCtx,
1338  int nVal,
1339  sqlite3_value **apVal
1340){
1341  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1342  (void)nVal;
1343  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1344  sqlite3_result_value(pCtx, apVal[0]);
1345}
1346
1347/*
1348** If in safe mode, print an error message described by the arguments
1349** and exit immediately.
1350*/
1351static void failIfSafeMode(
1352  ShellState *p,
1353  const char *zErrMsg,
1354  ...
1355){
1356  if( p->bSafeMode ){
1357    va_list ap;
1358    char *zMsg;
1359    va_start(ap, zErrMsg);
1360    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1361    va_end(ap);
1362    raw_printf(stderr, "line %d: ", p->lineno);
1363    utf8_printf(stderr, "%s\n", zMsg);
1364    exit(1);
1365  }
1366}
1367
1368/*
1369** SQL function:   edit(VALUE)
1370**                 edit(VALUE,EDITOR)
1371**
1372** These steps:
1373**
1374**     (1) Write VALUE into a temporary file.
1375**     (2) Run program EDITOR on that temporary file.
1376**     (3) Read the temporary file back and return its content as the result.
1377**     (4) Delete the temporary file
1378**
1379** If the EDITOR argument is omitted, use the value in the VISUAL
1380** environment variable.  If still there is no EDITOR, through an error.
1381**
1382** Also throw an error if the EDITOR program returns a non-zero exit code.
1383*/
1384#ifndef SQLITE_NOHAVE_SYSTEM
1385static void editFunc(
1386  sqlite3_context *context,
1387  int argc,
1388  sqlite3_value **argv
1389){
1390  const char *zEditor;
1391  char *zTempFile = 0;
1392  sqlite3 *db;
1393  char *zCmd = 0;
1394  int bBin;
1395  int rc;
1396  int hasCRNL = 0;
1397  FILE *f = 0;
1398  sqlite3_int64 sz;
1399  sqlite3_int64 x;
1400  unsigned char *p = 0;
1401
1402  if( argc==2 ){
1403    zEditor = (const char*)sqlite3_value_text(argv[1]);
1404  }else{
1405    zEditor = getenv("VISUAL");
1406  }
1407  if( zEditor==0 ){
1408    sqlite3_result_error(context, "no editor for edit()", -1);
1409    return;
1410  }
1411  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1412    sqlite3_result_error(context, "NULL input to edit()", -1);
1413    return;
1414  }
1415  db = sqlite3_context_db_handle(context);
1416  zTempFile = 0;
1417  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1418  if( zTempFile==0 ){
1419    sqlite3_uint64 r = 0;
1420    sqlite3_randomness(sizeof(r), &r);
1421    zTempFile = sqlite3_mprintf("temp%llx", r);
1422    if( zTempFile==0 ){
1423      sqlite3_result_error_nomem(context);
1424      return;
1425    }
1426  }
1427  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1428  /* When writing the file to be edited, do \n to \r\n conversions on systems
1429  ** that want \r\n line endings */
1430  f = fopen(zTempFile, bBin ? "wb" : "w");
1431  if( f==0 ){
1432    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1433    goto edit_func_end;
1434  }
1435  sz = sqlite3_value_bytes(argv[0]);
1436  if( bBin ){
1437    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1438  }else{
1439    const char *z = (const char*)sqlite3_value_text(argv[0]);
1440    /* Remember whether or not the value originally contained \r\n */
1441    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1442    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1443  }
1444  fclose(f);
1445  f = 0;
1446  if( x!=sz ){
1447    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1448    goto edit_func_end;
1449  }
1450  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1451  if( zCmd==0 ){
1452    sqlite3_result_error_nomem(context);
1453    goto edit_func_end;
1454  }
1455  rc = system(zCmd);
1456  sqlite3_free(zCmd);
1457  if( rc ){
1458    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1459    goto edit_func_end;
1460  }
1461  f = fopen(zTempFile, "rb");
1462  if( f==0 ){
1463    sqlite3_result_error(context,
1464      "edit() cannot reopen temp file after edit", -1);
1465    goto edit_func_end;
1466  }
1467  fseek(f, 0, SEEK_END);
1468  sz = ftell(f);
1469  rewind(f);
1470  p = sqlite3_malloc64( sz+1 );
1471  if( p==0 ){
1472    sqlite3_result_error_nomem(context);
1473    goto edit_func_end;
1474  }
1475  x = fread(p, 1, (size_t)sz, f);
1476  fclose(f);
1477  f = 0;
1478  if( x!=sz ){
1479    sqlite3_result_error(context, "could not read back the whole file", -1);
1480    goto edit_func_end;
1481  }
1482  if( bBin ){
1483    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1484  }else{
1485    sqlite3_int64 i, j;
1486    if( hasCRNL ){
1487      /* If the original contains \r\n then do no conversions back to \n */
1488    }else{
1489      /* If the file did not originally contain \r\n then convert any new
1490      ** \r\n back into \n */
1491      for(i=j=0; i<sz; i++){
1492        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1493        p[j++] = p[i];
1494      }
1495      sz = j;
1496      p[sz] = 0;
1497    }
1498    sqlite3_result_text64(context, (const char*)p, sz,
1499                          sqlite3_free, SQLITE_UTF8);
1500  }
1501  p = 0;
1502
1503edit_func_end:
1504  if( f ) fclose(f);
1505  unlink(zTempFile);
1506  sqlite3_free(zTempFile);
1507  sqlite3_free(p);
1508}
1509#endif /* SQLITE_NOHAVE_SYSTEM */
1510
1511/*
1512** Save or restore the current output mode
1513*/
1514static void outputModePush(ShellState *p){
1515  p->modePrior = p->mode;
1516  p->priorShFlgs = p->shellFlgs;
1517  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1518  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1519}
1520static void outputModePop(ShellState *p){
1521  p->mode = p->modePrior;
1522  p->shellFlgs = p->priorShFlgs;
1523  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1524  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1525}
1526
1527/*
1528** Output the given string as a hex-encoded blob (eg. X'1234' )
1529*/
1530static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1531  int i;
1532  unsigned char *aBlob = (unsigned char*)pBlob;
1533
1534  char *zStr = sqlite3_malloc(nBlob*2 + 1);
1535  shell_check_oom(zStr);
1536
1537  for(i=0; i<nBlob; i++){
1538    static const char aHex[] = {
1539        '0', '1', '2', '3', '4', '5', '6', '7',
1540        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1541    };
1542    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1543    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1544  }
1545  zStr[i*2] = '\0';
1546
1547  raw_printf(out,"X'%s'", zStr);
1548  sqlite3_free(zStr);
1549}
1550
1551/*
1552** Find a string that is not found anywhere in z[].  Return a pointer
1553** to that string.
1554**
1555** Try to use zA and zB first.  If both of those are already found in z[]
1556** then make up some string and store it in the buffer zBuf.
1557*/
1558static const char *unused_string(
1559  const char *z,                    /* Result must not appear anywhere in z */
1560  const char *zA, const char *zB,   /* Try these first */
1561  char *zBuf                        /* Space to store a generated string */
1562){
1563  unsigned i = 0;
1564  if( strstr(z, zA)==0 ) return zA;
1565  if( strstr(z, zB)==0 ) return zB;
1566  do{
1567    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1568  }while( strstr(z,zBuf)!=0 );
1569  return zBuf;
1570}
1571
1572/*
1573** Output the given string as a quoted string using SQL quoting conventions.
1574**
1575** See also: output_quoted_escaped_string()
1576*/
1577static void output_quoted_string(FILE *out, const char *z){
1578  int i;
1579  char c;
1580  setBinaryMode(out, 1);
1581  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1582  if( c==0 ){
1583    utf8_printf(out,"'%s'",z);
1584  }else{
1585    raw_printf(out, "'");
1586    while( *z ){
1587      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1588      if( c=='\'' ) i++;
1589      if( i ){
1590        utf8_printf(out, "%.*s", i, z);
1591        z += i;
1592      }
1593      if( c=='\'' ){
1594        raw_printf(out, "'");
1595        continue;
1596      }
1597      if( c==0 ){
1598        break;
1599      }
1600      z++;
1601    }
1602    raw_printf(out, "'");
1603  }
1604  setTextMode(out, 1);
1605}
1606
1607/*
1608** Output the given string as a quoted string using SQL quoting conventions.
1609** Additionallly , escape the "\n" and "\r" characters so that they do not
1610** get corrupted by end-of-line translation facilities in some operating
1611** systems.
1612**
1613** This is like output_quoted_string() but with the addition of the \r\n
1614** escape mechanism.
1615*/
1616static void output_quoted_escaped_string(FILE *out, const char *z){
1617  int i;
1618  char c;
1619  setBinaryMode(out, 1);
1620  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1621  if( c==0 ){
1622    utf8_printf(out,"'%s'",z);
1623  }else{
1624    const char *zNL = 0;
1625    const char *zCR = 0;
1626    int nNL = 0;
1627    int nCR = 0;
1628    char zBuf1[20], zBuf2[20];
1629    for(i=0; z[i]; i++){
1630      if( z[i]=='\n' ) nNL++;
1631      if( z[i]=='\r' ) nCR++;
1632    }
1633    if( nNL ){
1634      raw_printf(out, "replace(");
1635      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1636    }
1637    if( nCR ){
1638      raw_printf(out, "replace(");
1639      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1640    }
1641    raw_printf(out, "'");
1642    while( *z ){
1643      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1644      if( c=='\'' ) i++;
1645      if( i ){
1646        utf8_printf(out, "%.*s", i, z);
1647        z += i;
1648      }
1649      if( c=='\'' ){
1650        raw_printf(out, "'");
1651        continue;
1652      }
1653      if( c==0 ){
1654        break;
1655      }
1656      z++;
1657      if( c=='\n' ){
1658        raw_printf(out, "%s", zNL);
1659        continue;
1660      }
1661      raw_printf(out, "%s", zCR);
1662    }
1663    raw_printf(out, "'");
1664    if( nCR ){
1665      raw_printf(out, ",'%s',char(13))", zCR);
1666    }
1667    if( nNL ){
1668      raw_printf(out, ",'%s',char(10))", zNL);
1669    }
1670  }
1671  setTextMode(out, 1);
1672}
1673
1674/*
1675** Output the given string as a quoted according to C or TCL quoting rules.
1676*/
1677static void output_c_string(FILE *out, const char *z){
1678  unsigned int c;
1679  fputc('"', out);
1680  while( (c = *(z++))!=0 ){
1681    if( c=='\\' ){
1682      fputc(c, out);
1683      fputc(c, out);
1684    }else if( c=='"' ){
1685      fputc('\\', out);
1686      fputc('"', out);
1687    }else if( c=='\t' ){
1688      fputc('\\', out);
1689      fputc('t', out);
1690    }else if( c=='\n' ){
1691      fputc('\\', out);
1692      fputc('n', out);
1693    }else if( c=='\r' ){
1694      fputc('\\', out);
1695      fputc('r', out);
1696    }else if( !isprint(c&0xff) ){
1697      raw_printf(out, "\\%03o", c&0xff);
1698    }else{
1699      fputc(c, out);
1700    }
1701  }
1702  fputc('"', out);
1703}
1704
1705/*
1706** Output the given string as a quoted according to JSON quoting rules.
1707*/
1708static void output_json_string(FILE *out, const char *z, i64 n){
1709  unsigned int c;
1710  if( n<0 ) n = strlen(z);
1711  fputc('"', out);
1712  while( n-- ){
1713    c = *(z++);
1714    if( c=='\\' || c=='"' ){
1715      fputc('\\', out);
1716      fputc(c, out);
1717    }else if( c<=0x1f ){
1718      fputc('\\', out);
1719      if( c=='\b' ){
1720        fputc('b', out);
1721      }else if( c=='\f' ){
1722        fputc('f', out);
1723      }else if( c=='\n' ){
1724        fputc('n', out);
1725      }else if( c=='\r' ){
1726        fputc('r', out);
1727      }else if( c=='\t' ){
1728        fputc('t', out);
1729      }else{
1730         raw_printf(out, "u%04x",c);
1731      }
1732    }else{
1733      fputc(c, out);
1734    }
1735  }
1736  fputc('"', out);
1737}
1738
1739/*
1740** Output the given string with characters that are special to
1741** HTML escaped.
1742*/
1743static void output_html_string(FILE *out, const char *z){
1744  int i;
1745  if( z==0 ) z = "";
1746  while( *z ){
1747    for(i=0;   z[i]
1748            && z[i]!='<'
1749            && z[i]!='&'
1750            && z[i]!='>'
1751            && z[i]!='\"'
1752            && z[i]!='\'';
1753        i++){}
1754    if( i>0 ){
1755      utf8_printf(out,"%.*s",i,z);
1756    }
1757    if( z[i]=='<' ){
1758      raw_printf(out,"&lt;");
1759    }else if( z[i]=='&' ){
1760      raw_printf(out,"&amp;");
1761    }else if( z[i]=='>' ){
1762      raw_printf(out,"&gt;");
1763    }else if( z[i]=='\"' ){
1764      raw_printf(out,"&quot;");
1765    }else if( z[i]=='\'' ){
1766      raw_printf(out,"&#39;");
1767    }else{
1768      break;
1769    }
1770    z += i + 1;
1771  }
1772}
1773
1774/*
1775** If a field contains any character identified by a 1 in the following
1776** array, then the string must be quoted for CSV.
1777*/
1778static const char needCsvQuote[] = {
1779  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1780  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1781  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1782  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1783  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1784  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1785  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1786  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1787  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1788  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1789  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1790  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1791  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1792  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1793  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1794  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1795};
1796
1797/*
1798** Output a single term of CSV.  Actually, p->colSeparator is used for
1799** the separator, which may or may not be a comma.  p->nullValue is
1800** the null value.  Strings are quoted if necessary.  The separator
1801** is only issued if bSep is true.
1802*/
1803static void output_csv(ShellState *p, const char *z, int bSep){
1804  FILE *out = p->out;
1805  if( z==0 ){
1806    utf8_printf(out,"%s",p->nullValue);
1807  }else{
1808    unsigned i;
1809    for(i=0; z[i]; i++){
1810      if( needCsvQuote[((unsigned char*)z)[i]] ){
1811        i = 0;
1812        break;
1813      }
1814    }
1815    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1816      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1817      shell_check_oom(zQuoted);
1818      utf8_printf(out, "%s", zQuoted);
1819      sqlite3_free(zQuoted);
1820    }else{
1821      utf8_printf(out, "%s", z);
1822    }
1823  }
1824  if( bSep ){
1825    utf8_printf(p->out, "%s", p->colSeparator);
1826  }
1827}
1828
1829/*
1830** This routine runs when the user presses Ctrl-C
1831*/
1832static void interrupt_handler(int NotUsed){
1833  UNUSED_PARAMETER(NotUsed);
1834  seenInterrupt++;
1835  if( seenInterrupt>2 ) exit(1);
1836  if( globalDb ) sqlite3_interrupt(globalDb);
1837}
1838
1839#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1840/*
1841** This routine runs for console events (e.g. Ctrl-C) on Win32
1842*/
1843static BOOL WINAPI ConsoleCtrlHandler(
1844  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1845){
1846  if( dwCtrlType==CTRL_C_EVENT ){
1847    interrupt_handler(0);
1848    return TRUE;
1849  }
1850  return FALSE;
1851}
1852#endif
1853
1854#ifndef SQLITE_OMIT_AUTHORIZATION
1855/*
1856** This authorizer runs in safe mode.
1857*/
1858static int safeModeAuth(
1859  void *pClientData,
1860  int op,
1861  const char *zA1,
1862  const char *zA2,
1863  const char *zA3,
1864  const char *zA4
1865){
1866  ShellState *p = (ShellState*)pClientData;
1867  static const char *azProhibitedFunctions[] = {
1868    "edit",
1869    "fts3_tokenizer",
1870    "load_extension",
1871    "readfile",
1872    "writefile",
1873    "zipfile",
1874    "zipfile_cds",
1875  };
1876  UNUSED_PARAMETER(zA2);
1877  UNUSED_PARAMETER(zA3);
1878  UNUSED_PARAMETER(zA4);
1879  switch( op ){
1880    case SQLITE_ATTACH: {
1881#ifndef SQLITE_SHELL_FIDDLE
1882      /* In WASM builds the filesystem is a virtual sandbox, so
1883      ** there's no harm in using ATTACH. */
1884      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1885#endif
1886      break;
1887    }
1888    case SQLITE_FUNCTION: {
1889      int i;
1890      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1891        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1892          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1893                         azProhibitedFunctions[i]);
1894        }
1895      }
1896      break;
1897    }
1898  }
1899  return SQLITE_OK;
1900}
1901
1902/*
1903** When the ".auth ON" is set, the following authorizer callback is
1904** invoked.  It always returns SQLITE_OK.
1905*/
1906static int shellAuth(
1907  void *pClientData,
1908  int op,
1909  const char *zA1,
1910  const char *zA2,
1911  const char *zA3,
1912  const char *zA4
1913){
1914  ShellState *p = (ShellState*)pClientData;
1915  static const char *azAction[] = { 0,
1916     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1917     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1918     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1919     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1920     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1921     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1922     "PRAGMA",               "READ",                 "SELECT",
1923     "TRANSACTION",          "UPDATE",               "ATTACH",
1924     "DETACH",               "ALTER_TABLE",          "REINDEX",
1925     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1926     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1927  };
1928  int i;
1929  const char *az[4];
1930  az[0] = zA1;
1931  az[1] = zA2;
1932  az[2] = zA3;
1933  az[3] = zA4;
1934  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1935  for(i=0; i<4; i++){
1936    raw_printf(p->out, " ");
1937    if( az[i] ){
1938      output_c_string(p->out, az[i]);
1939    }else{
1940      raw_printf(p->out, "NULL");
1941    }
1942  }
1943  raw_printf(p->out, "\n");
1944  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1945  return SQLITE_OK;
1946}
1947#endif
1948
1949/*
1950** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1951**
1952** This routine converts some CREATE TABLE statements for shadow tables
1953** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1954**
1955** If the schema statement in z[] contains a start-of-comment and if
1956** sqlite3_complete() returns false, try to terminate the comment before
1957** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1958*/
1959static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1960  char *zToFree = 0;
1961  if( z==0 ) return;
1962  if( zTail==0 ) return;
1963  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1964    const char *zOrig = z;
1965    static const char *azTerm[] = { "", "*/", "\n" };
1966    int i;
1967    for(i=0; i<ArraySize(azTerm); i++){
1968      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1969      if( sqlite3_complete(zNew) ){
1970        size_t n = strlen(zNew);
1971        zNew[n-1] = 0;
1972        zToFree = zNew;
1973        z = zNew;
1974        break;
1975      }
1976      sqlite3_free(zNew);
1977    }
1978  }
1979  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1980    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1981  }else{
1982    utf8_printf(out, "%s%s", z, zTail);
1983  }
1984  sqlite3_free(zToFree);
1985}
1986static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1987  char c = z[n];
1988  z[n] = 0;
1989  printSchemaLine(out, z, zTail);
1990  z[n] = c;
1991}
1992
1993/*
1994** Return true if string z[] has nothing but whitespace and comments to the
1995** end of the first line.
1996*/
1997static int wsToEol(const char *z){
1998  int i;
1999  for(i=0; z[i]; i++){
2000    if( z[i]=='\n' ) return 1;
2001    if( IsSpace(z[i]) ) continue;
2002    if( z[i]=='-' && z[i+1]=='-' ) return 1;
2003    return 0;
2004  }
2005  return 1;
2006}
2007
2008/*
2009** Add a new entry to the EXPLAIN QUERY PLAN data
2010*/
2011static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
2012  EQPGraphRow *pNew;
2013  i64 nText;
2014  if( zText==0 ) return;
2015  nText = strlen(zText);
2016  if( p->autoEQPtest ){
2017    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
2018  }
2019  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
2020  shell_check_oom(pNew);
2021  pNew->iEqpId = iEqpId;
2022  pNew->iParentId = p2;
2023  memcpy(pNew->zText, zText, nText+1);
2024  pNew->pNext = 0;
2025  if( p->sGraph.pLast ){
2026    p->sGraph.pLast->pNext = pNew;
2027  }else{
2028    p->sGraph.pRow = pNew;
2029  }
2030  p->sGraph.pLast = pNew;
2031}
2032
2033/*
2034** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2035** in p->sGraph.
2036*/
2037static void eqp_reset(ShellState *p){
2038  EQPGraphRow *pRow, *pNext;
2039  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2040    pNext = pRow->pNext;
2041    sqlite3_free(pRow);
2042  }
2043  memset(&p->sGraph, 0, sizeof(p->sGraph));
2044}
2045
2046/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2047** pOld, or return the first such line if pOld is NULL
2048*/
2049static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2050  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2051  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2052  return pRow;
2053}
2054
2055/* Render a single level of the graph that has iEqpId as its parent.  Called
2056** recursively to render sublevels.
2057*/
2058static void eqp_render_level(ShellState *p, int iEqpId){
2059  EQPGraphRow *pRow, *pNext;
2060  i64 n = strlen(p->sGraph.zPrefix);
2061  char *z;
2062  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2063    pNext = eqp_next_row(p, iEqpId, pRow);
2064    z = pRow->zText;
2065    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2066                pNext ? "|--" : "`--", z);
2067    if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){
2068      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2069      eqp_render_level(p, pRow->iEqpId);
2070      p->sGraph.zPrefix[n] = 0;
2071    }
2072  }
2073}
2074
2075/*
2076** Display and reset the EXPLAIN QUERY PLAN data
2077*/
2078static void eqp_render(ShellState *p){
2079  EQPGraphRow *pRow = p->sGraph.pRow;
2080  if( pRow ){
2081    if( pRow->zText[0]=='-' ){
2082      if( pRow->pNext==0 ){
2083        eqp_reset(p);
2084        return;
2085      }
2086      utf8_printf(p->out, "%s\n", pRow->zText+3);
2087      p->sGraph.pRow = pRow->pNext;
2088      sqlite3_free(pRow);
2089    }else{
2090      utf8_printf(p->out, "QUERY PLAN\n");
2091    }
2092    p->sGraph.zPrefix[0] = 0;
2093    eqp_render_level(p, 0);
2094    eqp_reset(p);
2095  }
2096}
2097
2098#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2099/*
2100** Progress handler callback.
2101*/
2102static int progress_handler(void *pClientData) {
2103  ShellState *p = (ShellState*)pClientData;
2104  p->nProgress++;
2105  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2106    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2107    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2108    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2109    return 1;
2110  }
2111  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2112    raw_printf(p->out, "Progress %u\n", p->nProgress);
2113  }
2114  return 0;
2115}
2116#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2117
2118/*
2119** Print N dashes
2120*/
2121static void print_dashes(FILE *out, int N){
2122  const char zDash[] = "--------------------------------------------------";
2123  const int nDash = sizeof(zDash) - 1;
2124  while( N>nDash ){
2125    fputs(zDash, out);
2126    N -= nDash;
2127  }
2128  raw_printf(out, "%.*s", N, zDash);
2129}
2130
2131/*
2132** Print a markdown or table-style row separator using ascii-art
2133*/
2134static void print_row_separator(
2135  ShellState *p,
2136  int nArg,
2137  const char *zSep
2138){
2139  int i;
2140  if( nArg>0 ){
2141    fputs(zSep, p->out);
2142    print_dashes(p->out, p->actualWidth[0]+2);
2143    for(i=1; i<nArg; i++){
2144      fputs(zSep, p->out);
2145      print_dashes(p->out, p->actualWidth[i]+2);
2146    }
2147    fputs(zSep, p->out);
2148  }
2149  fputs("\n", p->out);
2150}
2151
2152/*
2153** This is the callback routine that the shell
2154** invokes for each row of a query result.
2155*/
2156static int shell_callback(
2157  void *pArg,
2158  int nArg,        /* Number of result columns */
2159  char **azArg,    /* Text of each result column */
2160  char **azCol,    /* Column names */
2161  int *aiType      /* Column types.  Might be NULL */
2162){
2163  int i;
2164  ShellState *p = (ShellState*)pArg;
2165
2166  if( azArg==0 ) return 0;
2167  switch( p->cMode ){
2168    case MODE_Count:
2169    case MODE_Off: {
2170      break;
2171    }
2172    case MODE_Line: {
2173      int w = 5;
2174      if( azArg==0 ) break;
2175      for(i=0; i<nArg; i++){
2176        int len = strlen30(azCol[i] ? azCol[i] : "");
2177        if( len>w ) w = len;
2178      }
2179      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2180      for(i=0; i<nArg; i++){
2181        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2182                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2183      }
2184      break;
2185    }
2186    case MODE_Explain: {
2187      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2188      if( nArg>ArraySize(aExplainWidth) ){
2189        nArg = ArraySize(aExplainWidth);
2190      }
2191      if( p->cnt++==0 ){
2192        for(i=0; i<nArg; i++){
2193          int w = aExplainWidth[i];
2194          utf8_width_print(p->out, w, azCol[i]);
2195          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2196        }
2197        for(i=0; i<nArg; i++){
2198          int w = aExplainWidth[i];
2199          print_dashes(p->out, w);
2200          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2201        }
2202      }
2203      if( azArg==0 ) break;
2204      for(i=0; i<nArg; i++){
2205        int w = aExplainWidth[i];
2206        if( i==nArg-1 ) w = 0;
2207        if( azArg[i] && strlenChar(azArg[i])>w ){
2208          w = strlenChar(azArg[i]);
2209        }
2210        if( i==1 && p->aiIndent && p->pStmt ){
2211          if( p->iIndent<p->nIndent ){
2212            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2213          }
2214          p->iIndent++;
2215        }
2216        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2217        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2218      }
2219      break;
2220    }
2221    case MODE_Semi: {   /* .schema and .fullschema output */
2222      printSchemaLine(p->out, azArg[0], ";\n");
2223      break;
2224    }
2225    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2226      char *z;
2227      int j;
2228      int nParen = 0;
2229      char cEnd = 0;
2230      char c;
2231      int nLine = 0;
2232      assert( nArg==1 );
2233      if( azArg[0]==0 ) break;
2234      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2235       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2236      ){
2237        utf8_printf(p->out, "%s;\n", azArg[0]);
2238        break;
2239      }
2240      z = sqlite3_mprintf("%s", azArg[0]);
2241      shell_check_oom(z);
2242      j = 0;
2243      for(i=0; IsSpace(z[i]); i++){}
2244      for(; (c = z[i])!=0; i++){
2245        if( IsSpace(c) ){
2246          if( z[j-1]=='\r' ) z[j-1] = '\n';
2247          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2248        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2249          j--;
2250        }
2251        z[j++] = c;
2252      }
2253      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2254      z[j] = 0;
2255      if( strlen30(z)>=79 ){
2256        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2257          if( c==cEnd ){
2258            cEnd = 0;
2259          }else if( c=='"' || c=='\'' || c=='`' ){
2260            cEnd = c;
2261          }else if( c=='[' ){
2262            cEnd = ']';
2263          }else if( c=='-' && z[i+1]=='-' ){
2264            cEnd = '\n';
2265          }else if( c=='(' ){
2266            nParen++;
2267          }else if( c==')' ){
2268            nParen--;
2269            if( nLine>0 && nParen==0 && j>0 ){
2270              printSchemaLineN(p->out, z, j, "\n");
2271              j = 0;
2272            }
2273          }
2274          z[j++] = c;
2275          if( nParen==1 && cEnd==0
2276           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2277          ){
2278            if( c=='\n' ) j--;
2279            printSchemaLineN(p->out, z, j, "\n  ");
2280            j = 0;
2281            nLine++;
2282            while( IsSpace(z[i+1]) ){ i++; }
2283          }
2284        }
2285        z[j] = 0;
2286      }
2287      printSchemaLine(p->out, z, ";\n");
2288      sqlite3_free(z);
2289      break;
2290    }
2291    case MODE_List: {
2292      if( p->cnt++==0 && p->showHeader ){
2293        for(i=0; i<nArg; i++){
2294          utf8_printf(p->out,"%s%s",azCol[i],
2295                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2296        }
2297      }
2298      if( azArg==0 ) break;
2299      for(i=0; i<nArg; i++){
2300        char *z = azArg[i];
2301        if( z==0 ) z = p->nullValue;
2302        utf8_printf(p->out, "%s", z);
2303        if( i<nArg-1 ){
2304          utf8_printf(p->out, "%s", p->colSeparator);
2305        }else{
2306          utf8_printf(p->out, "%s", p->rowSeparator);
2307        }
2308      }
2309      break;
2310    }
2311    case MODE_Html: {
2312      if( p->cnt++==0 && p->showHeader ){
2313        raw_printf(p->out,"<TR>");
2314        for(i=0; i<nArg; i++){
2315          raw_printf(p->out,"<TH>");
2316          output_html_string(p->out, azCol[i]);
2317          raw_printf(p->out,"</TH>\n");
2318        }
2319        raw_printf(p->out,"</TR>\n");
2320      }
2321      if( azArg==0 ) break;
2322      raw_printf(p->out,"<TR>");
2323      for(i=0; i<nArg; i++){
2324        raw_printf(p->out,"<TD>");
2325        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2326        raw_printf(p->out,"</TD>\n");
2327      }
2328      raw_printf(p->out,"</TR>\n");
2329      break;
2330    }
2331    case MODE_Tcl: {
2332      if( p->cnt++==0 && p->showHeader ){
2333        for(i=0; i<nArg; i++){
2334          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2335          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2336        }
2337        utf8_printf(p->out, "%s", p->rowSeparator);
2338      }
2339      if( azArg==0 ) break;
2340      for(i=0; i<nArg; i++){
2341        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2342        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2343      }
2344      utf8_printf(p->out, "%s", p->rowSeparator);
2345      break;
2346    }
2347    case MODE_Csv: {
2348      setBinaryMode(p->out, 1);
2349      if( p->cnt++==0 && p->showHeader ){
2350        for(i=0; i<nArg; i++){
2351          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2352        }
2353        utf8_printf(p->out, "%s", p->rowSeparator);
2354      }
2355      if( nArg>0 ){
2356        for(i=0; i<nArg; i++){
2357          output_csv(p, azArg[i], i<nArg-1);
2358        }
2359        utf8_printf(p->out, "%s", p->rowSeparator);
2360      }
2361      setTextMode(p->out, 1);
2362      break;
2363    }
2364    case MODE_Insert: {
2365      if( azArg==0 ) break;
2366      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2367      if( p->showHeader ){
2368        raw_printf(p->out,"(");
2369        for(i=0; i<nArg; i++){
2370          if( i>0 ) raw_printf(p->out, ",");
2371          if( quoteChar(azCol[i]) ){
2372            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2373            shell_check_oom(z);
2374            utf8_printf(p->out, "%s", z);
2375            sqlite3_free(z);
2376          }else{
2377            raw_printf(p->out, "%s", azCol[i]);
2378          }
2379        }
2380        raw_printf(p->out,")");
2381      }
2382      p->cnt++;
2383      for(i=0; i<nArg; i++){
2384        raw_printf(p->out, i>0 ? "," : " VALUES(");
2385        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2386          utf8_printf(p->out,"NULL");
2387        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2388          if( ShellHasFlag(p, SHFLG_Newlines) ){
2389            output_quoted_string(p->out, azArg[i]);
2390          }else{
2391            output_quoted_escaped_string(p->out, azArg[i]);
2392          }
2393        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2394          utf8_printf(p->out,"%s", azArg[i]);
2395        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2396          char z[50];
2397          double r = sqlite3_column_double(p->pStmt, i);
2398          sqlite3_uint64 ur;
2399          memcpy(&ur,&r,sizeof(r));
2400          if( ur==0x7ff0000000000000LL ){
2401            raw_printf(p->out, "1e999");
2402          }else if( ur==0xfff0000000000000LL ){
2403            raw_printf(p->out, "-1e999");
2404          }else{
2405            sqlite3_int64 ir = (sqlite3_int64)r;
2406            if( r==(double)ir ){
2407              sqlite3_snprintf(50,z,"%lld.0", ir);
2408            }else{
2409              sqlite3_snprintf(50,z,"%!.20g", r);
2410            }
2411            raw_printf(p->out, "%s", z);
2412          }
2413        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2414          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2415          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2416          output_hex_blob(p->out, pBlob, nBlob);
2417        }else if( isNumber(azArg[i], 0) ){
2418          utf8_printf(p->out,"%s", azArg[i]);
2419        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2420          output_quoted_string(p->out, azArg[i]);
2421        }else{
2422          output_quoted_escaped_string(p->out, azArg[i]);
2423        }
2424      }
2425      raw_printf(p->out,");\n");
2426      break;
2427    }
2428    case MODE_Json: {
2429      if( azArg==0 ) break;
2430      if( p->cnt==0 ){
2431        fputs("[{", p->out);
2432      }else{
2433        fputs(",\n{", p->out);
2434      }
2435      p->cnt++;
2436      for(i=0; i<nArg; i++){
2437        output_json_string(p->out, azCol[i], -1);
2438        putc(':', p->out);
2439        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2440          fputs("null",p->out);
2441        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2442          char z[50];
2443          double r = sqlite3_column_double(p->pStmt, i);
2444          sqlite3_uint64 ur;
2445          memcpy(&ur,&r,sizeof(r));
2446          if( ur==0x7ff0000000000000LL ){
2447            raw_printf(p->out, "1e999");
2448          }else if( ur==0xfff0000000000000LL ){
2449            raw_printf(p->out, "-1e999");
2450          }else{
2451            sqlite3_snprintf(50,z,"%!.20g", r);
2452            raw_printf(p->out, "%s", z);
2453          }
2454        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2455          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2456          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2457          output_json_string(p->out, pBlob, nBlob);
2458        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2459          output_json_string(p->out, azArg[i], -1);
2460        }else{
2461          utf8_printf(p->out,"%s", azArg[i]);
2462        }
2463        if( i<nArg-1 ){
2464          putc(',', p->out);
2465        }
2466      }
2467      putc('}', p->out);
2468      break;
2469    }
2470    case MODE_Quote: {
2471      if( azArg==0 ) break;
2472      if( p->cnt==0 && p->showHeader ){
2473        for(i=0; i<nArg; i++){
2474          if( i>0 ) fputs(p->colSeparator, p->out);
2475          output_quoted_string(p->out, azCol[i]);
2476        }
2477        fputs(p->rowSeparator, p->out);
2478      }
2479      p->cnt++;
2480      for(i=0; i<nArg; i++){
2481        if( i>0 ) fputs(p->colSeparator, p->out);
2482        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2483          utf8_printf(p->out,"NULL");
2484        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2485          output_quoted_string(p->out, azArg[i]);
2486        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2487          utf8_printf(p->out,"%s", azArg[i]);
2488        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2489          char z[50];
2490          double r = sqlite3_column_double(p->pStmt, i);
2491          sqlite3_snprintf(50,z,"%!.20g", r);
2492          raw_printf(p->out, "%s", z);
2493        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2494          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2495          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2496          output_hex_blob(p->out, pBlob, nBlob);
2497        }else if( isNumber(azArg[i], 0) ){
2498          utf8_printf(p->out,"%s", azArg[i]);
2499        }else{
2500          output_quoted_string(p->out, azArg[i]);
2501        }
2502      }
2503      fputs(p->rowSeparator, p->out);
2504      break;
2505    }
2506    case MODE_Ascii: {
2507      if( p->cnt++==0 && p->showHeader ){
2508        for(i=0; i<nArg; i++){
2509          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2510          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2511        }
2512        utf8_printf(p->out, "%s", p->rowSeparator);
2513      }
2514      if( azArg==0 ) break;
2515      for(i=0; i<nArg; i++){
2516        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2517        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2518      }
2519      utf8_printf(p->out, "%s", p->rowSeparator);
2520      break;
2521    }
2522    case MODE_EQP: {
2523      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2524      break;
2525    }
2526  }
2527  return 0;
2528}
2529
2530/*
2531** This is the callback routine that the SQLite library
2532** invokes for each row of a query result.
2533*/
2534static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2535  /* since we don't have type info, call the shell_callback with a NULL value */
2536  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2537}
2538
2539/*
2540** This is the callback routine from sqlite3_exec() that appends all
2541** output onto the end of a ShellText object.
2542*/
2543static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2544  ShellText *p = (ShellText*)pArg;
2545  int i;
2546  UNUSED_PARAMETER(az);
2547  if( azArg==0 ) return 0;
2548  if( p->n ) appendText(p, "|", 0);
2549  for(i=0; i<nArg; i++){
2550    if( i ) appendText(p, ",", 0);
2551    if( azArg[i] ) appendText(p, azArg[i], 0);
2552  }
2553  return 0;
2554}
2555
2556/*
2557** Generate an appropriate SELFTEST table in the main database.
2558*/
2559static void createSelftestTable(ShellState *p){
2560  char *zErrMsg = 0;
2561  sqlite3_exec(p->db,
2562    "SAVEPOINT selftest_init;\n"
2563    "CREATE TABLE IF NOT EXISTS selftest(\n"
2564    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2565    "  op TEXT,\n"                   /* Operator:  memo run */
2566    "  cmd TEXT,\n"                  /* Command text */
2567    "  ans TEXT\n"                   /* Desired answer */
2568    ");"
2569    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2570    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2571    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2572    "         'memo','Tests generated by --init');\n"
2573    "INSERT INTO [_shell$self]\n"
2574    "  SELECT 'run',\n"
2575    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2576                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2577    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2578                          "FROM sqlite_schema ORDER BY 2',224));\n"
2579    "INSERT INTO [_shell$self]\n"
2580    "  SELECT 'run',"
2581    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2582    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2583    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2584    "  FROM (\n"
2585    "    SELECT name FROM sqlite_schema\n"
2586    "     WHERE type='table'\n"
2587    "       AND name<>'selftest'\n"
2588    "       AND coalesce(rootpage,0)>0\n"
2589    "  )\n"
2590    " ORDER BY name;\n"
2591    "INSERT INTO [_shell$self]\n"
2592    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2593    "INSERT INTO selftest(tno,op,cmd,ans)"
2594    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2595    "DROP TABLE [_shell$self];"
2596    ,0,0,&zErrMsg);
2597  if( zErrMsg ){
2598    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2599    sqlite3_free(zErrMsg);
2600  }
2601  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2602}
2603
2604
2605/*
2606** Set the destination table field of the ShellState structure to
2607** the name of the table given.  Escape any quote characters in the
2608** table name.
2609*/
2610static void set_table_name(ShellState *p, const char *zName){
2611  int i, n;
2612  char cQuote;
2613  char *z;
2614
2615  if( p->zDestTable ){
2616    free(p->zDestTable);
2617    p->zDestTable = 0;
2618  }
2619  if( zName==0 ) return;
2620  cQuote = quoteChar(zName);
2621  n = strlen30(zName);
2622  if( cQuote ) n += n+2;
2623  z = p->zDestTable = malloc( n+1 );
2624  shell_check_oom(z);
2625  n = 0;
2626  if( cQuote ) z[n++] = cQuote;
2627  for(i=0; zName[i]; i++){
2628    z[n++] = zName[i];
2629    if( zName[i]==cQuote ) z[n++] = cQuote;
2630  }
2631  if( cQuote ) z[n++] = cQuote;
2632  z[n] = 0;
2633}
2634
2635/*
2636** Maybe construct two lines of text that point out the position of a
2637** syntax error.  Return a pointer to the text, in memory obtained from
2638** sqlite3_malloc().  Or, if the most recent error does not involve a
2639** specific token that we can point to, return an empty string.
2640**
2641** In all cases, the memory returned is obtained from sqlite3_malloc64()
2642** and should be released by the caller invoking sqlite3_free().
2643*/
2644static char *shell_error_context(const char *zSql, sqlite3 *db){
2645  int iOffset;
2646  size_t len;
2647  char *zCode;
2648  char *zMsg;
2649  int i;
2650  if( db==0
2651   || zSql==0
2652   || (iOffset = sqlite3_error_offset(db))<0
2653  ){
2654    return sqlite3_mprintf("");
2655  }
2656  while( iOffset>50 ){
2657    iOffset--;
2658    zSql++;
2659    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2660  }
2661  len = strlen(zSql);
2662  if( len>78 ){
2663    len = 78;
2664    while( (zSql[len]&0xc0)==0x80 ) len--;
2665  }
2666  zCode = sqlite3_mprintf("%.*s", len, zSql);
2667  shell_check_oom(zCode);
2668  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2669  if( iOffset<25 ){
2670    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2671  }else{
2672    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2673  }
2674  return zMsg;
2675}
2676
2677
2678/*
2679** Execute a query statement that will generate SQL output.  Print
2680** the result columns, comma-separated, on a line and then add a
2681** semicolon terminator to the end of that line.
2682**
2683** If the number of columns is 1 and that column contains text "--"
2684** then write the semicolon on a separate line.  That way, if a
2685** "--" comment occurs at the end of the statement, the comment
2686** won't consume the semicolon terminator.
2687*/
2688static int run_table_dump_query(
2689  ShellState *p,           /* Query context */
2690  const char *zSelect      /* SELECT statement to extract content */
2691){
2692  sqlite3_stmt *pSelect;
2693  int rc;
2694  int nResult;
2695  int i;
2696  const char *z;
2697  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2698  if( rc!=SQLITE_OK || !pSelect ){
2699    char *zContext = shell_error_context(zSelect, p->db);
2700    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2701                sqlite3_errmsg(p->db), zContext);
2702    sqlite3_free(zContext);
2703    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2704    return rc;
2705  }
2706  rc = sqlite3_step(pSelect);
2707  nResult = sqlite3_column_count(pSelect);
2708  while( rc==SQLITE_ROW ){
2709    z = (const char*)sqlite3_column_text(pSelect, 0);
2710    utf8_printf(p->out, "%s", z);
2711    for(i=1; i<nResult; i++){
2712      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2713    }
2714    if( z==0 ) z = "";
2715    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2716    if( z[0] ){
2717      raw_printf(p->out, "\n;\n");
2718    }else{
2719      raw_printf(p->out, ";\n");
2720    }
2721    rc = sqlite3_step(pSelect);
2722  }
2723  rc = sqlite3_finalize(pSelect);
2724  if( rc!=SQLITE_OK ){
2725    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2726                sqlite3_errmsg(p->db));
2727    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2728  }
2729  return rc;
2730}
2731
2732/*
2733** Allocate space and save off string indicating current error.
2734*/
2735static char *save_err_msg(
2736  sqlite3 *db,           /* Database to query */
2737  const char *zPhase,    /* When the error occcurs */
2738  int rc,                /* Error code returned from API */
2739  const char *zSql       /* SQL string, or NULL */
2740){
2741  char *zErr;
2742  char *zContext;
2743  sqlite3_str *pStr = sqlite3_str_new(0);
2744  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2745  if( rc>1 ){
2746    sqlite3_str_appendf(pStr, " (%d)", rc);
2747  }
2748  zContext = shell_error_context(zSql, db);
2749  if( zContext ){
2750    sqlite3_str_appendall(pStr, zContext);
2751    sqlite3_free(zContext);
2752  }
2753  zErr = sqlite3_str_finish(pStr);
2754  shell_check_oom(zErr);
2755  return zErr;
2756}
2757
2758#ifdef __linux__
2759/*
2760** Attempt to display I/O stats on Linux using /proc/PID/io
2761*/
2762static void displayLinuxIoStats(FILE *out){
2763  FILE *in;
2764  char z[200];
2765  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2766  in = fopen(z, "rb");
2767  if( in==0 ) return;
2768  while( fgets(z, sizeof(z), in)!=0 ){
2769    static const struct {
2770      const char *zPattern;
2771      const char *zDesc;
2772    } aTrans[] = {
2773      { "rchar: ",                  "Bytes received by read():" },
2774      { "wchar: ",                  "Bytes sent to write():"    },
2775      { "syscr: ",                  "Read() system calls:"      },
2776      { "syscw: ",                  "Write() system calls:"     },
2777      { "read_bytes: ",             "Bytes read from storage:"  },
2778      { "write_bytes: ",            "Bytes written to storage:" },
2779      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2780    };
2781    int i;
2782    for(i=0; i<ArraySize(aTrans); i++){
2783      int n = strlen30(aTrans[i].zPattern);
2784      if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){
2785        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2786        break;
2787      }
2788    }
2789  }
2790  fclose(in);
2791}
2792#endif
2793
2794/*
2795** Display a single line of status using 64-bit values.
2796*/
2797static void displayStatLine(
2798  ShellState *p,            /* The shell context */
2799  char *zLabel,             /* Label for this one line */
2800  char *zFormat,            /* Format for the result */
2801  int iStatusCtrl,          /* Which status to display */
2802  int bReset                /* True to reset the stats */
2803){
2804  sqlite3_int64 iCur = -1;
2805  sqlite3_int64 iHiwtr = -1;
2806  int i, nPercent;
2807  char zLine[200];
2808  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2809  for(i=0, nPercent=0; zFormat[i]; i++){
2810    if( zFormat[i]=='%' ) nPercent++;
2811  }
2812  if( nPercent>1 ){
2813    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2814  }else{
2815    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2816  }
2817  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2818}
2819
2820/*
2821** Display memory stats.
2822*/
2823static int display_stats(
2824  sqlite3 *db,                /* Database to query */
2825  ShellState *pArg,           /* Pointer to ShellState */
2826  int bReset                  /* True to reset the stats */
2827){
2828  int iCur;
2829  int iHiwtr;
2830  FILE *out;
2831  if( pArg==0 || pArg->out==0 ) return 0;
2832  out = pArg->out;
2833
2834  if( pArg->pStmt && pArg->statsOn==2 ){
2835    int nCol, i, x;
2836    sqlite3_stmt *pStmt = pArg->pStmt;
2837    char z[100];
2838    nCol = sqlite3_column_count(pStmt);
2839    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2840    for(i=0; i<nCol; i++){
2841      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2842      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2843#ifndef SQLITE_OMIT_DECLTYPE
2844      sqlite3_snprintf(30, z+x, "declared type:");
2845      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2846#endif
2847#ifdef SQLITE_ENABLE_COLUMN_METADATA
2848      sqlite3_snprintf(30, z+x, "database name:");
2849      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2850      sqlite3_snprintf(30, z+x, "table name:");
2851      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2852      sqlite3_snprintf(30, z+x, "origin name:");
2853      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2854#endif
2855    }
2856  }
2857
2858  if( pArg->statsOn==3 ){
2859    if( pArg->pStmt ){
2860      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2861      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2862    }
2863    return 0;
2864  }
2865
2866  displayStatLine(pArg, "Memory Used:",
2867     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2868  displayStatLine(pArg, "Number of Outstanding Allocations:",
2869     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2870  if( pArg->shellFlgs & SHFLG_Pagecache ){
2871    displayStatLine(pArg, "Number of Pcache Pages Used:",
2872       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2873  }
2874  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2875     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2876  displayStatLine(pArg, "Largest Allocation:",
2877     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2878  displayStatLine(pArg, "Largest Pcache Allocation:",
2879     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2880#ifdef YYTRACKMAXSTACKDEPTH
2881  displayStatLine(pArg, "Deepest Parser Stack:",
2882     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2883#endif
2884
2885  if( db ){
2886    if( pArg->shellFlgs & SHFLG_Lookaside ){
2887      iHiwtr = iCur = -1;
2888      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2889                        &iCur, &iHiwtr, bReset);
2890      raw_printf(pArg->out,
2891              "Lookaside Slots Used:                %d (max %d)\n",
2892              iCur, iHiwtr);
2893      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2894                        &iCur, &iHiwtr, bReset);
2895      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2896              iHiwtr);
2897      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2898                        &iCur, &iHiwtr, bReset);
2899      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2900              iHiwtr);
2901      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2902                        &iCur, &iHiwtr, bReset);
2903      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2904              iHiwtr);
2905    }
2906    iHiwtr = iCur = -1;
2907    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2908    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2909            iCur);
2910    iHiwtr = iCur = -1;
2911    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2912    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2913    iHiwtr = iCur = -1;
2914    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2915    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2916    iHiwtr = iCur = -1;
2917    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2918    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2919    iHiwtr = iCur = -1;
2920    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2921    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2922    iHiwtr = iCur = -1;
2923    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2924    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2925            iCur);
2926    iHiwtr = iCur = -1;
2927    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2928    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2929            iCur);
2930  }
2931
2932  if( pArg->pStmt ){
2933    int iHit, iMiss;
2934    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2935                               bReset);
2936    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2937    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2938    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2939    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2940    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2941    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2942    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2943    if( iHit || iMiss ){
2944      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2945            iHit, iHit+iMiss);
2946    }
2947    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2948    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2949    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2950    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2951    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2952    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2953    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2954    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2955  }
2956
2957#ifdef __linux__
2958  displayLinuxIoStats(pArg->out);
2959#endif
2960
2961  /* Do not remove this machine readable comment: extra-stats-output-here */
2962
2963  return 0;
2964}
2965
2966/*
2967** Display scan stats.
2968*/
2969static void display_scanstats(
2970  sqlite3 *db,                    /* Database to query */
2971  ShellState *pArg                /* Pointer to ShellState */
2972){
2973#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2974  UNUSED_PARAMETER(db);
2975  UNUSED_PARAMETER(pArg);
2976#else
2977  int i, k, n, mx;
2978  raw_printf(pArg->out, "-------- scanstats --------\n");
2979  mx = 0;
2980  for(k=0; k<=mx; k++){
2981    double rEstLoop = 1.0;
2982    for(i=n=0; 1; i++){
2983      sqlite3_stmt *p = pArg->pStmt;
2984      sqlite3_int64 nLoop, nVisit;
2985      double rEst;
2986      int iSid;
2987      const char *zExplain;
2988      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2989        break;
2990      }
2991      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2992      if( iSid>mx ) mx = iSid;
2993      if( iSid!=k ) continue;
2994      if( n==0 ){
2995        rEstLoop = (double)nLoop;
2996        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2997      }
2998      n++;
2999      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
3000      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
3001      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
3002      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
3003      rEstLoop *= rEst;
3004      raw_printf(pArg->out,
3005          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
3006          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
3007      );
3008    }
3009  }
3010  raw_printf(pArg->out, "---------------------------\n");
3011#endif
3012}
3013
3014/*
3015** Parameter azArray points to a zero-terminated array of strings. zStr
3016** points to a single nul-terminated string. Return non-zero if zStr
3017** is equal, according to strcmp(), to any of the strings in the array.
3018** Otherwise, return zero.
3019*/
3020static int str_in_array(const char *zStr, const char **azArray){
3021  int i;
3022  for(i=0; azArray[i]; i++){
3023    if( 0==cli_strcmp(zStr, azArray[i]) ) return 1;
3024  }
3025  return 0;
3026}
3027
3028/*
3029** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3030** and populate the ShellState.aiIndent[] array with the number of
3031** spaces each opcode should be indented before it is output.
3032**
3033** The indenting rules are:
3034**
3035**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3036**       all opcodes that occur between the p2 jump destination and the opcode
3037**       itself by 2 spaces.
3038**
3039**     * Do the previous for "Return" instructions for when P2 is positive.
3040**       See tag-20220407a in wherecode.c and vdbe.c.
3041**
3042**     * For each "Goto", if the jump destination is earlier in the program
3043**       and ends on one of:
3044**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3045**       or if the P1 parameter is one instead of zero,
3046**       then indent all opcodes between the earlier instruction
3047**       and "Goto" by 2 spaces.
3048*/
3049static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3050  const char *zSql;               /* The text of the SQL statement */
3051  const char *z;                  /* Used to check if this is an EXPLAIN */
3052  int *abYield = 0;               /* True if op is an OP_Yield */
3053  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3054  int iOp;                        /* Index of operation in p->aiIndent[] */
3055
3056  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3057                           "Return", 0 };
3058  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3059                            "Rewind", 0 };
3060  const char *azGoto[] = { "Goto", 0 };
3061
3062  /* Try to figure out if this is really an EXPLAIN statement. If this
3063  ** cannot be verified, return early.  */
3064  if( sqlite3_column_count(pSql)!=8 ){
3065    p->cMode = p->mode;
3066    return;
3067  }
3068  zSql = sqlite3_sql(pSql);
3069  if( zSql==0 ) return;
3070  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3071  if( sqlite3_strnicmp(z, "explain", 7) ){
3072    p->cMode = p->mode;
3073    return;
3074  }
3075
3076  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3077    int i;
3078    int iAddr = sqlite3_column_int(pSql, 0);
3079    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3080
3081    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3082    ** p2 is an instruction address, set variable p2op to the index of that
3083    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3084    ** the current instruction is part of a sub-program generated by an
3085    ** SQL trigger or foreign key.  */
3086    int p2 = sqlite3_column_int(pSql, 3);
3087    int p2op = (p2 + (iOp-iAddr));
3088
3089    /* Grow the p->aiIndent array as required */
3090    if( iOp>=nAlloc ){
3091      if( iOp==0 ){
3092        /* Do further verfication that this is explain output.  Abort if
3093        ** it is not */
3094        static const char *explainCols[] = {
3095           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3096        int jj;
3097        for(jj=0; jj<ArraySize(explainCols); jj++){
3098          if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3099            p->cMode = p->mode;
3100            sqlite3_reset(pSql);
3101            return;
3102          }
3103        }
3104      }
3105      nAlloc += 100;
3106      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3107      shell_check_oom(p->aiIndent);
3108      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3109      shell_check_oom(abYield);
3110    }
3111    abYield[iOp] = str_in_array(zOp, azYield);
3112    p->aiIndent[iOp] = 0;
3113    p->nIndent = iOp+1;
3114
3115    if( str_in_array(zOp, azNext) && p2op>0 ){
3116      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3117    }
3118    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3119     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3120    ){
3121      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3122    }
3123  }
3124
3125  p->iIndent = 0;
3126  sqlite3_free(abYield);
3127  sqlite3_reset(pSql);
3128}
3129
3130/*
3131** Free the array allocated by explain_data_prepare().
3132*/
3133static void explain_data_delete(ShellState *p){
3134  sqlite3_free(p->aiIndent);
3135  p->aiIndent = 0;
3136  p->nIndent = 0;
3137  p->iIndent = 0;
3138}
3139
3140/*
3141** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3142*/
3143static unsigned int savedSelectTrace;
3144static unsigned int savedWhereTrace;
3145static void disable_debug_trace_modes(void){
3146  unsigned int zero = 0;
3147  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3148  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3149  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3150  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3151}
3152static void restore_debug_trace_modes(void){
3153  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3154  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3155}
3156
3157/* Create the TEMP table used to store parameter bindings */
3158static void bind_table_init(ShellState *p){
3159  int wrSchema = 0;
3160  int defensiveMode = 0;
3161  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3162  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3163  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3164  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3165  sqlite3_exec(p->db,
3166    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3167    "  key TEXT PRIMARY KEY,\n"
3168    "  value\n"
3169    ") WITHOUT ROWID;",
3170    0, 0, 0);
3171  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3172  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3173}
3174
3175/*
3176** Bind parameters on a prepared statement.
3177**
3178** Parameter bindings are taken from a TEMP table of the form:
3179**
3180**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3181**    WITHOUT ROWID;
3182**
3183** No bindings occur if this table does not exist.  The name of the table
3184** begins with "sqlite_" so that it will not collide with ordinary application
3185** tables.  The table must be in the TEMP schema.
3186*/
3187static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3188  int nVar;
3189  int i;
3190  int rc;
3191  sqlite3_stmt *pQ = 0;
3192
3193  nVar = sqlite3_bind_parameter_count(pStmt);
3194  if( nVar==0 ) return;  /* Nothing to do */
3195  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3196                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3197    return; /* Parameter table does not exist */
3198  }
3199  rc = sqlite3_prepare_v2(pArg->db,
3200          "SELECT value FROM temp.sqlite_parameters"
3201          " WHERE key=?1", -1, &pQ, 0);
3202  if( rc || pQ==0 ) return;
3203  for(i=1; i<=nVar; i++){
3204    char zNum[30];
3205    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3206    if( zVar==0 ){
3207      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3208      zVar = zNum;
3209    }
3210    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3211    if( sqlite3_step(pQ)==SQLITE_ROW ){
3212      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3213    }else{
3214      sqlite3_bind_null(pStmt, i);
3215    }
3216    sqlite3_reset(pQ);
3217  }
3218  sqlite3_finalize(pQ);
3219}
3220
3221/*
3222** UTF8 box-drawing characters.  Imagine box lines like this:
3223**
3224**           1
3225**           |
3226**       4 --+-- 2
3227**           |
3228**           3
3229**
3230** Each box characters has between 2 and 4 of the lines leading from
3231** the center.  The characters are here identified by the numbers of
3232** their corresponding lines.
3233*/
3234#define BOX_24   "\342\224\200"  /* U+2500 --- */
3235#define BOX_13   "\342\224\202"  /* U+2502  |  */
3236#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3237#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3238#define BOX_12   "\342\224\224"  /* U+2514  '- */
3239#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3240#define BOX_123  "\342\224\234"  /* U+251c  |- */
3241#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3242#define BOX_234  "\342\224\254"  /* U+252c -,- */
3243#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3244#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3245
3246/* Draw horizontal line N characters long using unicode box
3247** characters
3248*/
3249static void print_box_line(FILE *out, int N){
3250  const char zDash[] =
3251      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3252      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3253  const int nDash = sizeof(zDash) - 1;
3254  N *= 3;
3255  while( N>nDash ){
3256    utf8_printf(out, zDash);
3257    N -= nDash;
3258  }
3259  utf8_printf(out, "%.*s", N, zDash);
3260}
3261
3262/*
3263** Draw a horizontal separator for a MODE_Box table.
3264*/
3265static void print_box_row_separator(
3266  ShellState *p,
3267  int nArg,
3268  const char *zSep1,
3269  const char *zSep2,
3270  const char *zSep3
3271){
3272  int i;
3273  if( nArg>0 ){
3274    utf8_printf(p->out, "%s", zSep1);
3275    print_box_line(p->out, p->actualWidth[0]+2);
3276    for(i=1; i<nArg; i++){
3277      utf8_printf(p->out, "%s", zSep2);
3278      print_box_line(p->out, p->actualWidth[i]+2);
3279    }
3280    utf8_printf(p->out, "%s", zSep3);
3281  }
3282  fputs("\n", p->out);
3283}
3284
3285/*
3286** z[] is a line of text that is to be displayed the .mode box or table or
3287** similar tabular formats.  z[] might contain control characters such
3288** as \n, \t, \f, or \r.
3289**
3290** Compute characters to display on the first line of z[].  Stop at the
3291** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3292** from malloc()) of that first line, which caller should free sometime.
3293** Write anything to display on the next line into *pzTail.  If this is
3294** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3295*/
3296static char *translateForDisplayAndDup(
3297  const unsigned char *z,            /* Input text to be transformed */
3298  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3299  int mxWidth,                       /* Max width.  0 means no limit */
3300  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3301){
3302  int i;                 /* Input bytes consumed */
3303  int j;                 /* Output bytes generated */
3304  int k;                 /* Input bytes to be displayed */
3305  int n;                 /* Output column number */
3306  unsigned char *zOut;   /* Output text */
3307
3308  if( z==0 ){
3309    *pzTail = 0;
3310    return 0;
3311  }
3312  if( mxWidth<0 ) mxWidth = -mxWidth;
3313  if( mxWidth==0 ) mxWidth = 1000000;
3314  i = j = n = 0;
3315  while( n<mxWidth ){
3316    if( z[i]>=' ' ){
3317      n++;
3318      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3319      continue;
3320    }
3321    if( z[i]=='\t' ){
3322      do{
3323        n++;
3324        j++;
3325      }while( (n&7)!=0 && n<mxWidth );
3326      i++;
3327      continue;
3328    }
3329    break;
3330  }
3331  if( n>=mxWidth && bWordWrap  ){
3332    /* Perhaps try to back up to a better place to break the line */
3333    for(k=i; k>i/2; k--){
3334      if( isspace(z[k-1]) ) break;
3335    }
3336    if( k<=i/2 ){
3337      for(k=i; k>i/2; k--){
3338        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3339      }
3340    }
3341    if( k<=i/2 ){
3342      k = i;
3343    }else{
3344      i = k;
3345      while( z[i]==' ' ) i++;
3346    }
3347  }else{
3348    k = i;
3349  }
3350  if( n>=mxWidth && z[i]>=' ' ){
3351   *pzTail = &z[i];
3352  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3353    *pzTail = z[i+2] ? &z[i+2] : 0;
3354  }else if( z[i]==0 || z[i+1]==0 ){
3355    *pzTail = 0;
3356  }else{
3357    *pzTail = &z[i+1];
3358  }
3359  zOut = malloc( j+1 );
3360  shell_check_oom(zOut);
3361  i = j = n = 0;
3362  while( i<k ){
3363    if( z[i]>=' ' ){
3364      n++;
3365      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3366      continue;
3367    }
3368    if( z[i]=='\t' ){
3369      do{
3370        n++;
3371        zOut[j++] = ' ';
3372      }while( (n&7)!=0 && n<mxWidth );
3373      i++;
3374      continue;
3375    }
3376    break;
3377  }
3378  zOut[j] = 0;
3379  return (char*)zOut;
3380}
3381
3382/* Extract the value of the i-th current column for pStmt as an SQL literal
3383** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3384** the caller.
3385*/
3386static char *quoted_column(sqlite3_stmt *pStmt, int i){
3387  switch( sqlite3_column_type(pStmt, i) ){
3388    case SQLITE_NULL: {
3389      return sqlite3_mprintf("NULL");
3390    }
3391    case SQLITE_INTEGER:
3392    case SQLITE_FLOAT: {
3393      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3394    }
3395    case SQLITE_TEXT: {
3396      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3397    }
3398    case SQLITE_BLOB: {
3399      int j;
3400      sqlite3_str *pStr = sqlite3_str_new(0);
3401      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3402      int n = sqlite3_column_bytes(pStmt,i);
3403      sqlite3_str_append(pStr, "x'", 2);
3404      for(j=0; j<n; j++){
3405        sqlite3_str_appendf(pStr, "%02x", a[j]);
3406      }
3407      sqlite3_str_append(pStr, "'", 1);
3408      return sqlite3_str_finish(pStr);
3409    }
3410  }
3411  return 0; /* Not reached */
3412}
3413
3414/*
3415** Run a prepared statement and output the result in one of the
3416** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3417** or MODE_Box.
3418**
3419** This is different from ordinary exec_prepared_stmt() in that
3420** it has to run the entire query and gather the results into memory
3421** first, in order to determine column widths, before providing
3422** any output.
3423*/
3424static void exec_prepared_stmt_columnar(
3425  ShellState *p,                        /* Pointer to ShellState */
3426  sqlite3_stmt *pStmt                   /* Statment to run */
3427){
3428  sqlite3_int64 nRow = 0;
3429  int nColumn = 0;
3430  char **azData = 0;
3431  sqlite3_int64 nAlloc = 0;
3432  char *abRowDiv = 0;
3433  const unsigned char *uz;
3434  const char *z;
3435  char **azQuoted = 0;
3436  int rc;
3437  sqlite3_int64 i, nData;
3438  int j, nTotal, w, n;
3439  const char *colSep = 0;
3440  const char *rowSep = 0;
3441  const unsigned char **azNextLine = 0;
3442  int bNextLine = 0;
3443  int bMultiLineRowExists = 0;
3444  int bw = p->cmOpts.bWordWrap;
3445  const char *zEmpty = "";
3446  const char *zShowNull = p->nullValue;
3447
3448  rc = sqlite3_step(pStmt);
3449  if( rc!=SQLITE_ROW ) return;
3450  nColumn = sqlite3_column_count(pStmt);
3451  nAlloc = nColumn*4;
3452  if( nAlloc<=0 ) nAlloc = 1;
3453  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3454  shell_check_oom(azData);
3455  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3456  shell_check_oom((void*)azNextLine);
3457  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3458  if( p->cmOpts.bQuote ){
3459    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3460    shell_check_oom(azQuoted);
3461    memset(azQuoted, 0, nColumn*sizeof(char*) );
3462  }
3463  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3464  shell_check_oom(abRowDiv);
3465  if( nColumn>p->nWidth ){
3466    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3467    shell_check_oom(p->colWidth);
3468    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3469    p->nWidth = nColumn;
3470    p->actualWidth = &p->colWidth[nColumn];
3471  }
3472  memset(p->actualWidth, 0, nColumn*sizeof(int));
3473  for(i=0; i<nColumn; i++){
3474    w = p->colWidth[i];
3475    if( w<0 ) w = -w;
3476    p->actualWidth[i] = w;
3477  }
3478  for(i=0; i<nColumn; i++){
3479    const unsigned char *zNotUsed;
3480    int wx = p->colWidth[i];
3481    if( wx==0 ){
3482      wx = p->cmOpts.iWrap;
3483    }
3484    if( wx<0 ) wx = -wx;
3485    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3486    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3487  }
3488  do{
3489    int useNextLine = bNextLine;
3490    bNextLine = 0;
3491    if( (nRow+2)*nColumn >= nAlloc ){
3492      nAlloc *= 2;
3493      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3494      shell_check_oom(azData);
3495      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3496      shell_check_oom(abRowDiv);
3497    }
3498    abRowDiv[nRow] = 1;
3499    nRow++;
3500    for(i=0; i<nColumn; i++){
3501      int wx = p->colWidth[i];
3502      if( wx==0 ){
3503        wx = p->cmOpts.iWrap;
3504      }
3505      if( wx<0 ) wx = -wx;
3506      if( useNextLine ){
3507        uz = azNextLine[i];
3508        if( uz==0 ) uz = (u8*)zEmpty;
3509      }else if( p->cmOpts.bQuote ){
3510        sqlite3_free(azQuoted[i]);
3511        azQuoted[i] = quoted_column(pStmt,i);
3512        uz = (const unsigned char*)azQuoted[i];
3513      }else{
3514        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3515        if( uz==0 ) uz = (u8*)zShowNull;
3516      }
3517      azData[nRow*nColumn + i]
3518        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3519      if( azNextLine[i] ){
3520        bNextLine = 1;
3521        abRowDiv[nRow-1] = 0;
3522        bMultiLineRowExists = 1;
3523      }
3524    }
3525  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3526  nTotal = nColumn*(nRow+1);
3527  for(i=0; i<nTotal; i++){
3528    z = azData[i];
3529    if( z==0 ) z = (char*)zEmpty;
3530    n = strlenChar(z);
3531    j = i%nColumn;
3532    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3533  }
3534  if( seenInterrupt ) goto columnar_end;
3535  if( nColumn==0 ) goto columnar_end;
3536  switch( p->cMode ){
3537    case MODE_Column: {
3538      colSep = "  ";
3539      rowSep = "\n";
3540      if( p->showHeader ){
3541        for(i=0; i<nColumn; i++){
3542          w = p->actualWidth[i];
3543          if( p->colWidth[i]<0 ) w = -w;
3544          utf8_width_print(p->out, w, azData[i]);
3545          fputs(i==nColumn-1?"\n":"  ", p->out);
3546        }
3547        for(i=0; i<nColumn; i++){
3548          print_dashes(p->out, p->actualWidth[i]);
3549          fputs(i==nColumn-1?"\n":"  ", p->out);
3550        }
3551      }
3552      break;
3553    }
3554    case MODE_Table: {
3555      colSep = " | ";
3556      rowSep = " |\n";
3557      print_row_separator(p, nColumn, "+");
3558      fputs("| ", p->out);
3559      for(i=0; i<nColumn; i++){
3560        w = p->actualWidth[i];
3561        n = strlenChar(azData[i]);
3562        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3563        fputs(i==nColumn-1?" |\n":" | ", p->out);
3564      }
3565      print_row_separator(p, nColumn, "+");
3566      break;
3567    }
3568    case MODE_Markdown: {
3569      colSep = " | ";
3570      rowSep = " |\n";
3571      fputs("| ", p->out);
3572      for(i=0; i<nColumn; i++){
3573        w = p->actualWidth[i];
3574        n = strlenChar(azData[i]);
3575        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3576        fputs(i==nColumn-1?" |\n":" | ", p->out);
3577      }
3578      print_row_separator(p, nColumn, "|");
3579      break;
3580    }
3581    case MODE_Box: {
3582      colSep = " " BOX_13 " ";
3583      rowSep = " " BOX_13 "\n";
3584      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3585      utf8_printf(p->out, BOX_13 " ");
3586      for(i=0; i<nColumn; i++){
3587        w = p->actualWidth[i];
3588        n = strlenChar(azData[i]);
3589        utf8_printf(p->out, "%*s%s%*s%s",
3590            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3591            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3592      }
3593      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3594      break;
3595    }
3596  }
3597  for(i=nColumn, j=0; i<nTotal; i++, j++){
3598    if( j==0 && p->cMode!=MODE_Column ){
3599      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3600    }
3601    z = azData[i];
3602    if( z==0 ) z = p->nullValue;
3603    w = p->actualWidth[j];
3604    if( p->colWidth[j]<0 ) w = -w;
3605    utf8_width_print(p->out, w, z);
3606    if( j==nColumn-1 ){
3607      utf8_printf(p->out, "%s", rowSep);
3608      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3609        if( p->cMode==MODE_Table ){
3610          print_row_separator(p, nColumn, "+");
3611        }else if( p->cMode==MODE_Box ){
3612          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3613        }else if( p->cMode==MODE_Column ){
3614          raw_printf(p->out, "\n");
3615        }
3616      }
3617      j = -1;
3618      if( seenInterrupt ) goto columnar_end;
3619    }else{
3620      utf8_printf(p->out, "%s", colSep);
3621    }
3622  }
3623  if( p->cMode==MODE_Table ){
3624    print_row_separator(p, nColumn, "+");
3625  }else if( p->cMode==MODE_Box ){
3626    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3627  }
3628columnar_end:
3629  if( seenInterrupt ){
3630    utf8_printf(p->out, "Interrupt\n");
3631  }
3632  nData = (nRow+1)*nColumn;
3633  for(i=0; i<nData; i++){
3634    z = azData[i];
3635    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3636  }
3637  sqlite3_free(azData);
3638  sqlite3_free((void*)azNextLine);
3639  sqlite3_free(abRowDiv);
3640  if( azQuoted ){
3641    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3642    sqlite3_free(azQuoted);
3643  }
3644}
3645
3646/*
3647** Run a prepared statement
3648*/
3649static void exec_prepared_stmt(
3650  ShellState *pArg,                                /* Pointer to ShellState */
3651  sqlite3_stmt *pStmt                              /* Statment to run */
3652){
3653  int rc;
3654  sqlite3_uint64 nRow = 0;
3655
3656  if( pArg->cMode==MODE_Column
3657   || pArg->cMode==MODE_Table
3658   || pArg->cMode==MODE_Box
3659   || pArg->cMode==MODE_Markdown
3660  ){
3661    exec_prepared_stmt_columnar(pArg, pStmt);
3662    return;
3663  }
3664
3665  /* perform the first step.  this will tell us if we
3666  ** have a result set or not and how wide it is.
3667  */
3668  rc = sqlite3_step(pStmt);
3669  /* if we have a result set... */
3670  if( SQLITE_ROW == rc ){
3671    /* allocate space for col name ptr, value ptr, and type */
3672    int nCol = sqlite3_column_count(pStmt);
3673    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3674    if( !pData ){
3675      shell_out_of_memory();
3676    }else{
3677      char **azCols = (char **)pData;      /* Names of result columns */
3678      char **azVals = &azCols[nCol];       /* Results */
3679      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3680      int i, x;
3681      assert(sizeof(int) <= sizeof(char *));
3682      /* save off ptrs to column names */
3683      for(i=0; i<nCol; i++){
3684        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3685      }
3686      do{
3687        nRow++;
3688        /* extract the data and data types */
3689        for(i=0; i<nCol; i++){
3690          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3691          if( x==SQLITE_BLOB
3692           && pArg
3693           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3694          ){
3695            azVals[i] = "";
3696          }else{
3697            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3698          }
3699          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3700            rc = SQLITE_NOMEM;
3701            break; /* from for */
3702          }
3703        } /* end for */
3704
3705        /* if data and types extracted successfully... */
3706        if( SQLITE_ROW == rc ){
3707          /* call the supplied callback with the result row data */
3708          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3709            rc = SQLITE_ABORT;
3710          }else{
3711            rc = sqlite3_step(pStmt);
3712          }
3713        }
3714      } while( SQLITE_ROW == rc );
3715      sqlite3_free(pData);
3716      if( pArg->cMode==MODE_Json ){
3717        fputs("]\n", pArg->out);
3718      }else if( pArg->cMode==MODE_Count ){
3719        char zBuf[200];
3720        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3721                         nRow, nRow!=1 ? "s" : "");
3722        printf("%s", zBuf);
3723      }
3724    }
3725  }
3726}
3727
3728#ifndef SQLITE_OMIT_VIRTUALTABLE
3729/*
3730** This function is called to process SQL if the previous shell command
3731** was ".expert". It passes the SQL in the second argument directly to
3732** the sqlite3expert object.
3733**
3734** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3735** code. In this case, (*pzErr) may be set to point to a buffer containing
3736** an English language error message. It is the responsibility of the
3737** caller to eventually free this buffer using sqlite3_free().
3738*/
3739static int expertHandleSQL(
3740  ShellState *pState,
3741  const char *zSql,
3742  char **pzErr
3743){
3744  assert( pState->expert.pExpert );
3745  assert( pzErr==0 || *pzErr==0 );
3746  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3747}
3748
3749/*
3750** This function is called either to silently clean up the object
3751** created by the ".expert" command (if bCancel==1), or to generate a
3752** report from it and then clean it up (if bCancel==0).
3753**
3754** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3755** code. In this case, (*pzErr) may be set to point to a buffer containing
3756** an English language error message. It is the responsibility of the
3757** caller to eventually free this buffer using sqlite3_free().
3758*/
3759static int expertFinish(
3760  ShellState *pState,
3761  int bCancel,
3762  char **pzErr
3763){
3764  int rc = SQLITE_OK;
3765  sqlite3expert *p = pState->expert.pExpert;
3766  assert( p );
3767  assert( bCancel || pzErr==0 || *pzErr==0 );
3768  if( bCancel==0 ){
3769    FILE *out = pState->out;
3770    int bVerbose = pState->expert.bVerbose;
3771
3772    rc = sqlite3_expert_analyze(p, pzErr);
3773    if( rc==SQLITE_OK ){
3774      int nQuery = sqlite3_expert_count(p);
3775      int i;
3776
3777      if( bVerbose ){
3778        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3779        raw_printf(out, "-- Candidates -----------------------------\n");
3780        raw_printf(out, "%s\n", zCand);
3781      }
3782      for(i=0; i<nQuery; i++){
3783        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3784        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3785        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3786        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3787        if( bVerbose ){
3788          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3789          raw_printf(out, "%s\n\n", zSql);
3790        }
3791        raw_printf(out, "%s\n", zIdx);
3792        raw_printf(out, "%s\n", zEQP);
3793      }
3794    }
3795  }
3796  sqlite3_expert_destroy(p);
3797  pState->expert.pExpert = 0;
3798  return rc;
3799}
3800
3801/*
3802** Implementation of ".expert" dot command.
3803*/
3804static int expertDotCommand(
3805  ShellState *pState,             /* Current shell tool state */
3806  char **azArg,                   /* Array of arguments passed to dot command */
3807  int nArg                        /* Number of entries in azArg[] */
3808){
3809  int rc = SQLITE_OK;
3810  char *zErr = 0;
3811  int i;
3812  int iSample = 0;
3813
3814  assert( pState->expert.pExpert==0 );
3815  memset(&pState->expert, 0, sizeof(ExpertInfo));
3816
3817  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3818    char *z = azArg[i];
3819    int n;
3820    if( z[0]=='-' && z[1]=='-' ) z++;
3821    n = strlen30(z);
3822    if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){
3823      pState->expert.bVerbose = 1;
3824    }
3825    else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
3826      if( i==(nArg-1) ){
3827        raw_printf(stderr, "option requires an argument: %s\n", z);
3828        rc = SQLITE_ERROR;
3829      }else{
3830        iSample = (int)integerValue(azArg[++i]);
3831        if( iSample<0 || iSample>100 ){
3832          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3833          rc = SQLITE_ERROR;
3834        }
3835      }
3836    }
3837    else{
3838      raw_printf(stderr, "unknown option: %s\n", z);
3839      rc = SQLITE_ERROR;
3840    }
3841  }
3842
3843  if( rc==SQLITE_OK ){
3844    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3845    if( pState->expert.pExpert==0 ){
3846      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3847      rc = SQLITE_ERROR;
3848    }else{
3849      sqlite3_expert_config(
3850          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3851      );
3852    }
3853  }
3854  sqlite3_free(zErr);
3855
3856  return rc;
3857}
3858#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3859
3860/*
3861** Execute a statement or set of statements.  Print
3862** any result rows/columns depending on the current mode
3863** set via the supplied callback.
3864**
3865** This is very similar to SQLite's built-in sqlite3_exec()
3866** function except it takes a slightly different callback
3867** and callback data argument.
3868*/
3869static int shell_exec(
3870  ShellState *pArg,                         /* Pointer to ShellState */
3871  const char *zSql,                         /* SQL to be evaluated */
3872  char **pzErrMsg                           /* Error msg written here */
3873){
3874  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3875  int rc = SQLITE_OK;             /* Return Code */
3876  int rc2;
3877  const char *zLeftover;          /* Tail of unprocessed SQL */
3878  sqlite3 *db = pArg->db;
3879
3880  if( pzErrMsg ){
3881    *pzErrMsg = NULL;
3882  }
3883
3884#ifndef SQLITE_OMIT_VIRTUALTABLE
3885  if( pArg->expert.pExpert ){
3886    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3887    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3888  }
3889#endif
3890
3891  while( zSql[0] && (SQLITE_OK == rc) ){
3892    static const char *zStmtSql;
3893    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3894    if( SQLITE_OK != rc ){
3895      if( pzErrMsg ){
3896        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3897      }
3898    }else{
3899      if( !pStmt ){
3900        /* this happens for a comment or white-space */
3901        zSql = zLeftover;
3902        while( IsSpace(zSql[0]) ) zSql++;
3903        continue;
3904      }
3905      zStmtSql = sqlite3_sql(pStmt);
3906      if( zStmtSql==0 ) zStmtSql = "";
3907      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3908
3909      /* save off the prepared statment handle and reset row count */
3910      if( pArg ){
3911        pArg->pStmt = pStmt;
3912        pArg->cnt = 0;
3913      }
3914
3915      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3916      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3917        sqlite3_stmt *pExplain;
3918        char *zEQP;
3919        int triggerEQP = 0;
3920        disable_debug_trace_modes();
3921        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3922        if( pArg->autoEQP>=AUTOEQP_trigger ){
3923          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3924        }
3925        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3926        shell_check_oom(zEQP);
3927        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3928        if( rc==SQLITE_OK ){
3929          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3930            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3931            int iEqpId = sqlite3_column_int(pExplain, 0);
3932            int iParentId = sqlite3_column_int(pExplain, 1);
3933            if( zEQPLine==0 ) zEQPLine = "";
3934            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3935            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3936          }
3937          eqp_render(pArg);
3938        }
3939        sqlite3_finalize(pExplain);
3940        sqlite3_free(zEQP);
3941        if( pArg->autoEQP>=AUTOEQP_full ){
3942          /* Also do an EXPLAIN for ".eqp full" mode */
3943          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3944          shell_check_oom(zEQP);
3945          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3946          if( rc==SQLITE_OK ){
3947            pArg->cMode = MODE_Explain;
3948            explain_data_prepare(pArg, pExplain);
3949            exec_prepared_stmt(pArg, pExplain);
3950            explain_data_delete(pArg);
3951          }
3952          sqlite3_finalize(pExplain);
3953          sqlite3_free(zEQP);
3954        }
3955        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3956          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3957          /* Reprepare pStmt before reactiving trace modes */
3958          sqlite3_finalize(pStmt);
3959          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3960          if( pArg ) pArg->pStmt = pStmt;
3961        }
3962        restore_debug_trace_modes();
3963      }
3964
3965      if( pArg ){
3966        pArg->cMode = pArg->mode;
3967        if( pArg->autoExplain ){
3968          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3969            pArg->cMode = MODE_Explain;
3970          }
3971          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3972            pArg->cMode = MODE_EQP;
3973          }
3974        }
3975
3976        /* If the shell is currently in ".explain" mode, gather the extra
3977        ** data required to add indents to the output.*/
3978        if( pArg->cMode==MODE_Explain ){
3979          explain_data_prepare(pArg, pStmt);
3980        }
3981      }
3982
3983      bind_prepared_stmt(pArg, pStmt);
3984      exec_prepared_stmt(pArg, pStmt);
3985      explain_data_delete(pArg);
3986      eqp_render(pArg);
3987
3988      /* print usage stats if stats on */
3989      if( pArg && pArg->statsOn ){
3990        display_stats(db, pArg, 0);
3991      }
3992
3993      /* print loop-counters if required */
3994      if( pArg && pArg->scanstatsOn ){
3995        display_scanstats(db, pArg);
3996      }
3997
3998      /* Finalize the statement just executed. If this fails, save a
3999      ** copy of the error message. Otherwise, set zSql to point to the
4000      ** next statement to execute. */
4001      rc2 = sqlite3_finalize(pStmt);
4002      if( rc!=SQLITE_NOMEM ) rc = rc2;
4003      if( rc==SQLITE_OK ){
4004        zSql = zLeftover;
4005        while( IsSpace(zSql[0]) ) zSql++;
4006      }else if( pzErrMsg ){
4007        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
4008      }
4009
4010      /* clear saved stmt handle */
4011      if( pArg ){
4012        pArg->pStmt = NULL;
4013      }
4014    }
4015  } /* end while */
4016
4017  return rc;
4018}
4019
4020/*
4021** Release memory previously allocated by tableColumnList().
4022*/
4023static void freeColumnList(char **azCol){
4024  int i;
4025  for(i=1; azCol[i]; i++){
4026    sqlite3_free(azCol[i]);
4027  }
4028  /* azCol[0] is a static string */
4029  sqlite3_free(azCol);
4030}
4031
4032/*
4033** Return a list of pointers to strings which are the names of all
4034** columns in table zTab.   The memory to hold the names is dynamically
4035** allocated and must be released by the caller using a subsequent call
4036** to freeColumnList().
4037**
4038** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
4039** value that needs to be preserved, then azCol[0] is filled in with the
4040** name of the rowid column.
4041**
4042** The first regular column in the table is azCol[1].  The list is terminated
4043** by an entry with azCol[i]==0.
4044*/
4045static char **tableColumnList(ShellState *p, const char *zTab){
4046  char **azCol = 0;
4047  sqlite3_stmt *pStmt;
4048  char *zSql;
4049  int nCol = 0;
4050  int nAlloc = 0;
4051  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4052  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4053  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4054  int rc;
4055
4056  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4057  shell_check_oom(zSql);
4058  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4059  sqlite3_free(zSql);
4060  if( rc ) return 0;
4061  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4062    if( nCol>=nAlloc-2 ){
4063      nAlloc = nAlloc*2 + nCol + 10;
4064      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4065      shell_check_oom(azCol);
4066    }
4067    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4068    shell_check_oom(azCol[nCol]);
4069    if( sqlite3_column_int(pStmt, 5) ){
4070      nPK++;
4071      if( nPK==1
4072       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4073                          "INTEGER")==0
4074      ){
4075        isIPK = 1;
4076      }else{
4077        isIPK = 0;
4078      }
4079    }
4080  }
4081  sqlite3_finalize(pStmt);
4082  if( azCol==0 ) return 0;
4083  azCol[0] = 0;
4084  azCol[nCol+1] = 0;
4085
4086  /* The decision of whether or not a rowid really needs to be preserved
4087  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4088  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4089  ** rowids on tables where the rowid is inaccessible because there are other
4090  ** columns in the table named "rowid", "_rowid_", and "oid".
4091  */
4092  if( preserveRowid && isIPK ){
4093    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4094    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4095    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4096    ** ROWID aliases.  To distinguish these cases, check to see if
4097    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4098    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4099    */
4100    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4101                           " WHERE origin='pk'", zTab);
4102    shell_check_oom(zSql);
4103    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4104    sqlite3_free(zSql);
4105    if( rc ){
4106      freeColumnList(azCol);
4107      return 0;
4108    }
4109    rc = sqlite3_step(pStmt);
4110    sqlite3_finalize(pStmt);
4111    preserveRowid = rc==SQLITE_ROW;
4112  }
4113  if( preserveRowid ){
4114    /* Only preserve the rowid if we can find a name to use for the
4115    ** rowid */
4116    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4117    int i, j;
4118    for(j=0; j<3; j++){
4119      for(i=1; i<=nCol; i++){
4120        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4121      }
4122      if( i>nCol ){
4123        /* At this point, we know that azRowid[j] is not the name of any
4124        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4125        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4126        ** tables will fail this last check */
4127        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4128        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4129        break;
4130      }
4131    }
4132  }
4133  return azCol;
4134}
4135
4136/*
4137** Toggle the reverse_unordered_selects setting.
4138*/
4139static void toggleSelectOrder(sqlite3 *db){
4140  sqlite3_stmt *pStmt = 0;
4141  int iSetting = 0;
4142  char zStmt[100];
4143  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4144  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4145    iSetting = sqlite3_column_int(pStmt, 0);
4146  }
4147  sqlite3_finalize(pStmt);
4148  sqlite3_snprintf(sizeof(zStmt), zStmt,
4149       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4150  sqlite3_exec(db, zStmt, 0, 0, 0);
4151}
4152
4153/*
4154** This is a different callback routine used for dumping the database.
4155** Each row received by this callback consists of a table name,
4156** the table type ("index" or "table") and SQL to create the table.
4157** This routine should print text sufficient to recreate the table.
4158*/
4159static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4160  int rc;
4161  const char *zTable;
4162  const char *zType;
4163  const char *zSql;
4164  ShellState *p = (ShellState *)pArg;
4165  int dataOnly;
4166  int noSys;
4167
4168  UNUSED_PARAMETER(azNotUsed);
4169  if( nArg!=3 || azArg==0 ) return 0;
4170  zTable = azArg[0];
4171  zType = azArg[1];
4172  zSql = azArg[2];
4173  if( zTable==0 ) return 0;
4174  if( zType==0 ) return 0;
4175  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4176  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4177
4178  if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4179    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4180  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4181    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4182  }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
4183    return 0;
4184  }else if( dataOnly ){
4185    /* no-op */
4186  }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4187    char *zIns;
4188    if( !p->writableSchema ){
4189      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4190      p->writableSchema = 1;
4191    }
4192    zIns = sqlite3_mprintf(
4193       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4194       "VALUES('table','%q','%q',0,'%q');",
4195       zTable, zTable, zSql);
4196    shell_check_oom(zIns);
4197    utf8_printf(p->out, "%s\n", zIns);
4198    sqlite3_free(zIns);
4199    return 0;
4200  }else{
4201    printSchemaLine(p->out, zSql, ";\n");
4202  }
4203
4204  if( cli_strcmp(zType, "table")==0 ){
4205    ShellText sSelect;
4206    ShellText sTable;
4207    char **azCol;
4208    int i;
4209    char *savedDestTable;
4210    int savedMode;
4211
4212    azCol = tableColumnList(p, zTable);
4213    if( azCol==0 ){
4214      p->nErr++;
4215      return 0;
4216    }
4217
4218    /* Always quote the table name, even if it appears to be pure ascii,
4219    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4220    initText(&sTable);
4221    appendText(&sTable, zTable, quoteChar(zTable));
4222    /* If preserving the rowid, add a column list after the table name.
4223    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4224    ** instead of the usual "INSERT INTO tab VALUES(...)".
4225    */
4226    if( azCol[0] ){
4227      appendText(&sTable, "(", 0);
4228      appendText(&sTable, azCol[0], 0);
4229      for(i=1; azCol[i]; i++){
4230        appendText(&sTable, ",", 0);
4231        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4232      }
4233      appendText(&sTable, ")", 0);
4234    }
4235
4236    /* Build an appropriate SELECT statement */
4237    initText(&sSelect);
4238    appendText(&sSelect, "SELECT ", 0);
4239    if( azCol[0] ){
4240      appendText(&sSelect, azCol[0], 0);
4241      appendText(&sSelect, ",", 0);
4242    }
4243    for(i=1; azCol[i]; i++){
4244      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4245      if( azCol[i+1] ){
4246        appendText(&sSelect, ",", 0);
4247      }
4248    }
4249    freeColumnList(azCol);
4250    appendText(&sSelect, " FROM ", 0);
4251    appendText(&sSelect, zTable, quoteChar(zTable));
4252
4253    savedDestTable = p->zDestTable;
4254    savedMode = p->mode;
4255    p->zDestTable = sTable.z;
4256    p->mode = p->cMode = MODE_Insert;
4257    rc = shell_exec(p, sSelect.z, 0);
4258    if( (rc&0xff)==SQLITE_CORRUPT ){
4259      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4260      toggleSelectOrder(p->db);
4261      shell_exec(p, sSelect.z, 0);
4262      toggleSelectOrder(p->db);
4263    }
4264    p->zDestTable = savedDestTable;
4265    p->mode = savedMode;
4266    freeText(&sTable);
4267    freeText(&sSelect);
4268    if( rc ) p->nErr++;
4269  }
4270  return 0;
4271}
4272
4273/*
4274** Run zQuery.  Use dump_callback() as the callback routine so that
4275** the contents of the query are output as SQL statements.
4276**
4277** If we get a SQLITE_CORRUPT error, rerun the query after appending
4278** "ORDER BY rowid DESC" to the end.
4279*/
4280static int run_schema_dump_query(
4281  ShellState *p,
4282  const char *zQuery
4283){
4284  int rc;
4285  char *zErr = 0;
4286  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4287  if( rc==SQLITE_CORRUPT ){
4288    char *zQ2;
4289    int len = strlen30(zQuery);
4290    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4291    if( zErr ){
4292      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4293      sqlite3_free(zErr);
4294      zErr = 0;
4295    }
4296    zQ2 = malloc( len+100 );
4297    if( zQ2==0 ) return rc;
4298    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4299    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4300    if( rc ){
4301      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4302    }else{
4303      rc = SQLITE_CORRUPT;
4304    }
4305    sqlite3_free(zErr);
4306    free(zQ2);
4307  }
4308  return rc;
4309}
4310
4311/*
4312** Text of help messages.
4313**
4314** The help text for each individual command begins with a line that starts
4315** with ".".  Subsequent lines are supplemental information.
4316**
4317** There must be two or more spaces between the end of the command and the
4318** start of the description of what that command does.
4319*/
4320static const char *(azHelp[]) = {
4321#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4322  && !defined(SQLITE_SHELL_FIDDLE)
4323  ".archive ...             Manage SQL archives",
4324  "   Each command must have exactly one of the following options:",
4325  "     -c, --create               Create a new archive",
4326  "     -u, --update               Add or update files with changed mtime",
4327  "     -i, --insert               Like -u but always add even if unchanged",
4328  "     -r, --remove               Remove files from archive",
4329  "     -t, --list                 List contents of archive",
4330  "     -x, --extract              Extract files from archive",
4331  "   Optional arguments:",
4332  "     -v, --verbose              Print each filename as it is processed",
4333  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4334  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4335  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4336  "     -g, --glob                 Use glob matching for names in archive",
4337  "     -n, --dryrun               Show the SQL that would have occurred",
4338  "   Examples:",
4339  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4340  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4341  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4342  "   See also:",
4343  "      http://sqlite.org/cli.html#sqlite_archive_support",
4344#endif
4345#ifndef SQLITE_OMIT_AUTHORIZATION
4346  ".auth ON|OFF             Show authorizer callbacks",
4347#endif
4348#ifndef SQLITE_SHELL_FIDDLE
4349  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4350  "   Options:",
4351  "       --append            Use the appendvfs",
4352  "       --async             Write to FILE without journal and fsync()",
4353#endif
4354  ".bail on|off             Stop after hitting an error.  Default OFF",
4355  ".binary on|off           Turn binary output on or off.  Default OFF",
4356#ifndef SQLITE_SHELL_FIDDLE
4357  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4358#endif
4359  ".changes on|off          Show number of rows changed by SQL",
4360#ifndef SQLITE_SHELL_FIDDLE
4361  ".check GLOB              Fail if output since .testcase does not match",
4362  ".clone NEWDB             Clone data into NEWDB from the existing database",
4363#endif
4364  ".connection [close] [#]  Open or close an auxiliary database connection",
4365  ".databases               List names and files of attached databases",
4366  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4367#if SQLITE_SHELL_HAVE_RECOVER
4368  ".dbinfo ?DB?             Show status information about the database",
4369#endif
4370  ".dump ?OBJECTS?          Render database content as SQL",
4371  "   Options:",
4372  "     --data-only            Output only INSERT statements",
4373  "     --newlines             Allow unescaped newline characters in output",
4374  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4375  "     --preserve-rowids      Include ROWID values in the output",
4376  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4377  "   Additional LIKE patterns can be given in subsequent arguments",
4378  ".echo on|off             Turn command echo on or off",
4379  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4380  "   Other Modes:",
4381#ifdef SQLITE_DEBUG
4382  "      test                  Show raw EXPLAIN QUERY PLAN output",
4383  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4384#endif
4385  "      trigger               Like \"full\" but also show trigger bytecode",
4386#ifndef SQLITE_SHELL_FIDDLE
4387  ".excel                   Display the output of next command in spreadsheet",
4388  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4389#endif
4390#ifndef SQLITE_SHELL_FIDDLE
4391  ".exit ?CODE?             Exit this program with return-code CODE",
4392#endif
4393  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4394  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4395  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4396  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4397  "   --help                  Show CMD details",
4398  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4399  ".headers on|off          Turn display of headers on or off",
4400  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4401#ifndef SQLITE_SHELL_FIDDLE
4402  ".import FILE TABLE       Import data from FILE into TABLE",
4403  "   Options:",
4404  "     --ascii               Use \\037 and \\036 as column and row separators",
4405  "     --csv                 Use , and \\n as column and row separators",
4406  "     --skip N              Skip the first N rows of input",
4407  "     --schema S            Target table to be S.TABLE",
4408  "     -v                    \"Verbose\" - increase auxiliary output",
4409  "   Notes:",
4410  "     *  If TABLE does not exist, it is created.  The first row of input",
4411  "        determines the column names.",
4412  "     *  If neither --csv or --ascii are used, the input mode is derived",
4413  "        from the \".mode\" output mode",
4414  "     *  If FILE begins with \"|\" then it is a command that generates the",
4415  "        input text.",
4416#endif
4417#ifndef SQLITE_OMIT_TEST_CONTROL
4418  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4419#endif
4420  ".indexes ?TABLE?         Show names of indexes",
4421  "                           If TABLE is specified, only show indexes for",
4422  "                           tables matching TABLE using the LIKE operator.",
4423#ifdef SQLITE_ENABLE_IOTRACE
4424  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4425#endif
4426  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4427  ".lint OPTIONS            Report potential schema issues.",
4428  "     Options:",
4429  "        fkey-indexes     Find missing foreign key indexes",
4430#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4431  ".load FILE ?ENTRY?       Load an extension library",
4432#endif
4433#ifndef SQLITE_SHELL_FIDDLE
4434  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4435#endif
4436  ".mode MODE ?OPTIONS?     Set output mode",
4437  "   MODE is one of:",
4438  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4439  "     box         Tables using unicode box-drawing characters",
4440  "     csv         Comma-separated values",
4441  "     column      Output in columns.  (See .width)",
4442  "     html        HTML <table> code",
4443  "     insert      SQL insert statements for TABLE",
4444  "     json        Results in a JSON array",
4445  "     line        One value per line",
4446  "     list        Values delimited by \"|\"",
4447  "     markdown    Markdown table format",
4448  "     qbox        Shorthand for \"box --wrap 60 --quote\"",
4449  "     quote       Escape answers as for SQL",
4450  "     table       ASCII-art table",
4451  "     tabs        Tab-separated values",
4452  "     tcl         TCL list elements",
4453  "   OPTIONS: (for columnar modes or insert mode):",
4454  "     --wrap N       Wrap output lines to no longer than N characters",
4455  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4456  "     --ww           Shorthand for \"--wordwrap 1\"",
4457  "     --quote        Quote output text as SQL literals",
4458  "     --noquote      Do not quote output text",
4459  "     TABLE          The name of SQL table used for \"insert\" mode",
4460#ifndef SQLITE_SHELL_FIDDLE
4461  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4462#endif
4463  ".nullvalue STRING        Use STRING in place of NULL values",
4464#ifndef SQLITE_SHELL_FIDDLE
4465  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4466  "     If FILE begins with '|' then open as a pipe",
4467  "       --bom  Put a UTF8 byte-order mark at the beginning",
4468  "       -e     Send output to the system text editor",
4469  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4470  /* Note that .open is (partially) available in WASM builds but is
4471  ** currently only intended to be used by the fiddle tool, not
4472  ** end users, so is "undocumented." */
4473  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4474  "     Options:",
4475  "        --append        Use appendvfs to append database to the end of FILE",
4476#endif
4477#ifndef SQLITE_OMIT_DESERIALIZE
4478  "        --deserialize   Load into memory using sqlite3_deserialize()",
4479  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4480  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4481#endif
4482  "        --new           Initialize FILE to an empty database",
4483  "        --nofollow      Do not follow symbolic links",
4484  "        --readonly      Open FILE readonly",
4485  "        --zip           FILE is a ZIP archive",
4486#ifndef SQLITE_SHELL_FIDDLE
4487  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4488  "   If FILE begins with '|' then open it as a pipe.",
4489  "   Options:",
4490  "     --bom                 Prefix output with a UTF8 byte-order mark",
4491  "     -e                    Send output to the system text editor",
4492  "     -x                    Send output as CSV to a spreadsheet",
4493#endif
4494  ".parameter CMD ...       Manage SQL parameter bindings",
4495  "   clear                   Erase all bindings",
4496  "   init                    Initialize the TEMP table that holds bindings",
4497  "   list                    List the current parameter bindings",
4498  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4499  "                           PARAMETER should start with one of: $ : @ ?",
4500  "   unset PARAMETER         Remove PARAMETER from the binding table",
4501  ".print STRING...         Print literal STRING",
4502#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4503  ".progress N              Invoke progress handler after every N opcodes",
4504  "   --limit N                 Interrupt after N progress callbacks",
4505  "   --once                    Do no more than one progress interrupt",
4506  "   --quiet|-q                No output except at interrupts",
4507  "   --reset                   Reset the count for each input and interrupt",
4508#endif
4509  ".prompt MAIN CONTINUE    Replace the standard prompts",
4510#ifndef SQLITE_SHELL_FIDDLE
4511  ".quit                    Exit this program",
4512  ".read FILE               Read input from FILE or command output",
4513  "    If FILE begins with \"|\", it is a command that generates the input.",
4514#endif
4515#if SQLITE_SHELL_HAVE_RECOVER
4516  ".recover                 Recover as much data as possible from corrupt db.",
4517  "   --ignore-freelist        Ignore pages that appear to be on db freelist",
4518  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4519  "   --no-rowids              Do not attempt to recover rowid values",
4520  "                            that are not also INTEGER PRIMARY KEYs",
4521#endif
4522#ifndef SQLITE_SHELL_FIDDLE
4523  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4524  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4525#endif
4526  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4527  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4528  "   Options:",
4529  "      --indent             Try to pretty-print the schema",
4530  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4531  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4532  "    Options:",
4533  "       --init               Create a new SELFTEST table",
4534  "       -v                   Verbose output",
4535  ".separator COL ?ROW?     Change the column and row separators",
4536#if defined(SQLITE_ENABLE_SESSION)
4537  ".session ?NAME? CMD ...  Create or control sessions",
4538  "   Subcommands:",
4539  "     attach TABLE             Attach TABLE",
4540  "     changeset FILE           Write a changeset into FILE",
4541  "     close                    Close one session",
4542  "     enable ?BOOLEAN?         Set or query the enable bit",
4543  "     filter GLOB...           Reject tables matching GLOBs",
4544  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4545  "     isempty                  Query whether the session is empty",
4546  "     list                     List currently open session names",
4547  "     open DB NAME             Open a new session on DB",
4548  "     patchset FILE            Write a patchset into FILE",
4549  "   If ?NAME? is omitted, the first defined session is used.",
4550#endif
4551  ".sha3sum ...             Compute a SHA3 hash of database content",
4552  "    Options:",
4553  "      --schema              Also hash the sqlite_schema table",
4554  "      --sha3-224            Use the sha3-224 algorithm",
4555  "      --sha3-256            Use the sha3-256 algorithm (default)",
4556  "      --sha3-384            Use the sha3-384 algorithm",
4557  "      --sha3-512            Use the sha3-512 algorithm",
4558  "    Any other argument is a LIKE pattern for tables to hash",
4559#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4560  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4561#endif
4562  ".show                    Show the current values for various settings",
4563  ".stats ?ARG?             Show stats or turn stats on or off",
4564  "   off                      Turn off automatic stat display",
4565  "   on                       Turn on automatic stat display",
4566  "   stmt                     Show statement stats",
4567  "   vmstep                   Show the virtual machine step count only",
4568#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4569  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4570#endif
4571  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4572#ifndef SQLITE_SHELL_FIDDLE
4573  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4574#endif
4575  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4576  "                           Run \".testctrl\" with no arguments for details",
4577  ".timeout MS              Try opening locked tables for MS milliseconds",
4578  ".timer on|off            Turn SQL timer on or off",
4579#ifndef SQLITE_OMIT_TRACE
4580  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4581  "    FILE                    Send output to FILE",
4582  "    stdout                  Send output to stdout",
4583  "    stderr                  Send output to stderr",
4584  "    off                     Disable tracing",
4585  "    --expanded              Expand query parameters",
4586#ifdef SQLITE_ENABLE_NORMALIZE
4587  "    --normalized            Normal the SQL statements",
4588#endif
4589  "    --plain                 Show SQL as it is input",
4590  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4591  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4592  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4593  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4594#endif /* SQLITE_OMIT_TRACE */
4595#ifdef SQLITE_DEBUG
4596  ".unmodule NAME ...       Unregister virtual table modules",
4597  "    --allexcept             Unregister everything except those named",
4598#endif
4599  ".vfsinfo ?AUX?           Information about the top-level VFS",
4600  ".vfslist                 List all available VFSes",
4601  ".vfsname ?AUX?           Print the name of the VFS stack",
4602  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4603  "     Negative values right-justify",
4604};
4605
4606/*
4607** Output help text.
4608**
4609** zPattern describes the set of commands for which help text is provided.
4610** If zPattern is NULL, then show all commands, but only give a one-line
4611** description of each.
4612**
4613** Return the number of matches.
4614*/
4615static int showHelp(FILE *out, const char *zPattern){
4616  int i = 0;
4617  int j = 0;
4618  int n = 0;
4619  char *zPat;
4620  if( zPattern==0
4621   || zPattern[0]=='0'
4622   || cli_strcmp(zPattern,"-a")==0
4623   || cli_strcmp(zPattern,"-all")==0
4624   || cli_strcmp(zPattern,"--all")==0
4625  ){
4626    /* Show all commands, but only one line per command */
4627    if( zPattern==0 ) zPattern = "";
4628    for(i=0; i<ArraySize(azHelp); i++){
4629      if( azHelp[i][0]=='.' || zPattern[0] ){
4630        utf8_printf(out, "%s\n", azHelp[i]);
4631        n++;
4632      }
4633    }
4634  }else{
4635    /* Look for commands that for which zPattern is an exact prefix */
4636    zPat = sqlite3_mprintf(".%s*", zPattern);
4637    shell_check_oom(zPat);
4638    for(i=0; i<ArraySize(azHelp); i++){
4639      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4640        utf8_printf(out, "%s\n", azHelp[i]);
4641        j = i+1;
4642        n++;
4643      }
4644    }
4645    sqlite3_free(zPat);
4646    if( n ){
4647      if( n==1 ){
4648        /* when zPattern is a prefix of exactly one command, then include the
4649        ** details of that command, which should begin at offset j */
4650        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4651          utf8_printf(out, "%s\n", azHelp[j]);
4652          j++;
4653        }
4654      }
4655      return n;
4656    }
4657    /* Look for commands that contain zPattern anywhere.  Show the complete
4658    ** text of all commands that match. */
4659    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4660    shell_check_oom(zPat);
4661    for(i=0; i<ArraySize(azHelp); i++){
4662      if( azHelp[i][0]=='.' ) j = i;
4663      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4664        utf8_printf(out, "%s\n", azHelp[j]);
4665        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4666          j++;
4667          utf8_printf(out, "%s\n", azHelp[j]);
4668        }
4669        i = j;
4670        n++;
4671      }
4672    }
4673    sqlite3_free(zPat);
4674  }
4675  return n;
4676}
4677
4678/* Forward reference */
4679static int process_input(ShellState *p);
4680
4681/*
4682** Read the content of file zName into memory obtained from sqlite3_malloc64()
4683** and return a pointer to the buffer. The caller is responsible for freeing
4684** the memory.
4685**
4686** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4687** read.
4688**
4689** For convenience, a nul-terminator byte is always appended to the data read
4690** from the file before the buffer is returned. This byte is not included in
4691** the final value of (*pnByte), if applicable.
4692**
4693** NULL is returned if any error is encountered. The final value of *pnByte
4694** is undefined in this case.
4695*/
4696static char *readFile(const char *zName, int *pnByte){
4697  FILE *in = fopen(zName, "rb");
4698  long nIn;
4699  size_t nRead;
4700  char *pBuf;
4701  if( in==0 ) return 0;
4702  fseek(in, 0, SEEK_END);
4703  nIn = ftell(in);
4704  rewind(in);
4705  pBuf = sqlite3_malloc64( nIn+1 );
4706  if( pBuf==0 ){ fclose(in); return 0; }
4707  nRead = fread(pBuf, nIn, 1, in);
4708  fclose(in);
4709  if( nRead!=1 ){
4710    sqlite3_free(pBuf);
4711    return 0;
4712  }
4713  pBuf[nIn] = 0;
4714  if( pnByte ) *pnByte = nIn;
4715  return pBuf;
4716}
4717
4718#if defined(SQLITE_ENABLE_SESSION)
4719/*
4720** Close a single OpenSession object and release all of its associated
4721** resources.
4722*/
4723static void session_close(OpenSession *pSession){
4724  int i;
4725  sqlite3session_delete(pSession->p);
4726  sqlite3_free(pSession->zName);
4727  for(i=0; i<pSession->nFilter; i++){
4728    sqlite3_free(pSession->azFilter[i]);
4729  }
4730  sqlite3_free(pSession->azFilter);
4731  memset(pSession, 0, sizeof(OpenSession));
4732}
4733#endif
4734
4735/*
4736** Close all OpenSession objects and release all associated resources.
4737*/
4738#if defined(SQLITE_ENABLE_SESSION)
4739static void session_close_all(ShellState *p, int i){
4740  int j;
4741  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4742  for(j=0; j<pAuxDb->nSession; j++){
4743    session_close(&pAuxDb->aSession[j]);
4744  }
4745  pAuxDb->nSession = 0;
4746}
4747#else
4748# define session_close_all(X,Y)
4749#endif
4750
4751/*
4752** Implementation of the xFilter function for an open session.  Omit
4753** any tables named by ".session filter" but let all other table through.
4754*/
4755#if defined(SQLITE_ENABLE_SESSION)
4756static int session_filter(void *pCtx, const char *zTab){
4757  OpenSession *pSession = (OpenSession*)pCtx;
4758  int i;
4759  for(i=0; i<pSession->nFilter; i++){
4760    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4761  }
4762  return 1;
4763}
4764#endif
4765
4766/*
4767** Try to deduce the type of file for zName based on its content.  Return
4768** one of the SHELL_OPEN_* constants.
4769**
4770** If the file does not exist or is empty but its name looks like a ZIP
4771** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4772** Otherwise, assume an ordinary database regardless of the filename if
4773** the type cannot be determined from content.
4774*/
4775int deduceDatabaseType(const char *zName, int dfltZip){
4776  FILE *f = fopen(zName, "rb");
4777  size_t n;
4778  int rc = SHELL_OPEN_UNSPEC;
4779  char zBuf[100];
4780  if( f==0 ){
4781    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4782       return SHELL_OPEN_ZIPFILE;
4783    }else{
4784       return SHELL_OPEN_NORMAL;
4785    }
4786  }
4787  n = fread(zBuf, 16, 1, f);
4788  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4789    fclose(f);
4790    return SHELL_OPEN_NORMAL;
4791  }
4792  fseek(f, -25, SEEK_END);
4793  n = fread(zBuf, 25, 1, f);
4794  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4795    rc = SHELL_OPEN_APPENDVFS;
4796  }else{
4797    fseek(f, -22, SEEK_END);
4798    n = fread(zBuf, 22, 1, f);
4799    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4800       && zBuf[3]==0x06 ){
4801      rc = SHELL_OPEN_ZIPFILE;
4802    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4803      rc = SHELL_OPEN_ZIPFILE;
4804    }
4805  }
4806  fclose(f);
4807  return rc;
4808}
4809
4810#ifndef SQLITE_OMIT_DESERIALIZE
4811/*
4812** Reconstruct an in-memory database using the output from the "dbtotxt"
4813** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4814** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4815*/
4816static unsigned char *readHexDb(ShellState *p, int *pnData){
4817  unsigned char *a = 0;
4818  int nLine;
4819  int n = 0;
4820  int pgsz = 0;
4821  int iOffset = 0;
4822  int j, k;
4823  int rc;
4824  FILE *in;
4825  const char *zDbFilename = p->pAuxDb->zDbFilename;
4826  unsigned int x[16];
4827  char zLine[1000];
4828  if( zDbFilename ){
4829    in = fopen(zDbFilename, "r");
4830    if( in==0 ){
4831      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4832      return 0;
4833    }
4834    nLine = 0;
4835  }else{
4836    in = p->in;
4837    nLine = p->lineno;
4838    if( in==0 ) in = stdin;
4839  }
4840  *pnData = 0;
4841  nLine++;
4842  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4843  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4844  if( rc!=2 ) goto readHexDb_error;
4845  if( n<0 ) goto readHexDb_error;
4846  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4847  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4848  a = sqlite3_malloc( n ? n : 1 );
4849  shell_check_oom(a);
4850  memset(a, 0, n);
4851  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4852    utf8_printf(stderr, "invalid pagesize\n");
4853    goto readHexDb_error;
4854  }
4855  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4856    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4857    if( rc==2 ){
4858      iOffset = k;
4859      continue;
4860    }
4861    if( cli_strncmp(zLine, "| end ", 6)==0 ){
4862      break;
4863    }
4864    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4865                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4866                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4867    if( rc==17 ){
4868      k = iOffset+j;
4869      if( k+16<=n && k>=0 ){
4870        int ii;
4871        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4872      }
4873    }
4874  }
4875  *pnData = n;
4876  if( in!=p->in ){
4877    fclose(in);
4878  }else{
4879    p->lineno = nLine;
4880  }
4881  return a;
4882
4883readHexDb_error:
4884  if( in!=p->in ){
4885    fclose(in);
4886  }else{
4887    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4888      nLine++;
4889      if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
4890    }
4891    p->lineno = nLine;
4892  }
4893  sqlite3_free(a);
4894  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4895  return 0;
4896}
4897#endif /* SQLITE_OMIT_DESERIALIZE */
4898
4899/*
4900** Scalar function "shell_int32". The first argument to this function
4901** must be a blob. The second a non-negative integer. This function
4902** reads and returns a 32-bit big-endian integer from byte
4903** offset (4*<arg2>) of the blob.
4904*/
4905static void shellInt32(
4906  sqlite3_context *context,
4907  int argc,
4908  sqlite3_value **argv
4909){
4910  const unsigned char *pBlob;
4911  int nBlob;
4912  int iInt;
4913
4914  UNUSED_PARAMETER(argc);
4915  nBlob = sqlite3_value_bytes(argv[0]);
4916  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4917  iInt = sqlite3_value_int(argv[1]);
4918
4919  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4920    const unsigned char *a = &pBlob[iInt*4];
4921    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4922                       + ((sqlite3_int64)a[1]<<16)
4923                       + ((sqlite3_int64)a[2]<< 8)
4924                       + ((sqlite3_int64)a[3]<< 0);
4925    sqlite3_result_int64(context, iVal);
4926  }
4927}
4928
4929/*
4930** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4931** using "..." with internal double-quote characters doubled.
4932*/
4933static void shellIdQuote(
4934  sqlite3_context *context,
4935  int argc,
4936  sqlite3_value **argv
4937){
4938  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4939  UNUSED_PARAMETER(argc);
4940  if( zName ){
4941    char *z = sqlite3_mprintf("\"%w\"", zName);
4942    sqlite3_result_text(context, z, -1, sqlite3_free);
4943  }
4944}
4945
4946/*
4947** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4948*/
4949static void shellUSleepFunc(
4950  sqlite3_context *context,
4951  int argcUnused,
4952  sqlite3_value **argv
4953){
4954  int sleep = sqlite3_value_int(argv[0]);
4955  (void)argcUnused;
4956  sqlite3_sleep(sleep/1000);
4957  sqlite3_result_int(context, sleep);
4958}
4959
4960/*
4961** Scalar function "shell_escape_crnl" used by the .recover command.
4962** The argument passed to this function is the output of built-in
4963** function quote(). If the first character of the input is "'",
4964** indicating that the value passed to quote() was a text value,
4965** then this function searches the input for "\n" and "\r" characters
4966** and adds a wrapper similar to the following:
4967**
4968**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4969**
4970** Or, if the first character of the input is not "'", then a copy
4971** of the input is returned.
4972*/
4973static void shellEscapeCrnl(
4974  sqlite3_context *context,
4975  int argc,
4976  sqlite3_value **argv
4977){
4978  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4979  UNUSED_PARAMETER(argc);
4980  if( zText && zText[0]=='\'' ){
4981    i64 nText = sqlite3_value_bytes(argv[0]);
4982    i64 i;
4983    char zBuf1[20];
4984    char zBuf2[20];
4985    const char *zNL = 0;
4986    const char *zCR = 0;
4987    i64 nCR = 0;
4988    i64 nNL = 0;
4989
4990    for(i=0; zText[i]; i++){
4991      if( zNL==0 && zText[i]=='\n' ){
4992        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4993        nNL = strlen(zNL);
4994      }
4995      if( zCR==0 && zText[i]=='\r' ){
4996        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4997        nCR = strlen(zCR);
4998      }
4999    }
5000
5001    if( zNL || zCR ){
5002      i64 iOut = 0;
5003      i64 nMax = (nNL > nCR) ? nNL : nCR;
5004      i64 nAlloc = nMax * nText + (nMax+64)*2;
5005      char *zOut = (char*)sqlite3_malloc64(nAlloc);
5006      if( zOut==0 ){
5007        sqlite3_result_error_nomem(context);
5008        return;
5009      }
5010
5011      if( zNL && zCR ){
5012        memcpy(&zOut[iOut], "replace(replace(", 16);
5013        iOut += 16;
5014      }else{
5015        memcpy(&zOut[iOut], "replace(", 8);
5016        iOut += 8;
5017      }
5018      for(i=0; zText[i]; i++){
5019        if( zText[i]=='\n' ){
5020          memcpy(&zOut[iOut], zNL, nNL);
5021          iOut += nNL;
5022        }else if( zText[i]=='\r' ){
5023          memcpy(&zOut[iOut], zCR, nCR);
5024          iOut += nCR;
5025        }else{
5026          zOut[iOut] = zText[i];
5027          iOut++;
5028        }
5029      }
5030
5031      if( zNL ){
5032        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5033        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5034        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5035      }
5036      if( zCR ){
5037        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5038        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5039        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5040      }
5041
5042      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5043      sqlite3_free(zOut);
5044      return;
5045    }
5046  }
5047
5048  sqlite3_result_value(context, argv[0]);
5049}
5050
5051/* Flags for open_db().
5052**
5053** The default behavior of open_db() is to exit(1) if the database fails to
5054** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5055** but still returns without calling exit.
5056**
5057** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5058** ZIP archive if the file does not exist or is empty and its name matches
5059** the *.zip pattern.
5060*/
5061#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5062#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5063
5064/*
5065** Make sure the database is open.  If it is not, then open it.  If
5066** the database fails to open, print an error message and exit.
5067*/
5068static void open_db(ShellState *p, int openFlags){
5069  if( p->db==0 ){
5070    const char *zDbFilename = p->pAuxDb->zDbFilename;
5071    if( p->openMode==SHELL_OPEN_UNSPEC ){
5072      if( zDbFilename==0 || zDbFilename[0]==0 ){
5073        p->openMode = SHELL_OPEN_NORMAL;
5074      }else{
5075        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5076                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5077      }
5078    }
5079    switch( p->openMode ){
5080      case SHELL_OPEN_APPENDVFS: {
5081        sqlite3_open_v2(zDbFilename, &p->db,
5082           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5083        break;
5084      }
5085      case SHELL_OPEN_HEXDB:
5086      case SHELL_OPEN_DESERIALIZE: {
5087        sqlite3_open(0, &p->db);
5088        break;
5089      }
5090      case SHELL_OPEN_ZIPFILE: {
5091        sqlite3_open(":memory:", &p->db);
5092        break;
5093      }
5094      case SHELL_OPEN_READONLY: {
5095        sqlite3_open_v2(zDbFilename, &p->db,
5096            SQLITE_OPEN_READONLY|p->openFlags, 0);
5097        break;
5098      }
5099      case SHELL_OPEN_UNSPEC:
5100      case SHELL_OPEN_NORMAL: {
5101        sqlite3_open_v2(zDbFilename, &p->db,
5102           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5103        break;
5104      }
5105    }
5106    globalDb = p->db;
5107    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5108      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5109          zDbFilename, sqlite3_errmsg(p->db));
5110      if( openFlags & OPEN_DB_KEEPALIVE ){
5111        sqlite3_open(":memory:", &p->db);
5112        return;
5113      }
5114      exit(1);
5115    }
5116#ifndef SQLITE_OMIT_LOAD_EXTENSION
5117    sqlite3_enable_load_extension(p->db, 1);
5118#endif
5119    sqlite3_shathree_init(p->db, 0, 0);
5120    sqlite3_uint_init(p->db, 0, 0);
5121    sqlite3_decimal_init(p->db, 0, 0);
5122    sqlite3_regexp_init(p->db, 0, 0);
5123    sqlite3_ieee_init(p->db, 0, 0);
5124    sqlite3_series_init(p->db, 0, 0);
5125#ifndef SQLITE_SHELL_FIDDLE
5126    sqlite3_fileio_init(p->db, 0, 0);
5127    sqlite3_completion_init(p->db, 0, 0);
5128#endif
5129#if SQLITE_SHELL_HAVE_RECOVER
5130    sqlite3_dbdata_init(p->db, 0, 0);
5131#endif
5132#ifdef SQLITE_HAVE_ZLIB
5133    if( !p->bSafeModePersist ){
5134      sqlite3_zipfile_init(p->db, 0, 0);
5135      sqlite3_sqlar_init(p->db, 0, 0);
5136    }
5137#endif
5138    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5139                            shellAddSchemaName, 0, 0);
5140    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5141                            shellModuleSchema, 0, 0);
5142    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5143                            shellPutsFunc, 0, 0);
5144    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5145                            shellEscapeCrnl, 0, 0);
5146    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5147                            shellInt32, 0, 0);
5148    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5149                            shellIdQuote, 0, 0);
5150    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5151                            shellUSleepFunc, 0, 0);
5152#ifndef SQLITE_NOHAVE_SYSTEM
5153    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5154                            editFunc, 0, 0);
5155    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5156                            editFunc, 0, 0);
5157#endif
5158    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5159      char *zSql = sqlite3_mprintf(
5160         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5161      shell_check_oom(zSql);
5162      sqlite3_exec(p->db, zSql, 0, 0, 0);
5163      sqlite3_free(zSql);
5164    }
5165#ifndef SQLITE_OMIT_DESERIALIZE
5166    else
5167    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5168      int rc;
5169      int nData = 0;
5170      unsigned char *aData;
5171      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5172        aData = (unsigned char*)readFile(zDbFilename, &nData);
5173      }else{
5174        aData = readHexDb(p, &nData);
5175        if( aData==0 ){
5176          return;
5177        }
5178      }
5179      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5180                   SQLITE_DESERIALIZE_RESIZEABLE |
5181                   SQLITE_DESERIALIZE_FREEONCLOSE);
5182      if( rc ){
5183        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5184      }
5185      if( p->szMax>0 ){
5186        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5187      }
5188    }
5189#endif
5190  }
5191  if( p->bSafeModePersist && p->db!=0 ){
5192    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5193  }
5194}
5195
5196/*
5197** Attempt to close the databaes connection.  Report errors.
5198*/
5199void close_db(sqlite3 *db){
5200  int rc = sqlite3_close(db);
5201  if( rc ){
5202    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5203        rc, sqlite3_errmsg(db));
5204  }
5205}
5206
5207#if HAVE_READLINE || HAVE_EDITLINE
5208/*
5209** Readline completion callbacks
5210*/
5211static char *readline_completion_generator(const char *text, int state){
5212  static sqlite3_stmt *pStmt = 0;
5213  char *zRet;
5214  if( state==0 ){
5215    char *zSql;
5216    sqlite3_finalize(pStmt);
5217    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5218                           "  FROM completion(%Q) ORDER BY 1", text);
5219    shell_check_oom(zSql);
5220    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5221    sqlite3_free(zSql);
5222  }
5223  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5224    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5225    zRet = z ? strdup(z) : 0;
5226  }else{
5227    sqlite3_finalize(pStmt);
5228    pStmt = 0;
5229    zRet = 0;
5230  }
5231  return zRet;
5232}
5233static char **readline_completion(const char *zText, int iStart, int iEnd){
5234  rl_attempted_completion_over = 1;
5235  return rl_completion_matches(zText, readline_completion_generator);
5236}
5237
5238#elif HAVE_LINENOISE
5239/*
5240** Linenoise completion callback
5241*/
5242static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5243  i64 nLine = strlen(zLine);
5244  i64 i, iStart;
5245  sqlite3_stmt *pStmt = 0;
5246  char *zSql;
5247  char zBuf[1000];
5248
5249  if( nLine>sizeof(zBuf)-30 ) return;
5250  if( zLine[0]=='.' || zLine[0]=='#') return;
5251  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5252  if( i==nLine-1 ) return;
5253  iStart = i+1;
5254  memcpy(zBuf, zLine, iStart);
5255  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5256                         "  FROM completion(%Q,%Q) ORDER BY 1",
5257                         &zLine[iStart], zLine);
5258  shell_check_oom(zSql);
5259  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5260  sqlite3_free(zSql);
5261  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5262  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5263    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5264    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5265    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5266      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5267      linenoiseAddCompletion(lc, zBuf);
5268    }
5269  }
5270  sqlite3_finalize(pStmt);
5271}
5272#endif
5273
5274/*
5275** Do C-language style dequoting.
5276**
5277**    \a    -> alarm
5278**    \b    -> backspace
5279**    \t    -> tab
5280**    \n    -> newline
5281**    \v    -> vertical tab
5282**    \f    -> form feed
5283**    \r    -> carriage return
5284**    \s    -> space
5285**    \"    -> "
5286**    \'    -> '
5287**    \\    -> backslash
5288**    \NNN  -> ascii character NNN in octal
5289*/
5290static void resolve_backslashes(char *z){
5291  int i, j;
5292  char c;
5293  while( *z && *z!='\\' ) z++;
5294  for(i=j=0; (c = z[i])!=0; i++, j++){
5295    if( c=='\\' && z[i+1]!=0 ){
5296      c = z[++i];
5297      if( c=='a' ){
5298        c = '\a';
5299      }else if( c=='b' ){
5300        c = '\b';
5301      }else if( c=='t' ){
5302        c = '\t';
5303      }else if( c=='n' ){
5304        c = '\n';
5305      }else if( c=='v' ){
5306        c = '\v';
5307      }else if( c=='f' ){
5308        c = '\f';
5309      }else if( c=='r' ){
5310        c = '\r';
5311      }else if( c=='"' ){
5312        c = '"';
5313      }else if( c=='\'' ){
5314        c = '\'';
5315      }else if( c=='\\' ){
5316        c = '\\';
5317      }else if( c>='0' && c<='7' ){
5318        c -= '0';
5319        if( z[i+1]>='0' && z[i+1]<='7' ){
5320          i++;
5321          c = (c<<3) + z[i] - '0';
5322          if( z[i+1]>='0' && z[i+1]<='7' ){
5323            i++;
5324            c = (c<<3) + z[i] - '0';
5325          }
5326        }
5327      }
5328    }
5329    z[j] = c;
5330  }
5331  if( j<i ) z[j] = 0;
5332}
5333
5334/*
5335** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5336** for TRUE and FALSE.  Return the integer value if appropriate.
5337*/
5338static int booleanValue(const char *zArg){
5339  int i;
5340  if( zArg[0]=='0' && zArg[1]=='x' ){
5341    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5342  }else{
5343    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5344  }
5345  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5346  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5347    return 1;
5348  }
5349  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5350    return 0;
5351  }
5352  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5353          zArg);
5354  return 0;
5355}
5356
5357/*
5358** Set or clear a shell flag according to a boolean value.
5359*/
5360static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5361  if( booleanValue(zArg) ){
5362    ShellSetFlag(p, mFlag);
5363  }else{
5364    ShellClearFlag(p, mFlag);
5365  }
5366}
5367
5368/*
5369** Close an output file, assuming it is not stderr or stdout
5370*/
5371static void output_file_close(FILE *f){
5372  if( f && f!=stdout && f!=stderr ) fclose(f);
5373}
5374
5375/*
5376** Try to open an output file.   The names "stdout" and "stderr" are
5377** recognized and do the right thing.  NULL is returned if the output
5378** filename is "off".
5379*/
5380static FILE *output_file_open(const char *zFile, int bTextMode){
5381  FILE *f;
5382  if( cli_strcmp(zFile,"stdout")==0 ){
5383    f = stdout;
5384  }else if( cli_strcmp(zFile, "stderr")==0 ){
5385    f = stderr;
5386  }else if( cli_strcmp(zFile, "off")==0 ){
5387    f = 0;
5388  }else{
5389    f = fopen(zFile, bTextMode ? "w" : "wb");
5390    if( f==0 ){
5391      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5392    }
5393  }
5394  return f;
5395}
5396
5397#ifndef SQLITE_OMIT_TRACE
5398/*
5399** A routine for handling output from sqlite3_trace().
5400*/
5401static int sql_trace_callback(
5402  unsigned mType,         /* The trace type */
5403  void *pArg,             /* The ShellState pointer */
5404  void *pP,               /* Usually a pointer to sqlite_stmt */
5405  void *pX                /* Auxiliary output */
5406){
5407  ShellState *p = (ShellState*)pArg;
5408  sqlite3_stmt *pStmt;
5409  const char *zSql;
5410  i64 nSql;
5411  if( p->traceOut==0 ) return 0;
5412  if( mType==SQLITE_TRACE_CLOSE ){
5413    utf8_printf(p->traceOut, "-- closing database connection\n");
5414    return 0;
5415  }
5416  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5417    zSql = (const char*)pX;
5418  }else{
5419    pStmt = (sqlite3_stmt*)pP;
5420    switch( p->eTraceType ){
5421      case SHELL_TRACE_EXPANDED: {
5422        zSql = sqlite3_expanded_sql(pStmt);
5423        break;
5424      }
5425#ifdef SQLITE_ENABLE_NORMALIZE
5426      case SHELL_TRACE_NORMALIZED: {
5427        zSql = sqlite3_normalized_sql(pStmt);
5428        break;
5429      }
5430#endif
5431      default: {
5432        zSql = sqlite3_sql(pStmt);
5433        break;
5434      }
5435    }
5436  }
5437  if( zSql==0 ) return 0;
5438  nSql = strlen(zSql);
5439  if( nSql>1000000000 ) nSql = 1000000000;
5440  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5441  switch( mType ){
5442    case SQLITE_TRACE_ROW:
5443    case SQLITE_TRACE_STMT: {
5444      utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5445      break;
5446    }
5447    case SQLITE_TRACE_PROFILE: {
5448      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5449      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5450      break;
5451    }
5452  }
5453  return 0;
5454}
5455#endif
5456
5457/*
5458** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5459** a useful spot to set a debugger breakpoint.
5460*/
5461static void test_breakpoint(void){
5462  static int nCall = 0;
5463  nCall++;
5464}
5465
5466/*
5467** An object used to read a CSV and other files for import.
5468*/
5469typedef struct ImportCtx ImportCtx;
5470struct ImportCtx {
5471  const char *zFile;  /* Name of the input file */
5472  FILE *in;           /* Read the CSV text from this input stream */
5473  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5474  char *z;            /* Accumulated text for a field */
5475  int n;              /* Number of bytes in z */
5476  int nAlloc;         /* Space allocated for z[] */
5477  int nLine;          /* Current line number */
5478  int nRow;           /* Number of rows imported */
5479  int nErr;           /* Number of errors encountered */
5480  int bNotFirst;      /* True if one or more bytes already read */
5481  int cTerm;          /* Character that terminated the most recent field */
5482  int cColSep;        /* The column separator character.  (Usually ",") */
5483  int cRowSep;        /* The row separator character.  (Usually "\n") */
5484};
5485
5486/* Clean up resourced used by an ImportCtx */
5487static void import_cleanup(ImportCtx *p){
5488  if( p->in!=0 && p->xCloser!=0 ){
5489    p->xCloser(p->in);
5490    p->in = 0;
5491  }
5492  sqlite3_free(p->z);
5493  p->z = 0;
5494}
5495
5496/* Append a single byte to z[] */
5497static void import_append_char(ImportCtx *p, int c){
5498  if( p->n+1>=p->nAlloc ){
5499    p->nAlloc += p->nAlloc + 100;
5500    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5501    shell_check_oom(p->z);
5502  }
5503  p->z[p->n++] = (char)c;
5504}
5505
5506/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5507** with the option of having a separator other than ",".
5508**
5509**   +  Input comes from p->in.
5510**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5511**      from sqlite3_malloc64().
5512**   +  Use p->cSep as the column separator.  The default is ",".
5513**   +  Use p->rSep as the row separator.  The default is "\n".
5514**   +  Keep track of the line number in p->nLine.
5515**   +  Store the character that terminates the field in p->cTerm.  Store
5516**      EOF on end-of-file.
5517**   +  Report syntax errors on stderr
5518*/
5519static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5520  int c;
5521  int cSep = p->cColSep;
5522  int rSep = p->cRowSep;
5523  p->n = 0;
5524  c = fgetc(p->in);
5525  if( c==EOF || seenInterrupt ){
5526    p->cTerm = EOF;
5527    return 0;
5528  }
5529  if( c=='"' ){
5530    int pc, ppc;
5531    int startLine = p->nLine;
5532    int cQuote = c;
5533    pc = ppc = 0;
5534    while( 1 ){
5535      c = fgetc(p->in);
5536      if( c==rSep ) p->nLine++;
5537      if( c==cQuote ){
5538        if( pc==cQuote ){
5539          pc = 0;
5540          continue;
5541        }
5542      }
5543      if( (c==cSep && pc==cQuote)
5544       || (c==rSep && pc==cQuote)
5545       || (c==rSep && pc=='\r' && ppc==cQuote)
5546       || (c==EOF && pc==cQuote)
5547      ){
5548        do{ p->n--; }while( p->z[p->n]!=cQuote );
5549        p->cTerm = c;
5550        break;
5551      }
5552      if( pc==cQuote && c!='\r' ){
5553        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5554                p->zFile, p->nLine, cQuote);
5555      }
5556      if( c==EOF ){
5557        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5558                p->zFile, startLine, cQuote);
5559        p->cTerm = c;
5560        break;
5561      }
5562      import_append_char(p, c);
5563      ppc = pc;
5564      pc = c;
5565    }
5566  }else{
5567    /* If this is the first field being parsed and it begins with the
5568    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5569    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5570      import_append_char(p, c);
5571      c = fgetc(p->in);
5572      if( (c&0xff)==0xbb ){
5573        import_append_char(p, c);
5574        c = fgetc(p->in);
5575        if( (c&0xff)==0xbf ){
5576          p->bNotFirst = 1;
5577          p->n = 0;
5578          return csv_read_one_field(p);
5579        }
5580      }
5581    }
5582    while( c!=EOF && c!=cSep && c!=rSep ){
5583      import_append_char(p, c);
5584      c = fgetc(p->in);
5585    }
5586    if( c==rSep ){
5587      p->nLine++;
5588      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5589    }
5590    p->cTerm = c;
5591  }
5592  if( p->z ) p->z[p->n] = 0;
5593  p->bNotFirst = 1;
5594  return p->z;
5595}
5596
5597/* Read a single field of ASCII delimited text.
5598**
5599**   +  Input comes from p->in.
5600**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5601**      from sqlite3_malloc64().
5602**   +  Use p->cSep as the column separator.  The default is "\x1F".
5603**   +  Use p->rSep as the row separator.  The default is "\x1E".
5604**   +  Keep track of the row number in p->nLine.
5605**   +  Store the character that terminates the field in p->cTerm.  Store
5606**      EOF on end-of-file.
5607**   +  Report syntax errors on stderr
5608*/
5609static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5610  int c;
5611  int cSep = p->cColSep;
5612  int rSep = p->cRowSep;
5613  p->n = 0;
5614  c = fgetc(p->in);
5615  if( c==EOF || seenInterrupt ){
5616    p->cTerm = EOF;
5617    return 0;
5618  }
5619  while( c!=EOF && c!=cSep && c!=rSep ){
5620    import_append_char(p, c);
5621    c = fgetc(p->in);
5622  }
5623  if( c==rSep ){
5624    p->nLine++;
5625  }
5626  p->cTerm = c;
5627  if( p->z ) p->z[p->n] = 0;
5628  return p->z;
5629}
5630
5631/*
5632** Try to transfer data for table zTable.  If an error is seen while
5633** moving forward, try to go backwards.  The backwards movement won't
5634** work for WITHOUT ROWID tables.
5635*/
5636static void tryToCloneData(
5637  ShellState *p,
5638  sqlite3 *newDb,
5639  const char *zTable
5640){
5641  sqlite3_stmt *pQuery = 0;
5642  sqlite3_stmt *pInsert = 0;
5643  char *zQuery = 0;
5644  char *zInsert = 0;
5645  int rc;
5646  int i, j, n;
5647  int nTable = strlen30(zTable);
5648  int k = 0;
5649  int cnt = 0;
5650  const int spinRate = 10000;
5651
5652  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5653  shell_check_oom(zQuery);
5654  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5655  if( rc ){
5656    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5657            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5658            zQuery);
5659    goto end_data_xfer;
5660  }
5661  n = sqlite3_column_count(pQuery);
5662  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5663  shell_check_oom(zInsert);
5664  sqlite3_snprintf(200+nTable,zInsert,
5665                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5666  i = strlen30(zInsert);
5667  for(j=1; j<n; j++){
5668    memcpy(zInsert+i, ",?", 2);
5669    i += 2;
5670  }
5671  memcpy(zInsert+i, ");", 3);
5672  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5673  if( rc ){
5674    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5675            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5676            zQuery);
5677    goto end_data_xfer;
5678  }
5679  for(k=0; k<2; k++){
5680    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5681      for(i=0; i<n; i++){
5682        switch( sqlite3_column_type(pQuery, i) ){
5683          case SQLITE_NULL: {
5684            sqlite3_bind_null(pInsert, i+1);
5685            break;
5686          }
5687          case SQLITE_INTEGER: {
5688            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5689            break;
5690          }
5691          case SQLITE_FLOAT: {
5692            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5693            break;
5694          }
5695          case SQLITE_TEXT: {
5696            sqlite3_bind_text(pInsert, i+1,
5697                             (const char*)sqlite3_column_text(pQuery,i),
5698                             -1, SQLITE_STATIC);
5699            break;
5700          }
5701          case SQLITE_BLOB: {
5702            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5703                                            sqlite3_column_bytes(pQuery,i),
5704                                            SQLITE_STATIC);
5705            break;
5706          }
5707        }
5708      } /* End for */
5709      rc = sqlite3_step(pInsert);
5710      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5711        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5712                        sqlite3_errmsg(newDb));
5713      }
5714      sqlite3_reset(pInsert);
5715      cnt++;
5716      if( (cnt%spinRate)==0 ){
5717        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5718        fflush(stdout);
5719      }
5720    } /* End while */
5721    if( rc==SQLITE_DONE ) break;
5722    sqlite3_finalize(pQuery);
5723    sqlite3_free(zQuery);
5724    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5725                             zTable);
5726    shell_check_oom(zQuery);
5727    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5728    if( rc ){
5729      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5730      break;
5731    }
5732  } /* End for(k=0...) */
5733
5734end_data_xfer:
5735  sqlite3_finalize(pQuery);
5736  sqlite3_finalize(pInsert);
5737  sqlite3_free(zQuery);
5738  sqlite3_free(zInsert);
5739}
5740
5741
5742/*
5743** Try to transfer all rows of the schema that match zWhere.  For
5744** each row, invoke xForEach() on the object defined by that row.
5745** If an error is encountered while moving forward through the
5746** sqlite_schema table, try again moving backwards.
5747*/
5748static void tryToCloneSchema(
5749  ShellState *p,
5750  sqlite3 *newDb,
5751  const char *zWhere,
5752  void (*xForEach)(ShellState*,sqlite3*,const char*)
5753){
5754  sqlite3_stmt *pQuery = 0;
5755  char *zQuery = 0;
5756  int rc;
5757  const unsigned char *zName;
5758  const unsigned char *zSql;
5759  char *zErrMsg = 0;
5760
5761  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5762                           " WHERE %s", zWhere);
5763  shell_check_oom(zQuery);
5764  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5765  if( rc ){
5766    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5767                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5768                    zQuery);
5769    goto end_schema_xfer;
5770  }
5771  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5772    zName = sqlite3_column_text(pQuery, 0);
5773    zSql = sqlite3_column_text(pQuery, 1);
5774    if( zName==0 || zSql==0 ) continue;
5775    printf("%s... ", zName); fflush(stdout);
5776    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5777    if( zErrMsg ){
5778      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5779      sqlite3_free(zErrMsg);
5780      zErrMsg = 0;
5781    }
5782    if( xForEach ){
5783      xForEach(p, newDb, (const char*)zName);
5784    }
5785    printf("done\n");
5786  }
5787  if( rc!=SQLITE_DONE ){
5788    sqlite3_finalize(pQuery);
5789    sqlite3_free(zQuery);
5790    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5791                             " WHERE %s ORDER BY rowid DESC", zWhere);
5792    shell_check_oom(zQuery);
5793    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5794    if( rc ){
5795      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5796                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5797                      zQuery);
5798      goto end_schema_xfer;
5799    }
5800    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5801      zName = sqlite3_column_text(pQuery, 0);
5802      zSql = sqlite3_column_text(pQuery, 1);
5803      if( zName==0 || zSql==0 ) continue;
5804      printf("%s... ", zName); fflush(stdout);
5805      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5806      if( zErrMsg ){
5807        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5808        sqlite3_free(zErrMsg);
5809        zErrMsg = 0;
5810      }
5811      if( xForEach ){
5812        xForEach(p, newDb, (const char*)zName);
5813      }
5814      printf("done\n");
5815    }
5816  }
5817end_schema_xfer:
5818  sqlite3_finalize(pQuery);
5819  sqlite3_free(zQuery);
5820}
5821
5822/*
5823** Open a new database file named "zNewDb".  Try to recover as much information
5824** as possible out of the main database (which might be corrupt) and write it
5825** into zNewDb.
5826*/
5827static void tryToClone(ShellState *p, const char *zNewDb){
5828  int rc;
5829  sqlite3 *newDb = 0;
5830  if( access(zNewDb,0)==0 ){
5831    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5832    return;
5833  }
5834  rc = sqlite3_open(zNewDb, &newDb);
5835  if( rc ){
5836    utf8_printf(stderr, "Cannot create output database: %s\n",
5837            sqlite3_errmsg(newDb));
5838  }else{
5839    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5840    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5841    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5842    tryToCloneSchema(p, newDb, "type!='table'", 0);
5843    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5844    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5845  }
5846  close_db(newDb);
5847}
5848
5849/*
5850** Change the output file back to stdout.
5851**
5852** If the p->doXdgOpen flag is set, that means the output was being
5853** redirected to a temporary file named by p->zTempFile.  In that case,
5854** launch start/open/xdg-open on that temporary file.
5855*/
5856static void output_reset(ShellState *p){
5857  if( p->outfile[0]=='|' ){
5858#ifndef SQLITE_OMIT_POPEN
5859    pclose(p->out);
5860#endif
5861  }else{
5862    output_file_close(p->out);
5863#ifndef SQLITE_NOHAVE_SYSTEM
5864    if( p->doXdgOpen ){
5865      const char *zXdgOpenCmd =
5866#if defined(_WIN32)
5867      "start";
5868#elif defined(__APPLE__)
5869      "open";
5870#else
5871      "xdg-open";
5872#endif
5873      char *zCmd;
5874      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5875      if( system(zCmd) ){
5876        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5877      }else{
5878        /* Give the start/open/xdg-open command some time to get
5879        ** going before we continue, and potential delete the
5880        ** p->zTempFile data file out from under it */
5881        sqlite3_sleep(2000);
5882      }
5883      sqlite3_free(zCmd);
5884      outputModePop(p);
5885      p->doXdgOpen = 0;
5886    }
5887#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5888  }
5889  p->outfile[0] = 0;
5890  p->out = stdout;
5891}
5892
5893/*
5894** Run an SQL command and return the single integer result.
5895*/
5896static int db_int(sqlite3 *db, const char *zSql){
5897  sqlite3_stmt *pStmt;
5898  int res = 0;
5899  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5900  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5901    res = sqlite3_column_int(pStmt,0);
5902  }
5903  sqlite3_finalize(pStmt);
5904  return res;
5905}
5906
5907#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5908/*
5909** Convert a 2-byte or 4-byte big-endian integer into a native integer
5910*/
5911static unsigned int get2byteInt(unsigned char *a){
5912  return (a[0]<<8) + a[1];
5913}
5914static unsigned int get4byteInt(unsigned char *a){
5915  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5916}
5917
5918/*
5919** Implementation of the ".dbinfo" command.
5920**
5921** Return 1 on error, 2 to exit, and 0 otherwise.
5922*/
5923static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5924  static const struct { const char *zName; int ofst; } aField[] = {
5925     { "file change counter:",  24  },
5926     { "database page count:",  28  },
5927     { "freelist page count:",  36  },
5928     { "schema cookie:",        40  },
5929     { "schema format:",        44  },
5930     { "default cache size:",   48  },
5931     { "autovacuum top root:",  52  },
5932     { "incremental vacuum:",   64  },
5933     { "text encoding:",        56  },
5934     { "user version:",         60  },
5935     { "application id:",       68  },
5936     { "software version:",     96  },
5937  };
5938  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5939     { "number of tables:",
5940       "SELECT count(*) FROM %s WHERE type='table'" },
5941     { "number of indexes:",
5942       "SELECT count(*) FROM %s WHERE type='index'" },
5943     { "number of triggers:",
5944       "SELECT count(*) FROM %s WHERE type='trigger'" },
5945     { "number of views:",
5946       "SELECT count(*) FROM %s WHERE type='view'" },
5947     { "schema size:",
5948       "SELECT total(length(sql)) FROM %s" },
5949  };
5950  int i, rc;
5951  unsigned iDataVersion;
5952  char *zSchemaTab;
5953  char *zDb = nArg>=2 ? azArg[1] : "main";
5954  sqlite3_stmt *pStmt = 0;
5955  unsigned char aHdr[100];
5956  open_db(p, 0);
5957  if( p->db==0 ) return 1;
5958  rc = sqlite3_prepare_v2(p->db,
5959             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5960             -1, &pStmt, 0);
5961  if( rc ){
5962    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5963    sqlite3_finalize(pStmt);
5964    return 1;
5965  }
5966  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5967  if( sqlite3_step(pStmt)==SQLITE_ROW
5968   && sqlite3_column_bytes(pStmt,0)>100
5969  ){
5970    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5971    sqlite3_finalize(pStmt);
5972  }else{
5973    raw_printf(stderr, "unable to read database header\n");
5974    sqlite3_finalize(pStmt);
5975    return 1;
5976  }
5977  i = get2byteInt(aHdr+16);
5978  if( i==1 ) i = 65536;
5979  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5980  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5981  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5982  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5983  for(i=0; i<ArraySize(aField); i++){
5984    int ofst = aField[i].ofst;
5985    unsigned int val = get4byteInt(aHdr + ofst);
5986    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5987    switch( ofst ){
5988      case 56: {
5989        if( val==1 ) raw_printf(p->out, " (utf8)");
5990        if( val==2 ) raw_printf(p->out, " (utf16le)");
5991        if( val==3 ) raw_printf(p->out, " (utf16be)");
5992      }
5993    }
5994    raw_printf(p->out, "\n");
5995  }
5996  if( zDb==0 ){
5997    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5998  }else if( cli_strcmp(zDb,"temp")==0 ){
5999    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6000  }else{
6001    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6002  }
6003  for(i=0; i<ArraySize(aQuery); i++){
6004    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6005    int val = db_int(p->db, zSql);
6006    sqlite3_free(zSql);
6007    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
6008  }
6009  sqlite3_free(zSchemaTab);
6010  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6011  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
6012  return 0;
6013}
6014#endif /* SQLITE_SHELL_HAVE_RECOVER */
6015
6016/*
6017** Print the current sqlite3_errmsg() value to stderr and return 1.
6018*/
6019static int shellDatabaseError(sqlite3 *db){
6020  const char *zErr = sqlite3_errmsg(db);
6021  utf8_printf(stderr, "Error: %s\n", zErr);
6022  return 1;
6023}
6024
6025/*
6026** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
6027** if they match and FALSE (0) if they do not match.
6028**
6029** Globbing rules:
6030**
6031**      '*'       Matches any sequence of zero or more characters.
6032**
6033**      '?'       Matches exactly one character.
6034**
6035**     [...]      Matches one character from the enclosed list of
6036**                characters.
6037**
6038**     [^...]     Matches one character not in the enclosed list.
6039**
6040**      '#'       Matches any sequence of one or more digits with an
6041**                optional + or - sign in front
6042**
6043**      ' '       Any span of whitespace matches any other span of
6044**                whitespace.
6045**
6046** Extra whitespace at the end of z[] is ignored.
6047*/
6048static int testcase_glob(const char *zGlob, const char *z){
6049  int c, c2;
6050  int invert;
6051  int seen;
6052
6053  while( (c = (*(zGlob++)))!=0 ){
6054    if( IsSpace(c) ){
6055      if( !IsSpace(*z) ) return 0;
6056      while( IsSpace(*zGlob) ) zGlob++;
6057      while( IsSpace(*z) ) z++;
6058    }else if( c=='*' ){
6059      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6060        if( c=='?' && (*(z++))==0 ) return 0;
6061      }
6062      if( c==0 ){
6063        return 1;
6064      }else if( c=='[' ){
6065        while( *z && testcase_glob(zGlob-1,z)==0 ){
6066          z++;
6067        }
6068        return (*z)!=0;
6069      }
6070      while( (c2 = (*(z++)))!=0 ){
6071        while( c2!=c ){
6072          c2 = *(z++);
6073          if( c2==0 ) return 0;
6074        }
6075        if( testcase_glob(zGlob,z) ) return 1;
6076      }
6077      return 0;
6078    }else if( c=='?' ){
6079      if( (*(z++))==0 ) return 0;
6080    }else if( c=='[' ){
6081      int prior_c = 0;
6082      seen = 0;
6083      invert = 0;
6084      c = *(z++);
6085      if( c==0 ) return 0;
6086      c2 = *(zGlob++);
6087      if( c2=='^' ){
6088        invert = 1;
6089        c2 = *(zGlob++);
6090      }
6091      if( c2==']' ){
6092        if( c==']' ) seen = 1;
6093        c2 = *(zGlob++);
6094      }
6095      while( c2 && c2!=']' ){
6096        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6097          c2 = *(zGlob++);
6098          if( c>=prior_c && c<=c2 ) seen = 1;
6099          prior_c = 0;
6100        }else{
6101          if( c==c2 ){
6102            seen = 1;
6103          }
6104          prior_c = c2;
6105        }
6106        c2 = *(zGlob++);
6107      }
6108      if( c2==0 || (seen ^ invert)==0 ) return 0;
6109    }else if( c=='#' ){
6110      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6111      if( !IsDigit(z[0]) ) return 0;
6112      z++;
6113      while( IsDigit(z[0]) ){ z++; }
6114    }else{
6115      if( c!=(*(z++)) ) return 0;
6116    }
6117  }
6118  while( IsSpace(*z) ){ z++; }
6119  return *z==0;
6120}
6121
6122
6123/*
6124** Compare the string as a command-line option with either one or two
6125** initial "-" characters.
6126*/
6127static int optionMatch(const char *zStr, const char *zOpt){
6128  if( zStr[0]!='-' ) return 0;
6129  zStr++;
6130  if( zStr[0]=='-' ) zStr++;
6131  return cli_strcmp(zStr, zOpt)==0;
6132}
6133
6134/*
6135** Delete a file.
6136*/
6137int shellDeleteFile(const char *zFilename){
6138  int rc;
6139#ifdef _WIN32
6140  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6141  rc = _wunlink(z);
6142  sqlite3_free(z);
6143#else
6144  rc = unlink(zFilename);
6145#endif
6146  return rc;
6147}
6148
6149/*
6150** Try to delete the temporary file (if there is one) and free the
6151** memory used to hold the name of the temp file.
6152*/
6153static void clearTempFile(ShellState *p){
6154  if( p->zTempFile==0 ) return;
6155  if( p->doXdgOpen ) return;
6156  if( shellDeleteFile(p->zTempFile) ) return;
6157  sqlite3_free(p->zTempFile);
6158  p->zTempFile = 0;
6159}
6160
6161/*
6162** Create a new temp file name with the given suffix.
6163*/
6164static void newTempFile(ShellState *p, const char *zSuffix){
6165  clearTempFile(p);
6166  sqlite3_free(p->zTempFile);
6167  p->zTempFile = 0;
6168  if( p->db ){
6169    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6170  }
6171  if( p->zTempFile==0 ){
6172    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6173    ** will not work and we will need to fallback to guessing */
6174    char *zTemp;
6175    sqlite3_uint64 r;
6176    sqlite3_randomness(sizeof(r), &r);
6177    zTemp = getenv("TEMP");
6178    if( zTemp==0 ) zTemp = getenv("TMP");
6179    if( zTemp==0 ){
6180#ifdef _WIN32
6181      zTemp = "\\tmp";
6182#else
6183      zTemp = "/tmp";
6184#endif
6185    }
6186    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6187  }else{
6188    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6189  }
6190  shell_check_oom(p->zTempFile);
6191}
6192
6193
6194/*
6195** The implementation of SQL scalar function fkey_collate_clause(), used
6196** by the ".lint fkey-indexes" command. This scalar function is always
6197** called with four arguments - the parent table name, the parent column name,
6198** the child table name and the child column name.
6199**
6200**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6201**
6202** If either of the named tables or columns do not exist, this function
6203** returns an empty string. An empty string is also returned if both tables
6204** and columns exist but have the same default collation sequence. Or,
6205** if both exist but the default collation sequences are different, this
6206** function returns the string " COLLATE <parent-collation>", where
6207** <parent-collation> is the default collation sequence of the parent column.
6208*/
6209static void shellFkeyCollateClause(
6210  sqlite3_context *pCtx,
6211  int nVal,
6212  sqlite3_value **apVal
6213){
6214  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6215  const char *zParent;
6216  const char *zParentCol;
6217  const char *zParentSeq;
6218  const char *zChild;
6219  const char *zChildCol;
6220  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6221  int rc;
6222
6223  assert( nVal==4 );
6224  zParent = (const char*)sqlite3_value_text(apVal[0]);
6225  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6226  zChild = (const char*)sqlite3_value_text(apVal[2]);
6227  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6228
6229  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6230  rc = sqlite3_table_column_metadata(
6231      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6232  );
6233  if( rc==SQLITE_OK ){
6234    rc = sqlite3_table_column_metadata(
6235        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6236    );
6237  }
6238
6239  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6240    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6241    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6242    sqlite3_free(z);
6243  }
6244}
6245
6246
6247/*
6248** The implementation of dot-command ".lint fkey-indexes".
6249*/
6250static int lintFkeyIndexes(
6251  ShellState *pState,             /* Current shell tool state */
6252  char **azArg,                   /* Array of arguments passed to dot command */
6253  int nArg                        /* Number of entries in azArg[] */
6254){
6255  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6256  FILE *out = pState->out;        /* Stream to write non-error output to */
6257  int bVerbose = 0;               /* If -verbose is present */
6258  int bGroupByParent = 0;         /* If -groupbyparent is present */
6259  int i;                          /* To iterate through azArg[] */
6260  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6261  int rc;                         /* Return code */
6262  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6263
6264  /*
6265  ** This SELECT statement returns one row for each foreign key constraint
6266  ** in the schema of the main database. The column values are:
6267  **
6268  ** 0. The text of an SQL statement similar to:
6269  **
6270  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6271  **
6272  **    This SELECT is similar to the one that the foreign keys implementation
6273  **    needs to run internally on child tables. If there is an index that can
6274  **    be used to optimize this query, then it can also be used by the FK
6275  **    implementation to optimize DELETE or UPDATE statements on the parent
6276  **    table.
6277  **
6278  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6279  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6280  **    contains an index that can be used to optimize the query.
6281  **
6282  ** 2. Human readable text that describes the child table and columns. e.g.
6283  **
6284  **       "child_table(child_key1, child_key2)"
6285  **
6286  ** 3. Human readable text that describes the parent table and columns. e.g.
6287  **
6288  **       "parent_table(parent_key1, parent_key2)"
6289  **
6290  ** 4. A full CREATE INDEX statement for an index that could be used to
6291  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6292  **
6293  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6294  **
6295  ** 5. The name of the parent table.
6296  **
6297  ** These six values are used by the C logic below to generate the report.
6298  */
6299  const char *zSql =
6300  "SELECT "
6301    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6302    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6303    "  || fkey_collate_clause("
6304    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6305    ", "
6306    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6307    "  || group_concat('*=?', ' AND ') || ')'"
6308    ", "
6309    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6310    ", "
6311    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6312    ", "
6313    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6314    "  || ' ON ' || quote(s.name) || '('"
6315    "  || group_concat(quote(f.[from]) ||"
6316    "        fkey_collate_clause("
6317    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6318    "  || ');'"
6319    ", "
6320    "     f.[table] "
6321    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6322    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6323    "GROUP BY s.name, f.id "
6324    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6325  ;
6326  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6327
6328  for(i=2; i<nArg; i++){
6329    int n = strlen30(azArg[i]);
6330    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6331      bVerbose = 1;
6332    }
6333    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6334      bGroupByParent = 1;
6335      zIndent = "    ";
6336    }
6337    else{
6338      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6339          azArg[0], azArg[1]
6340      );
6341      return SQLITE_ERROR;
6342    }
6343  }
6344
6345  /* Register the fkey_collate_clause() SQL function */
6346  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6347      0, shellFkeyCollateClause, 0, 0
6348  );
6349
6350
6351  if( rc==SQLITE_OK ){
6352    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6353  }
6354  if( rc==SQLITE_OK ){
6355    sqlite3_bind_int(pSql, 1, bGroupByParent);
6356  }
6357
6358  if( rc==SQLITE_OK ){
6359    int rc2;
6360    char *zPrev = 0;
6361    while( SQLITE_ROW==sqlite3_step(pSql) ){
6362      int res = -1;
6363      sqlite3_stmt *pExplain = 0;
6364      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6365      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6366      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6367      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6368      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6369      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6370
6371      if( zEQP==0 ) continue;
6372      if( zGlob==0 ) continue;
6373      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6374      if( rc!=SQLITE_OK ) break;
6375      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6376        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6377        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6378                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6379      }
6380      rc = sqlite3_finalize(pExplain);
6381      if( rc!=SQLITE_OK ) break;
6382
6383      if( res<0 ){
6384        raw_printf(stderr, "Error: internal error");
6385        break;
6386      }else{
6387        if( bGroupByParent
6388        && (bVerbose || res==0)
6389        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6390        ){
6391          raw_printf(out, "-- Parent table %s\n", zParent);
6392          sqlite3_free(zPrev);
6393          zPrev = sqlite3_mprintf("%s", zParent);
6394        }
6395
6396        if( res==0 ){
6397          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6398        }else if( bVerbose ){
6399          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6400              zIndent, zFrom, zTarget
6401          );
6402        }
6403      }
6404    }
6405    sqlite3_free(zPrev);
6406
6407    if( rc!=SQLITE_OK ){
6408      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6409    }
6410
6411    rc2 = sqlite3_finalize(pSql);
6412    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6413      rc = rc2;
6414      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6415    }
6416  }else{
6417    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6418  }
6419
6420  return rc;
6421}
6422
6423/*
6424** Implementation of ".lint" dot command.
6425*/
6426static int lintDotCommand(
6427  ShellState *pState,             /* Current shell tool state */
6428  char **azArg,                   /* Array of arguments passed to dot command */
6429  int nArg                        /* Number of entries in azArg[] */
6430){
6431  int n;
6432  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6433  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6434  return lintFkeyIndexes(pState, azArg, nArg);
6435
6436 usage:
6437  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6438  raw_printf(stderr, "Where sub-commands are:\n");
6439  raw_printf(stderr, "    fkey-indexes\n");
6440  return SQLITE_ERROR;
6441}
6442
6443#if !defined SQLITE_OMIT_VIRTUALTABLE
6444static void shellPrepare(
6445  sqlite3 *db,
6446  int *pRc,
6447  const char *zSql,
6448  sqlite3_stmt **ppStmt
6449){
6450  *ppStmt = 0;
6451  if( *pRc==SQLITE_OK ){
6452    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6453    if( rc!=SQLITE_OK ){
6454      raw_printf(stderr, "sql error: %s (%d)\n",
6455          sqlite3_errmsg(db), sqlite3_errcode(db)
6456      );
6457      *pRc = rc;
6458    }
6459  }
6460}
6461
6462/*
6463** Create a prepared statement using printf-style arguments for the SQL.
6464**
6465** This routine is could be marked "static".  But it is not always used,
6466** depending on compile-time options.  By omitting the "static", we avoid
6467** nuisance compiler warnings about "defined but not used".
6468*/
6469void shellPreparePrintf(
6470  sqlite3 *db,
6471  int *pRc,
6472  sqlite3_stmt **ppStmt,
6473  const char *zFmt,
6474  ...
6475){
6476  *ppStmt = 0;
6477  if( *pRc==SQLITE_OK ){
6478    va_list ap;
6479    char *z;
6480    va_start(ap, zFmt);
6481    z = sqlite3_vmprintf(zFmt, ap);
6482    va_end(ap);
6483    if( z==0 ){
6484      *pRc = SQLITE_NOMEM;
6485    }else{
6486      shellPrepare(db, pRc, z, ppStmt);
6487      sqlite3_free(z);
6488    }
6489  }
6490}
6491
6492/* Finalize the prepared statement created using shellPreparePrintf().
6493**
6494** This routine is could be marked "static".  But it is not always used,
6495** depending on compile-time options.  By omitting the "static", we avoid
6496** nuisance compiler warnings about "defined but not used".
6497*/
6498void shellFinalize(
6499  int *pRc,
6500  sqlite3_stmt *pStmt
6501){
6502  if( pStmt ){
6503    sqlite3 *db = sqlite3_db_handle(pStmt);
6504    int rc = sqlite3_finalize(pStmt);
6505    if( *pRc==SQLITE_OK ){
6506      if( rc!=SQLITE_OK ){
6507        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6508      }
6509      *pRc = rc;
6510    }
6511  }
6512}
6513
6514/* Reset the prepared statement created using shellPreparePrintf().
6515**
6516** This routine is could be marked "static".  But it is not always used,
6517** depending on compile-time options.  By omitting the "static", we avoid
6518** nuisance compiler warnings about "defined but not used".
6519*/
6520void shellReset(
6521  int *pRc,
6522  sqlite3_stmt *pStmt
6523){
6524  int rc = sqlite3_reset(pStmt);
6525  if( *pRc==SQLITE_OK ){
6526    if( rc!=SQLITE_OK ){
6527      sqlite3 *db = sqlite3_db_handle(pStmt);
6528      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6529    }
6530    *pRc = rc;
6531  }
6532}
6533#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6534
6535#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6536/******************************************************************************
6537** The ".archive" or ".ar" command.
6538*/
6539/*
6540** Structure representing a single ".ar" command.
6541*/
6542typedef struct ArCommand ArCommand;
6543struct ArCommand {
6544  u8 eCmd;                        /* An AR_CMD_* value */
6545  u8 bVerbose;                    /* True if --verbose */
6546  u8 bZip;                        /* True if the archive is a ZIP */
6547  u8 bDryRun;                     /* True if --dry-run */
6548  u8 bAppend;                     /* True if --append */
6549  u8 bGlob;                       /* True if --glob */
6550  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6551  int nArg;                       /* Number of command arguments */
6552  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6553  const char *zFile;              /* --file argument, or NULL */
6554  const char *zDir;               /* --directory argument, or NULL */
6555  char **azArg;                   /* Array of command arguments */
6556  ShellState *p;                  /* Shell state */
6557  sqlite3 *db;                    /* Database containing the archive */
6558};
6559
6560/*
6561** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6562*/
6563static int arUsage(FILE *f){
6564  showHelp(f,"archive");
6565  return SQLITE_ERROR;
6566}
6567
6568/*
6569** Print an error message for the .ar command to stderr and return
6570** SQLITE_ERROR.
6571*/
6572static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6573  va_list ap;
6574  char *z;
6575  va_start(ap, zFmt);
6576  z = sqlite3_vmprintf(zFmt, ap);
6577  va_end(ap);
6578  utf8_printf(stderr, "Error: %s\n", z);
6579  if( pAr->fromCmdLine ){
6580    utf8_printf(stderr, "Use \"-A\" for more help\n");
6581  }else{
6582    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6583  }
6584  sqlite3_free(z);
6585  return SQLITE_ERROR;
6586}
6587
6588/*
6589** Values for ArCommand.eCmd.
6590*/
6591#define AR_CMD_CREATE       1
6592#define AR_CMD_UPDATE       2
6593#define AR_CMD_INSERT       3
6594#define AR_CMD_EXTRACT      4
6595#define AR_CMD_LIST         5
6596#define AR_CMD_HELP         6
6597#define AR_CMD_REMOVE       7
6598
6599/*
6600** Other (non-command) switches.
6601*/
6602#define AR_SWITCH_VERBOSE     8
6603#define AR_SWITCH_FILE        9
6604#define AR_SWITCH_DIRECTORY  10
6605#define AR_SWITCH_APPEND     11
6606#define AR_SWITCH_DRYRUN     12
6607#define AR_SWITCH_GLOB       13
6608
6609static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6610  switch( eSwitch ){
6611    case AR_CMD_CREATE:
6612    case AR_CMD_EXTRACT:
6613    case AR_CMD_LIST:
6614    case AR_CMD_REMOVE:
6615    case AR_CMD_UPDATE:
6616    case AR_CMD_INSERT:
6617    case AR_CMD_HELP:
6618      if( pAr->eCmd ){
6619        return arErrorMsg(pAr, "multiple command options");
6620      }
6621      pAr->eCmd = eSwitch;
6622      break;
6623
6624    case AR_SWITCH_DRYRUN:
6625      pAr->bDryRun = 1;
6626      break;
6627    case AR_SWITCH_GLOB:
6628      pAr->bGlob = 1;
6629      break;
6630    case AR_SWITCH_VERBOSE:
6631      pAr->bVerbose = 1;
6632      break;
6633    case AR_SWITCH_APPEND:
6634      pAr->bAppend = 1;
6635      /* Fall thru into --file */
6636    case AR_SWITCH_FILE:
6637      pAr->zFile = zArg;
6638      break;
6639    case AR_SWITCH_DIRECTORY:
6640      pAr->zDir = zArg;
6641      break;
6642  }
6643
6644  return SQLITE_OK;
6645}
6646
6647/*
6648** Parse the command line for an ".ar" command. The results are written into
6649** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6650** successfully, otherwise an error message is written to stderr and
6651** SQLITE_ERROR returned.
6652*/
6653static int arParseCommand(
6654  char **azArg,                   /* Array of arguments passed to dot command */
6655  int nArg,                       /* Number of entries in azArg[] */
6656  ArCommand *pAr                  /* Populate this object */
6657){
6658  struct ArSwitch {
6659    const char *zLong;
6660    char cShort;
6661    u8 eSwitch;
6662    u8 bArg;
6663  } aSwitch[] = {
6664    { "create",    'c', AR_CMD_CREATE,       0 },
6665    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6666    { "insert",    'i', AR_CMD_INSERT,       0 },
6667    { "list",      't', AR_CMD_LIST,         0 },
6668    { "remove",    'r', AR_CMD_REMOVE,       0 },
6669    { "update",    'u', AR_CMD_UPDATE,       0 },
6670    { "help",      'h', AR_CMD_HELP,         0 },
6671    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6672    { "file",      'f', AR_SWITCH_FILE,      1 },
6673    { "append",    'a', AR_SWITCH_APPEND,    1 },
6674    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6675    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6676    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6677  };
6678  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6679  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6680
6681  if( nArg<=1 ){
6682    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6683    return arUsage(stderr);
6684  }else{
6685    char *z = azArg[1];
6686    if( z[0]!='-' ){
6687      /* Traditional style [tar] invocation */
6688      int i;
6689      int iArg = 2;
6690      for(i=0; z[i]; i++){
6691        const char *zArg = 0;
6692        struct ArSwitch *pOpt;
6693        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6694          if( z[i]==pOpt->cShort ) break;
6695        }
6696        if( pOpt==pEnd ){
6697          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6698        }
6699        if( pOpt->bArg ){
6700          if( iArg>=nArg ){
6701            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6702          }
6703          zArg = azArg[iArg++];
6704        }
6705        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6706      }
6707      pAr->nArg = nArg-iArg;
6708      if( pAr->nArg>0 ){
6709        pAr->azArg = &azArg[iArg];
6710      }
6711    }else{
6712      /* Non-traditional invocation */
6713      int iArg;
6714      for(iArg=1; iArg<nArg; iArg++){
6715        int n;
6716        z = azArg[iArg];
6717        if( z[0]!='-' ){
6718          /* All remaining command line words are command arguments. */
6719          pAr->azArg = &azArg[iArg];
6720          pAr->nArg = nArg-iArg;
6721          break;
6722        }
6723        n = strlen30(z);
6724
6725        if( z[1]!='-' ){
6726          int i;
6727          /* One or more short options */
6728          for(i=1; i<n; i++){
6729            const char *zArg = 0;
6730            struct ArSwitch *pOpt;
6731            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6732              if( z[i]==pOpt->cShort ) break;
6733            }
6734            if( pOpt==pEnd ){
6735              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6736            }
6737            if( pOpt->bArg ){
6738              if( i<(n-1) ){
6739                zArg = &z[i+1];
6740                i = n;
6741              }else{
6742                if( iArg>=(nArg-1) ){
6743                  return arErrorMsg(pAr, "option requires an argument: %c",
6744                                    z[i]);
6745                }
6746                zArg = azArg[++iArg];
6747              }
6748            }
6749            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6750          }
6751        }else if( z[2]=='\0' ){
6752          /* A -- option, indicating that all remaining command line words
6753          ** are command arguments.  */
6754          pAr->azArg = &azArg[iArg+1];
6755          pAr->nArg = nArg-iArg-1;
6756          break;
6757        }else{
6758          /* A long option */
6759          const char *zArg = 0;             /* Argument for option, if any */
6760          struct ArSwitch *pMatch = 0;      /* Matching option */
6761          struct ArSwitch *pOpt;            /* Iterator */
6762          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6763            const char *zLong = pOpt->zLong;
6764            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6765              if( pMatch ){
6766                return arErrorMsg(pAr, "ambiguous option: %s",z);
6767              }else{
6768                pMatch = pOpt;
6769              }
6770            }
6771          }
6772
6773          if( pMatch==0 ){
6774            return arErrorMsg(pAr, "unrecognized option: %s", z);
6775          }
6776          if( pMatch->bArg ){
6777            if( iArg>=(nArg-1) ){
6778              return arErrorMsg(pAr, "option requires an argument: %s", z);
6779            }
6780            zArg = azArg[++iArg];
6781          }
6782          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6783        }
6784      }
6785    }
6786  }
6787
6788  return SQLITE_OK;
6789}
6790
6791/*
6792** This function assumes that all arguments within the ArCommand.azArg[]
6793** array refer to archive members, as for the --extract, --list or --remove
6794** commands. It checks that each of them are "present". If any specified
6795** file is not present in the archive, an error is printed to stderr and an
6796** error code returned. Otherwise, if all specified arguments are present
6797** in the archive, SQLITE_OK is returned. Here, "present" means either an
6798** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6799** when pAr->bGlob is true.
6800**
6801** This function strips any trailing '/' characters from each argument.
6802** This is consistent with the way the [tar] command seems to work on
6803** Linux.
6804*/
6805static int arCheckEntries(ArCommand *pAr){
6806  int rc = SQLITE_OK;
6807  if( pAr->nArg ){
6808    int i, j;
6809    sqlite3_stmt *pTest = 0;
6810    const char *zSel = (pAr->bGlob)
6811      ? "SELECT name FROM %s WHERE glob($name,name)"
6812      : "SELECT name FROM %s WHERE name=$name";
6813
6814    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6815    j = sqlite3_bind_parameter_index(pTest, "$name");
6816    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6817      char *z = pAr->azArg[i];
6818      int n = strlen30(z);
6819      int bOk = 0;
6820      while( n>0 && z[n-1]=='/' ) n--;
6821      z[n] = '\0';
6822      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6823      if( SQLITE_ROW==sqlite3_step(pTest) ){
6824        bOk = 1;
6825      }
6826      shellReset(&rc, pTest);
6827      if( rc==SQLITE_OK && bOk==0 ){
6828        utf8_printf(stderr, "not found in archive: %s\n", z);
6829        rc = SQLITE_ERROR;
6830      }
6831    }
6832    shellFinalize(&rc, pTest);
6833  }
6834  return rc;
6835}
6836
6837/*
6838** Format a WHERE clause that can be used against the "sqlar" table to
6839** identify all archive members that match the command arguments held
6840** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6841** The caller is responsible for eventually calling sqlite3_free() on
6842** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6843** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6844*/
6845static void arWhereClause(
6846  int *pRc,
6847  ArCommand *pAr,
6848  char **pzWhere                  /* OUT: New WHERE clause */
6849){
6850  char *zWhere = 0;
6851  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6852  if( *pRc==SQLITE_OK ){
6853    if( pAr->nArg==0 ){
6854      zWhere = sqlite3_mprintf("1");
6855    }else{
6856      int i;
6857      const char *zSep = "";
6858      for(i=0; i<pAr->nArg; i++){
6859        const char *z = pAr->azArg[i];
6860        zWhere = sqlite3_mprintf(
6861          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6862          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6863        );
6864        if( zWhere==0 ){
6865          *pRc = SQLITE_NOMEM;
6866          break;
6867        }
6868        zSep = " OR ";
6869      }
6870    }
6871  }
6872  *pzWhere = zWhere;
6873}
6874
6875/*
6876** Implementation of .ar "lisT" command.
6877*/
6878static int arListCommand(ArCommand *pAr){
6879  const char *zSql = "SELECT %s FROM %s WHERE %s";
6880  const char *azCols[] = {
6881    "name",
6882    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6883  };
6884
6885  char *zWhere = 0;
6886  sqlite3_stmt *pSql = 0;
6887  int rc;
6888
6889  rc = arCheckEntries(pAr);
6890  arWhereClause(&rc, pAr, &zWhere);
6891
6892  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6893                     pAr->zSrcTable, zWhere);
6894  if( pAr->bDryRun ){
6895    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6896  }else{
6897    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6898      if( pAr->bVerbose ){
6899        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6900            sqlite3_column_text(pSql, 0),
6901            sqlite3_column_int(pSql, 1),
6902            sqlite3_column_text(pSql, 2),
6903            sqlite3_column_text(pSql, 3)
6904        );
6905      }else{
6906        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6907      }
6908    }
6909  }
6910  shellFinalize(&rc, pSql);
6911  sqlite3_free(zWhere);
6912  return rc;
6913}
6914
6915
6916/*
6917** Implementation of .ar "Remove" command.
6918*/
6919static int arRemoveCommand(ArCommand *pAr){
6920  int rc = 0;
6921  char *zSql = 0;
6922  char *zWhere = 0;
6923
6924  if( pAr->nArg ){
6925    /* Verify that args actually exist within the archive before proceeding.
6926    ** And formulate a WHERE clause to match them.  */
6927    rc = arCheckEntries(pAr);
6928    arWhereClause(&rc, pAr, &zWhere);
6929  }
6930  if( rc==SQLITE_OK ){
6931    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6932                           pAr->zSrcTable, zWhere);
6933    if( pAr->bDryRun ){
6934      utf8_printf(pAr->p->out, "%s\n", zSql);
6935    }else{
6936      char *zErr = 0;
6937      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6938      if( rc==SQLITE_OK ){
6939        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6940        if( rc!=SQLITE_OK ){
6941          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6942        }else{
6943          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6944        }
6945      }
6946      if( zErr ){
6947        utf8_printf(stdout, "ERROR: %s\n", zErr);
6948        sqlite3_free(zErr);
6949      }
6950    }
6951  }
6952  sqlite3_free(zWhere);
6953  sqlite3_free(zSql);
6954  return rc;
6955}
6956
6957/*
6958** Implementation of .ar "eXtract" command.
6959*/
6960static int arExtractCommand(ArCommand *pAr){
6961  const char *zSql1 =
6962    "SELECT "
6963    " ($dir || name),"
6964    " writefile(($dir || name), %s, mode, mtime) "
6965    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6966    " AND name NOT GLOB '*..[/\\]*'";
6967
6968  const char *azExtraArg[] = {
6969    "sqlar_uncompress(data, sz)",
6970    "data"
6971  };
6972
6973  sqlite3_stmt *pSql = 0;
6974  int rc = SQLITE_OK;
6975  char *zDir = 0;
6976  char *zWhere = 0;
6977  int i, j;
6978
6979  /* If arguments are specified, check that they actually exist within
6980  ** the archive before proceeding. And formulate a WHERE clause to
6981  ** match them.  */
6982  rc = arCheckEntries(pAr);
6983  arWhereClause(&rc, pAr, &zWhere);
6984
6985  if( rc==SQLITE_OK ){
6986    if( pAr->zDir ){
6987      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6988    }else{
6989      zDir = sqlite3_mprintf("");
6990    }
6991    if( zDir==0 ) rc = SQLITE_NOMEM;
6992  }
6993
6994  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6995      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6996  );
6997
6998  if( rc==SQLITE_OK ){
6999    j = sqlite3_bind_parameter_index(pSql, "$dir");
7000    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7001
7002    /* Run the SELECT statement twice. The first time, writefile() is called
7003    ** for all archive members that should be extracted. The second time,
7004    ** only for the directories. This is because the timestamps for
7005    ** extracted directories must be reset after they are populated (as
7006    ** populating them changes the timestamp).  */
7007    for(i=0; i<2; i++){
7008      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7009      sqlite3_bind_int(pSql, j, i);
7010      if( pAr->bDryRun ){
7011        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
7012      }else{
7013        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7014          if( i==0 && pAr->bVerbose ){
7015            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
7016          }
7017        }
7018      }
7019      shellReset(&rc, pSql);
7020    }
7021    shellFinalize(&rc, pSql);
7022  }
7023
7024  sqlite3_free(zDir);
7025  sqlite3_free(zWhere);
7026  return rc;
7027}
7028
7029/*
7030** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
7031*/
7032static int arExecSql(ArCommand *pAr, const char *zSql){
7033  int rc;
7034  if( pAr->bDryRun ){
7035    utf8_printf(pAr->p->out, "%s\n", zSql);
7036    rc = SQLITE_OK;
7037  }else{
7038    char *zErr = 0;
7039    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7040    if( zErr ){
7041      utf8_printf(stdout, "ERROR: %s\n", zErr);
7042      sqlite3_free(zErr);
7043    }
7044  }
7045  return rc;
7046}
7047
7048
7049/*
7050** Implementation of .ar "create", "insert", and "update" commands.
7051**
7052**     create    ->     Create a new SQL archive
7053**     insert    ->     Insert or reinsert all files listed
7054**     update    ->     Insert files that have changed or that were not
7055**                      previously in the archive
7056**
7057** Create the "sqlar" table in the database if it does not already exist.
7058** Then add each file in the azFile[] array to the archive. Directories
7059** are added recursively. If argument bVerbose is non-zero, a message is
7060** printed on stdout for each file archived.
7061**
7062** The create command is the same as update, except that it drops
7063** any existing "sqlar" table before beginning.  The "insert" command
7064** always overwrites every file named on the command-line, where as
7065** "update" only overwrites if the size or mtime or mode has changed.
7066*/
7067static int arCreateOrUpdateCommand(
7068  ArCommand *pAr,                 /* Command arguments and options */
7069  int bUpdate,                    /* true for a --create. */
7070  int bOnlyIfChanged              /* Only update if file has changed */
7071){
7072  const char *zCreate =
7073      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7074      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7075      "  mode INT,               -- access permissions\n"
7076      "  mtime INT,              -- last modification time\n"
7077      "  sz INT,                 -- original file size\n"
7078      "  data BLOB               -- compressed content\n"
7079      ")";
7080  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7081  const char *zInsertFmt[2] = {
7082     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7083     "  SELECT\n"
7084     "    %s,\n"
7085     "    mode,\n"
7086     "    mtime,\n"
7087     "    CASE substr(lsmode(mode),1,1)\n"
7088     "      WHEN '-' THEN length(data)\n"
7089     "      WHEN 'd' THEN 0\n"
7090     "      ELSE -1 END,\n"
7091     "    sqlar_compress(data)\n"
7092     "  FROM fsdir(%Q,%Q) AS disk\n"
7093     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7094     ,
7095     "REPLACE INTO %s(name,mode,mtime,data)\n"
7096     "  SELECT\n"
7097     "    %s,\n"
7098     "    mode,\n"
7099     "    mtime,\n"
7100     "    data\n"
7101     "  FROM fsdir(%Q,%Q) AS disk\n"
7102     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7103  };
7104  int i;                          /* For iterating through azFile[] */
7105  int rc;                         /* Return code */
7106  const char *zTab = 0;           /* SQL table into which to insert */
7107  char *zSql;
7108  char zTemp[50];
7109  char *zExists = 0;
7110
7111  arExecSql(pAr, "PRAGMA page_size=512");
7112  rc = arExecSql(pAr, "SAVEPOINT ar;");
7113  if( rc!=SQLITE_OK ) return rc;
7114  zTemp[0] = 0;
7115  if( pAr->bZip ){
7116    /* Initialize the zipfile virtual table, if necessary */
7117    if( pAr->zFile ){
7118      sqlite3_uint64 r;
7119      sqlite3_randomness(sizeof(r),&r);
7120      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7121      zTab = zTemp;
7122      zSql = sqlite3_mprintf(
7123         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7124         zTab, pAr->zFile
7125      );
7126      rc = arExecSql(pAr, zSql);
7127      sqlite3_free(zSql);
7128    }else{
7129      zTab = "zip";
7130    }
7131  }else{
7132    /* Initialize the table for an SQLAR */
7133    zTab = "sqlar";
7134    if( bUpdate==0 ){
7135      rc = arExecSql(pAr, zDrop);
7136      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7137    }
7138    rc = arExecSql(pAr, zCreate);
7139  }
7140  if( bOnlyIfChanged ){
7141    zExists = sqlite3_mprintf(
7142      " AND NOT EXISTS("
7143          "SELECT 1 FROM %s AS mem"
7144          " WHERE mem.name=disk.name"
7145          " AND mem.mtime=disk.mtime"
7146          " AND mem.mode=disk.mode)", zTab);
7147  }else{
7148    zExists = sqlite3_mprintf("");
7149  }
7150  if( zExists==0 ) rc = SQLITE_NOMEM;
7151  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7152    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7153        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7154        pAr->azArg[i], pAr->zDir, zExists);
7155    rc = arExecSql(pAr, zSql2);
7156    sqlite3_free(zSql2);
7157  }
7158end_ar_transaction:
7159  if( rc!=SQLITE_OK ){
7160    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7161  }else{
7162    rc = arExecSql(pAr, "RELEASE ar;");
7163    if( pAr->bZip && pAr->zFile ){
7164      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7165      arExecSql(pAr, zSql);
7166      sqlite3_free(zSql);
7167    }
7168  }
7169  sqlite3_free(zExists);
7170  return rc;
7171}
7172
7173/*
7174** Implementation of ".ar" dot command.
7175*/
7176static int arDotCommand(
7177  ShellState *pState,          /* Current shell tool state */
7178  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7179  char **azArg,                /* Array of arguments passed to dot command */
7180  int nArg                     /* Number of entries in azArg[] */
7181){
7182  ArCommand cmd;
7183  int rc;
7184  memset(&cmd, 0, sizeof(cmd));
7185  cmd.fromCmdLine = fromCmdLine;
7186  rc = arParseCommand(azArg, nArg, &cmd);
7187  if( rc==SQLITE_OK ){
7188    int eDbType = SHELL_OPEN_UNSPEC;
7189    cmd.p = pState;
7190    cmd.db = pState->db;
7191    if( cmd.zFile ){
7192      eDbType = deduceDatabaseType(cmd.zFile, 1);
7193    }else{
7194      eDbType = pState->openMode;
7195    }
7196    if( eDbType==SHELL_OPEN_ZIPFILE ){
7197      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7198        if( cmd.zFile==0 ){
7199          cmd.zSrcTable = sqlite3_mprintf("zip");
7200        }else{
7201          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7202        }
7203      }
7204      cmd.bZip = 1;
7205    }else if( cmd.zFile ){
7206      int flags;
7207      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7208      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7209           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7210        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7211      }else{
7212        flags = SQLITE_OPEN_READONLY;
7213      }
7214      cmd.db = 0;
7215      if( cmd.bDryRun ){
7216        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7217             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7218      }
7219      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7220             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7221      if( rc!=SQLITE_OK ){
7222        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7223            cmd.zFile, sqlite3_errmsg(cmd.db)
7224        );
7225        goto end_ar_command;
7226      }
7227      sqlite3_fileio_init(cmd.db, 0, 0);
7228      sqlite3_sqlar_init(cmd.db, 0, 0);
7229      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7230                              shellPutsFunc, 0, 0);
7231
7232    }
7233    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7234      if( cmd.eCmd!=AR_CMD_CREATE
7235       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7236      ){
7237        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7238        rc = SQLITE_ERROR;
7239        goto end_ar_command;
7240      }
7241      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7242    }
7243
7244    switch( cmd.eCmd ){
7245      case AR_CMD_CREATE:
7246        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7247        break;
7248
7249      case AR_CMD_EXTRACT:
7250        rc = arExtractCommand(&cmd);
7251        break;
7252
7253      case AR_CMD_LIST:
7254        rc = arListCommand(&cmd);
7255        break;
7256
7257      case AR_CMD_HELP:
7258        arUsage(pState->out);
7259        break;
7260
7261      case AR_CMD_INSERT:
7262        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7263        break;
7264
7265      case AR_CMD_REMOVE:
7266        rc = arRemoveCommand(&cmd);
7267        break;
7268
7269      default:
7270        assert( cmd.eCmd==AR_CMD_UPDATE );
7271        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7272        break;
7273    }
7274  }
7275end_ar_command:
7276  if( cmd.db!=pState->db ){
7277    close_db(cmd.db);
7278  }
7279  sqlite3_free(cmd.zSrcTable);
7280
7281  return rc;
7282}
7283/* End of the ".archive" or ".ar" command logic
7284*******************************************************************************/
7285#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7286
7287#if SQLITE_SHELL_HAVE_RECOVER
7288
7289/*
7290** This function is used as a callback by the recover extension. Simply
7291** print the supplied SQL statement to stdout.
7292*/
7293static int recoverSqlCb(void *pCtx, const char *zSql){
7294  ShellState *pState = (ShellState*)pCtx;
7295  utf8_printf(pState->out, "%s;\n", zSql);
7296  return SQLITE_OK;
7297}
7298
7299/*
7300** This function is called to recover data from the database. A script
7301** to construct a new database containing all recovered data is output
7302** on stream pState->out.
7303*/
7304static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7305  int rc = SQLITE_OK;
7306  const char *zRecoveryDb = "";   /* Name of "recovery" database.  Debug only */
7307  const char *zLAF = "lost_and_found";
7308  int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
7309  int bRowids = 1;                /* 0 if --no-rowids */
7310  sqlite3_recover *p = 0;
7311  int i = 0;
7312
7313  for(i=1; i<nArg; i++){
7314    char *z = azArg[i];
7315    int n;
7316    if( z[0]=='-' && z[1]=='-' ) z++;
7317    n = strlen30(z);
7318    if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7319      bFreelist = 0;
7320    }else
7321    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7322      /* This option determines the name of the ATTACH-ed database used
7323      ** internally by the recovery extension.  The default is "" which
7324      ** means to use a temporary database that is automatically deleted
7325      ** when closed.  This option is undocumented and might disappear at
7326      ** any moment. */
7327      i++;
7328      zRecoveryDb = azArg[i];
7329    }else
7330    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7331      i++;
7332      zLAF = azArg[i];
7333    }else
7334    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7335      bRowids = 0;
7336    }
7337    else{
7338      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7339      showHelp(pState->out, azArg[0]);
7340      return 1;
7341    }
7342  }
7343
7344  p = sqlite3_recover_init_sql(
7345      pState->db, "main", recoverSqlCb, (void*)pState
7346  );
7347
7348  sqlite3_recover_config(p, 789, (void*)zRecoveryDb);  /* Debug use only */
7349  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7350  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7351  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7352
7353  sqlite3_recover_run(p);
7354  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7355    const char *zErr = sqlite3_recover_errmsg(p);
7356    int errCode = sqlite3_recover_errcode(p);
7357    raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
7358  }
7359  rc = sqlite3_recover_finish(p);
7360  return rc;
7361}
7362#endif /* SQLITE_SHELL_HAVE_RECOVER */
7363
7364
7365/*
7366 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7367 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7368 *   close db and set it to 0, and return the columns spec, to later
7369 *   be sqlite3_free()'ed by the caller.
7370 * The return is 0 when either:
7371 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7372 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7373 * The 3rd argument, pRenamed, references an out parameter. If the
7374 * pointer is non-zero, its referent will be set to a summary of renames
7375 * done if renaming was necessary, or set to 0 if none was done. The out
7376 * string (if any) must be sqlite3_free()'ed by the caller.
7377 */
7378#ifdef SHELL_DEBUG
7379#define rc_err_oom_die(rc) \
7380  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7381  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7382    fprintf(stderr,"E:%d\n",rc), assert(0)
7383#else
7384static void rc_err_oom_die(int rc){
7385  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7386  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7387}
7388#endif
7389
7390#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7391static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7392#else  /* Otherwise, memory is faster/better for the transient DB. */
7393static const char *zCOL_DB = ":memory:";
7394#endif
7395
7396/* Define character (as C string) to separate generated column ordinal
7397 * from protected part of incoming column names. This defaults to "_"
7398 * so that incoming column identifiers that did not need not be quoted
7399 * remain usable without being quoted. It must be one character.
7400 */
7401#ifndef SHELL_AUTOCOLUMN_SEP
7402# define AUTOCOLUMN_SEP "_"
7403#else
7404# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7405#endif
7406
7407static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7408  /* Queries and D{D,M}L used here */
7409  static const char * const zTabMake = "\
7410CREATE TABLE ColNames(\
7411 cpos INTEGER PRIMARY KEY,\
7412 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7413CREATE VIEW RepeatedNames AS \
7414SELECT DISTINCT t.name FROM ColNames t \
7415WHERE t.name COLLATE NOCASE IN (\
7416 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7417);\
7418";
7419  static const char * const zTabFill = "\
7420INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7421 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7422";
7423  static const char * const zHasDupes = "\
7424SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7425 <count(name) FROM ColNames\
7426";
7427#ifdef SHELL_COLUMN_RENAME_CLEAN
7428  static const char * const zDedoctor = "\
7429UPDATE ColNames SET chop=iif(\
7430  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7431  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7432 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7433 0\
7434)\
7435";
7436#endif
7437  static const char * const zSetReps = "\
7438UPDATE ColNames AS t SET reps=\
7439(SELECT count(*) FROM ColNames d \
7440 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7441 COLLATE NOCASE\
7442)\
7443";
7444#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7445  static const char * const zColDigits = "\
7446SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7447";
7448#else
7449  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7450  static const char * const zColDigits = "\
7451SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7452 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7453 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7454";
7455#endif
7456  static const char * const zRenameRank =
7457#ifdef SHELL_COLUMN_RENAME_CLEAN
7458    "UPDATE ColNames AS t SET suff="
7459    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7460#else /* ...RENAME_MINIMAL_ONE_PASS */
7461"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7462"  SELECT 0 AS nlz"
7463"  UNION"
7464"  SELECT nlz+1 AS nlz FROM Lzn"
7465"  WHERE EXISTS("
7466"   SELECT 1"
7467"   FROM ColNames t, ColNames o"
7468"   WHERE"
7469"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7470"     printf('%s"AUTOCOLUMN_SEP"%s',"
7471"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7472"     t.name"
7473"    )"
7474"    ="
7475"    iif(o.name IN (SELECT * FROM RepeatedNames),"
7476"     printf('%s"AUTOCOLUMN_SEP"%s',"
7477"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7478"     o.name"
7479"    )"
7480"    COLLATE NOCASE"
7481"    AND o.cpos<>t.cpos"
7482"   GROUP BY t.cpos"
7483"  )"
7484") UPDATE Colnames AS t SET"
7485" chop = 0," /* No chopping, never touch incoming names. */
7486" suff = iif(name IN (SELECT * FROM RepeatedNames),"
7487"  printf('"AUTOCOLUMN_SEP"%s', substring("
7488"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7489"  ''"
7490" )"
7491#endif
7492    ;
7493  static const char * const zCollectVar = "\
7494SELECT\
7495 '('||x'0a'\
7496 || group_concat(\
7497  cname||' TEXT',\
7498  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7499 ||')' AS ColsSpec \
7500FROM (\
7501 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7502 FROM ColNames ORDER BY cpos\
7503)";
7504  static const char * const zRenamesDone =
7505    "SELECT group_concat("
7506    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7507    " ','||x'0a')"
7508    "FROM ColNames WHERE suff<>'' OR chop!=0"
7509    ;
7510  int rc;
7511  sqlite3_stmt *pStmt = 0;
7512  assert(pDb!=0);
7513  if( zColNew ){
7514    /* Add initial or additional column. Init db if necessary. */
7515    if( *pDb==0 ){
7516      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7517#ifdef SHELL_COLFIX_DB
7518      if(*zCOL_DB!=':')
7519        sqlite3_exec(*pDb,"drop table if exists ColNames;"
7520                     "drop view if exists RepeatedNames;",0,0,0);
7521#endif
7522      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7523      rc_err_oom_die(rc);
7524    }
7525    assert(*pDb!=0);
7526    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7527    rc_err_oom_die(rc);
7528    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7529    rc_err_oom_die(rc);
7530    rc = sqlite3_step(pStmt);
7531    rc_err_oom_die(rc);
7532    sqlite3_finalize(pStmt);
7533    return 0;
7534  }else if( *pDb==0 ){
7535    return 0;
7536  }else{
7537    /* Formulate the columns spec, close the DB, zero *pDb. */
7538    char *zColsSpec = 0;
7539    int hasDupes = db_int(*pDb, zHasDupes);
7540    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7541    if( hasDupes ){
7542#ifdef SHELL_COLUMN_RENAME_CLEAN
7543      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7544      rc_err_oom_die(rc);
7545#endif
7546      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7547      rc_err_oom_die(rc);
7548      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7549      rc_err_oom_die(rc);
7550      sqlite3_bind_int(pStmt, 1, nDigits);
7551      rc = sqlite3_step(pStmt);
7552      sqlite3_finalize(pStmt);
7553      assert(rc==SQLITE_DONE);
7554    }
7555    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7556    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7557    rc_err_oom_die(rc);
7558    rc = sqlite3_step(pStmt);
7559    if( rc==SQLITE_ROW ){
7560      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7561    }else{
7562      zColsSpec = 0;
7563    }
7564    if( pzRenamed!=0 ){
7565      if( !hasDupes ) *pzRenamed = 0;
7566      else{
7567        sqlite3_finalize(pStmt);
7568        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7569            && SQLITE_ROW==sqlite3_step(pStmt) ){
7570          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7571        }else
7572          *pzRenamed = 0;
7573      }
7574    }
7575    sqlite3_finalize(pStmt);
7576    sqlite3_close(*pDb);
7577    *pDb = 0;
7578    return zColsSpec;
7579  }
7580}
7581
7582/*
7583** If an input line begins with "." then invoke this routine to
7584** process that line.
7585**
7586** Return 1 on error, 2 to exit, and 0 otherwise.
7587*/
7588static int do_meta_command(char *zLine, ShellState *p){
7589  int h = 1;
7590  int nArg = 0;
7591  int n, c;
7592  int rc = 0;
7593  char *azArg[52];
7594
7595#ifndef SQLITE_OMIT_VIRTUALTABLE
7596  if( p->expert.pExpert ){
7597    expertFinish(p, 1, 0);
7598  }
7599#endif
7600
7601  /* Parse the input line into tokens.
7602  */
7603  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7604    while( IsSpace(zLine[h]) ){ h++; }
7605    if( zLine[h]==0 ) break;
7606    if( zLine[h]=='\'' || zLine[h]=='"' ){
7607      int delim = zLine[h++];
7608      azArg[nArg++] = &zLine[h];
7609      while( zLine[h] && zLine[h]!=delim ){
7610        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7611        h++;
7612      }
7613      if( zLine[h]==delim ){
7614        zLine[h++] = 0;
7615      }
7616      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7617    }else{
7618      azArg[nArg++] = &zLine[h];
7619      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7620      if( zLine[h] ) zLine[h++] = 0;
7621      resolve_backslashes(azArg[nArg-1]);
7622    }
7623  }
7624  azArg[nArg] = 0;
7625
7626  /* Process the input line.
7627  */
7628  if( nArg==0 ) return 0; /* no tokens, no error */
7629  n = strlen30(azArg[0]);
7630  c = azArg[0][0];
7631  clearTempFile(p);
7632
7633#ifndef SQLITE_OMIT_AUTHORIZATION
7634  if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
7635    if( nArg!=2 ){
7636      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7637      rc = 1;
7638      goto meta_command_exit;
7639    }
7640    open_db(p, 0);
7641    if( booleanValue(azArg[1]) ){
7642      sqlite3_set_authorizer(p->db, shellAuth, p);
7643    }else if( p->bSafeModePersist ){
7644      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7645    }else{
7646      sqlite3_set_authorizer(p->db, 0, 0);
7647    }
7648  }else
7649#endif
7650
7651#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7652  && !defined(SQLITE_SHELL_FIDDLE)
7653  if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
7654    open_db(p, 0);
7655    failIfSafeMode(p, "cannot run .archive in safe mode");
7656    rc = arDotCommand(p, 0, azArg, nArg);
7657  }else
7658#endif
7659
7660#ifndef SQLITE_SHELL_FIDDLE
7661  if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
7662   || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
7663  ){
7664    const char *zDestFile = 0;
7665    const char *zDb = 0;
7666    sqlite3 *pDest;
7667    sqlite3_backup *pBackup;
7668    int j;
7669    int bAsync = 0;
7670    const char *zVfs = 0;
7671    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7672    for(j=1; j<nArg; j++){
7673      const char *z = azArg[j];
7674      if( z[0]=='-' ){
7675        if( z[1]=='-' ) z++;
7676        if( cli_strcmp(z, "-append")==0 ){
7677          zVfs = "apndvfs";
7678        }else
7679        if( cli_strcmp(z, "-async")==0 ){
7680          bAsync = 1;
7681        }else
7682        {
7683          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7684          return 1;
7685        }
7686      }else if( zDestFile==0 ){
7687        zDestFile = azArg[j];
7688      }else if( zDb==0 ){
7689        zDb = zDestFile;
7690        zDestFile = azArg[j];
7691      }else{
7692        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7693        return 1;
7694      }
7695    }
7696    if( zDestFile==0 ){
7697      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7698      return 1;
7699    }
7700    if( zDb==0 ) zDb = "main";
7701    rc = sqlite3_open_v2(zDestFile, &pDest,
7702                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7703    if( rc!=SQLITE_OK ){
7704      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7705      close_db(pDest);
7706      return 1;
7707    }
7708    if( bAsync ){
7709      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7710                   0, 0, 0);
7711    }
7712    open_db(p, 0);
7713    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7714    if( pBackup==0 ){
7715      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7716      close_db(pDest);
7717      return 1;
7718    }
7719    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7720    sqlite3_backup_finish(pBackup);
7721    if( rc==SQLITE_DONE ){
7722      rc = 0;
7723    }else{
7724      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7725      rc = 1;
7726    }
7727    close_db(pDest);
7728  }else
7729#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7730
7731  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
7732    if( nArg==2 ){
7733      bail_on_error = booleanValue(azArg[1]);
7734    }else{
7735      raw_printf(stderr, "Usage: .bail on|off\n");
7736      rc = 1;
7737    }
7738  }else
7739
7740  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
7741    if( nArg==2 ){
7742      if( booleanValue(azArg[1]) ){
7743        setBinaryMode(p->out, 1);
7744      }else{
7745        setTextMode(p->out, 1);
7746      }
7747    }else{
7748      raw_printf(stderr, "Usage: .binary on|off\n");
7749      rc = 1;
7750    }
7751  }else
7752
7753  /* The undocumented ".breakpoint" command causes a call to the no-op
7754  ** routine named test_breakpoint().
7755  */
7756  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
7757    test_breakpoint();
7758  }else
7759
7760#ifndef SQLITE_SHELL_FIDDLE
7761  if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
7762    failIfSafeMode(p, "cannot run .cd in safe mode");
7763    if( nArg==2 ){
7764#if defined(_WIN32) || defined(WIN32)
7765      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7766      rc = !SetCurrentDirectoryW(z);
7767      sqlite3_free(z);
7768#else
7769      rc = chdir(azArg[1]);
7770#endif
7771      if( rc ){
7772        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7773        rc = 1;
7774      }
7775    }else{
7776      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7777      rc = 1;
7778    }
7779  }else
7780#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7781
7782  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
7783    if( nArg==2 ){
7784      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7785    }else{
7786      raw_printf(stderr, "Usage: .changes on|off\n");
7787      rc = 1;
7788    }
7789  }else
7790
7791#ifndef SQLITE_SHELL_FIDDLE
7792  /* Cancel output redirection, if it is currently set (by .testcase)
7793  ** Then read the content of the testcase-out.txt file and compare against
7794  ** azArg[1].  If there are differences, report an error and exit.
7795  */
7796  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
7797    char *zRes = 0;
7798    output_reset(p);
7799    if( nArg!=2 ){
7800      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7801      rc = 2;
7802    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7803      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7804      rc = 2;
7805    }else if( testcase_glob(azArg[1],zRes)==0 ){
7806      utf8_printf(stderr,
7807                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7808                 p->zTestcase, azArg[1], zRes);
7809      rc = 1;
7810    }else{
7811      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7812      p->nCheck++;
7813    }
7814    sqlite3_free(zRes);
7815  }else
7816#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7817
7818#ifndef SQLITE_SHELL_FIDDLE
7819  if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
7820    failIfSafeMode(p, "cannot run .clone in safe mode");
7821    if( nArg==2 ){
7822      tryToClone(p, azArg[1]);
7823    }else{
7824      raw_printf(stderr, "Usage: .clone FILENAME\n");
7825      rc = 1;
7826    }
7827  }else
7828#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7829
7830  if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
7831    if( nArg==1 ){
7832      /* List available connections */
7833      int i;
7834      for(i=0; i<ArraySize(p->aAuxDb); i++){
7835        const char *zFile = p->aAuxDb[i].zDbFilename;
7836        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7837          zFile = "(not open)";
7838        }else if( zFile==0 ){
7839          zFile = "(memory)";
7840        }else if( zFile[0]==0 ){
7841          zFile = "(temporary-file)";
7842        }
7843        if( p->pAuxDb == &p->aAuxDb[i] ){
7844          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7845        }else if( p->aAuxDb[i].db!=0 ){
7846          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7847        }
7848      }
7849    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7850      int i = azArg[1][0] - '0';
7851      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7852        p->pAuxDb->db = p->db;
7853        p->pAuxDb = &p->aAuxDb[i];
7854        globalDb = p->db = p->pAuxDb->db;
7855        p->pAuxDb->db = 0;
7856      }
7857    }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
7858           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7859      int i = azArg[2][0] - '0';
7860      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7861        /* No-op */
7862      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7863        raw_printf(stderr, "cannot close the active database connection\n");
7864        rc = 1;
7865      }else if( p->aAuxDb[i].db ){
7866        session_close_all(p, i);
7867        close_db(p->aAuxDb[i].db);
7868        p->aAuxDb[i].db = 0;
7869      }
7870    }else{
7871      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7872      rc = 1;
7873    }
7874  }else
7875
7876  if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
7877    char **azName = 0;
7878    int nName = 0;
7879    sqlite3_stmt *pStmt;
7880    int i;
7881    open_db(p, 0);
7882    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7883    if( rc ){
7884      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7885      rc = 1;
7886    }else{
7887      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7888        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7889        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7890        if( zSchema==0 || zFile==0 ) continue;
7891        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7892        shell_check_oom(azName);
7893        azName[nName*2] = strdup(zSchema);
7894        azName[nName*2+1] = strdup(zFile);
7895        nName++;
7896      }
7897    }
7898    sqlite3_finalize(pStmt);
7899    for(i=0; i<nName; i++){
7900      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7901      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7902      const char *z = azName[i*2+1];
7903      utf8_printf(p->out, "%s: %s %s%s\n",
7904         azName[i*2],
7905         z && z[0] ? z : "\"\"",
7906         bRdonly ? "r/o" : "r/w",
7907         eTxn==SQLITE_TXN_NONE ? "" :
7908            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7909      free(azName[i*2]);
7910      free(azName[i*2+1]);
7911    }
7912    sqlite3_free(azName);
7913  }else
7914
7915  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
7916    static const struct DbConfigChoices {
7917      const char *zName;
7918      int op;
7919    } aDbConfig[] = {
7920        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7921        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7922        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7923        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7924        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7925        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7926        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7927        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7928        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7929        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7930        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7931        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7932        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7933        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7934        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7935        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7936    };
7937    int ii, v;
7938    open_db(p, 0);
7939    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7940      if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7941      if( nArg>=3 ){
7942        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7943      }
7944      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7945      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7946      if( nArg>1 ) break;
7947    }
7948    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7949      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7950      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7951    }
7952  }else
7953
7954#if SQLITE_SHELL_HAVE_RECOVER
7955  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
7956    rc = shell_dbinfo_command(p, nArg, azArg);
7957  }else
7958
7959  if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
7960    open_db(p, 0);
7961    rc = recoverDatabaseCmd(p, nArg, azArg);
7962  }else
7963#endif /* SQLITE_SHELL_HAVE_RECOVER */
7964
7965  if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
7966    char *zLike = 0;
7967    char *zSql;
7968    int i;
7969    int savedShowHeader = p->showHeader;
7970    int savedShellFlags = p->shellFlgs;
7971    ShellClearFlag(p,
7972       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7973       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7974    for(i=1; i<nArg; i++){
7975      if( azArg[i][0]=='-' ){
7976        const char *z = azArg[i]+1;
7977        if( z[0]=='-' ) z++;
7978        if( cli_strcmp(z,"preserve-rowids")==0 ){
7979#ifdef SQLITE_OMIT_VIRTUALTABLE
7980          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7981                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7982          rc = 1;
7983          sqlite3_free(zLike);
7984          goto meta_command_exit;
7985#else
7986          ShellSetFlag(p, SHFLG_PreserveRowid);
7987#endif
7988        }else
7989        if( cli_strcmp(z,"newlines")==0 ){
7990          ShellSetFlag(p, SHFLG_Newlines);
7991        }else
7992        if( cli_strcmp(z,"data-only")==0 ){
7993          ShellSetFlag(p, SHFLG_DumpDataOnly);
7994        }else
7995        if( cli_strcmp(z,"nosys")==0 ){
7996          ShellSetFlag(p, SHFLG_DumpNoSys);
7997        }else
7998        {
7999          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8000          rc = 1;
8001          sqlite3_free(zLike);
8002          goto meta_command_exit;
8003        }
8004      }else{
8005        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8006        ** only dump data for tables for which either the table name matches
8007        ** the LIKE pattern, or the table appears to be a shadow table of
8008        ** a virtual table for which the name matches the LIKE pattern.
8009        */
8010        char *zExpr = sqlite3_mprintf(
8011            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8012            "  SELECT 1 FROM sqlite_schema WHERE "
8013            "    name LIKE %Q ESCAPE '\\' AND"
8014            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8015            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8016            ")", azArg[i], azArg[i]
8017        );
8018
8019        if( zLike ){
8020          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8021        }else{
8022          zLike = zExpr;
8023        }
8024      }
8025    }
8026
8027    open_db(p, 0);
8028
8029    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8030      /* When playing back a "dump", the content might appear in an order
8031      ** which causes immediate foreign key constraints to be violated.
8032      ** So disable foreign-key constraint enforcement to prevent problems. */
8033      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8034      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8035    }
8036    p->writableSchema = 0;
8037    p->showHeader = 0;
8038    /* Set writable_schema=ON since doing so forces SQLite to initialize
8039    ** as much of the schema as it can even if the sqlite_schema table is
8040    ** corrupt. */
8041    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8042    p->nErr = 0;
8043    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8044    zSql = sqlite3_mprintf(
8045      "SELECT name, type, sql FROM sqlite_schema AS o "
8046      "WHERE (%s) AND type=='table'"
8047      "  AND sql NOT NULL"
8048      " ORDER BY tbl_name='sqlite_sequence', rowid",
8049      zLike
8050    );
8051    run_schema_dump_query(p,zSql);
8052    sqlite3_free(zSql);
8053    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8054      zSql = sqlite3_mprintf(
8055        "SELECT sql FROM sqlite_schema AS o "
8056        "WHERE (%s) AND sql NOT NULL"
8057        "  AND type IN ('index','trigger','view')",
8058        zLike
8059      );
8060      run_table_dump_query(p, zSql);
8061      sqlite3_free(zSql);
8062    }
8063    sqlite3_free(zLike);
8064    if( p->writableSchema ){
8065      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8066      p->writableSchema = 0;
8067    }
8068    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8069    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8070    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8071      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8072    }
8073    p->showHeader = savedShowHeader;
8074    p->shellFlgs = savedShellFlags;
8075  }else
8076
8077  if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8078    if( nArg==2 ){
8079      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8080    }else{
8081      raw_printf(stderr, "Usage: .echo on|off\n");
8082      rc = 1;
8083    }
8084  }else
8085
8086  if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8087    if( nArg==2 ){
8088      p->autoEQPtest = 0;
8089      if( p->autoEQPtrace ){
8090        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8091        p->autoEQPtrace = 0;
8092      }
8093      if( cli_strcmp(azArg[1],"full")==0 ){
8094        p->autoEQP = AUTOEQP_full;
8095      }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8096        p->autoEQP = AUTOEQP_trigger;
8097#ifdef SQLITE_DEBUG
8098      }else if( cli_strcmp(azArg[1],"test")==0 ){
8099        p->autoEQP = AUTOEQP_on;
8100        p->autoEQPtest = 1;
8101      }else if( cli_strcmp(azArg[1],"trace")==0 ){
8102        p->autoEQP = AUTOEQP_full;
8103        p->autoEQPtrace = 1;
8104        open_db(p, 0);
8105        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8106        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8107#endif
8108      }else{
8109        p->autoEQP = (u8)booleanValue(azArg[1]);
8110      }
8111    }else{
8112      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8113      rc = 1;
8114    }
8115  }else
8116
8117#ifndef SQLITE_SHELL_FIDDLE
8118  if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8119    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8120    rc = 2;
8121  }else
8122#endif
8123
8124  /* The ".explain" command is automatic now.  It is largely pointless.  It
8125  ** retained purely for backwards compatibility */
8126  if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8127    int val = 1;
8128    if( nArg>=2 ){
8129      if( cli_strcmp(azArg[1],"auto")==0 ){
8130        val = 99;
8131      }else{
8132        val =  booleanValue(azArg[1]);
8133      }
8134    }
8135    if( val==1 && p->mode!=MODE_Explain ){
8136      p->normalMode = p->mode;
8137      p->mode = MODE_Explain;
8138      p->autoExplain = 0;
8139    }else if( val==0 ){
8140      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8141      p->autoExplain = 0;
8142    }else if( val==99 ){
8143      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8144      p->autoExplain = 1;
8145    }
8146  }else
8147
8148#ifndef SQLITE_OMIT_VIRTUALTABLE
8149  if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8150    if( p->bSafeMode ){
8151      raw_printf(stderr,
8152        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8153        azArg[0]);
8154      rc = 1;
8155    }else{
8156      open_db(p, 0);
8157      expertDotCommand(p, azArg, nArg);
8158    }
8159  }else
8160#endif
8161
8162  if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8163    static const struct {
8164       const char *zCtrlName;   /* Name of a test-control option */
8165       int ctrlCode;            /* Integer code for that option */
8166       const char *zUsage;      /* Usage notes */
8167    } aCtrl[] = {
8168      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8169      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8170      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8171      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8172      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8173   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8174      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8175      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8176      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8177      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8178   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8179    };
8180    int filectrl = -1;
8181    int iCtrl = -1;
8182    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8183    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8184    int n2, i;
8185    const char *zCmd = 0;
8186    const char *zSchema = 0;
8187
8188    open_db(p, 0);
8189    zCmd = nArg>=2 ? azArg[1] : "help";
8190
8191    if( zCmd[0]=='-'
8192     && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8193     && nArg>=4
8194    ){
8195      zSchema = azArg[2];
8196      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8197      nArg -= 2;
8198      zCmd = azArg[1];
8199    }
8200
8201    /* The argument can optionally begin with "-" or "--" */
8202    if( zCmd[0]=='-' && zCmd[1] ){
8203      zCmd++;
8204      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8205    }
8206
8207    /* --help lists all file-controls */
8208    if( cli_strcmp(zCmd,"help")==0 ){
8209      utf8_printf(p->out, "Available file-controls:\n");
8210      for(i=0; i<ArraySize(aCtrl); i++){
8211        utf8_printf(p->out, "  .filectrl %s %s\n",
8212                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8213      }
8214      rc = 1;
8215      goto meta_command_exit;
8216    }
8217
8218    /* convert filectrl text option to value. allow any unique prefix
8219    ** of the option name, or a numerical value. */
8220    n2 = strlen30(zCmd);
8221    for(i=0; i<ArraySize(aCtrl); i++){
8222      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8223        if( filectrl<0 ){
8224          filectrl = aCtrl[i].ctrlCode;
8225          iCtrl = i;
8226        }else{
8227          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8228                              "Use \".filectrl --help\" for help\n", zCmd);
8229          rc = 1;
8230          goto meta_command_exit;
8231        }
8232      }
8233    }
8234    if( filectrl<0 ){
8235      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8236                         "Use \".filectrl --help\" for help\n", zCmd);
8237    }else{
8238      switch(filectrl){
8239        case SQLITE_FCNTL_SIZE_LIMIT: {
8240          if( nArg!=2 && nArg!=3 ) break;
8241          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8242          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8243          isOk = 1;
8244          break;
8245        }
8246        case SQLITE_FCNTL_LOCK_TIMEOUT:
8247        case SQLITE_FCNTL_CHUNK_SIZE: {
8248          int x;
8249          if( nArg!=3 ) break;
8250          x = (int)integerValue(azArg[2]);
8251          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8252          isOk = 2;
8253          break;
8254        }
8255        case SQLITE_FCNTL_PERSIST_WAL:
8256        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8257          int x;
8258          if( nArg!=2 && nArg!=3 ) break;
8259          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8260          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8261          iRes = x;
8262          isOk = 1;
8263          break;
8264        }
8265        case SQLITE_FCNTL_DATA_VERSION:
8266        case SQLITE_FCNTL_HAS_MOVED: {
8267          int x;
8268          if( nArg!=2 ) break;
8269          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8270          iRes = x;
8271          isOk = 1;
8272          break;
8273        }
8274        case SQLITE_FCNTL_TEMPFILENAME: {
8275          char *z = 0;
8276          if( nArg!=2 ) break;
8277          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8278          if( z ){
8279            utf8_printf(p->out, "%s\n", z);
8280            sqlite3_free(z);
8281          }
8282          isOk = 2;
8283          break;
8284        }
8285        case SQLITE_FCNTL_RESERVE_BYTES: {
8286          int x;
8287          if( nArg>=3 ){
8288            x = atoi(azArg[2]);
8289            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8290          }
8291          x = -1;
8292          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8293          utf8_printf(p->out,"%d\n", x);
8294          isOk = 2;
8295          break;
8296        }
8297      }
8298    }
8299    if( isOk==0 && iCtrl>=0 ){
8300      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8301      rc = 1;
8302    }else if( isOk==1 ){
8303      char zBuf[100];
8304      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8305      raw_printf(p->out, "%s\n", zBuf);
8306    }
8307  }else
8308
8309  if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8310    ShellState data;
8311    int doStats = 0;
8312    memcpy(&data, p, sizeof(data));
8313    data.showHeader = 0;
8314    data.cMode = data.mode = MODE_Semi;
8315    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8316      data.cMode = data.mode = MODE_Pretty;
8317      nArg = 1;
8318    }
8319    if( nArg!=1 ){
8320      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8321      rc = 1;
8322      goto meta_command_exit;
8323    }
8324    open_db(p, 0);
8325    rc = sqlite3_exec(p->db,
8326       "SELECT sql FROM"
8327       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8328       "     FROM sqlite_schema UNION ALL"
8329       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8330       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8331       "ORDER BY x",
8332       callback, &data, 0
8333    );
8334    if( rc==SQLITE_OK ){
8335      sqlite3_stmt *pStmt;
8336      rc = sqlite3_prepare_v2(p->db,
8337               "SELECT rowid FROM sqlite_schema"
8338               " WHERE name GLOB 'sqlite_stat[134]'",
8339               -1, &pStmt, 0);
8340      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8341      sqlite3_finalize(pStmt);
8342    }
8343    if( doStats==0 ){
8344      raw_printf(p->out, "/* No STAT tables available */\n");
8345    }else{
8346      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8347      data.cMode = data.mode = MODE_Insert;
8348      data.zDestTable = "sqlite_stat1";
8349      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8350      data.zDestTable = "sqlite_stat4";
8351      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8352      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8353    }
8354  }else
8355
8356  if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8357    if( nArg==2 ){
8358      p->showHeader = booleanValue(azArg[1]);
8359      p->shellFlgs |= SHFLG_HeaderSet;
8360    }else{
8361      raw_printf(stderr, "Usage: .headers on|off\n");
8362      rc = 1;
8363    }
8364  }else
8365
8366  if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8367    if( nArg>=2 ){
8368      n = showHelp(p->out, azArg[1]);
8369      if( n==0 ){
8370        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8371      }
8372    }else{
8373      showHelp(p->out, 0);
8374    }
8375  }else
8376
8377#ifndef SQLITE_SHELL_FIDDLE
8378  if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8379    char *zTable = 0;           /* Insert data into this table */
8380    char *zSchema = 0;          /* within this schema (may default to "main") */
8381    char *zFile = 0;            /* Name of file to extra content from */
8382    sqlite3_stmt *pStmt = NULL; /* A statement */
8383    int nCol;                   /* Number of columns in the table */
8384    int nByte;                  /* Number of bytes in an SQL string */
8385    int i, j;                   /* Loop counters */
8386    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8387    int nSep;                   /* Number of bytes in p->colSeparator[] */
8388    char *zSql;                 /* An SQL statement */
8389    char *zFullTabName;         /* Table name with schema if applicable */
8390    ImportCtx sCtx;             /* Reader context */
8391    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8392    int eVerbose = 0;           /* Larger for more console output */
8393    int nSkip = 0;              /* Initial lines to skip */
8394    int useOutputMode = 1;      /* Use output mode to determine separators */
8395    char *zCreate = 0;          /* CREATE TABLE statement text */
8396
8397    failIfSafeMode(p, "cannot run .import in safe mode");
8398    memset(&sCtx, 0, sizeof(sCtx));
8399    if( p->mode==MODE_Ascii ){
8400      xRead = ascii_read_one_field;
8401    }else{
8402      xRead = csv_read_one_field;
8403    }
8404    rc = 1;
8405    for(i=1; i<nArg; i++){
8406      char *z = azArg[i];
8407      if( z[0]=='-' && z[1]=='-' ) z++;
8408      if( z[0]!='-' ){
8409        if( zFile==0 ){
8410          zFile = z;
8411        }else if( zTable==0 ){
8412          zTable = z;
8413        }else{
8414          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8415          showHelp(p->out, "import");
8416          goto meta_command_exit;
8417        }
8418      }else if( cli_strcmp(z,"-v")==0 ){
8419        eVerbose++;
8420      }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8421        zSchema = azArg[++i];
8422      }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8423        nSkip = integerValue(azArg[++i]);
8424      }else if( cli_strcmp(z,"-ascii")==0 ){
8425        sCtx.cColSep = SEP_Unit[0];
8426        sCtx.cRowSep = SEP_Record[0];
8427        xRead = ascii_read_one_field;
8428        useOutputMode = 0;
8429      }else if( cli_strcmp(z,"-csv")==0 ){
8430        sCtx.cColSep = ',';
8431        sCtx.cRowSep = '\n';
8432        xRead = csv_read_one_field;
8433        useOutputMode = 0;
8434      }else{
8435        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8436        showHelp(p->out, "import");
8437        goto meta_command_exit;
8438      }
8439    }
8440    if( zTable==0 ){
8441      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8442                  zFile==0 ? "FILE" : "TABLE");
8443      showHelp(p->out, "import");
8444      goto meta_command_exit;
8445    }
8446    seenInterrupt = 0;
8447    open_db(p, 0);
8448    if( useOutputMode ){
8449      /* If neither the --csv or --ascii options are specified, then set
8450      ** the column and row separator characters from the output mode. */
8451      nSep = strlen30(p->colSeparator);
8452      if( nSep==0 ){
8453        raw_printf(stderr,
8454                   "Error: non-null column separator required for import\n");
8455        goto meta_command_exit;
8456      }
8457      if( nSep>1 ){
8458        raw_printf(stderr,
8459              "Error: multi-character column separators not allowed"
8460              " for import\n");
8461        goto meta_command_exit;
8462      }
8463      nSep = strlen30(p->rowSeparator);
8464      if( nSep==0 ){
8465        raw_printf(stderr,
8466            "Error: non-null row separator required for import\n");
8467        goto meta_command_exit;
8468      }
8469      if( nSep==2 && p->mode==MODE_Csv
8470       && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8471      ){
8472        /* When importing CSV (only), if the row separator is set to the
8473        ** default output row separator, change it to the default input
8474        ** row separator.  This avoids having to maintain different input
8475        ** and output row separators. */
8476        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8477        nSep = strlen30(p->rowSeparator);
8478      }
8479      if( nSep>1 ){
8480        raw_printf(stderr, "Error: multi-character row separators not allowed"
8481                           " for import\n");
8482        goto meta_command_exit;
8483      }
8484      sCtx.cColSep = p->colSeparator[0];
8485      sCtx.cRowSep = p->rowSeparator[0];
8486    }
8487    sCtx.zFile = zFile;
8488    sCtx.nLine = 1;
8489    if( sCtx.zFile[0]=='|' ){
8490#ifdef SQLITE_OMIT_POPEN
8491      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8492      goto meta_command_exit;
8493#else
8494      sCtx.in = popen(sCtx.zFile+1, "r");
8495      sCtx.zFile = "<pipe>";
8496      sCtx.xCloser = pclose;
8497#endif
8498    }else{
8499      sCtx.in = fopen(sCtx.zFile, "rb");
8500      sCtx.xCloser = fclose;
8501    }
8502    if( sCtx.in==0 ){
8503      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8504      goto meta_command_exit;
8505    }
8506    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8507      char zSep[2];
8508      zSep[1] = 0;
8509      zSep[0] = sCtx.cColSep;
8510      utf8_printf(p->out, "Column separator ");
8511      output_c_string(p->out, zSep);
8512      utf8_printf(p->out, ", row separator ");
8513      zSep[0] = sCtx.cRowSep;
8514      output_c_string(p->out, zSep);
8515      utf8_printf(p->out, "\n");
8516    }
8517    sCtx.z = sqlite3_malloc64(120);
8518    if( sCtx.z==0 ){
8519      import_cleanup(&sCtx);
8520      shell_out_of_memory();
8521    }
8522    /* Below, resources must be freed before exit. */
8523    while( (nSkip--)>0 ){
8524      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8525    }
8526    if( zSchema!=0 ){
8527      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8528    }else{
8529      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8530    }
8531    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8532    if( zSql==0 || zFullTabName==0 ){
8533      import_cleanup(&sCtx);
8534      shell_out_of_memory();
8535    }
8536    nByte = strlen30(zSql);
8537    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8538    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8539    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8540      sqlite3 *dbCols = 0;
8541      char *zRenames = 0;
8542      char *zColDefs;
8543      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8544      while( xRead(&sCtx) ){
8545        zAutoColumn(sCtx.z, &dbCols, 0);
8546        if( sCtx.cTerm!=sCtx.cColSep ) break;
8547      }
8548      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8549      if( zRenames!=0 ){
8550        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8551                    "Columns renamed during .import %s due to duplicates:\n"
8552                    "%s\n", sCtx.zFile, zRenames);
8553        sqlite3_free(zRenames);
8554      }
8555      assert(dbCols==0);
8556      if( zColDefs==0 ){
8557        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8558      import_fail:
8559        sqlite3_free(zCreate);
8560        sqlite3_free(zSql);
8561        sqlite3_free(zFullTabName);
8562        import_cleanup(&sCtx);
8563        rc = 1;
8564        goto meta_command_exit;
8565      }
8566      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8567      if( eVerbose>=1 ){
8568        utf8_printf(p->out, "%s\n", zCreate);
8569      }
8570      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8571      if( rc ){
8572        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8573        goto import_fail;
8574      }
8575      sqlite3_free(zCreate);
8576      zCreate = 0;
8577      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8578    }
8579    if( rc ){
8580      if (pStmt) sqlite3_finalize(pStmt);
8581      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8582      goto import_fail;
8583    }
8584    sqlite3_free(zSql);
8585    nCol = sqlite3_column_count(pStmt);
8586    sqlite3_finalize(pStmt);
8587    pStmt = 0;
8588    if( nCol==0 ) return 0; /* no columns, no error */
8589    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8590    if( zSql==0 ){
8591      import_cleanup(&sCtx);
8592      shell_out_of_memory();
8593    }
8594    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8595    j = strlen30(zSql);
8596    for(i=1; i<nCol; i++){
8597      zSql[j++] = ',';
8598      zSql[j++] = '?';
8599    }
8600    zSql[j++] = ')';
8601    zSql[j] = 0;
8602    if( eVerbose>=2 ){
8603      utf8_printf(p->out, "Insert using: %s\n", zSql);
8604    }
8605    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8606    if( rc ){
8607      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8608      if (pStmt) sqlite3_finalize(pStmt);
8609      goto import_fail;
8610    }
8611    sqlite3_free(zSql);
8612    sqlite3_free(zFullTabName);
8613    needCommit = sqlite3_get_autocommit(p->db);
8614    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8615    do{
8616      int startLine = sCtx.nLine;
8617      for(i=0; i<nCol; i++){
8618        char *z = xRead(&sCtx);
8619        /*
8620        ** Did we reach end-of-file before finding any columns?
8621        ** If so, stop instead of NULL filling the remaining columns.
8622        */
8623        if( z==0 && i==0 ) break;
8624        /*
8625        ** Did we reach end-of-file OR end-of-line before finding any
8626        ** columns in ASCII mode?  If so, stop instead of NULL filling
8627        ** the remaining columns.
8628        */
8629        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8630        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8631        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8632          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8633                          "filling the rest with NULL\n",
8634                          sCtx.zFile, startLine, nCol, i+1);
8635          i += 2;
8636          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8637        }
8638      }
8639      if( sCtx.cTerm==sCtx.cColSep ){
8640        do{
8641          xRead(&sCtx);
8642          i++;
8643        }while( sCtx.cTerm==sCtx.cColSep );
8644        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8645                        "extras ignored\n",
8646                        sCtx.zFile, startLine, nCol, i);
8647      }
8648      if( i>=nCol ){
8649        sqlite3_step(pStmt);
8650        rc = sqlite3_reset(pStmt);
8651        if( rc!=SQLITE_OK ){
8652          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8653                      startLine, sqlite3_errmsg(p->db));
8654          sCtx.nErr++;
8655        }else{
8656          sCtx.nRow++;
8657        }
8658      }
8659    }while( sCtx.cTerm!=EOF );
8660
8661    import_cleanup(&sCtx);
8662    sqlite3_finalize(pStmt);
8663    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8664    if( eVerbose>0 ){
8665      utf8_printf(p->out,
8666          "Added %d rows with %d errors using %d lines of input\n",
8667          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8668    }
8669  }else
8670#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8671
8672#ifndef SQLITE_UNTESTABLE
8673  if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
8674    char *zSql;
8675    char *zCollist = 0;
8676    sqlite3_stmt *pStmt;
8677    int tnum = 0;
8678    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8679    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8680    int i;
8681    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8682      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8683                          "       .imposter off\n");
8684      /* Also allowed, but not documented:
8685      **
8686      **    .imposter TABLE IMPOSTER
8687      **
8688      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8689      ** imposter is another WITHOUT ROWID table with the columns in
8690      ** storage order. */
8691      rc = 1;
8692      goto meta_command_exit;
8693    }
8694    open_db(p, 0);
8695    if( nArg==2 ){
8696      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8697      goto meta_command_exit;
8698    }
8699    zSql = sqlite3_mprintf(
8700      "SELECT rootpage, 0 FROM sqlite_schema"
8701      " WHERE name='%q' AND type='index'"
8702      "UNION ALL "
8703      "SELECT rootpage, 1 FROM sqlite_schema"
8704      " WHERE name='%q' AND type='table'"
8705      "   AND sql LIKE '%%without%%rowid%%'",
8706      azArg[1], azArg[1]
8707    );
8708    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8709    sqlite3_free(zSql);
8710    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8711      tnum = sqlite3_column_int(pStmt, 0);
8712      isWO = sqlite3_column_int(pStmt, 1);
8713    }
8714    sqlite3_finalize(pStmt);
8715    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8716    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8717    sqlite3_free(zSql);
8718    i = 0;
8719    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8720      char zLabel[20];
8721      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8722      i++;
8723      if( zCol==0 ){
8724        if( sqlite3_column_int(pStmt,1)==-1 ){
8725          zCol = "_ROWID_";
8726        }else{
8727          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8728          zCol = zLabel;
8729        }
8730      }
8731      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8732        lenPK = (int)strlen(zCollist);
8733      }
8734      if( zCollist==0 ){
8735        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8736      }else{
8737        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8738      }
8739    }
8740    sqlite3_finalize(pStmt);
8741    if( i==0 || tnum==0 ){
8742      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8743      rc = 1;
8744      sqlite3_free(zCollist);
8745      goto meta_command_exit;
8746    }
8747    if( lenPK==0 ) lenPK = 100000;
8748    zSql = sqlite3_mprintf(
8749          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8750          azArg[2], zCollist, lenPK, zCollist);
8751    sqlite3_free(zCollist);
8752    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8753    if( rc==SQLITE_OK ){
8754      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8755      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8756      if( rc ){
8757        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8758      }else{
8759        utf8_printf(stdout, "%s;\n", zSql);
8760        raw_printf(stdout,
8761          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8762          azArg[1], isWO ? "table" : "index"
8763        );
8764      }
8765    }else{
8766      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8767      rc = 1;
8768    }
8769    sqlite3_free(zSql);
8770  }else
8771#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8772
8773#ifdef SQLITE_ENABLE_IOTRACE
8774  if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
8775    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8776    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8777    iotrace = 0;
8778    if( nArg<2 ){
8779      sqlite3IoTrace = 0;
8780    }else if( cli_strcmp(azArg[1], "-")==0 ){
8781      sqlite3IoTrace = iotracePrintf;
8782      iotrace = stdout;
8783    }else{
8784      iotrace = fopen(azArg[1], "w");
8785      if( iotrace==0 ){
8786        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8787        sqlite3IoTrace = 0;
8788        rc = 1;
8789      }else{
8790        sqlite3IoTrace = iotracePrintf;
8791      }
8792    }
8793  }else
8794#endif
8795
8796  if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
8797    static const struct {
8798       const char *zLimitName;   /* Name of a limit */
8799       int limitCode;            /* Integer code for that limit */
8800    } aLimit[] = {
8801      { "length",                SQLITE_LIMIT_LENGTH                    },
8802      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8803      { "column",                SQLITE_LIMIT_COLUMN                    },
8804      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8805      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8806      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8807      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8808      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8809      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8810      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8811      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8812      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8813    };
8814    int i, n2;
8815    open_db(p, 0);
8816    if( nArg==1 ){
8817      for(i=0; i<ArraySize(aLimit); i++){
8818        printf("%20s %d\n", aLimit[i].zLimitName,
8819               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8820      }
8821    }else if( nArg>3 ){
8822      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8823      rc = 1;
8824      goto meta_command_exit;
8825    }else{
8826      int iLimit = -1;
8827      n2 = strlen30(azArg[1]);
8828      for(i=0; i<ArraySize(aLimit); i++){
8829        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8830          if( iLimit<0 ){
8831            iLimit = i;
8832          }else{
8833            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8834            rc = 1;
8835            goto meta_command_exit;
8836          }
8837        }
8838      }
8839      if( iLimit<0 ){
8840        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8841                        "enter \".limits\" with no arguments for a list.\n",
8842                         azArg[1]);
8843        rc = 1;
8844        goto meta_command_exit;
8845      }
8846      if( nArg==3 ){
8847        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8848                      (int)integerValue(azArg[2]));
8849      }
8850      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8851             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8852    }
8853  }else
8854
8855  if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
8856    open_db(p, 0);
8857    lintDotCommand(p, azArg, nArg);
8858  }else
8859
8860#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
8861  if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
8862    const char *zFile, *zProc;
8863    char *zErrMsg = 0;
8864    failIfSafeMode(p, "cannot run .load in safe mode");
8865    if( nArg<2 ){
8866      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8867      rc = 1;
8868      goto meta_command_exit;
8869    }
8870    zFile = azArg[1];
8871    zProc = nArg>=3 ? azArg[2] : 0;
8872    open_db(p, 0);
8873    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8874    if( rc!=SQLITE_OK ){
8875      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8876      sqlite3_free(zErrMsg);
8877      rc = 1;
8878    }
8879  }else
8880#endif
8881
8882#ifndef SQLITE_SHELL_FIDDLE
8883  if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
8884    failIfSafeMode(p, "cannot run .log in safe mode");
8885    if( nArg!=2 ){
8886      raw_printf(stderr, "Usage: .log FILENAME\n");
8887      rc = 1;
8888    }else{
8889      const char *zFile = azArg[1];
8890      output_file_close(p->pLog);
8891      p->pLog = output_file_open(zFile, 0);
8892    }
8893  }else
8894#endif
8895
8896  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
8897    const char *zMode = 0;
8898    const char *zTabname = 0;
8899    int i, n2;
8900    ColModeOpts cmOpts = ColModeOpts_default;
8901    for(i=1; i<nArg; i++){
8902      const char *z = azArg[i];
8903      if( optionMatch(z,"wrap") && i+1<nArg ){
8904        cmOpts.iWrap = integerValue(azArg[++i]);
8905      }else if( optionMatch(z,"ww") ){
8906        cmOpts.bWordWrap = 1;
8907      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
8908        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
8909      }else if( optionMatch(z,"quote") ){
8910        cmOpts.bQuote = 1;
8911      }else if( optionMatch(z,"noquote") ){
8912        cmOpts.bQuote = 0;
8913      }else if( zMode==0 ){
8914        zMode = z;
8915        /* Apply defaults for qbox pseudo-mode.  If that
8916         * overwrites already-set values, user was informed of this.
8917         */
8918        if( cli_strcmp(z, "qbox")==0 ){
8919          ColModeOpts cmo = ColModeOpts_default_qbox;
8920          zMode = "box";
8921          cmOpts = cmo;
8922        }
8923      }else if( zTabname==0 ){
8924        zTabname = z;
8925      }else if( z[0]=='-' ){
8926        utf8_printf(stderr, "unknown option: %s\n", z);
8927        utf8_printf(stderr, "options:\n"
8928                            "  --noquote\n"
8929                            "  --quote\n"
8930                            "  --wordwrap on/off\n"
8931                            "  --wrap N\n"
8932                            "  --ww\n");
8933        rc = 1;
8934        goto meta_command_exit;
8935      }else{
8936        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8937        rc = 1;
8938        goto meta_command_exit;
8939      }
8940    }
8941    if( zMode==0 ){
8942      if( p->mode==MODE_Column
8943       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
8944      ){
8945        raw_printf
8946          (p->out,
8947           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
8948           modeDescr[p->mode], p->cmOpts.iWrap,
8949           p->cmOpts.bWordWrap ? "on" : "off",
8950           p->cmOpts.bQuote ? "" : "no");
8951      }else{
8952        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8953      }
8954      zMode = modeDescr[p->mode];
8955    }
8956    n2 = strlen30(zMode);
8957    if( cli_strncmp(zMode,"lines",n2)==0 ){
8958      p->mode = MODE_Line;
8959      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8960    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
8961      p->mode = MODE_Column;
8962      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8963        p->showHeader = 1;
8964      }
8965      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8966      p->cmOpts = cmOpts;
8967    }else if( cli_strncmp(zMode,"list",n2)==0 ){
8968      p->mode = MODE_List;
8969      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8970      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8971    }else if( cli_strncmp(zMode,"html",n2)==0 ){
8972      p->mode = MODE_Html;
8973    }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
8974      p->mode = MODE_Tcl;
8975      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8976      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8977    }else if( cli_strncmp(zMode,"csv",n2)==0 ){
8978      p->mode = MODE_Csv;
8979      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8980      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8981    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
8982      p->mode = MODE_List;
8983      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8984    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
8985      p->mode = MODE_Insert;
8986      set_table_name(p, zTabname ? zTabname : "table");
8987    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
8988      p->mode = MODE_Quote;
8989      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8990      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8991    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
8992      p->mode = MODE_Ascii;
8993      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8994      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8995    }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
8996      p->mode = MODE_Markdown;
8997      p->cmOpts = cmOpts;
8998    }else if( cli_strncmp(zMode,"table",n2)==0 ){
8999      p->mode = MODE_Table;
9000      p->cmOpts = cmOpts;
9001    }else if( cli_strncmp(zMode,"box",n2)==0 ){
9002      p->mode = MODE_Box;
9003      p->cmOpts = cmOpts;
9004    }else if( cli_strncmp(zMode,"count",n2)==0 ){
9005      p->mode = MODE_Count;
9006    }else if( cli_strncmp(zMode,"off",n2)==0 ){
9007      p->mode = MODE_Off;
9008    }else if( cli_strncmp(zMode,"json",n2)==0 ){
9009      p->mode = MODE_Json;
9010    }else{
9011      raw_printf(stderr, "Error: mode should be one of: "
9012         "ascii box column csv html insert json line list markdown "
9013         "qbox quote table tabs tcl\n");
9014      rc = 1;
9015    }
9016    p->cMode = p->mode;
9017  }else
9018
9019#ifndef SQLITE_SHELL_FIDDLE
9020  if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9021    if( nArg!=2 ){
9022      raw_printf(stderr, "Usage: .nonce NONCE\n");
9023      rc = 1;
9024    }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9025      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9026                 p->lineno, azArg[1]);
9027      exit(1);
9028    }else{
9029      p->bSafeMode = 0;
9030      return 0;  /* Return immediately to bypass the safe mode reset
9031                 ** at the end of this procedure */
9032    }
9033  }else
9034#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9035
9036  if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9037    if( nArg==2 ){
9038      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9039                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9040    }else{
9041      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9042      rc = 1;
9043    }
9044  }else
9045
9046  if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9047    const char *zFN = 0;     /* Pointer to constant filename */
9048    char *zNewFilename = 0;  /* Name of the database file to open */
9049    int iName = 1;           /* Index in azArg[] of the filename */
9050    int newFlag = 0;         /* True to delete file before opening */
9051    int openMode = SHELL_OPEN_UNSPEC;
9052
9053    /* Check for command-line arguments */
9054    for(iName=1; iName<nArg; iName++){
9055      const char *z = azArg[iName];
9056#ifndef SQLITE_SHELL_FIDDLE
9057      if( optionMatch(z,"new") ){
9058        newFlag = 1;
9059#ifdef SQLITE_HAVE_ZLIB
9060      }else if( optionMatch(z, "zip") ){
9061        openMode = SHELL_OPEN_ZIPFILE;
9062#endif
9063      }else if( optionMatch(z, "append") ){
9064        openMode = SHELL_OPEN_APPENDVFS;
9065      }else if( optionMatch(z, "readonly") ){
9066        openMode = SHELL_OPEN_READONLY;
9067      }else if( optionMatch(z, "nofollow") ){
9068        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9069#ifndef SQLITE_OMIT_DESERIALIZE
9070      }else if( optionMatch(z, "deserialize") ){
9071        openMode = SHELL_OPEN_DESERIALIZE;
9072      }else if( optionMatch(z, "hexdb") ){
9073        openMode = SHELL_OPEN_HEXDB;
9074      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9075        p->szMax = integerValue(azArg[++iName]);
9076#endif /* SQLITE_OMIT_DESERIALIZE */
9077      }else
9078#endif /* !SQLITE_SHELL_FIDDLE */
9079      if( z[0]=='-' ){
9080        utf8_printf(stderr, "unknown option: %s\n", z);
9081        rc = 1;
9082        goto meta_command_exit;
9083      }else if( zFN ){
9084        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9085        rc = 1;
9086        goto meta_command_exit;
9087      }else{
9088        zFN = z;
9089      }
9090    }
9091
9092    /* Close the existing database */
9093    session_close_all(p, -1);
9094    close_db(p->db);
9095    p->db = 0;
9096    p->pAuxDb->zDbFilename = 0;
9097    sqlite3_free(p->pAuxDb->zFreeOnClose);
9098    p->pAuxDb->zFreeOnClose = 0;
9099    p->openMode = openMode;
9100    p->openFlags = 0;
9101    p->szMax = 0;
9102
9103    /* If a filename is specified, try to open it first */
9104    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9105      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9106#ifndef SQLITE_SHELL_FIDDLE
9107      if( p->bSafeMode
9108       && p->openMode!=SHELL_OPEN_HEXDB
9109       && zFN
9110       && cli_strcmp(zFN,":memory:")!=0
9111      ){
9112        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9113      }
9114#else
9115      /* WASM mode has its own sandboxed pseudo-filesystem. */
9116#endif
9117      if( zFN ){
9118        zNewFilename = sqlite3_mprintf("%s", zFN);
9119        shell_check_oom(zNewFilename);
9120      }else{
9121        zNewFilename = 0;
9122      }
9123      p->pAuxDb->zDbFilename = zNewFilename;
9124      open_db(p, OPEN_DB_KEEPALIVE);
9125      if( p->db==0 ){
9126        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9127        sqlite3_free(zNewFilename);
9128      }else{
9129        p->pAuxDb->zFreeOnClose = zNewFilename;
9130      }
9131    }
9132    if( p->db==0 ){
9133      /* As a fall-back open a TEMP database */
9134      p->pAuxDb->zDbFilename = 0;
9135      open_db(p, 0);
9136    }
9137  }else
9138
9139#ifndef SQLITE_SHELL_FIDDLE
9140  if( (c=='o'
9141        && (cli_strncmp(azArg[0], "output", n)==0
9142            || cli_strncmp(azArg[0], "once", n)==0))
9143   || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9144  ){
9145    char *zFile = 0;
9146    int bTxtMode = 0;
9147    int i;
9148    int eMode = 0;
9149    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9150    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9151
9152    zBOM[0] = 0;
9153    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9154    if( c=='e' ){
9155      eMode = 'x';
9156      bOnce = 2;
9157    }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9158      bOnce = 1;
9159    }
9160    for(i=1; i<nArg; i++){
9161      char *z = azArg[i];
9162      if( z[0]=='-' ){
9163        if( z[1]=='-' ) z++;
9164        if( cli_strcmp(z,"-bom")==0 ){
9165          zBOM[0] = 0xef;
9166          zBOM[1] = 0xbb;
9167          zBOM[2] = 0xbf;
9168          zBOM[3] = 0;
9169        }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9170          eMode = 'x';  /* spreadsheet */
9171        }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9172          eMode = 'e';  /* text editor */
9173        }else{
9174          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9175                      azArg[i]);
9176          showHelp(p->out, azArg[0]);
9177          rc = 1;
9178          goto meta_command_exit;
9179        }
9180      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9181        zFile = sqlite3_mprintf("%s", z);
9182        if( zFile && zFile[0]=='|' ){
9183          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9184          break;
9185        }
9186      }else{
9187        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9188                    azArg[i]);
9189        showHelp(p->out, azArg[0]);
9190        rc = 1;
9191        sqlite3_free(zFile);
9192        goto meta_command_exit;
9193      }
9194    }
9195    if( zFile==0 ){
9196      zFile = sqlite3_mprintf("stdout");
9197    }
9198    if( bOnce ){
9199      p->outCount = 2;
9200    }else{
9201      p->outCount = 0;
9202    }
9203    output_reset(p);
9204#ifndef SQLITE_NOHAVE_SYSTEM
9205    if( eMode=='e' || eMode=='x' ){
9206      p->doXdgOpen = 1;
9207      outputModePush(p);
9208      if( eMode=='x' ){
9209        /* spreadsheet mode.  Output as CSV. */
9210        newTempFile(p, "csv");
9211        ShellClearFlag(p, SHFLG_Echo);
9212        p->mode = MODE_Csv;
9213        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9214        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9215      }else{
9216        /* text editor mode */
9217        newTempFile(p, "txt");
9218        bTxtMode = 1;
9219      }
9220      sqlite3_free(zFile);
9221      zFile = sqlite3_mprintf("%s", p->zTempFile);
9222    }
9223#endif /* SQLITE_NOHAVE_SYSTEM */
9224    shell_check_oom(zFile);
9225    if( zFile[0]=='|' ){
9226#ifdef SQLITE_OMIT_POPEN
9227      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9228      rc = 1;
9229      p->out = stdout;
9230#else
9231      p->out = popen(zFile + 1, "w");
9232      if( p->out==0 ){
9233        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9234        p->out = stdout;
9235        rc = 1;
9236      }else{
9237        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9238        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9239      }
9240#endif
9241    }else{
9242      p->out = output_file_open(zFile, bTxtMode);
9243      if( p->out==0 ){
9244        if( cli_strcmp(zFile,"off")!=0 ){
9245          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9246        }
9247        p->out = stdout;
9248        rc = 1;
9249      } else {
9250        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9251        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9252      }
9253    }
9254    sqlite3_free(zFile);
9255  }else
9256#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9257
9258  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9259    open_db(p,0);
9260    if( nArg<=1 ) goto parameter_syntax_error;
9261
9262    /* .parameter clear
9263    ** Clear all bind parameters by dropping the TEMP table that holds them.
9264    */
9265    if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9266      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9267                   0, 0, 0);
9268    }else
9269
9270    /* .parameter list
9271    ** List all bind parameters.
9272    */
9273    if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9274      sqlite3_stmt *pStmt = 0;
9275      int rx;
9276      int len = 0;
9277      rx = sqlite3_prepare_v2(p->db,
9278             "SELECT max(length(key)) "
9279             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9280      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9281        len = sqlite3_column_int(pStmt, 0);
9282        if( len>40 ) len = 40;
9283      }
9284      sqlite3_finalize(pStmt);
9285      pStmt = 0;
9286      if( len ){
9287        rx = sqlite3_prepare_v2(p->db,
9288             "SELECT key, quote(value) "
9289             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9290        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9291          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9292                      sqlite3_column_text(pStmt,1));
9293        }
9294        sqlite3_finalize(pStmt);
9295      }
9296    }else
9297
9298    /* .parameter init
9299    ** Make sure the TEMP table used to hold bind parameters exists.
9300    ** Create it if necessary.
9301    */
9302    if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9303      bind_table_init(p);
9304    }else
9305
9306    /* .parameter set NAME VALUE
9307    ** Set or reset a bind parameter.  NAME should be the full parameter
9308    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9309    ** VALUE can be in either SQL literal notation, or if not it will be
9310    ** understood to be a text string.
9311    */
9312    if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9313      int rx;
9314      char *zSql;
9315      sqlite3_stmt *pStmt;
9316      const char *zKey = azArg[2];
9317      const char *zValue = azArg[3];
9318      bind_table_init(p);
9319      zSql = sqlite3_mprintf(
9320                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9321                  "VALUES(%Q,%s);", zKey, zValue);
9322      shell_check_oom(zSql);
9323      pStmt = 0;
9324      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9325      sqlite3_free(zSql);
9326      if( rx!=SQLITE_OK ){
9327        sqlite3_finalize(pStmt);
9328        pStmt = 0;
9329        zSql = sqlite3_mprintf(
9330                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9331                   "VALUES(%Q,%Q);", zKey, zValue);
9332        shell_check_oom(zSql);
9333        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9334        sqlite3_free(zSql);
9335        if( rx!=SQLITE_OK ){
9336          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9337          sqlite3_finalize(pStmt);
9338          pStmt = 0;
9339          rc = 1;
9340        }
9341      }
9342      sqlite3_step(pStmt);
9343      sqlite3_finalize(pStmt);
9344    }else
9345
9346    /* .parameter unset NAME
9347    ** Remove the NAME binding from the parameter binding table, if it
9348    ** exists.
9349    */
9350    if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9351      char *zSql = sqlite3_mprintf(
9352          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9353      shell_check_oom(zSql);
9354      sqlite3_exec(p->db, zSql, 0, 0, 0);
9355      sqlite3_free(zSql);
9356    }else
9357    /* If no command name matches, show a syntax error */
9358    parameter_syntax_error:
9359    showHelp(p->out, "parameter");
9360  }else
9361
9362  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9363    int i;
9364    for(i=1; i<nArg; i++){
9365      if( i>1 ) raw_printf(p->out, " ");
9366      utf8_printf(p->out, "%s", azArg[i]);
9367    }
9368    raw_printf(p->out, "\n");
9369  }else
9370
9371#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9372  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9373    int i;
9374    int nn = 0;
9375    p->flgProgress = 0;
9376    p->mxProgress = 0;
9377    p->nProgress = 0;
9378    for(i=1; i<nArg; i++){
9379      const char *z = azArg[i];
9380      if( z[0]=='-' ){
9381        z++;
9382        if( z[0]=='-' ) z++;
9383        if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9384          p->flgProgress |= SHELL_PROGRESS_QUIET;
9385          continue;
9386        }
9387        if( cli_strcmp(z,"reset")==0 ){
9388          p->flgProgress |= SHELL_PROGRESS_RESET;
9389          continue;
9390        }
9391        if( cli_strcmp(z,"once")==0 ){
9392          p->flgProgress |= SHELL_PROGRESS_ONCE;
9393          continue;
9394        }
9395        if( cli_strcmp(z,"limit")==0 ){
9396          if( i+1>=nArg ){
9397            utf8_printf(stderr, "Error: missing argument on --limit\n");
9398            rc = 1;
9399            goto meta_command_exit;
9400          }else{
9401            p->mxProgress = (int)integerValue(azArg[++i]);
9402          }
9403          continue;
9404        }
9405        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9406        rc = 1;
9407        goto meta_command_exit;
9408      }else{
9409        nn = (int)integerValue(z);
9410      }
9411    }
9412    open_db(p, 0);
9413    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9414  }else
9415#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9416
9417  if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9418    if( nArg >= 2) {
9419      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9420    }
9421    if( nArg >= 3) {
9422      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9423    }
9424  }else
9425
9426#ifndef SQLITE_SHELL_FIDDLE
9427  if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9428    rc = 2;
9429  }else
9430#endif
9431
9432#ifndef SQLITE_SHELL_FIDDLE
9433  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9434    FILE *inSaved = p->in;
9435    int savedLineno = p->lineno;
9436    failIfSafeMode(p, "cannot run .read in safe mode");
9437    if( nArg!=2 ){
9438      raw_printf(stderr, "Usage: .read FILE\n");
9439      rc = 1;
9440      goto meta_command_exit;
9441    }
9442    if( azArg[1][0]=='|' ){
9443#ifdef SQLITE_OMIT_POPEN
9444      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9445      rc = 1;
9446      p->out = stdout;
9447#else
9448      p->in = popen(azArg[1]+1, "r");
9449      if( p->in==0 ){
9450        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9451        rc = 1;
9452      }else{
9453        rc = process_input(p);
9454        pclose(p->in);
9455      }
9456#endif
9457    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9458      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9459      rc = 1;
9460    }else{
9461      rc = process_input(p);
9462      fclose(p->in);
9463    }
9464    p->in = inSaved;
9465    p->lineno = savedLineno;
9466  }else
9467#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9468
9469#ifndef SQLITE_SHELL_FIDDLE
9470  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9471    const char *zSrcFile;
9472    const char *zDb;
9473    sqlite3 *pSrc;
9474    sqlite3_backup *pBackup;
9475    int nTimeout = 0;
9476
9477    failIfSafeMode(p, "cannot run .restore in safe mode");
9478    if( nArg==2 ){
9479      zSrcFile = azArg[1];
9480      zDb = "main";
9481    }else if( nArg==3 ){
9482      zSrcFile = azArg[2];
9483      zDb = azArg[1];
9484    }else{
9485      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9486      rc = 1;
9487      goto meta_command_exit;
9488    }
9489    rc = sqlite3_open(zSrcFile, &pSrc);
9490    if( rc!=SQLITE_OK ){
9491      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9492      close_db(pSrc);
9493      return 1;
9494    }
9495    open_db(p, 0);
9496    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9497    if( pBackup==0 ){
9498      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9499      close_db(pSrc);
9500      return 1;
9501    }
9502    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9503          || rc==SQLITE_BUSY  ){
9504      if( rc==SQLITE_BUSY ){
9505        if( nTimeout++ >= 3 ) break;
9506        sqlite3_sleep(100);
9507      }
9508    }
9509    sqlite3_backup_finish(pBackup);
9510    if( rc==SQLITE_DONE ){
9511      rc = 0;
9512    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9513      raw_printf(stderr, "Error: source database is busy\n");
9514      rc = 1;
9515    }else{
9516      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9517      rc = 1;
9518    }
9519    close_db(pSrc);
9520  }else
9521#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9522
9523  if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9524    if( nArg==2 ){
9525      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9526#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9527      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9528#endif
9529    }else{
9530      raw_printf(stderr, "Usage: .scanstats on|off\n");
9531      rc = 1;
9532    }
9533  }else
9534
9535  if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
9536    ShellText sSelect;
9537    ShellState data;
9538    char *zErrMsg = 0;
9539    const char *zDiv = "(";
9540    const char *zName = 0;
9541    int iSchema = 0;
9542    int bDebug = 0;
9543    int bNoSystemTabs = 0;
9544    int ii;
9545
9546    open_db(p, 0);
9547    memcpy(&data, p, sizeof(data));
9548    data.showHeader = 0;
9549    data.cMode = data.mode = MODE_Semi;
9550    initText(&sSelect);
9551    for(ii=1; ii<nArg; ii++){
9552      if( optionMatch(azArg[ii],"indent") ){
9553        data.cMode = data.mode = MODE_Pretty;
9554      }else if( optionMatch(azArg[ii],"debug") ){
9555        bDebug = 1;
9556      }else if( optionMatch(azArg[ii],"nosys") ){
9557        bNoSystemTabs = 1;
9558      }else if( azArg[ii][0]=='-' ){
9559        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9560        rc = 1;
9561        goto meta_command_exit;
9562      }else if( zName==0 ){
9563        zName = azArg[ii];
9564      }else{
9565        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9566        rc = 1;
9567        goto meta_command_exit;
9568      }
9569    }
9570    if( zName!=0 ){
9571      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9572                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9573                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9574                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9575      if( isSchema ){
9576        char *new_argv[2], *new_colv[2];
9577        new_argv[0] = sqlite3_mprintf(
9578                      "CREATE TABLE %s (\n"
9579                      "  type text,\n"
9580                      "  name text,\n"
9581                      "  tbl_name text,\n"
9582                      "  rootpage integer,\n"
9583                      "  sql text\n"
9584                      ")", zName);
9585        shell_check_oom(new_argv[0]);
9586        new_argv[1] = 0;
9587        new_colv[0] = "sql";
9588        new_colv[1] = 0;
9589        callback(&data, 1, new_argv, new_colv);
9590        sqlite3_free(new_argv[0]);
9591      }
9592    }
9593    if( zDiv ){
9594      sqlite3_stmt *pStmt = 0;
9595      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9596                              -1, &pStmt, 0);
9597      if( rc ){
9598        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9599        sqlite3_finalize(pStmt);
9600        rc = 1;
9601        goto meta_command_exit;
9602      }
9603      appendText(&sSelect, "SELECT sql FROM", 0);
9604      iSchema = 0;
9605      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9606        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9607        char zScNum[30];
9608        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9609        appendText(&sSelect, zDiv, 0);
9610        zDiv = " UNION ALL ";
9611        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9612        if( sqlite3_stricmp(zDb, "main")!=0 ){
9613          appendText(&sSelect, zDb, '\'');
9614        }else{
9615          appendText(&sSelect, "NULL", 0);
9616        }
9617        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9618        appendText(&sSelect, zScNum, 0);
9619        appendText(&sSelect, " AS snum, ", 0);
9620        appendText(&sSelect, zDb, '\'');
9621        appendText(&sSelect, " AS sname FROM ", 0);
9622        appendText(&sSelect, zDb, quoteChar(zDb));
9623        appendText(&sSelect, ".sqlite_schema", 0);
9624      }
9625      sqlite3_finalize(pStmt);
9626#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9627      if( zName ){
9628        appendText(&sSelect,
9629           " UNION ALL SELECT shell_module_schema(name),"
9630           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9631        0);
9632      }
9633#endif
9634      appendText(&sSelect, ") WHERE ", 0);
9635      if( zName ){
9636        char *zQarg = sqlite3_mprintf("%Q", zName);
9637        int bGlob;
9638        shell_check_oom(zQarg);
9639        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9640                strchr(zName, '[') != 0;
9641        if( strchr(zName, '.') ){
9642          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9643        }else{
9644          appendText(&sSelect, "lower(tbl_name)", 0);
9645        }
9646        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9647        appendText(&sSelect, zQarg, 0);
9648        if( !bGlob ){
9649          appendText(&sSelect, " ESCAPE '\\' ", 0);
9650        }
9651        appendText(&sSelect, " AND ", 0);
9652        sqlite3_free(zQarg);
9653      }
9654      if( bNoSystemTabs ){
9655        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9656      }
9657      appendText(&sSelect, "sql IS NOT NULL"
9658                           " ORDER BY snum, rowid", 0);
9659      if( bDebug ){
9660        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9661      }else{
9662        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9663      }
9664      freeText(&sSelect);
9665    }
9666    if( zErrMsg ){
9667      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9668      sqlite3_free(zErrMsg);
9669      rc = 1;
9670    }else if( rc != SQLITE_OK ){
9671      raw_printf(stderr,"Error: querying schema information\n");
9672      rc = 1;
9673    }else{
9674      rc = 0;
9675    }
9676  }else
9677
9678  if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
9679   || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
9680  ){
9681    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9682    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9683  }else
9684
9685#if defined(SQLITE_ENABLE_SESSION)
9686  if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
9687    struct AuxDb *pAuxDb = p->pAuxDb;
9688    OpenSession *pSession = &pAuxDb->aSession[0];
9689    char **azCmd = &azArg[1];
9690    int iSes = 0;
9691    int nCmd = nArg - 1;
9692    int i;
9693    if( nArg<=1 ) goto session_syntax_error;
9694    open_db(p, 0);
9695    if( nArg>=3 ){
9696      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9697        if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9698      }
9699      if( iSes<pAuxDb->nSession ){
9700        pSession = &pAuxDb->aSession[iSes];
9701        azCmd++;
9702        nCmd--;
9703      }else{
9704        pSession = &pAuxDb->aSession[0];
9705        iSes = 0;
9706      }
9707    }
9708
9709    /* .session attach TABLE
9710    ** Invoke the sqlite3session_attach() interface to attach a particular
9711    ** table so that it is never filtered.
9712    */
9713    if( cli_strcmp(azCmd[0],"attach")==0 ){
9714      if( nCmd!=2 ) goto session_syntax_error;
9715      if( pSession->p==0 ){
9716        session_not_open:
9717        raw_printf(stderr, "ERROR: No sessions are open\n");
9718      }else{
9719        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9720        if( rc ){
9721          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9722          rc = 0;
9723        }
9724      }
9725    }else
9726
9727    /* .session changeset FILE
9728    ** .session patchset FILE
9729    ** Write a changeset or patchset into a file.  The file is overwritten.
9730    */
9731    if( cli_strcmp(azCmd[0],"changeset")==0
9732     || cli_strcmp(azCmd[0],"patchset")==0
9733    ){
9734      FILE *out = 0;
9735      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9736      if( nCmd!=2 ) goto session_syntax_error;
9737      if( pSession->p==0 ) goto session_not_open;
9738      out = fopen(azCmd[1], "wb");
9739      if( out==0 ){
9740        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9741                    azCmd[1]);
9742      }else{
9743        int szChng;
9744        void *pChng;
9745        if( azCmd[0][0]=='c' ){
9746          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9747        }else{
9748          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9749        }
9750        if( rc ){
9751          printf("Error: error code %d\n", rc);
9752          rc = 0;
9753        }
9754        if( pChng
9755          && fwrite(pChng, szChng, 1, out)!=1 ){
9756          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9757                  szChng);
9758        }
9759        sqlite3_free(pChng);
9760        fclose(out);
9761      }
9762    }else
9763
9764    /* .session close
9765    ** Close the identified session
9766    */
9767    if( cli_strcmp(azCmd[0], "close")==0 ){
9768      if( nCmd!=1 ) goto session_syntax_error;
9769      if( pAuxDb->nSession ){
9770        session_close(pSession);
9771        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9772      }
9773    }else
9774
9775    /* .session enable ?BOOLEAN?
9776    ** Query or set the enable flag
9777    */
9778    if( cli_strcmp(azCmd[0], "enable")==0 ){
9779      int ii;
9780      if( nCmd>2 ) goto session_syntax_error;
9781      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9782      if( pAuxDb->nSession ){
9783        ii = sqlite3session_enable(pSession->p, ii);
9784        utf8_printf(p->out, "session %s enable flag = %d\n",
9785                    pSession->zName, ii);
9786      }
9787    }else
9788
9789    /* .session filter GLOB ....
9790    ** Set a list of GLOB patterns of table names to be excluded.
9791    */
9792    if( cli_strcmp(azCmd[0], "filter")==0 ){
9793      int ii, nByte;
9794      if( nCmd<2 ) goto session_syntax_error;
9795      if( pAuxDb->nSession ){
9796        for(ii=0; ii<pSession->nFilter; ii++){
9797          sqlite3_free(pSession->azFilter[ii]);
9798        }
9799        sqlite3_free(pSession->azFilter);
9800        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9801        pSession->azFilter = sqlite3_malloc( nByte );
9802        if( pSession->azFilter==0 ){
9803          raw_printf(stderr, "Error: out or memory\n");
9804          exit(1);
9805        }
9806        for(ii=1; ii<nCmd; ii++){
9807          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9808          shell_check_oom(x);
9809        }
9810        pSession->nFilter = ii-1;
9811      }
9812    }else
9813
9814    /* .session indirect ?BOOLEAN?
9815    ** Query or set the indirect flag
9816    */
9817    if( cli_strcmp(azCmd[0], "indirect")==0 ){
9818      int ii;
9819      if( nCmd>2 ) goto session_syntax_error;
9820      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9821      if( pAuxDb->nSession ){
9822        ii = sqlite3session_indirect(pSession->p, ii);
9823        utf8_printf(p->out, "session %s indirect flag = %d\n",
9824                    pSession->zName, ii);
9825      }
9826    }else
9827
9828    /* .session isempty
9829    ** Determine if the session is empty
9830    */
9831    if( cli_strcmp(azCmd[0], "isempty")==0 ){
9832      int ii;
9833      if( nCmd!=1 ) goto session_syntax_error;
9834      if( pAuxDb->nSession ){
9835        ii = sqlite3session_isempty(pSession->p);
9836        utf8_printf(p->out, "session %s isempty flag = %d\n",
9837                    pSession->zName, ii);
9838      }
9839    }else
9840
9841    /* .session list
9842    ** List all currently open sessions
9843    */
9844    if( cli_strcmp(azCmd[0],"list")==0 ){
9845      for(i=0; i<pAuxDb->nSession; i++){
9846        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9847      }
9848    }else
9849
9850    /* .session open DB NAME
9851    ** Open a new session called NAME on the attached database DB.
9852    ** DB is normally "main".
9853    */
9854    if( cli_strcmp(azCmd[0],"open")==0 ){
9855      char *zName;
9856      if( nCmd!=3 ) goto session_syntax_error;
9857      zName = azCmd[2];
9858      if( zName[0]==0 ) goto session_syntax_error;
9859      for(i=0; i<pAuxDb->nSession; i++){
9860        if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9861          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9862          goto meta_command_exit;
9863        }
9864      }
9865      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9866        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9867        goto meta_command_exit;
9868      }
9869      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9870      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9871      if( rc ){
9872        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9873        rc = 0;
9874        goto meta_command_exit;
9875      }
9876      pSession->nFilter = 0;
9877      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9878      pAuxDb->nSession++;
9879      pSession->zName = sqlite3_mprintf("%s", zName);
9880      shell_check_oom(pSession->zName);
9881    }else
9882    /* If no command name matches, show a syntax error */
9883    session_syntax_error:
9884    showHelp(p->out, "session");
9885  }else
9886#endif
9887
9888#ifdef SQLITE_DEBUG
9889  /* Undocumented commands for internal testing.  Subject to change
9890  ** without notice. */
9891  if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
9892    if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9893      int i, v;
9894      for(i=1; i<nArg; i++){
9895        v = booleanValue(azArg[i]);
9896        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9897      }
9898    }
9899    if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
9900      int i; sqlite3_int64 v;
9901      for(i=1; i<nArg; i++){
9902        char zBuf[200];
9903        v = integerValue(azArg[i]);
9904        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9905        utf8_printf(p->out, "%s", zBuf);
9906      }
9907    }
9908  }else
9909#endif
9910
9911  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
9912    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9913    int bVerbose = 0;        /* Verbose output */
9914    int bSelftestExists;     /* True if SELFTEST already exists */
9915    int i, k;                /* Loop counters */
9916    int nTest = 0;           /* Number of tests runs */
9917    int nErr = 0;            /* Number of errors seen */
9918    ShellText str;           /* Answer for a query */
9919    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9920
9921    open_db(p,0);
9922    for(i=1; i<nArg; i++){
9923      const char *z = azArg[i];
9924      if( z[0]=='-' && z[1]=='-' ) z++;
9925      if( cli_strcmp(z,"-init")==0 ){
9926        bIsInit = 1;
9927      }else
9928      if( cli_strcmp(z,"-v")==0 ){
9929        bVerbose++;
9930      }else
9931      {
9932        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9933                    azArg[i], azArg[0]);
9934        raw_printf(stderr, "Should be one of: --init -v\n");
9935        rc = 1;
9936        goto meta_command_exit;
9937      }
9938    }
9939    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9940           != SQLITE_OK ){
9941      bSelftestExists = 0;
9942    }else{
9943      bSelftestExists = 1;
9944    }
9945    if( bIsInit ){
9946      createSelftestTable(p);
9947      bSelftestExists = 1;
9948    }
9949    initText(&str);
9950    appendText(&str, "x", 0);
9951    for(k=bSelftestExists; k>=0; k--){
9952      if( k==1 ){
9953        rc = sqlite3_prepare_v2(p->db,
9954            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9955            -1, &pStmt, 0);
9956      }else{
9957        rc = sqlite3_prepare_v2(p->db,
9958          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9959          "      (1,'run','PRAGMA integrity_check','ok')",
9960          -1, &pStmt, 0);
9961      }
9962      if( rc ){
9963        raw_printf(stderr, "Error querying the selftest table\n");
9964        rc = 1;
9965        sqlite3_finalize(pStmt);
9966        goto meta_command_exit;
9967      }
9968      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9969        int tno = sqlite3_column_int(pStmt, 0);
9970        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9971        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9972        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9973
9974        if( zOp==0 ) continue;
9975        if( zSql==0 ) continue;
9976        if( zAns==0 ) continue;
9977        k = 0;
9978        if( bVerbose>0 ){
9979          printf("%d: %s %s\n", tno, zOp, zSql);
9980        }
9981        if( cli_strcmp(zOp,"memo")==0 ){
9982          utf8_printf(p->out, "%s\n", zSql);
9983        }else
9984        if( cli_strcmp(zOp,"run")==0 ){
9985          char *zErrMsg = 0;
9986          str.n = 0;
9987          str.z[0] = 0;
9988          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9989          nTest++;
9990          if( bVerbose ){
9991            utf8_printf(p->out, "Result: %s\n", str.z);
9992          }
9993          if( rc || zErrMsg ){
9994            nErr++;
9995            rc = 1;
9996            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9997            sqlite3_free(zErrMsg);
9998          }else if( cli_strcmp(zAns,str.z)!=0 ){
9999            nErr++;
10000            rc = 1;
10001            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10002            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10003          }
10004        }else
10005        {
10006          utf8_printf(stderr,
10007            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10008          rc = 1;
10009          break;
10010        }
10011      } /* End loop over rows of content from SELFTEST */
10012      sqlite3_finalize(pStmt);
10013    } /* End loop over k */
10014    freeText(&str);
10015    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10016  }else
10017
10018  if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10019    if( nArg<2 || nArg>3 ){
10020      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10021      rc = 1;
10022    }
10023    if( nArg>=2 ){
10024      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10025                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10026    }
10027    if( nArg>=3 ){
10028      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10029                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10030    }
10031  }else
10032
10033  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10034    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10035    int i;                   /* Loop counter */
10036    int bSchema = 0;         /* Also hash the schema */
10037    int bSeparate = 0;       /* Hash each table separately */
10038    int iSize = 224;         /* Hash algorithm to use */
10039    int bDebug = 0;          /* Only show the query that would have run */
10040    sqlite3_stmt *pStmt;     /* For querying tables names */
10041    char *zSql;              /* SQL to be run */
10042    char *zSep;              /* Separator */
10043    ShellText sSql;          /* Complete SQL for the query to run the hash */
10044    ShellText sQuery;        /* Set of queries used to read all content */
10045    open_db(p, 0);
10046    for(i=1; i<nArg; i++){
10047      const char *z = azArg[i];
10048      if( z[0]=='-' ){
10049        z++;
10050        if( z[0]=='-' ) z++;
10051        if( cli_strcmp(z,"schema")==0 ){
10052          bSchema = 1;
10053        }else
10054        if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10055         || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10056        ){
10057          iSize = atoi(&z[5]);
10058        }else
10059        if( cli_strcmp(z,"debug")==0 ){
10060          bDebug = 1;
10061        }else
10062        {
10063          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10064                      azArg[i], azArg[0]);
10065          showHelp(p->out, azArg[0]);
10066          rc = 1;
10067          goto meta_command_exit;
10068        }
10069      }else if( zLike ){
10070        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10071        rc = 1;
10072        goto meta_command_exit;
10073      }else{
10074        zLike = z;
10075        bSeparate = 1;
10076        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10077      }
10078    }
10079    if( bSchema ){
10080      zSql = "SELECT lower(name) FROM sqlite_schema"
10081             " WHERE type='table' AND coalesce(rootpage,0)>1"
10082             " UNION ALL SELECT 'sqlite_schema'"
10083             " ORDER BY 1 collate nocase";
10084    }else{
10085      zSql = "SELECT lower(name) FROM sqlite_schema"
10086             " WHERE type='table' AND coalesce(rootpage,0)>1"
10087             " AND name NOT LIKE 'sqlite_%'"
10088             " ORDER BY 1 collate nocase";
10089    }
10090    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10091    initText(&sQuery);
10092    initText(&sSql);
10093    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10094    zSep = "VALUES(";
10095    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10096      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10097      if( zTab==0 ) continue;
10098      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10099      if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10100        appendText(&sQuery,"SELECT * FROM ", 0);
10101        appendText(&sQuery,zTab,'"');
10102        appendText(&sQuery," NOT INDEXED;", 0);
10103      }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10104        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10105                           " ORDER BY name;", 0);
10106      }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10107        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10108                           " ORDER BY name;", 0);
10109      }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10110        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10111                           " ORDER BY tbl,idx;", 0);
10112      }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10113        appendText(&sQuery, "SELECT * FROM ", 0);
10114        appendText(&sQuery, zTab, 0);
10115        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10116      }
10117      appendText(&sSql, zSep, 0);
10118      appendText(&sSql, sQuery.z, '\'');
10119      sQuery.n = 0;
10120      appendText(&sSql, ",", 0);
10121      appendText(&sSql, zTab, '\'');
10122      zSep = "),(";
10123    }
10124    sqlite3_finalize(pStmt);
10125    if( bSeparate ){
10126      zSql = sqlite3_mprintf(
10127          "%s))"
10128          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10129          "   FROM [sha3sum$query]",
10130          sSql.z, iSize);
10131    }else{
10132      zSql = sqlite3_mprintf(
10133          "%s))"
10134          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10135          "   FROM [sha3sum$query]",
10136          sSql.z, iSize);
10137    }
10138    shell_check_oom(zSql);
10139    freeText(&sQuery);
10140    freeText(&sSql);
10141    if( bDebug ){
10142      utf8_printf(p->out, "%s\n", zSql);
10143    }else{
10144      shell_exec(p, zSql, 0);
10145    }
10146    sqlite3_free(zSql);
10147  }else
10148
10149#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10150  if( c=='s'
10151   && (cli_strncmp(azArg[0], "shell", n)==0
10152       || cli_strncmp(azArg[0],"system",n)==0)
10153  ){
10154    char *zCmd;
10155    int i, x;
10156    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10157    if( nArg<2 ){
10158      raw_printf(stderr, "Usage: .system COMMAND\n");
10159      rc = 1;
10160      goto meta_command_exit;
10161    }
10162    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10163    for(i=2; i<nArg && zCmd!=0; i++){
10164      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10165                             zCmd, azArg[i]);
10166    }
10167    x = zCmd!=0 ? system(zCmd) : 1;
10168    sqlite3_free(zCmd);
10169    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10170  }else
10171#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10172
10173  if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10174    static const char *azBool[] = { "off", "on", "trigger", "full"};
10175    const char *zOut;
10176    int i;
10177    if( nArg!=1 ){
10178      raw_printf(stderr, "Usage: .show\n");
10179      rc = 1;
10180      goto meta_command_exit;
10181    }
10182    utf8_printf(p->out, "%12.12s: %s\n","echo",
10183                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10184    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10185    utf8_printf(p->out, "%12.12s: %s\n","explain",
10186         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10187    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10188    if( p->mode==MODE_Column
10189     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10190    ){
10191      utf8_printf
10192        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10193         modeDescr[p->mode], p->cmOpts.iWrap,
10194         p->cmOpts.bWordWrap ? "on" : "off",
10195         p->cmOpts.bQuote ? "" : "no");
10196    }else{
10197      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10198    }
10199    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10200      output_c_string(p->out, p->nullValue);
10201      raw_printf(p->out, "\n");
10202    utf8_printf(p->out,"%12.12s: %s\n","output",
10203            strlen30(p->outfile) ? p->outfile : "stdout");
10204    utf8_printf(p->out,"%12.12s: ", "colseparator");
10205      output_c_string(p->out, p->colSeparator);
10206      raw_printf(p->out, "\n");
10207    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10208      output_c_string(p->out, p->rowSeparator);
10209      raw_printf(p->out, "\n");
10210    switch( p->statsOn ){
10211      case 0:  zOut = "off";     break;
10212      default: zOut = "on";      break;
10213      case 2:  zOut = "stmt";    break;
10214      case 3:  zOut = "vmstep";  break;
10215    }
10216    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10217    utf8_printf(p->out, "%12.12s: ", "width");
10218    for (i=0;i<p->nWidth;i++) {
10219      raw_printf(p->out, "%d ", p->colWidth[i]);
10220    }
10221    raw_printf(p->out, "\n");
10222    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10223                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10224  }else
10225
10226  if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10227    if( nArg==2 ){
10228      if( cli_strcmp(azArg[1],"stmt")==0 ){
10229        p->statsOn = 2;
10230      }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10231        p->statsOn = 3;
10232      }else{
10233        p->statsOn = (u8)booleanValue(azArg[1]);
10234      }
10235    }else if( nArg==1 ){
10236      display_stats(p->db, p, 0);
10237    }else{
10238      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10239      rc = 1;
10240    }
10241  }else
10242
10243  if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10244   || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10245                 || cli_strncmp(azArg[0], "indexes", n)==0) )
10246  ){
10247    sqlite3_stmt *pStmt;
10248    char **azResult;
10249    int nRow, nAlloc;
10250    int ii;
10251    ShellText s;
10252    initText(&s);
10253    open_db(p, 0);
10254    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10255    if( rc ){
10256      sqlite3_finalize(pStmt);
10257      return shellDatabaseError(p->db);
10258    }
10259
10260    if( nArg>2 && c=='i' ){
10261      /* It is an historical accident that the .indexes command shows an error
10262      ** when called with the wrong number of arguments whereas the .tables
10263      ** command does not. */
10264      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10265      rc = 1;
10266      sqlite3_finalize(pStmt);
10267      goto meta_command_exit;
10268    }
10269    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10270      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10271      if( zDbName==0 ) continue;
10272      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10273      if( sqlite3_stricmp(zDbName, "main")==0 ){
10274        appendText(&s, "SELECT name FROM ", 0);
10275      }else{
10276        appendText(&s, "SELECT ", 0);
10277        appendText(&s, zDbName, '\'');
10278        appendText(&s, "||'.'||name FROM ", 0);
10279      }
10280      appendText(&s, zDbName, '"');
10281      appendText(&s, ".sqlite_schema ", 0);
10282      if( c=='t' ){
10283        appendText(&s," WHERE type IN ('table','view')"
10284                      "   AND name NOT LIKE 'sqlite_%'"
10285                      "   AND name LIKE ?1", 0);
10286      }else{
10287        appendText(&s," WHERE type='index'"
10288                      "   AND tbl_name LIKE ?1", 0);
10289      }
10290    }
10291    rc = sqlite3_finalize(pStmt);
10292    if( rc==SQLITE_OK ){
10293      appendText(&s, " ORDER BY 1", 0);
10294      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10295    }
10296    freeText(&s);
10297    if( rc ) return shellDatabaseError(p->db);
10298
10299    /* Run the SQL statement prepared by the above block. Store the results
10300    ** as an array of nul-terminated strings in azResult[].  */
10301    nRow = nAlloc = 0;
10302    azResult = 0;
10303    if( nArg>1 ){
10304      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10305    }else{
10306      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10307    }
10308    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10309      if( nRow>=nAlloc ){
10310        char **azNew;
10311        int n2 = nAlloc*2 + 10;
10312        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10313        shell_check_oom(azNew);
10314        nAlloc = n2;
10315        azResult = azNew;
10316      }
10317      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10318      shell_check_oom(azResult[nRow]);
10319      nRow++;
10320    }
10321    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10322      rc = shellDatabaseError(p->db);
10323    }
10324
10325    /* Pretty-print the contents of array azResult[] to the output */
10326    if( rc==0 && nRow>0 ){
10327      int len, maxlen = 0;
10328      int i, j;
10329      int nPrintCol, nPrintRow;
10330      for(i=0; i<nRow; i++){
10331        len = strlen30(azResult[i]);
10332        if( len>maxlen ) maxlen = len;
10333      }
10334      nPrintCol = 80/(maxlen+2);
10335      if( nPrintCol<1 ) nPrintCol = 1;
10336      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10337      for(i=0; i<nPrintRow; i++){
10338        for(j=i; j<nRow; j+=nPrintRow){
10339          char *zSp = j<nPrintRow ? "" : "  ";
10340          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10341                      azResult[j] ? azResult[j]:"");
10342        }
10343        raw_printf(p->out, "\n");
10344      }
10345    }
10346
10347    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10348    sqlite3_free(azResult);
10349  }else
10350
10351#ifndef SQLITE_SHELL_FIDDLE
10352  /* Begin redirecting output to the file "testcase-out.txt" */
10353  if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10354    output_reset(p);
10355    p->out = output_file_open("testcase-out.txt", 0);
10356    if( p->out==0 ){
10357      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10358    }
10359    if( nArg>=2 ){
10360      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10361    }else{
10362      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10363    }
10364  }else
10365#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10366
10367#ifndef SQLITE_UNTESTABLE
10368  if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10369    static const struct {
10370       const char *zCtrlName;   /* Name of a test-control option */
10371       int ctrlCode;            /* Integer code for that option */
10372       int unSafe;              /* Not valid for --safe mode */
10373       const char *zUsage;      /* Usage notes */
10374    } aCtrl[] = {
10375      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10376      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10377    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10378    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10379      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10380      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10381    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10382      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10383      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10384      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10385      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10386      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10387#ifdef YYCOVERAGE
10388      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10389#endif
10390      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10391      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10392      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10393      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10394      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10395      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10396      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10397    };
10398    int testctrl = -1;
10399    int iCtrl = -1;
10400    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10401    int isOk = 0;
10402    int i, n2;
10403    const char *zCmd = 0;
10404
10405    open_db(p, 0);
10406    zCmd = nArg>=2 ? azArg[1] : "help";
10407
10408    /* The argument can optionally begin with "-" or "--" */
10409    if( zCmd[0]=='-' && zCmd[1] ){
10410      zCmd++;
10411      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10412    }
10413
10414    /* --help lists all test-controls */
10415    if( cli_strcmp(zCmd,"help")==0 ){
10416      utf8_printf(p->out, "Available test-controls:\n");
10417      for(i=0; i<ArraySize(aCtrl); i++){
10418        utf8_printf(p->out, "  .testctrl %s %s\n",
10419                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10420      }
10421      rc = 1;
10422      goto meta_command_exit;
10423    }
10424
10425    /* convert testctrl text option to value. allow any unique prefix
10426    ** of the option name, or a numerical value. */
10427    n2 = strlen30(zCmd);
10428    for(i=0; i<ArraySize(aCtrl); i++){
10429      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10430        if( testctrl<0 ){
10431          testctrl = aCtrl[i].ctrlCode;
10432          iCtrl = i;
10433        }else{
10434          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10435                              "Use \".testctrl --help\" for help\n", zCmd);
10436          rc = 1;
10437          goto meta_command_exit;
10438        }
10439      }
10440    }
10441    if( testctrl<0 ){
10442      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10443                         "Use \".testctrl --help\" for help\n", zCmd);
10444    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10445      utf8_printf(stderr,
10446         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10447         p->lineno, aCtrl[iCtrl].zCtrlName);
10448      exit(1);
10449    }else{
10450      switch(testctrl){
10451
10452        /* sqlite3_test_control(int, db, int) */
10453        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10454          if( nArg==3 ){
10455            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10456            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10457            isOk = 3;
10458          }
10459          break;
10460
10461        /* sqlite3_test_control(int) */
10462        case SQLITE_TESTCTRL_PRNG_SAVE:
10463        case SQLITE_TESTCTRL_PRNG_RESTORE:
10464        case SQLITE_TESTCTRL_BYTEORDER:
10465          if( nArg==2 ){
10466            rc2 = sqlite3_test_control(testctrl);
10467            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10468          }
10469          break;
10470
10471        /* sqlite3_test_control(int, uint) */
10472        case SQLITE_TESTCTRL_PENDING_BYTE:
10473          if( nArg==3 ){
10474            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10475            rc2 = sqlite3_test_control(testctrl, opt);
10476            isOk = 3;
10477          }
10478          break;
10479
10480        /* sqlite3_test_control(int, int, sqlite3*) */
10481        case SQLITE_TESTCTRL_PRNG_SEED:
10482          if( nArg==3 || nArg==4 ){
10483            int ii = (int)integerValue(azArg[2]);
10484            sqlite3 *db;
10485            if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
10486              sqlite3_randomness(sizeof(ii),&ii);
10487              printf("-- random seed: %d\n", ii);
10488            }
10489            if( nArg==3 ){
10490              db = 0;
10491            }else{
10492              db = p->db;
10493              /* Make sure the schema has been loaded */
10494              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10495            }
10496            rc2 = sqlite3_test_control(testctrl, ii, db);
10497            isOk = 3;
10498          }
10499          break;
10500
10501        /* sqlite3_test_control(int, int) */
10502        case SQLITE_TESTCTRL_ASSERT:
10503        case SQLITE_TESTCTRL_ALWAYS:
10504          if( nArg==3 ){
10505            int opt = booleanValue(azArg[2]);
10506            rc2 = sqlite3_test_control(testctrl, opt);
10507            isOk = 1;
10508          }
10509          break;
10510
10511        /* sqlite3_test_control(int, int) */
10512        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10513        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10514          if( nArg==3 ){
10515            int opt = booleanValue(azArg[2]);
10516            rc2 = sqlite3_test_control(testctrl, opt);
10517            isOk = 3;
10518          }
10519          break;
10520
10521        /* sqlite3_test_control(sqlite3*) */
10522        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10523          rc2 = sqlite3_test_control(testctrl, p->db);
10524          isOk = 3;
10525          break;
10526
10527        case SQLITE_TESTCTRL_IMPOSTER:
10528          if( nArg==5 ){
10529            rc2 = sqlite3_test_control(testctrl, p->db,
10530                          azArg[2],
10531                          integerValue(azArg[3]),
10532                          integerValue(azArg[4]));
10533            isOk = 3;
10534          }
10535          break;
10536
10537        case SQLITE_TESTCTRL_SEEK_COUNT: {
10538          u64 x = 0;
10539          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10540          utf8_printf(p->out, "%llu\n", x);
10541          isOk = 3;
10542          break;
10543        }
10544
10545#ifdef YYCOVERAGE
10546        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10547          if( nArg==2 ){
10548            sqlite3_test_control(testctrl, p->out);
10549            isOk = 3;
10550          }
10551          break;
10552        }
10553#endif
10554#ifdef SQLITE_DEBUG
10555        case SQLITE_TESTCTRL_TUNE: {
10556          if( nArg==4 ){
10557            int id = (int)integerValue(azArg[2]);
10558            int val = (int)integerValue(azArg[3]);
10559            sqlite3_test_control(testctrl, id, &val);
10560            isOk = 3;
10561          }else if( nArg==3 ){
10562            int id = (int)integerValue(azArg[2]);
10563            sqlite3_test_control(testctrl, -id, &rc2);
10564            isOk = 1;
10565          }else if( nArg==2 ){
10566            int id = 1;
10567            while(1){
10568              int val = 0;
10569              rc2 = sqlite3_test_control(testctrl, -id, &val);
10570              if( rc2!=SQLITE_OK ) break;
10571              if( id>1 ) utf8_printf(p->out, "  ");
10572              utf8_printf(p->out, "%d: %d", id, val);
10573              id++;
10574            }
10575            if( id>1 ) utf8_printf(p->out, "\n");
10576            isOk = 3;
10577          }
10578          break;
10579        }
10580#endif
10581        case SQLITE_TESTCTRL_SORTER_MMAP:
10582          if( nArg==3 ){
10583            int opt = (unsigned int)integerValue(azArg[2]);
10584            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10585            isOk = 3;
10586          }
10587          break;
10588      }
10589    }
10590    if( isOk==0 && iCtrl>=0 ){
10591      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10592      rc = 1;
10593    }else if( isOk==1 ){
10594      raw_printf(p->out, "%d\n", rc2);
10595    }else if( isOk==2 ){
10596      raw_printf(p->out, "0x%08x\n", rc2);
10597    }
10598  }else
10599#endif /* !defined(SQLITE_UNTESTABLE) */
10600
10601  if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
10602    open_db(p, 0);
10603    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10604  }else
10605
10606  if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
10607    if( nArg==2 ){
10608      enableTimer = booleanValue(azArg[1]);
10609      if( enableTimer && !HAS_TIMER ){
10610        raw_printf(stderr, "Error: timer not available on this system.\n");
10611        enableTimer = 0;
10612      }
10613    }else{
10614      raw_printf(stderr, "Usage: .timer on|off\n");
10615      rc = 1;
10616    }
10617  }else
10618
10619#ifndef SQLITE_OMIT_TRACE
10620  if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
10621    int mType = 0;
10622    int jj;
10623    open_db(p, 0);
10624    for(jj=1; jj<nArg; jj++){
10625      const char *z = azArg[jj];
10626      if( z[0]=='-' ){
10627        if( optionMatch(z, "expanded") ){
10628          p->eTraceType = SHELL_TRACE_EXPANDED;
10629        }
10630#ifdef SQLITE_ENABLE_NORMALIZE
10631        else if( optionMatch(z, "normalized") ){
10632          p->eTraceType = SHELL_TRACE_NORMALIZED;
10633        }
10634#endif
10635        else if( optionMatch(z, "plain") ){
10636          p->eTraceType = SHELL_TRACE_PLAIN;
10637        }
10638        else if( optionMatch(z, "profile") ){
10639          mType |= SQLITE_TRACE_PROFILE;
10640        }
10641        else if( optionMatch(z, "row") ){
10642          mType |= SQLITE_TRACE_ROW;
10643        }
10644        else if( optionMatch(z, "stmt") ){
10645          mType |= SQLITE_TRACE_STMT;
10646        }
10647        else if( optionMatch(z, "close") ){
10648          mType |= SQLITE_TRACE_CLOSE;
10649        }
10650        else {
10651          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10652          rc = 1;
10653          goto meta_command_exit;
10654        }
10655      }else{
10656        output_file_close(p->traceOut);
10657        p->traceOut = output_file_open(azArg[1], 0);
10658      }
10659    }
10660    if( p->traceOut==0 ){
10661      sqlite3_trace_v2(p->db, 0, 0, 0);
10662    }else{
10663      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10664      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10665    }
10666  }else
10667#endif /* !defined(SQLITE_OMIT_TRACE) */
10668
10669#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10670  if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
10671    int ii;
10672    int lenOpt;
10673    char *zOpt;
10674    if( nArg<2 ){
10675      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10676      rc = 1;
10677      goto meta_command_exit;
10678    }
10679    open_db(p, 0);
10680    zOpt = azArg[1];
10681    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10682    lenOpt = (int)strlen(zOpt);
10683    if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10684      assert( azArg[nArg]==0 );
10685      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10686    }else{
10687      for(ii=1; ii<nArg; ii++){
10688        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10689      }
10690    }
10691  }else
10692#endif
10693
10694#if SQLITE_USER_AUTHENTICATION
10695  if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
10696    if( nArg<2 ){
10697      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10698      rc = 1;
10699      goto meta_command_exit;
10700    }
10701    open_db(p, 0);
10702    if( cli_strcmp(azArg[1],"login")==0 ){
10703      if( nArg!=4 ){
10704        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10705        rc = 1;
10706        goto meta_command_exit;
10707      }
10708      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10709                                     strlen30(azArg[3]));
10710      if( rc ){
10711        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10712        rc = 1;
10713      }
10714    }else if( cli_strcmp(azArg[1],"add")==0 ){
10715      if( nArg!=5 ){
10716        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10717        rc = 1;
10718        goto meta_command_exit;
10719      }
10720      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10721                            booleanValue(azArg[4]));
10722      if( rc ){
10723        raw_printf(stderr, "User-Add failed: %d\n", rc);
10724        rc = 1;
10725      }
10726    }else if( cli_strcmp(azArg[1],"edit")==0 ){
10727      if( nArg!=5 ){
10728        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10729        rc = 1;
10730        goto meta_command_exit;
10731      }
10732      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10733                              booleanValue(azArg[4]));
10734      if( rc ){
10735        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10736        rc = 1;
10737      }
10738    }else if( cli_strcmp(azArg[1],"delete")==0 ){
10739      if( nArg!=3 ){
10740        raw_printf(stderr, "Usage: .user delete USER\n");
10741        rc = 1;
10742        goto meta_command_exit;
10743      }
10744      rc = sqlite3_user_delete(p->db, azArg[2]);
10745      if( rc ){
10746        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10747        rc = 1;
10748      }
10749    }else{
10750      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10751      rc = 1;
10752      goto meta_command_exit;
10753    }
10754  }else
10755#endif /* SQLITE_USER_AUTHENTICATION */
10756
10757  if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
10758    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10759        sqlite3_libversion(), sqlite3_sourceid());
10760#if SQLITE_HAVE_ZLIB
10761    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10762#endif
10763#define CTIMEOPT_VAL_(opt) #opt
10764#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10765#if defined(__clang__) && defined(__clang_major__)
10766    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10767                    CTIMEOPT_VAL(__clang_minor__) "."
10768                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10769#elif defined(_MSC_VER)
10770    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10771#elif defined(__GNUC__) && defined(__VERSION__)
10772    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10773#endif
10774  }else
10775
10776  if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
10777    const char *zDbName = nArg==2 ? azArg[1] : "main";
10778    sqlite3_vfs *pVfs = 0;
10779    if( p->db ){
10780      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10781      if( pVfs ){
10782        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10783        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10784        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10785        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10786      }
10787    }
10788  }else
10789
10790  if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
10791    sqlite3_vfs *pVfs;
10792    sqlite3_vfs *pCurrent = 0;
10793    if( p->db ){
10794      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10795    }
10796    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10797      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10798           pVfs==pCurrent ? "  <--- CURRENT" : "");
10799      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10800      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10801      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10802      if( pVfs->pNext ){
10803        raw_printf(p->out, "-----------------------------------\n");
10804      }
10805    }
10806  }else
10807
10808  if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
10809    const char *zDbName = nArg==2 ? azArg[1] : "main";
10810    char *zVfsName = 0;
10811    if( p->db ){
10812      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10813      if( zVfsName ){
10814        utf8_printf(p->out, "%s\n", zVfsName);
10815        sqlite3_free(zVfsName);
10816      }
10817    }
10818  }else
10819
10820  if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
10821    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10822    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10823  }else
10824
10825  if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
10826    int j;
10827    assert( nArg<=ArraySize(azArg) );
10828    p->nWidth = nArg-1;
10829    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10830    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10831    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10832    for(j=1; j<nArg; j++){
10833      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10834    }
10835  }else
10836
10837  {
10838    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10839      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10840    rc = 1;
10841  }
10842
10843meta_command_exit:
10844  if( p->outCount ){
10845    p->outCount--;
10846    if( p->outCount==0 ) output_reset(p);
10847  }
10848  p->bSafeMode = p->bSafeModePersist;
10849  return rc;
10850}
10851
10852/* Line scan result and intermediate states (supporting scan resumption)
10853*/
10854#ifndef CHAR_BIT
10855# define CHAR_BIT 8
10856#endif
10857typedef enum {
10858  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10859  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10860  QSS_Start = 0
10861} QuickScanState;
10862#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10863#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10864#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10865#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10866#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10867
10868/*
10869** Scan line for classification to guide shell's handling.
10870** The scan is resumable for subsequent lines when prior
10871** return values are passed as the 2nd argument.
10872*/
10873static QuickScanState quickscan(char *zLine, QuickScanState qss){
10874  char cin;
10875  char cWait = (char)qss; /* intentional narrowing loss */
10876  if( cWait==0 ){
10877  PlainScan:
10878    assert( cWait==0 );
10879    while( (cin = *zLine++)!=0 ){
10880      if( IsSpace(cin) )
10881        continue;
10882      switch (cin){
10883      case '-':
10884        if( *zLine!='-' )
10885          break;
10886        while((cin = *++zLine)!=0 )
10887          if( cin=='\n')
10888            goto PlainScan;
10889        return qss;
10890      case ';':
10891        qss |= QSS_EndingSemi;
10892        continue;
10893      case '/':
10894        if( *zLine=='*' ){
10895          ++zLine;
10896          cWait = '*';
10897          qss = QSS_SETV(qss, cWait);
10898          goto TermScan;
10899        }
10900        break;
10901      case '[':
10902        cin = ']';
10903        /* fall thru */
10904      case '`': case '\'': case '"':
10905        cWait = cin;
10906        qss = QSS_HasDark | cWait;
10907        goto TermScan;
10908      default:
10909        break;
10910      }
10911      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10912    }
10913  }else{
10914  TermScan:
10915    while( (cin = *zLine++)!=0 ){
10916      if( cin==cWait ){
10917        switch( cWait ){
10918        case '*':
10919          if( *zLine != '/' )
10920            continue;
10921          ++zLine;
10922          cWait = 0;
10923          qss = QSS_SETV(qss, 0);
10924          goto PlainScan;
10925        case '`': case '\'': case '"':
10926          if(*zLine==cWait){
10927            ++zLine;
10928            continue;
10929          }
10930          /* fall thru */
10931        case ']':
10932          cWait = 0;
10933          qss = QSS_SETV(qss, 0);
10934          goto PlainScan;
10935        default: assert(0);
10936        }
10937      }
10938    }
10939  }
10940  return qss;
10941}
10942
10943/*
10944** Return TRUE if the line typed in is an SQL command terminator other
10945** than a semi-colon.  The SQL Server style "go" command is understood
10946** as is the Oracle "/".
10947*/
10948static int line_is_command_terminator(char *zLine){
10949  while( IsSpace(zLine[0]) ){ zLine++; };
10950  if( zLine[0]=='/' )
10951    zLine += 1; /* Oracle */
10952  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10953    zLine += 2; /* SQL Server */
10954  else
10955    return 0;
10956  return quickscan(zLine, QSS_Start)==QSS_Start;
10957}
10958
10959/*
10960** We need a default sqlite3_complete() implementation to use in case
10961** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10962** any arbitrary text is a complete SQL statement.  This is not very
10963** user-friendly, but it does seem to work.
10964*/
10965#ifdef SQLITE_OMIT_COMPLETE
10966#define sqlite3_complete(x) 1
10967#endif
10968
10969/*
10970** Return true if zSql is a complete SQL statement.  Return false if it
10971** ends in the middle of a string literal or C-style comment.
10972*/
10973static int line_is_complete(char *zSql, int nSql){
10974  int rc;
10975  if( zSql==0 ) return 1;
10976  zSql[nSql] = ';';
10977  zSql[nSql+1] = 0;
10978  rc = sqlite3_complete(zSql);
10979  zSql[nSql] = 0;
10980  return rc;
10981}
10982
10983/*
10984** Run a single line of SQL.  Return the number of errors.
10985*/
10986static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10987  int rc;
10988  char *zErrMsg = 0;
10989
10990  open_db(p, 0);
10991  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10992  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10993  BEGIN_TIMER;
10994  rc = shell_exec(p, zSql, &zErrMsg);
10995  END_TIMER;
10996  if( rc || zErrMsg ){
10997    char zPrefix[100];
10998    const char *zErrorTail;
10999    const char *zErrorType;
11000    if( zErrMsg==0 ){
11001      zErrorType = "Error";
11002      zErrorTail = sqlite3_errmsg(p->db);
11003    }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11004      zErrorType = "Parse error";
11005      zErrorTail = &zErrMsg[12];
11006    }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11007      zErrorType = "Runtime error";
11008      zErrorTail = &zErrMsg[10];
11009    }else{
11010      zErrorType = "Error";
11011      zErrorTail = zErrMsg;
11012    }
11013    if( in!=0 || !stdin_is_interactive ){
11014      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11015                       "%s near line %d:", zErrorType, startline);
11016    }else{
11017      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11018    }
11019    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11020    sqlite3_free(zErrMsg);
11021    zErrMsg = 0;
11022    return 1;
11023  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11024    char zLineBuf[2000];
11025    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11026            "changes: %lld   total_changes: %lld",
11027            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11028    raw_printf(p->out, "%s\n", zLineBuf);
11029  }
11030  return 0;
11031}
11032
11033static void echo_group_input(ShellState *p, const char *zDo){
11034  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11035}
11036
11037#ifdef SQLITE_SHELL_FIDDLE
11038/*
11039** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11040** because we need the global shellState and cannot access it from that function
11041** without moving lots of code around (creating a larger/messier diff).
11042*/
11043static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11044  /* Parse the next line from shellState.wasm.zInput. */
11045  const char *zBegin = shellState.wasm.zPos;
11046  const char *z = zBegin;
11047  char *zLine = 0;
11048  i64 nZ = 0;
11049
11050  UNUSED_PARAMETER(in);
11051  UNUSED_PARAMETER(isContinuation);
11052  if(!z || !*z){
11053    return 0;
11054  }
11055  while(*z && isspace(*z)) ++z;
11056  zBegin = z;
11057  for(; *z && '\n'!=*z; ++nZ, ++z){}
11058  if(nZ>0 && '\r'==zBegin[nZ-1]){
11059    --nZ;
11060  }
11061  shellState.wasm.zPos = z;
11062  zLine = realloc(zPrior, nZ+1);
11063  shell_check_oom(zLine);
11064  memcpy(zLine, zBegin, nZ);
11065  zLine[nZ] = 0;
11066  return zLine;
11067}
11068#endif /* SQLITE_SHELL_FIDDLE */
11069
11070/*
11071** Read input from *in and process it.  If *in==0 then input
11072** is interactive - the user is typing it it.  Otherwise, input
11073** is coming from a file or device.  A prompt is issued and history
11074** is saved only if input is interactive.  An interrupt signal will
11075** cause this routine to exit immediately, unless input is interactive.
11076**
11077** Return the number of errors.
11078*/
11079static int process_input(ShellState *p){
11080  char *zLine = 0;          /* A single input line */
11081  char *zSql = 0;           /* Accumulated SQL text */
11082  i64 nLine;                /* Length of current line */
11083  i64 nSql = 0;             /* Bytes of zSql[] used */
11084  i64 nAlloc = 0;           /* Allocated zSql[] space */
11085  int rc;                   /* Error code */
11086  int errCnt = 0;           /* Number of errors seen */
11087  i64 startline = 0;        /* Line number for start of current input */
11088  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11089
11090  if( p->inputNesting==MAX_INPUT_NESTING ){
11091    /* This will be more informative in a later version. */
11092    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11093                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11094    return 1;
11095  }
11096  ++p->inputNesting;
11097  p->lineno = 0;
11098  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11099    fflush(p->out);
11100    zLine = one_input_line(p->in, zLine, nSql>0);
11101    if( zLine==0 ){
11102      /* End of input */
11103      if( p->in==0 && stdin_is_interactive ) printf("\n");
11104      break;
11105    }
11106    if( seenInterrupt ){
11107      if( p->in!=0 ) break;
11108      seenInterrupt = 0;
11109    }
11110    p->lineno++;
11111    if( QSS_INPLAIN(qss)
11112        && line_is_command_terminator(zLine)
11113        && line_is_complete(zSql, nSql) ){
11114      memcpy(zLine,";",2);
11115    }
11116    qss = quickscan(zLine, qss);
11117    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11118      /* Just swallow single-line whitespace */
11119      echo_group_input(p, zLine);
11120      qss = QSS_Start;
11121      continue;
11122    }
11123    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11124      echo_group_input(p, zLine);
11125      if( zLine[0]=='.' ){
11126        rc = do_meta_command(zLine, p);
11127        if( rc==2 ){ /* exit requested */
11128          break;
11129        }else if( rc ){
11130          errCnt++;
11131        }
11132      }
11133      qss = QSS_Start;
11134      continue;
11135    }
11136    /* No single-line dispositions remain; accumulate line(s). */
11137    nLine = strlen(zLine);
11138    if( nSql+nLine+2>=nAlloc ){
11139      /* Grow buffer by half-again increments when big. */
11140      nAlloc = nSql+(nSql>>1)+nLine+100;
11141      zSql = realloc(zSql, nAlloc);
11142      shell_check_oom(zSql);
11143    }
11144    if( nSql==0 ){
11145      i64 i;
11146      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11147      assert( nAlloc>0 && zSql!=0 );
11148      memcpy(zSql, zLine+i, nLine+1-i);
11149      startline = p->lineno;
11150      nSql = nLine-i;
11151    }else{
11152      zSql[nSql++] = '\n';
11153      memcpy(zSql+nSql, zLine, nLine+1);
11154      nSql += nLine;
11155    }
11156    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11157      echo_group_input(p, zSql);
11158      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11159      nSql = 0;
11160      if( p->outCount ){
11161        output_reset(p);
11162        p->outCount = 0;
11163      }else{
11164        clearTempFile(p);
11165      }
11166      p->bSafeMode = p->bSafeModePersist;
11167      qss = QSS_Start;
11168    }else if( nSql && QSS_PLAINWHITE(qss) ){
11169      echo_group_input(p, zSql);
11170      nSql = 0;
11171      qss = QSS_Start;
11172    }
11173  }
11174  if( nSql ){
11175    /* This may be incomplete. Let the SQL parser deal with that. */
11176    echo_group_input(p, zSql);
11177    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11178  }
11179  free(zSql);
11180  free(zLine);
11181  --p->inputNesting;
11182  return errCnt>0;
11183}
11184
11185/*
11186** Return a pathname which is the user's home directory.  A
11187** 0 return indicates an error of some kind.
11188*/
11189static char *find_home_dir(int clearFlag){
11190  static char *home_dir = NULL;
11191  if( clearFlag ){
11192    free(home_dir);
11193    home_dir = 0;
11194    return 0;
11195  }
11196  if( home_dir ) return home_dir;
11197
11198#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11199     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11200  {
11201    struct passwd *pwent;
11202    uid_t uid = getuid();
11203    if( (pwent=getpwuid(uid)) != NULL) {
11204      home_dir = pwent->pw_dir;
11205    }
11206  }
11207#endif
11208
11209#if defined(_WIN32_WCE)
11210  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11211   */
11212  home_dir = "/";
11213#else
11214
11215#if defined(_WIN32) || defined(WIN32)
11216  if (!home_dir) {
11217    home_dir = getenv("USERPROFILE");
11218  }
11219#endif
11220
11221  if (!home_dir) {
11222    home_dir = getenv("HOME");
11223  }
11224
11225#if defined(_WIN32) || defined(WIN32)
11226  if (!home_dir) {
11227    char *zDrive, *zPath;
11228    int n;
11229    zDrive = getenv("HOMEDRIVE");
11230    zPath = getenv("HOMEPATH");
11231    if( zDrive && zPath ){
11232      n = strlen30(zDrive) + strlen30(zPath) + 1;
11233      home_dir = malloc( n );
11234      if( home_dir==0 ) return 0;
11235      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11236      return home_dir;
11237    }
11238    home_dir = "c:\\";
11239  }
11240#endif
11241
11242#endif /* !_WIN32_WCE */
11243
11244  if( home_dir ){
11245    i64 n = strlen(home_dir) + 1;
11246    char *z = malloc( n );
11247    if( z ) memcpy(z, home_dir, n);
11248    home_dir = z;
11249  }
11250
11251  return home_dir;
11252}
11253
11254/*
11255** Read input from the file given by sqliterc_override.  Or if that
11256** parameter is NULL, take input from ~/.sqliterc
11257**
11258** Returns the number of errors.
11259*/
11260static void process_sqliterc(
11261  ShellState *p,                  /* Configuration data */
11262  const char *sqliterc_override   /* Name of config file. NULL to use default */
11263){
11264  char *home_dir = NULL;
11265  const char *sqliterc = sqliterc_override;
11266  char *zBuf = 0;
11267  FILE *inSaved = p->in;
11268  int savedLineno = p->lineno;
11269
11270  if (sqliterc == NULL) {
11271    home_dir = find_home_dir(0);
11272    if( home_dir==0 ){
11273      raw_printf(stderr, "-- warning: cannot find home directory;"
11274                      " cannot read ~/.sqliterc\n");
11275      return;
11276    }
11277    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11278    shell_check_oom(zBuf);
11279    sqliterc = zBuf;
11280  }
11281  p->in = fopen(sqliterc,"rb");
11282  if( p->in ){
11283    if( stdin_is_interactive ){
11284      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11285    }
11286    if( process_input(p) && bail_on_error ) exit(1);
11287    fclose(p->in);
11288  }else if( sqliterc_override!=0 ){
11289    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11290    if( bail_on_error ) exit(1);
11291  }
11292  p->in = inSaved;
11293  p->lineno = savedLineno;
11294  sqlite3_free(zBuf);
11295}
11296
11297/*
11298** Show available command line options
11299*/
11300static const char zOptions[] =
11301#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11302  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11303#endif
11304  "   -append              append the database to the end of the file\n"
11305  "   -ascii               set output mode to 'ascii'\n"
11306  "   -bail                stop after hitting an error\n"
11307  "   -batch               force batch I/O\n"
11308  "   -box                 set output mode to 'box'\n"
11309  "   -column              set output mode to 'column'\n"
11310  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11311  "   -csv                 set output mode to 'csv'\n"
11312#if !defined(SQLITE_OMIT_DESERIALIZE)
11313  "   -deserialize         open the database using sqlite3_deserialize()\n"
11314#endif
11315  "   -echo                print inputs before execution\n"
11316  "   -init FILENAME       read/process named file\n"
11317  "   -[no]header          turn headers on or off\n"
11318#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11319  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11320#endif
11321  "   -help                show this message\n"
11322  "   -html                set output mode to HTML\n"
11323  "   -interactive         force interactive I/O\n"
11324  "   -json                set output mode to 'json'\n"
11325  "   -line                set output mode to 'line'\n"
11326  "   -list                set output mode to 'list'\n"
11327  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11328  "   -markdown            set output mode to 'markdown'\n"
11329#if !defined(SQLITE_OMIT_DESERIALIZE)
11330  "   -maxsize N           maximum size for a --deserialize database\n"
11331#endif
11332  "   -memtrace            trace all memory allocations and deallocations\n"
11333  "   -mmap N              default mmap size set to N\n"
11334#ifdef SQLITE_ENABLE_MULTIPLEX
11335  "   -multiplex           enable the multiplexor VFS\n"
11336#endif
11337  "   -newline SEP         set output row separator. Default: '\\n'\n"
11338  "   -nofollow            refuse to open symbolic links to database files\n"
11339  "   -nonce STRING        set the safe-mode escape nonce\n"
11340  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11341  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11342  "   -quote               set output mode to 'quote'\n"
11343  "   -readonly            open the database read-only\n"
11344  "   -safe                enable safe-mode\n"
11345  "   -separator SEP       set output column separator. Default: '|'\n"
11346#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11347  "   -sorterref SIZE      sorter references threshold size\n"
11348#endif
11349  "   -stats               print memory stats before each finalize\n"
11350  "   -table               set output mode to 'table'\n"
11351  "   -tabs                set output mode to 'tabs'\n"
11352  "   -version             show SQLite version\n"
11353  "   -vfs NAME            use NAME as the default VFS\n"
11354#ifdef SQLITE_ENABLE_VFSTRACE
11355  "   -vfstrace            enable tracing of all VFS calls\n"
11356#endif
11357#ifdef SQLITE_HAVE_ZLIB
11358  "   -zip                 open the file as a ZIP Archive\n"
11359#endif
11360;
11361static void usage(int showDetail){
11362  utf8_printf(stderr,
11363      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11364      "FILENAME is the name of an SQLite database. A new database is created\n"
11365      "if the file does not previously exist.\n", Argv0);
11366  if( showDetail ){
11367    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11368  }else{
11369    raw_printf(stderr, "Use the -help option for additional information\n");
11370  }
11371  exit(1);
11372}
11373
11374/*
11375** Internal check:  Verify that the SQLite is uninitialized.  Print a
11376** error message if it is initialized.
11377*/
11378static void verify_uninitialized(void){
11379  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11380    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11381                        " initialization.\n");
11382  }
11383}
11384
11385/*
11386** Initialize the state information in data
11387*/
11388static void main_init(ShellState *data) {
11389  memset(data, 0, sizeof(*data));
11390  data->normalMode = data->cMode = data->mode = MODE_List;
11391  data->autoExplain = 1;
11392  data->pAuxDb = &data->aAuxDb[0];
11393  memcpy(data->colSeparator,SEP_Column, 2);
11394  memcpy(data->rowSeparator,SEP_Row, 2);
11395  data->showHeader = 0;
11396  data->shellFlgs = SHFLG_Lookaside;
11397  verify_uninitialized();
11398  sqlite3_config(SQLITE_CONFIG_URI, 1);
11399  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11400  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11401  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11402  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11403}
11404
11405/*
11406** Output text to the console in a font that attracts extra attention.
11407*/
11408#ifdef _WIN32
11409static void printBold(const char *zText){
11410#if !SQLITE_OS_WINRT
11411  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11412  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11413  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11414  SetConsoleTextAttribute(out,
11415         FOREGROUND_RED|FOREGROUND_INTENSITY
11416  );
11417#endif
11418  printf("%s", zText);
11419#if !SQLITE_OS_WINRT
11420  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11421#endif
11422}
11423#else
11424static void printBold(const char *zText){
11425  printf("\033[1m%s\033[0m", zText);
11426}
11427#endif
11428
11429/*
11430** Get the argument to an --option.  Throw an error and die if no argument
11431** is available.
11432*/
11433static char *cmdline_option_value(int argc, char **argv, int i){
11434  if( i==argc ){
11435    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11436            argv[0], argv[argc-1]);
11437    exit(1);
11438  }
11439  return argv[i];
11440}
11441
11442#ifndef SQLITE_SHELL_IS_UTF8
11443#  if (defined(_WIN32) || defined(WIN32)) \
11444   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11445#    define SQLITE_SHELL_IS_UTF8          (0)
11446#  else
11447#    define SQLITE_SHELL_IS_UTF8          (1)
11448#  endif
11449#endif
11450
11451#ifdef SQLITE_SHELL_FIDDLE
11452#  define main fiddle_main
11453#endif
11454
11455#if SQLITE_SHELL_IS_UTF8
11456int SQLITE_CDECL main(int argc, char **argv){
11457#else
11458int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11459  char **argv;
11460#endif
11461#ifdef SQLITE_DEBUG
11462  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
11463#endif
11464  char *zErrMsg = 0;
11465#ifdef SQLITE_SHELL_FIDDLE
11466#  define data shellState
11467#else
11468  ShellState data;
11469#endif
11470  const char *zInitFile = 0;
11471  int i;
11472  int rc = 0;
11473  int warnInmemoryDb = 0;
11474  int readStdin = 1;
11475  int nCmd = 0;
11476  char **azCmd = 0;
11477  const char *zVfs = 0;           /* Value of -vfs command-line option */
11478#if !SQLITE_SHELL_IS_UTF8
11479  char **argvToFree = 0;
11480  int argcToFree = 0;
11481#endif
11482
11483  setBinaryMode(stdin, 0);
11484  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11485#ifdef SQLITE_SHELL_FIDDLE
11486  stdin_is_interactive = 0;
11487  stdout_is_console = 1;
11488  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
11489#else
11490  stdin_is_interactive = isatty(0);
11491  stdout_is_console = isatty(1);
11492#endif
11493
11494#if !defined(_WIN32_WCE)
11495  if( getenv("SQLITE_DEBUG_BREAK") ){
11496    if( isatty(0) && isatty(2) ){
11497      fprintf(stderr,
11498          "attach debugger to process %d and press any key to continue.\n",
11499          GETPID());
11500      fgetc(stdin);
11501    }else{
11502#if defined(_WIN32) || defined(WIN32)
11503#if SQLITE_OS_WINRT
11504      __debugbreak();
11505#else
11506      DebugBreak();
11507#endif
11508#elif defined(SIGTRAP)
11509      raise(SIGTRAP);
11510#endif
11511    }
11512  }
11513#endif
11514
11515#if USE_SYSTEM_SQLITE+0!=1
11516  if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11517    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11518            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11519    exit(1);
11520  }
11521#endif
11522  main_init(&data);
11523
11524  /* On Windows, we must translate command-line arguments into UTF-8.
11525  ** The SQLite memory allocator subsystem has to be enabled in order to
11526  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11527  ** subsequent sqlite3_config() calls will work.  So copy all results into
11528  ** memory that does not come from the SQLite memory allocator.
11529  */
11530#if !SQLITE_SHELL_IS_UTF8
11531  sqlite3_initialize();
11532  argvToFree = malloc(sizeof(argv[0])*argc*2);
11533  shell_check_oom(argvToFree);
11534  argcToFree = argc;
11535  argv = argvToFree + argc;
11536  for(i=0; i<argc; i++){
11537    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11538    i64 n;
11539    shell_check_oom(z);
11540    n = strlen(z);
11541    argv[i] = malloc( n+1 );
11542    shell_check_oom(argv[i]);
11543    memcpy(argv[i], z, n+1);
11544    argvToFree[i] = argv[i];
11545    sqlite3_free(z);
11546  }
11547  sqlite3_shutdown();
11548#endif
11549
11550  assert( argc>=1 && argv && argv[0] );
11551  Argv0 = argv[0];
11552
11553  /* Make sure we have a valid signal handler early, before anything
11554  ** else is done.
11555  */
11556#ifdef SIGINT
11557  signal(SIGINT, interrupt_handler);
11558#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11559  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11560#endif
11561
11562#ifdef SQLITE_SHELL_DBNAME_PROC
11563  {
11564    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11565    ** of a C-function that will provide the name of the database file.  Use
11566    ** this compile-time option to embed this shell program in larger
11567    ** applications. */
11568    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11569    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11570    warnInmemoryDb = 0;
11571  }
11572#endif
11573
11574  /* Do an initial pass through the command-line argument to locate
11575  ** the name of the database file, the name of the initialization file,
11576  ** the size of the alternative malloc heap,
11577  ** and the first command to execute.
11578  */
11579  verify_uninitialized();
11580  for(i=1; i<argc; i++){
11581    char *z;
11582    z = argv[i];
11583    if( z[0]!='-' ){
11584      if( data.aAuxDb->zDbFilename==0 ){
11585        data.aAuxDb->zDbFilename = z;
11586      }else{
11587        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11588        ** mean that nothing is read from stdin */
11589        readStdin = 0;
11590        nCmd++;
11591        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11592        shell_check_oom(azCmd);
11593        azCmd[nCmd-1] = z;
11594      }
11595    }
11596    if( z[1]=='-' ) z++;
11597    if( cli_strcmp(z,"-separator")==0
11598     || cli_strcmp(z,"-nullvalue")==0
11599     || cli_strcmp(z,"-newline")==0
11600     || cli_strcmp(z,"-cmd")==0
11601    ){
11602      (void)cmdline_option_value(argc, argv, ++i);
11603    }else if( cli_strcmp(z,"-init")==0 ){
11604      zInitFile = cmdline_option_value(argc, argv, ++i);
11605    }else if( cli_strcmp(z,"-batch")==0 ){
11606      /* Need to check for batch mode here to so we can avoid printing
11607      ** informational messages (like from process_sqliterc) before
11608      ** we do the actual processing of arguments later in a second pass.
11609      */
11610      stdin_is_interactive = 0;
11611    }else if( cli_strcmp(z,"-heap")==0 ){
11612#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11613      const char *zSize;
11614      sqlite3_int64 szHeap;
11615
11616      zSize = cmdline_option_value(argc, argv, ++i);
11617      szHeap = integerValue(zSize);
11618      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11619      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11620#else
11621      (void)cmdline_option_value(argc, argv, ++i);
11622#endif
11623    }else if( cli_strcmp(z,"-pagecache")==0 ){
11624      sqlite3_int64 n, sz;
11625      sz = integerValue(cmdline_option_value(argc,argv,++i));
11626      if( sz>70000 ) sz = 70000;
11627      if( sz<0 ) sz = 0;
11628      n = integerValue(cmdline_option_value(argc,argv,++i));
11629      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11630        n = 0xffffffffffffLL/sz;
11631      }
11632      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11633                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11634      data.shellFlgs |= SHFLG_Pagecache;
11635    }else if( cli_strcmp(z,"-lookaside")==0 ){
11636      int n, sz;
11637      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11638      if( sz<0 ) sz = 0;
11639      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11640      if( n<0 ) n = 0;
11641      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11642      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11643    }else if( cli_strcmp(z,"-threadsafe")==0 ){
11644      int n;
11645      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11646      switch( n ){
11647         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11648         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11649         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11650      }
11651#ifdef SQLITE_ENABLE_VFSTRACE
11652    }else if( cli_strcmp(z,"-vfstrace")==0 ){
11653      extern int vfstrace_register(
11654         const char *zTraceName,
11655         const char *zOldVfsName,
11656         int (*xOut)(const char*,void*),
11657         void *pOutArg,
11658         int makeDefault
11659      );
11660      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11661#endif
11662#ifdef SQLITE_ENABLE_MULTIPLEX
11663    }else if( cli_strcmp(z,"-multiplex")==0 ){
11664      extern int sqlite3_multiple_initialize(const char*,int);
11665      sqlite3_multiplex_initialize(0, 1);
11666#endif
11667    }else if( cli_strcmp(z,"-mmap")==0 ){
11668      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11669      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11670#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11671    }else if( cli_strcmp(z,"-sorterref")==0 ){
11672      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11673      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11674#endif
11675    }else if( cli_strcmp(z,"-vfs")==0 ){
11676      zVfs = cmdline_option_value(argc, argv, ++i);
11677#ifdef SQLITE_HAVE_ZLIB
11678    }else if( cli_strcmp(z,"-zip")==0 ){
11679      data.openMode = SHELL_OPEN_ZIPFILE;
11680#endif
11681    }else if( cli_strcmp(z,"-append")==0 ){
11682      data.openMode = SHELL_OPEN_APPENDVFS;
11683#ifndef SQLITE_OMIT_DESERIALIZE
11684    }else if( cli_strcmp(z,"-deserialize")==0 ){
11685      data.openMode = SHELL_OPEN_DESERIALIZE;
11686    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
11687      data.szMax = integerValue(argv[++i]);
11688#endif
11689    }else if( cli_strcmp(z,"-readonly")==0 ){
11690      data.openMode = SHELL_OPEN_READONLY;
11691    }else if( cli_strcmp(z,"-nofollow")==0 ){
11692      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11693#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11694    }else if( cli_strncmp(z, "-A",2)==0 ){
11695      /* All remaining command-line arguments are passed to the ".archive"
11696      ** command, so ignore them */
11697      break;
11698#endif
11699    }else if( cli_strcmp(z, "-memtrace")==0 ){
11700      sqlite3MemTraceActivate(stderr);
11701    }else if( cli_strcmp(z,"-bail")==0 ){
11702      bail_on_error = 1;
11703    }else if( cli_strcmp(z,"-nonce")==0 ){
11704      free(data.zNonce);
11705      data.zNonce = strdup(argv[++i]);
11706    }else if( cli_strcmp(z,"-safe")==0 ){
11707      /* no-op - catch this on the second pass */
11708    }
11709  }
11710  verify_uninitialized();
11711
11712
11713#ifdef SQLITE_SHELL_INIT_PROC
11714  {
11715    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11716    ** of a C-function that will perform initialization actions on SQLite that
11717    ** occur just before or after sqlite3_initialize(). Use this compile-time
11718    ** option to embed this shell program in larger applications. */
11719    extern void SQLITE_SHELL_INIT_PROC(void);
11720    SQLITE_SHELL_INIT_PROC();
11721  }
11722#else
11723  /* All the sqlite3_config() calls have now been made. So it is safe
11724  ** to call sqlite3_initialize() and process any command line -vfs option. */
11725  sqlite3_initialize();
11726#endif
11727
11728  if( zVfs ){
11729    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11730    if( pVfs ){
11731      sqlite3_vfs_register(pVfs, 1);
11732    }else{
11733      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11734      exit(1);
11735    }
11736  }
11737
11738  if( data.pAuxDb->zDbFilename==0 ){
11739#ifndef SQLITE_OMIT_MEMORYDB
11740    data.pAuxDb->zDbFilename = ":memory:";
11741    warnInmemoryDb = argc==1;
11742#else
11743    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11744    return 1;
11745#endif
11746  }
11747  data.out = stdout;
11748#ifndef SQLITE_SHELL_FIDDLE
11749  sqlite3_appendvfs_init(0,0,0);
11750#endif
11751
11752  /* Go ahead and open the database file if it already exists.  If the
11753  ** file does not exist, delay opening it.  This prevents empty database
11754  ** files from being created if a user mistypes the database name argument
11755  ** to the sqlite command-line tool.
11756  */
11757  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11758    open_db(&data, 0);
11759  }
11760
11761  /* Process the initialization file if there is one.  If no -init option
11762  ** is given on the command line, look for a file named ~/.sqliterc and
11763  ** try to process it.
11764  */
11765  process_sqliterc(&data,zInitFile);
11766
11767  /* Make a second pass through the command-line argument and set
11768  ** options.  This second pass is delayed until after the initialization
11769  ** file is processed so that the command-line arguments will override
11770  ** settings in the initialization file.
11771  */
11772  for(i=1; i<argc; i++){
11773    char *z = argv[i];
11774    if( z[0]!='-' ) continue;
11775    if( z[1]=='-' ){ z++; }
11776    if( cli_strcmp(z,"-init")==0 ){
11777      i++;
11778    }else if( cli_strcmp(z,"-html")==0 ){
11779      data.mode = MODE_Html;
11780    }else if( cli_strcmp(z,"-list")==0 ){
11781      data.mode = MODE_List;
11782    }else if( cli_strcmp(z,"-quote")==0 ){
11783      data.mode = MODE_Quote;
11784      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11785      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11786    }else if( cli_strcmp(z,"-line")==0 ){
11787      data.mode = MODE_Line;
11788    }else if( cli_strcmp(z,"-column")==0 ){
11789      data.mode = MODE_Column;
11790    }else if( cli_strcmp(z,"-json")==0 ){
11791      data.mode = MODE_Json;
11792    }else if( cli_strcmp(z,"-markdown")==0 ){
11793      data.mode = MODE_Markdown;
11794    }else if( cli_strcmp(z,"-table")==0 ){
11795      data.mode = MODE_Table;
11796    }else if( cli_strcmp(z,"-box")==0 ){
11797      data.mode = MODE_Box;
11798    }else if( cli_strcmp(z,"-csv")==0 ){
11799      data.mode = MODE_Csv;
11800      memcpy(data.colSeparator,",",2);
11801#ifdef SQLITE_HAVE_ZLIB
11802    }else if( cli_strcmp(z,"-zip")==0 ){
11803      data.openMode = SHELL_OPEN_ZIPFILE;
11804#endif
11805    }else if( cli_strcmp(z,"-append")==0 ){
11806      data.openMode = SHELL_OPEN_APPENDVFS;
11807#ifndef SQLITE_OMIT_DESERIALIZE
11808    }else if( cli_strcmp(z,"-deserialize")==0 ){
11809      data.openMode = SHELL_OPEN_DESERIALIZE;
11810    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
11811      data.szMax = integerValue(argv[++i]);
11812#endif
11813    }else if( cli_strcmp(z,"-readonly")==0 ){
11814      data.openMode = SHELL_OPEN_READONLY;
11815    }else if( cli_strcmp(z,"-nofollow")==0 ){
11816      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11817    }else if( cli_strcmp(z,"-ascii")==0 ){
11818      data.mode = MODE_Ascii;
11819      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11820      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11821    }else if( cli_strcmp(z,"-tabs")==0 ){
11822      data.mode = MODE_List;
11823      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11824      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11825    }else if( cli_strcmp(z,"-separator")==0 ){
11826      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11827                       "%s",cmdline_option_value(argc,argv,++i));
11828    }else if( cli_strcmp(z,"-newline")==0 ){
11829      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11830                       "%s",cmdline_option_value(argc,argv,++i));
11831    }else if( cli_strcmp(z,"-nullvalue")==0 ){
11832      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11833                       "%s",cmdline_option_value(argc,argv,++i));
11834    }else if( cli_strcmp(z,"-header")==0 ){
11835      data.showHeader = 1;
11836      ShellSetFlag(&data, SHFLG_HeaderSet);
11837     }else if( cli_strcmp(z,"-noheader")==0 ){
11838      data.showHeader = 0;
11839      ShellSetFlag(&data, SHFLG_HeaderSet);
11840    }else if( cli_strcmp(z,"-echo")==0 ){
11841      ShellSetFlag(&data, SHFLG_Echo);
11842    }else if( cli_strcmp(z,"-eqp")==0 ){
11843      data.autoEQP = AUTOEQP_on;
11844    }else if( cli_strcmp(z,"-eqpfull")==0 ){
11845      data.autoEQP = AUTOEQP_full;
11846    }else if( cli_strcmp(z,"-stats")==0 ){
11847      data.statsOn = 1;
11848    }else if( cli_strcmp(z,"-scanstats")==0 ){
11849      data.scanstatsOn = 1;
11850    }else if( cli_strcmp(z,"-backslash")==0 ){
11851      /* Undocumented command-line option: -backslash
11852      ** Causes C-style backslash escapes to be evaluated in SQL statements
11853      ** prior to sending the SQL into SQLite.  Useful for injecting
11854      ** crazy bytes in the middle of SQL statements for testing and debugging.
11855      */
11856      ShellSetFlag(&data, SHFLG_Backslash);
11857    }else if( cli_strcmp(z,"-bail")==0 ){
11858      /* No-op.  The bail_on_error flag should already be set. */
11859    }else if( cli_strcmp(z,"-version")==0 ){
11860      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11861      return 0;
11862    }else if( cli_strcmp(z,"-interactive")==0 ){
11863      stdin_is_interactive = 1;
11864    }else if( cli_strcmp(z,"-batch")==0 ){
11865      stdin_is_interactive = 0;
11866    }else if( cli_strcmp(z,"-heap")==0 ){
11867      i++;
11868    }else if( cli_strcmp(z,"-pagecache")==0 ){
11869      i+=2;
11870    }else if( cli_strcmp(z,"-lookaside")==0 ){
11871      i+=2;
11872    }else if( cli_strcmp(z,"-threadsafe")==0 ){
11873      i+=2;
11874    }else if( cli_strcmp(z,"-nonce")==0 ){
11875      i += 2;
11876    }else if( cli_strcmp(z,"-mmap")==0 ){
11877      i++;
11878    }else if( cli_strcmp(z,"-memtrace")==0 ){
11879      i++;
11880#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11881    }else if( cli_strcmp(z,"-sorterref")==0 ){
11882      i++;
11883#endif
11884    }else if( cli_strcmp(z,"-vfs")==0 ){
11885      i++;
11886#ifdef SQLITE_ENABLE_VFSTRACE
11887    }else if( cli_strcmp(z,"-vfstrace")==0 ){
11888      i++;
11889#endif
11890#ifdef SQLITE_ENABLE_MULTIPLEX
11891    }else if( cli_strcmp(z,"-multiplex")==0 ){
11892      i++;
11893#endif
11894    }else if( cli_strcmp(z,"-help")==0 ){
11895      usage(1);
11896    }else if( cli_strcmp(z,"-cmd")==0 ){
11897      /* Run commands that follow -cmd first and separately from commands
11898      ** that simply appear on the command-line.  This seems goofy.  It would
11899      ** be better if all commands ran in the order that they appear.  But
11900      ** we retain the goofy behavior for historical compatibility. */
11901      if( i==argc-1 ) break;
11902      z = cmdline_option_value(argc,argv,++i);
11903      if( z[0]=='.' ){
11904        rc = do_meta_command(z, &data);
11905        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11906      }else{
11907        open_db(&data, 0);
11908        rc = shell_exec(&data, z, &zErrMsg);
11909        if( zErrMsg!=0 ){
11910          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11911          if( bail_on_error ) return rc!=0 ? rc : 1;
11912        }else if( rc!=0 ){
11913          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11914          if( bail_on_error ) return rc;
11915        }
11916      }
11917#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11918    }else if( cli_strncmp(z, "-A", 2)==0 ){
11919      if( nCmd>0 ){
11920        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11921                            " with \"%s\"\n", z);
11922        return 1;
11923      }
11924      open_db(&data, OPEN_DB_ZIPFILE);
11925      if( z[2] ){
11926        argv[i] = &z[2];
11927        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11928      }else{
11929        arDotCommand(&data, 1, argv+i, argc-i);
11930      }
11931      readStdin = 0;
11932      break;
11933#endif
11934    }else if( cli_strcmp(z,"-safe")==0 ){
11935      data.bSafeMode = data.bSafeModePersist = 1;
11936    }else{
11937      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11938      raw_printf(stderr,"Use -help for a list of options.\n");
11939      return 1;
11940    }
11941    data.cMode = data.mode;
11942  }
11943
11944  if( !readStdin ){
11945    /* Run all arguments that do not begin with '-' as if they were separate
11946    ** command-line inputs, except for the argToSkip argument which contains
11947    ** the database filename.
11948    */
11949    for(i=0; i<nCmd; i++){
11950      if( azCmd[i][0]=='.' ){
11951        rc = do_meta_command(azCmd[i], &data);
11952        if( rc ){
11953          free(azCmd);
11954          return rc==2 ? 0 : rc;
11955        }
11956      }else{
11957        open_db(&data, 0);
11958        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11959        if( zErrMsg || rc ){
11960          if( zErrMsg!=0 ){
11961            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11962          }else{
11963            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11964          }
11965          sqlite3_free(zErrMsg);
11966          free(azCmd);
11967          return rc!=0 ? rc : 1;
11968        }
11969      }
11970    }
11971  }else{
11972    /* Run commands received from standard input
11973    */
11974    if( stdin_is_interactive ){
11975      char *zHome;
11976      char *zHistory;
11977      int nHistory;
11978      printf(
11979        "SQLite version %s %.19s\n" /*extra-version-info*/
11980        "Enter \".help\" for usage hints.\n",
11981        sqlite3_libversion(), sqlite3_sourceid()
11982      );
11983      if( warnInmemoryDb ){
11984        printf("Connected to a ");
11985        printBold("transient in-memory database");
11986        printf(".\nUse \".open FILENAME\" to reopen on a "
11987               "persistent database.\n");
11988      }
11989      zHistory = getenv("SQLITE_HISTORY");
11990      if( zHistory ){
11991        zHistory = strdup(zHistory);
11992      }else if( (zHome = find_home_dir(0))!=0 ){
11993        nHistory = strlen30(zHome) + 20;
11994        if( (zHistory = malloc(nHistory))!=0 ){
11995          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11996        }
11997      }
11998      if( zHistory ){ shell_read_history(zHistory); }
11999#if HAVE_READLINE || HAVE_EDITLINE
12000      rl_attempted_completion_function = readline_completion;
12001#elif HAVE_LINENOISE
12002      linenoiseSetCompletionCallback(linenoise_completion);
12003#endif
12004      data.in = 0;
12005      rc = process_input(&data);
12006      if( zHistory ){
12007        shell_stifle_history(2000);
12008        shell_write_history(zHistory);
12009        free(zHistory);
12010      }
12011    }else{
12012      data.in = stdin;
12013      rc = process_input(&data);
12014    }
12015  }
12016#ifndef SQLITE_SHELL_FIDDLE
12017  /* In WASM mode we have to leave the db state in place so that
12018  ** client code can "push" SQL into it after this call returns. */
12019  free(azCmd);
12020  set_table_name(&data, 0);
12021  if( data.db ){
12022    session_close_all(&data, -1);
12023    close_db(data.db);
12024  }
12025  for(i=0; i<ArraySize(data.aAuxDb); i++){
12026    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12027    if( data.aAuxDb[i].db ){
12028      session_close_all(&data, i);
12029      close_db(data.aAuxDb[i].db);
12030    }
12031  }
12032  find_home_dir(1);
12033  output_reset(&data);
12034  data.doXdgOpen = 0;
12035  clearTempFile(&data);
12036#if !SQLITE_SHELL_IS_UTF8
12037  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12038  free(argvToFree);
12039#endif
12040  free(data.colWidth);
12041  free(data.zNonce);
12042  /* Clear the global data structure so that valgrind will detect memory
12043  ** leaks */
12044  memset(&data, 0, sizeof(data));
12045#ifdef SQLITE_DEBUG
12046  if( sqlite3_memory_used()>mem_main_enter ){
12047    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12048                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12049  }
12050#endif
12051#endif /* !SQLITE_SHELL_FIDDLE */
12052  return rc;
12053}
12054
12055
12056#ifdef SQLITE_SHELL_FIDDLE
12057/* Only for emcc experimentation purposes. */
12058int fiddle_experiment(int a,int b){
12059  return a + b;
12060}
12061
12062/*
12063** Returns a pointer to the current DB handle.
12064*/
12065sqlite3 * fiddle_db_handle(){
12066  return globalDb;
12067}
12068
12069/*
12070** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12071** "main" is assumed. Returns 0 if no db with the given name is
12072** open.
12073*/
12074sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12075  sqlite3_vfs * pVfs = 0;
12076  if(globalDb){
12077    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12078                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
12079  }
12080  return pVfs;
12081}
12082
12083/* Only for emcc experimentation purposes. */
12084sqlite3 * fiddle_db_arg(sqlite3 *arg){
12085    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12086    return arg;
12087}
12088
12089/*
12090** Intended to be called via a SharedWorker() while a separate
12091** SharedWorker() (which manages the wasm module) is performing work
12092** which should be interrupted. Unfortunately, SharedWorker is not
12093** portable enough to make real use of.
12094*/
12095void fiddle_interrupt(void){
12096  if( globalDb ) sqlite3_interrupt(globalDb);
12097}
12098
12099/*
12100** Returns the filename of the given db name, assuming "main" if
12101** zDbName is NULL. Returns NULL if globalDb is not opened.
12102*/
12103const char * fiddle_db_filename(const char * zDbName){
12104    return globalDb
12105      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12106      : NULL;
12107}
12108
12109/*
12110** Completely wipes out the contents of the currently-opened database
12111** but leaves its storage intact for reuse.
12112*/
12113void fiddle_reset_db(void){
12114  if( globalDb ){
12115    int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12116    if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12117    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12118  }
12119}
12120
12121/*
12122** Uses the current database's VFS xRead to stream the db file's
12123** contents out to the given callback. The callback gets a single
12124** chunk of size n (its 2nd argument) on each call and must return 0
12125** on success, non-0 on error. This function returns 0 on success,
12126** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12127** code from the callback. Note that this is not thread-friendly: it
12128** expects that it will be the only thread reading the db file and
12129** takes no measures to ensure that is the case.
12130*/
12131int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12132  sqlite3_int64 nSize = 0;
12133  sqlite3_int64 nPos = 0;
12134  sqlite3_file * pFile = 0;
12135  unsigned char buf[1024 * 8];
12136  int nBuf = (int)sizeof(buf);
12137  int rc = shellState.db
12138    ? sqlite3_file_control(shellState.db, "main",
12139                           SQLITE_FCNTL_FILE_POINTER, &pFile)
12140    : SQLITE_NOTFOUND;
12141  if( rc ) return rc;
12142  rc = pFile->pMethods->xFileSize(pFile, &nSize);
12143  if( rc ) return rc;
12144  if(nSize % nBuf){
12145    /* DB size is not an even multiple of the buffer size. Reduce
12146    ** buffer size so that we do not unduly inflate the db size when
12147    ** exporting. */
12148    if(0 == nSize % 4096) nBuf = 4096;
12149    else if(0 == nSize % 2048) nBuf = 2048;
12150    else if(0 == nSize % 1024) nBuf = 1024;
12151    else nBuf = 512;
12152  }
12153  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12154    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12155    if(SQLITE_IOERR_SHORT_READ == rc){
12156      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12157    }
12158    if( 0==rc ) rc = xCallback(buf, nBuf);
12159  }
12160  return rc;
12161}
12162
12163/*
12164** Trivial exportable function for emscripten. It processes zSql as if
12165** it were input to the sqlite3 shell and redirects all output to the
12166** wasm binding. fiddle_main() must have been called before this
12167** is called, or results are undefined.
12168*/
12169void fiddle_exec(const char * zSql){
12170  if(zSql && *zSql){
12171    if('.'==*zSql) puts(zSql);
12172    shellState.wasm.zInput = zSql;
12173    shellState.wasm.zPos = zSql;
12174    process_input(&shellState);
12175    shellState.wasm.zInput = shellState.wasm.zPos = 0;
12176  }
12177}
12178#endif /* SQLITE_SHELL_FIDDLE */
12179