xref: /sqlite-3.40.0/src/shell.c.in (revision 549907fd)
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  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4519  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4520  "   --no-rowids              Do not attempt to recover rowid values",
4521  "                            that are not also INTEGER PRIMARY KEYs",
4522#endif
4523#ifndef SQLITE_SHELL_FIDDLE
4524  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4525  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4526#endif
4527  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4528  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4529  "   Options:",
4530  "      --indent             Try to pretty-print the schema",
4531  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4532  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4533  "    Options:",
4534  "       --init               Create a new SELFTEST table",
4535  "       -v                   Verbose output",
4536  ".separator COL ?ROW?     Change the column and row separators",
4537#if defined(SQLITE_ENABLE_SESSION)
4538  ".session ?NAME? CMD ...  Create or control sessions",
4539  "   Subcommands:",
4540  "     attach TABLE             Attach TABLE",
4541  "     changeset FILE           Write a changeset into FILE",
4542  "     close                    Close one session",
4543  "     enable ?BOOLEAN?         Set or query the enable bit",
4544  "     filter GLOB...           Reject tables matching GLOBs",
4545  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4546  "     isempty                  Query whether the session is empty",
4547  "     list                     List currently open session names",
4548  "     open DB NAME             Open a new session on DB",
4549  "     patchset FILE            Write a patchset into FILE",
4550  "   If ?NAME? is omitted, the first defined session is used.",
4551#endif
4552  ".sha3sum ...             Compute a SHA3 hash of database content",
4553  "    Options:",
4554  "      --schema              Also hash the sqlite_schema table",
4555  "      --sha3-224            Use the sha3-224 algorithm",
4556  "      --sha3-256            Use the sha3-256 algorithm (default)",
4557  "      --sha3-384            Use the sha3-384 algorithm",
4558  "      --sha3-512            Use the sha3-512 algorithm",
4559  "    Any other argument is a LIKE pattern for tables to hash",
4560#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4561  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4562#endif
4563  ".show                    Show the current values for various settings",
4564  ".stats ?ARG?             Show stats or turn stats on or off",
4565  "   off                      Turn off automatic stat display",
4566  "   on                       Turn on automatic stat display",
4567  "   stmt                     Show statement stats",
4568  "   vmstep                   Show the virtual machine step count only",
4569#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4570  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4571#endif
4572  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4573#ifndef SQLITE_SHELL_FIDDLE
4574  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4575#endif
4576  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4577  "                           Run \".testctrl\" with no arguments for details",
4578  ".timeout MS              Try opening locked tables for MS milliseconds",
4579  ".timer on|off            Turn SQL timer on or off",
4580#ifndef SQLITE_OMIT_TRACE
4581  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4582  "    FILE                    Send output to FILE",
4583  "    stdout                  Send output to stdout",
4584  "    stderr                  Send output to stderr",
4585  "    off                     Disable tracing",
4586  "    --expanded              Expand query parameters",
4587#ifdef SQLITE_ENABLE_NORMALIZE
4588  "    --normalized            Normal the SQL statements",
4589#endif
4590  "    --plain                 Show SQL as it is input",
4591  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4592  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4593  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4594  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4595#endif /* SQLITE_OMIT_TRACE */
4596#ifdef SQLITE_DEBUG
4597  ".unmodule NAME ...       Unregister virtual table modules",
4598  "    --allexcept             Unregister everything except those named",
4599#endif
4600  ".vfsinfo ?AUX?           Information about the top-level VFS",
4601  ".vfslist                 List all available VFSes",
4602  ".vfsname ?AUX?           Print the name of the VFS stack",
4603  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4604  "     Negative values right-justify",
4605};
4606
4607/*
4608** Output help text.
4609**
4610** zPattern describes the set of commands for which help text is provided.
4611** If zPattern is NULL, then show all commands, but only give a one-line
4612** description of each.
4613**
4614** Return the number of matches.
4615*/
4616static int showHelp(FILE *out, const char *zPattern){
4617  int i = 0;
4618  int j = 0;
4619  int n = 0;
4620  char *zPat;
4621  if( zPattern==0
4622   || zPattern[0]=='0'
4623   || cli_strcmp(zPattern,"-a")==0
4624   || cli_strcmp(zPattern,"-all")==0
4625   || cli_strcmp(zPattern,"--all")==0
4626  ){
4627    /* Show all commands, but only one line per command */
4628    if( zPattern==0 ) zPattern = "";
4629    for(i=0; i<ArraySize(azHelp); i++){
4630      if( azHelp[i][0]=='.' || zPattern[0] ){
4631        utf8_printf(out, "%s\n", azHelp[i]);
4632        n++;
4633      }
4634    }
4635  }else{
4636    /* Look for commands that for which zPattern is an exact prefix */
4637    zPat = sqlite3_mprintf(".%s*", zPattern);
4638    shell_check_oom(zPat);
4639    for(i=0; i<ArraySize(azHelp); i++){
4640      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4641        utf8_printf(out, "%s\n", azHelp[i]);
4642        j = i+1;
4643        n++;
4644      }
4645    }
4646    sqlite3_free(zPat);
4647    if( n ){
4648      if( n==1 ){
4649        /* when zPattern is a prefix of exactly one command, then include the
4650        ** details of that command, which should begin at offset j */
4651        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4652          utf8_printf(out, "%s\n", azHelp[j]);
4653          j++;
4654        }
4655      }
4656      return n;
4657    }
4658    /* Look for commands that contain zPattern anywhere.  Show the complete
4659    ** text of all commands that match. */
4660    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4661    shell_check_oom(zPat);
4662    for(i=0; i<ArraySize(azHelp); i++){
4663      if( azHelp[i][0]=='.' ) j = i;
4664      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4665        utf8_printf(out, "%s\n", azHelp[j]);
4666        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4667          j++;
4668          utf8_printf(out, "%s\n", azHelp[j]);
4669        }
4670        i = j;
4671        n++;
4672      }
4673    }
4674    sqlite3_free(zPat);
4675  }
4676  return n;
4677}
4678
4679/* Forward reference */
4680static int process_input(ShellState *p);
4681
4682/*
4683** Read the content of file zName into memory obtained from sqlite3_malloc64()
4684** and return a pointer to the buffer. The caller is responsible for freeing
4685** the memory.
4686**
4687** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4688** read.
4689**
4690** For convenience, a nul-terminator byte is always appended to the data read
4691** from the file before the buffer is returned. This byte is not included in
4692** the final value of (*pnByte), if applicable.
4693**
4694** NULL is returned if any error is encountered. The final value of *pnByte
4695** is undefined in this case.
4696*/
4697static char *readFile(const char *zName, int *pnByte){
4698  FILE *in = fopen(zName, "rb");
4699  long nIn;
4700  size_t nRead;
4701  char *pBuf;
4702  if( in==0 ) return 0;
4703  fseek(in, 0, SEEK_END);
4704  nIn = ftell(in);
4705  rewind(in);
4706  pBuf = sqlite3_malloc64( nIn+1 );
4707  if( pBuf==0 ){ fclose(in); return 0; }
4708  nRead = fread(pBuf, nIn, 1, in);
4709  fclose(in);
4710  if( nRead!=1 ){
4711    sqlite3_free(pBuf);
4712    return 0;
4713  }
4714  pBuf[nIn] = 0;
4715  if( pnByte ) *pnByte = nIn;
4716  return pBuf;
4717}
4718
4719#if defined(SQLITE_ENABLE_SESSION)
4720/*
4721** Close a single OpenSession object and release all of its associated
4722** resources.
4723*/
4724static void session_close(OpenSession *pSession){
4725  int i;
4726  sqlite3session_delete(pSession->p);
4727  sqlite3_free(pSession->zName);
4728  for(i=0; i<pSession->nFilter; i++){
4729    sqlite3_free(pSession->azFilter[i]);
4730  }
4731  sqlite3_free(pSession->azFilter);
4732  memset(pSession, 0, sizeof(OpenSession));
4733}
4734#endif
4735
4736/*
4737** Close all OpenSession objects and release all associated resources.
4738*/
4739#if defined(SQLITE_ENABLE_SESSION)
4740static void session_close_all(ShellState *p, int i){
4741  int j;
4742  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4743  for(j=0; j<pAuxDb->nSession; j++){
4744    session_close(&pAuxDb->aSession[j]);
4745  }
4746  pAuxDb->nSession = 0;
4747}
4748#else
4749# define session_close_all(X,Y)
4750#endif
4751
4752/*
4753** Implementation of the xFilter function for an open session.  Omit
4754** any tables named by ".session filter" but let all other table through.
4755*/
4756#if defined(SQLITE_ENABLE_SESSION)
4757static int session_filter(void *pCtx, const char *zTab){
4758  OpenSession *pSession = (OpenSession*)pCtx;
4759  int i;
4760  for(i=0; i<pSession->nFilter; i++){
4761    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4762  }
4763  return 1;
4764}
4765#endif
4766
4767/*
4768** Try to deduce the type of file for zName based on its content.  Return
4769** one of the SHELL_OPEN_* constants.
4770**
4771** If the file does not exist or is empty but its name looks like a ZIP
4772** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4773** Otherwise, assume an ordinary database regardless of the filename if
4774** the type cannot be determined from content.
4775*/
4776int deduceDatabaseType(const char *zName, int dfltZip){
4777  FILE *f = fopen(zName, "rb");
4778  size_t n;
4779  int rc = SHELL_OPEN_UNSPEC;
4780  char zBuf[100];
4781  if( f==0 ){
4782    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4783       return SHELL_OPEN_ZIPFILE;
4784    }else{
4785       return SHELL_OPEN_NORMAL;
4786    }
4787  }
4788  n = fread(zBuf, 16, 1, f);
4789  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4790    fclose(f);
4791    return SHELL_OPEN_NORMAL;
4792  }
4793  fseek(f, -25, SEEK_END);
4794  n = fread(zBuf, 25, 1, f);
4795  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4796    rc = SHELL_OPEN_APPENDVFS;
4797  }else{
4798    fseek(f, -22, SEEK_END);
4799    n = fread(zBuf, 22, 1, f);
4800    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4801       && zBuf[3]==0x06 ){
4802      rc = SHELL_OPEN_ZIPFILE;
4803    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4804      rc = SHELL_OPEN_ZIPFILE;
4805    }
4806  }
4807  fclose(f);
4808  return rc;
4809}
4810
4811#ifndef SQLITE_OMIT_DESERIALIZE
4812/*
4813** Reconstruct an in-memory database using the output from the "dbtotxt"
4814** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4815** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4816*/
4817static unsigned char *readHexDb(ShellState *p, int *pnData){
4818  unsigned char *a = 0;
4819  int nLine;
4820  int n = 0;
4821  int pgsz = 0;
4822  int iOffset = 0;
4823  int j, k;
4824  int rc;
4825  FILE *in;
4826  const char *zDbFilename = p->pAuxDb->zDbFilename;
4827  unsigned int x[16];
4828  char zLine[1000];
4829  if( zDbFilename ){
4830    in = fopen(zDbFilename, "r");
4831    if( in==0 ){
4832      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4833      return 0;
4834    }
4835    nLine = 0;
4836  }else{
4837    in = p->in;
4838    nLine = p->lineno;
4839    if( in==0 ) in = stdin;
4840  }
4841  *pnData = 0;
4842  nLine++;
4843  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4844  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4845  if( rc!=2 ) goto readHexDb_error;
4846  if( n<0 ) goto readHexDb_error;
4847  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4848  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4849  a = sqlite3_malloc( n ? n : 1 );
4850  shell_check_oom(a);
4851  memset(a, 0, n);
4852  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4853    utf8_printf(stderr, "invalid pagesize\n");
4854    goto readHexDb_error;
4855  }
4856  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4857    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4858    if( rc==2 ){
4859      iOffset = k;
4860      continue;
4861    }
4862    if( cli_strncmp(zLine, "| end ", 6)==0 ){
4863      break;
4864    }
4865    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4866                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4867                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4868    if( rc==17 ){
4869      k = iOffset+j;
4870      if( k+16<=n && k>=0 ){
4871        int ii;
4872        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4873      }
4874    }
4875  }
4876  *pnData = n;
4877  if( in!=p->in ){
4878    fclose(in);
4879  }else{
4880    p->lineno = nLine;
4881  }
4882  return a;
4883
4884readHexDb_error:
4885  if( in!=p->in ){
4886    fclose(in);
4887  }else{
4888    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4889      nLine++;
4890      if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
4891    }
4892    p->lineno = nLine;
4893  }
4894  sqlite3_free(a);
4895  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4896  return 0;
4897}
4898#endif /* SQLITE_OMIT_DESERIALIZE */
4899
4900/*
4901** Scalar function "shell_int32". The first argument to this function
4902** must be a blob. The second a non-negative integer. This function
4903** reads and returns a 32-bit big-endian integer from byte
4904** offset (4*<arg2>) of the blob.
4905*/
4906static void shellInt32(
4907  sqlite3_context *context,
4908  int argc,
4909  sqlite3_value **argv
4910){
4911  const unsigned char *pBlob;
4912  int nBlob;
4913  int iInt;
4914
4915  UNUSED_PARAMETER(argc);
4916  nBlob = sqlite3_value_bytes(argv[0]);
4917  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4918  iInt = sqlite3_value_int(argv[1]);
4919
4920  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4921    const unsigned char *a = &pBlob[iInt*4];
4922    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4923                       + ((sqlite3_int64)a[1]<<16)
4924                       + ((sqlite3_int64)a[2]<< 8)
4925                       + ((sqlite3_int64)a[3]<< 0);
4926    sqlite3_result_int64(context, iVal);
4927  }
4928}
4929
4930/*
4931** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4932** using "..." with internal double-quote characters doubled.
4933*/
4934static void shellIdQuote(
4935  sqlite3_context *context,
4936  int argc,
4937  sqlite3_value **argv
4938){
4939  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4940  UNUSED_PARAMETER(argc);
4941  if( zName ){
4942    char *z = sqlite3_mprintf("\"%w\"", zName);
4943    sqlite3_result_text(context, z, -1, sqlite3_free);
4944  }
4945}
4946
4947/*
4948** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4949*/
4950static void shellUSleepFunc(
4951  sqlite3_context *context,
4952  int argcUnused,
4953  sqlite3_value **argv
4954){
4955  int sleep = sqlite3_value_int(argv[0]);
4956  (void)argcUnused;
4957  sqlite3_sleep(sleep/1000);
4958  sqlite3_result_int(context, sleep);
4959}
4960
4961/*
4962** Scalar function "shell_escape_crnl" used by the .recover command.
4963** The argument passed to this function is the output of built-in
4964** function quote(). If the first character of the input is "'",
4965** indicating that the value passed to quote() was a text value,
4966** then this function searches the input for "\n" and "\r" characters
4967** and adds a wrapper similar to the following:
4968**
4969**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4970**
4971** Or, if the first character of the input is not "'", then a copy
4972** of the input is returned.
4973*/
4974static void shellEscapeCrnl(
4975  sqlite3_context *context,
4976  int argc,
4977  sqlite3_value **argv
4978){
4979  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4980  UNUSED_PARAMETER(argc);
4981  if( zText && zText[0]=='\'' ){
4982    i64 nText = sqlite3_value_bytes(argv[0]);
4983    i64 i;
4984    char zBuf1[20];
4985    char zBuf2[20];
4986    const char *zNL = 0;
4987    const char *zCR = 0;
4988    i64 nCR = 0;
4989    i64 nNL = 0;
4990
4991    for(i=0; zText[i]; i++){
4992      if( zNL==0 && zText[i]=='\n' ){
4993        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4994        nNL = strlen(zNL);
4995      }
4996      if( zCR==0 && zText[i]=='\r' ){
4997        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4998        nCR = strlen(zCR);
4999      }
5000    }
5001
5002    if( zNL || zCR ){
5003      i64 iOut = 0;
5004      i64 nMax = (nNL > nCR) ? nNL : nCR;
5005      i64 nAlloc = nMax * nText + (nMax+64)*2;
5006      char *zOut = (char*)sqlite3_malloc64(nAlloc);
5007      if( zOut==0 ){
5008        sqlite3_result_error_nomem(context);
5009        return;
5010      }
5011
5012      if( zNL && zCR ){
5013        memcpy(&zOut[iOut], "replace(replace(", 16);
5014        iOut += 16;
5015      }else{
5016        memcpy(&zOut[iOut], "replace(", 8);
5017        iOut += 8;
5018      }
5019      for(i=0; zText[i]; i++){
5020        if( zText[i]=='\n' ){
5021          memcpy(&zOut[iOut], zNL, nNL);
5022          iOut += nNL;
5023        }else if( zText[i]=='\r' ){
5024          memcpy(&zOut[iOut], zCR, nCR);
5025          iOut += nCR;
5026        }else{
5027          zOut[iOut] = zText[i];
5028          iOut++;
5029        }
5030      }
5031
5032      if( zNL ){
5033        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5034        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5035        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5036      }
5037      if( zCR ){
5038        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5039        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5040        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5041      }
5042
5043      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5044      sqlite3_free(zOut);
5045      return;
5046    }
5047  }
5048
5049  sqlite3_result_value(context, argv[0]);
5050}
5051
5052/* Flags for open_db().
5053**
5054** The default behavior of open_db() is to exit(1) if the database fails to
5055** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5056** but still returns without calling exit.
5057**
5058** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5059** ZIP archive if the file does not exist or is empty and its name matches
5060** the *.zip pattern.
5061*/
5062#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5063#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5064
5065/*
5066** Make sure the database is open.  If it is not, then open it.  If
5067** the database fails to open, print an error message and exit.
5068*/
5069static void open_db(ShellState *p, int openFlags){
5070  if( p->db==0 ){
5071    const char *zDbFilename = p->pAuxDb->zDbFilename;
5072    if( p->openMode==SHELL_OPEN_UNSPEC ){
5073      if( zDbFilename==0 || zDbFilename[0]==0 ){
5074        p->openMode = SHELL_OPEN_NORMAL;
5075      }else{
5076        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5077                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5078      }
5079    }
5080    switch( p->openMode ){
5081      case SHELL_OPEN_APPENDVFS: {
5082        sqlite3_open_v2(zDbFilename, &p->db,
5083           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5084        break;
5085      }
5086      case SHELL_OPEN_HEXDB:
5087      case SHELL_OPEN_DESERIALIZE: {
5088        sqlite3_open(0, &p->db);
5089        break;
5090      }
5091      case SHELL_OPEN_ZIPFILE: {
5092        sqlite3_open(":memory:", &p->db);
5093        break;
5094      }
5095      case SHELL_OPEN_READONLY: {
5096        sqlite3_open_v2(zDbFilename, &p->db,
5097            SQLITE_OPEN_READONLY|p->openFlags, 0);
5098        break;
5099      }
5100      case SHELL_OPEN_UNSPEC:
5101      case SHELL_OPEN_NORMAL: {
5102        sqlite3_open_v2(zDbFilename, &p->db,
5103           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5104        break;
5105      }
5106    }
5107    globalDb = p->db;
5108    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5109      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5110          zDbFilename, sqlite3_errmsg(p->db));
5111      if( openFlags & OPEN_DB_KEEPALIVE ){
5112        sqlite3_open(":memory:", &p->db);
5113        return;
5114      }
5115      exit(1);
5116    }
5117#ifndef SQLITE_OMIT_LOAD_EXTENSION
5118    sqlite3_enable_load_extension(p->db, 1);
5119#endif
5120    sqlite3_shathree_init(p->db, 0, 0);
5121    sqlite3_uint_init(p->db, 0, 0);
5122    sqlite3_decimal_init(p->db, 0, 0);
5123    sqlite3_regexp_init(p->db, 0, 0);
5124    sqlite3_ieee_init(p->db, 0, 0);
5125    sqlite3_series_init(p->db, 0, 0);
5126#ifndef SQLITE_SHELL_FIDDLE
5127    sqlite3_fileio_init(p->db, 0, 0);
5128    sqlite3_completion_init(p->db, 0, 0);
5129#endif
5130#if SQLITE_SHELL_HAVE_RECOVER
5131    sqlite3_dbdata_init(p->db, 0, 0);
5132#endif
5133#ifdef SQLITE_HAVE_ZLIB
5134    if( !p->bSafeModePersist ){
5135      sqlite3_zipfile_init(p->db, 0, 0);
5136      sqlite3_sqlar_init(p->db, 0, 0);
5137    }
5138#endif
5139    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5140                            shellAddSchemaName, 0, 0);
5141    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5142                            shellModuleSchema, 0, 0);
5143    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5144                            shellPutsFunc, 0, 0);
5145    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5146                            shellEscapeCrnl, 0, 0);
5147    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5148                            shellInt32, 0, 0);
5149    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5150                            shellIdQuote, 0, 0);
5151    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5152                            shellUSleepFunc, 0, 0);
5153#ifndef SQLITE_NOHAVE_SYSTEM
5154    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5155                            editFunc, 0, 0);
5156    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5157                            editFunc, 0, 0);
5158#endif
5159    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5160      char *zSql = sqlite3_mprintf(
5161         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5162      shell_check_oom(zSql);
5163      sqlite3_exec(p->db, zSql, 0, 0, 0);
5164      sqlite3_free(zSql);
5165    }
5166#ifndef SQLITE_OMIT_DESERIALIZE
5167    else
5168    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5169      int rc;
5170      int nData = 0;
5171      unsigned char *aData;
5172      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5173        aData = (unsigned char*)readFile(zDbFilename, &nData);
5174      }else{
5175        aData = readHexDb(p, &nData);
5176        if( aData==0 ){
5177          return;
5178        }
5179      }
5180      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5181                   SQLITE_DESERIALIZE_RESIZEABLE |
5182                   SQLITE_DESERIALIZE_FREEONCLOSE);
5183      if( rc ){
5184        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5185      }
5186      if( p->szMax>0 ){
5187        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5188      }
5189    }
5190#endif
5191  }
5192  if( p->bSafeModePersist && p->db!=0 ){
5193    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5194  }
5195}
5196
5197/*
5198** Attempt to close the databaes connection.  Report errors.
5199*/
5200void close_db(sqlite3 *db){
5201  int rc = sqlite3_close(db);
5202  if( rc ){
5203    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5204        rc, sqlite3_errmsg(db));
5205  }
5206}
5207
5208#if HAVE_READLINE || HAVE_EDITLINE
5209/*
5210** Readline completion callbacks
5211*/
5212static char *readline_completion_generator(const char *text, int state){
5213  static sqlite3_stmt *pStmt = 0;
5214  char *zRet;
5215  if( state==0 ){
5216    char *zSql;
5217    sqlite3_finalize(pStmt);
5218    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5219                           "  FROM completion(%Q) ORDER BY 1", text);
5220    shell_check_oom(zSql);
5221    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5222    sqlite3_free(zSql);
5223  }
5224  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5225    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5226    zRet = z ? strdup(z) : 0;
5227  }else{
5228    sqlite3_finalize(pStmt);
5229    pStmt = 0;
5230    zRet = 0;
5231  }
5232  return zRet;
5233}
5234static char **readline_completion(const char *zText, int iStart, int iEnd){
5235  rl_attempted_completion_over = 1;
5236  return rl_completion_matches(zText, readline_completion_generator);
5237}
5238
5239#elif HAVE_LINENOISE
5240/*
5241** Linenoise completion callback
5242*/
5243static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5244  i64 nLine = strlen(zLine);
5245  i64 i, iStart;
5246  sqlite3_stmt *pStmt = 0;
5247  char *zSql;
5248  char zBuf[1000];
5249
5250  if( nLine>sizeof(zBuf)-30 ) return;
5251  if( zLine[0]=='.' || zLine[0]=='#') return;
5252  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5253  if( i==nLine-1 ) return;
5254  iStart = i+1;
5255  memcpy(zBuf, zLine, iStart);
5256  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5257                         "  FROM completion(%Q,%Q) ORDER BY 1",
5258                         &zLine[iStart], zLine);
5259  shell_check_oom(zSql);
5260  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5261  sqlite3_free(zSql);
5262  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5263  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5264    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5265    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5266    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5267      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5268      linenoiseAddCompletion(lc, zBuf);
5269    }
5270  }
5271  sqlite3_finalize(pStmt);
5272}
5273#endif
5274
5275/*
5276** Do C-language style dequoting.
5277**
5278**    \a    -> alarm
5279**    \b    -> backspace
5280**    \t    -> tab
5281**    \n    -> newline
5282**    \v    -> vertical tab
5283**    \f    -> form feed
5284**    \r    -> carriage return
5285**    \s    -> space
5286**    \"    -> "
5287**    \'    -> '
5288**    \\    -> backslash
5289**    \NNN  -> ascii character NNN in octal
5290*/
5291static void resolve_backslashes(char *z){
5292  int i, j;
5293  char c;
5294  while( *z && *z!='\\' ) z++;
5295  for(i=j=0; (c = z[i])!=0; i++, j++){
5296    if( c=='\\' && z[i+1]!=0 ){
5297      c = z[++i];
5298      if( c=='a' ){
5299        c = '\a';
5300      }else if( c=='b' ){
5301        c = '\b';
5302      }else if( c=='t' ){
5303        c = '\t';
5304      }else if( c=='n' ){
5305        c = '\n';
5306      }else if( c=='v' ){
5307        c = '\v';
5308      }else if( c=='f' ){
5309        c = '\f';
5310      }else if( c=='r' ){
5311        c = '\r';
5312      }else if( c=='"' ){
5313        c = '"';
5314      }else if( c=='\'' ){
5315        c = '\'';
5316      }else if( c=='\\' ){
5317        c = '\\';
5318      }else if( c>='0' && c<='7' ){
5319        c -= '0';
5320        if( z[i+1]>='0' && z[i+1]<='7' ){
5321          i++;
5322          c = (c<<3) + z[i] - '0';
5323          if( z[i+1]>='0' && z[i+1]<='7' ){
5324            i++;
5325            c = (c<<3) + z[i] - '0';
5326          }
5327        }
5328      }
5329    }
5330    z[j] = c;
5331  }
5332  if( j<i ) z[j] = 0;
5333}
5334
5335/*
5336** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5337** for TRUE and FALSE.  Return the integer value if appropriate.
5338*/
5339static int booleanValue(const char *zArg){
5340  int i;
5341  if( zArg[0]=='0' && zArg[1]=='x' ){
5342    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5343  }else{
5344    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5345  }
5346  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5347  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5348    return 1;
5349  }
5350  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5351    return 0;
5352  }
5353  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5354          zArg);
5355  return 0;
5356}
5357
5358/*
5359** Set or clear a shell flag according to a boolean value.
5360*/
5361static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5362  if( booleanValue(zArg) ){
5363    ShellSetFlag(p, mFlag);
5364  }else{
5365    ShellClearFlag(p, mFlag);
5366  }
5367}
5368
5369/*
5370** Close an output file, assuming it is not stderr or stdout
5371*/
5372static void output_file_close(FILE *f){
5373  if( f && f!=stdout && f!=stderr ) fclose(f);
5374}
5375
5376/*
5377** Try to open an output file.   The names "stdout" and "stderr" are
5378** recognized and do the right thing.  NULL is returned if the output
5379** filename is "off".
5380*/
5381static FILE *output_file_open(const char *zFile, int bTextMode){
5382  FILE *f;
5383  if( cli_strcmp(zFile,"stdout")==0 ){
5384    f = stdout;
5385  }else if( cli_strcmp(zFile, "stderr")==0 ){
5386    f = stderr;
5387  }else if( cli_strcmp(zFile, "off")==0 ){
5388    f = 0;
5389  }else{
5390    f = fopen(zFile, bTextMode ? "w" : "wb");
5391    if( f==0 ){
5392      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5393    }
5394  }
5395  return f;
5396}
5397
5398#ifndef SQLITE_OMIT_TRACE
5399/*
5400** A routine for handling output from sqlite3_trace().
5401*/
5402static int sql_trace_callback(
5403  unsigned mType,         /* The trace type */
5404  void *pArg,             /* The ShellState pointer */
5405  void *pP,               /* Usually a pointer to sqlite_stmt */
5406  void *pX                /* Auxiliary output */
5407){
5408  ShellState *p = (ShellState*)pArg;
5409  sqlite3_stmt *pStmt;
5410  const char *zSql;
5411  i64 nSql;
5412  if( p->traceOut==0 ) return 0;
5413  if( mType==SQLITE_TRACE_CLOSE ){
5414    utf8_printf(p->traceOut, "-- closing database connection\n");
5415    return 0;
5416  }
5417  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5418    zSql = (const char*)pX;
5419  }else{
5420    pStmt = (sqlite3_stmt*)pP;
5421    switch( p->eTraceType ){
5422      case SHELL_TRACE_EXPANDED: {
5423        zSql = sqlite3_expanded_sql(pStmt);
5424        break;
5425      }
5426#ifdef SQLITE_ENABLE_NORMALIZE
5427      case SHELL_TRACE_NORMALIZED: {
5428        zSql = sqlite3_normalized_sql(pStmt);
5429        break;
5430      }
5431#endif
5432      default: {
5433        zSql = sqlite3_sql(pStmt);
5434        break;
5435      }
5436    }
5437  }
5438  if( zSql==0 ) return 0;
5439  nSql = strlen(zSql);
5440  if( nSql>1000000000 ) nSql = 1000000000;
5441  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5442  switch( mType ){
5443    case SQLITE_TRACE_ROW:
5444    case SQLITE_TRACE_STMT: {
5445      utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
5446      break;
5447    }
5448    case SQLITE_TRACE_PROFILE: {
5449      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5450      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
5451      break;
5452    }
5453  }
5454  return 0;
5455}
5456#endif
5457
5458/*
5459** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5460** a useful spot to set a debugger breakpoint.
5461*/
5462static void test_breakpoint(void){
5463  static int nCall = 0;
5464  nCall++;
5465}
5466
5467/*
5468** An object used to read a CSV and other files for import.
5469*/
5470typedef struct ImportCtx ImportCtx;
5471struct ImportCtx {
5472  const char *zFile;  /* Name of the input file */
5473  FILE *in;           /* Read the CSV text from this input stream */
5474  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5475  char *z;            /* Accumulated text for a field */
5476  int n;              /* Number of bytes in z */
5477  int nAlloc;         /* Space allocated for z[] */
5478  int nLine;          /* Current line number */
5479  int nRow;           /* Number of rows imported */
5480  int nErr;           /* Number of errors encountered */
5481  int bNotFirst;      /* True if one or more bytes already read */
5482  int cTerm;          /* Character that terminated the most recent field */
5483  int cColSep;        /* The column separator character.  (Usually ",") */
5484  int cRowSep;        /* The row separator character.  (Usually "\n") */
5485};
5486
5487/* Clean up resourced used by an ImportCtx */
5488static void import_cleanup(ImportCtx *p){
5489  if( p->in!=0 && p->xCloser!=0 ){
5490    p->xCloser(p->in);
5491    p->in = 0;
5492  }
5493  sqlite3_free(p->z);
5494  p->z = 0;
5495}
5496
5497/* Append a single byte to z[] */
5498static void import_append_char(ImportCtx *p, int c){
5499  if( p->n+1>=p->nAlloc ){
5500    p->nAlloc += p->nAlloc + 100;
5501    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5502    shell_check_oom(p->z);
5503  }
5504  p->z[p->n++] = (char)c;
5505}
5506
5507/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5508** with the option of having a separator other than ",".
5509**
5510**   +  Input comes from p->in.
5511**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5512**      from sqlite3_malloc64().
5513**   +  Use p->cSep as the column separator.  The default is ",".
5514**   +  Use p->rSep as the row separator.  The default is "\n".
5515**   +  Keep track of the line number in p->nLine.
5516**   +  Store the character that terminates the field in p->cTerm.  Store
5517**      EOF on end-of-file.
5518**   +  Report syntax errors on stderr
5519*/
5520static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5521  int c;
5522  int cSep = p->cColSep;
5523  int rSep = p->cRowSep;
5524  p->n = 0;
5525  c = fgetc(p->in);
5526  if( c==EOF || seenInterrupt ){
5527    p->cTerm = EOF;
5528    return 0;
5529  }
5530  if( c=='"' ){
5531    int pc, ppc;
5532    int startLine = p->nLine;
5533    int cQuote = c;
5534    pc = ppc = 0;
5535    while( 1 ){
5536      c = fgetc(p->in);
5537      if( c==rSep ) p->nLine++;
5538      if( c==cQuote ){
5539        if( pc==cQuote ){
5540          pc = 0;
5541          continue;
5542        }
5543      }
5544      if( (c==cSep && pc==cQuote)
5545       || (c==rSep && pc==cQuote)
5546       || (c==rSep && pc=='\r' && ppc==cQuote)
5547       || (c==EOF && pc==cQuote)
5548      ){
5549        do{ p->n--; }while( p->z[p->n]!=cQuote );
5550        p->cTerm = c;
5551        break;
5552      }
5553      if( pc==cQuote && c!='\r' ){
5554        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5555                p->zFile, p->nLine, cQuote);
5556      }
5557      if( c==EOF ){
5558        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5559                p->zFile, startLine, cQuote);
5560        p->cTerm = c;
5561        break;
5562      }
5563      import_append_char(p, c);
5564      ppc = pc;
5565      pc = c;
5566    }
5567  }else{
5568    /* If this is the first field being parsed and it begins with the
5569    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5570    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5571      import_append_char(p, c);
5572      c = fgetc(p->in);
5573      if( (c&0xff)==0xbb ){
5574        import_append_char(p, c);
5575        c = fgetc(p->in);
5576        if( (c&0xff)==0xbf ){
5577          p->bNotFirst = 1;
5578          p->n = 0;
5579          return csv_read_one_field(p);
5580        }
5581      }
5582    }
5583    while( c!=EOF && c!=cSep && c!=rSep ){
5584      import_append_char(p, c);
5585      c = fgetc(p->in);
5586    }
5587    if( c==rSep ){
5588      p->nLine++;
5589      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5590    }
5591    p->cTerm = c;
5592  }
5593  if( p->z ) p->z[p->n] = 0;
5594  p->bNotFirst = 1;
5595  return p->z;
5596}
5597
5598/* Read a single field of ASCII delimited text.
5599**
5600**   +  Input comes from p->in.
5601**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5602**      from sqlite3_malloc64().
5603**   +  Use p->cSep as the column separator.  The default is "\x1F".
5604**   +  Use p->rSep as the row separator.  The default is "\x1E".
5605**   +  Keep track of the row number in p->nLine.
5606**   +  Store the character that terminates the field in p->cTerm.  Store
5607**      EOF on end-of-file.
5608**   +  Report syntax errors on stderr
5609*/
5610static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5611  int c;
5612  int cSep = p->cColSep;
5613  int rSep = p->cRowSep;
5614  p->n = 0;
5615  c = fgetc(p->in);
5616  if( c==EOF || seenInterrupt ){
5617    p->cTerm = EOF;
5618    return 0;
5619  }
5620  while( c!=EOF && c!=cSep && c!=rSep ){
5621    import_append_char(p, c);
5622    c = fgetc(p->in);
5623  }
5624  if( c==rSep ){
5625    p->nLine++;
5626  }
5627  p->cTerm = c;
5628  if( p->z ) p->z[p->n] = 0;
5629  return p->z;
5630}
5631
5632/*
5633** Try to transfer data for table zTable.  If an error is seen while
5634** moving forward, try to go backwards.  The backwards movement won't
5635** work for WITHOUT ROWID tables.
5636*/
5637static void tryToCloneData(
5638  ShellState *p,
5639  sqlite3 *newDb,
5640  const char *zTable
5641){
5642  sqlite3_stmt *pQuery = 0;
5643  sqlite3_stmt *pInsert = 0;
5644  char *zQuery = 0;
5645  char *zInsert = 0;
5646  int rc;
5647  int i, j, n;
5648  int nTable = strlen30(zTable);
5649  int k = 0;
5650  int cnt = 0;
5651  const int spinRate = 10000;
5652
5653  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5654  shell_check_oom(zQuery);
5655  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5656  if( rc ){
5657    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5658            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5659            zQuery);
5660    goto end_data_xfer;
5661  }
5662  n = sqlite3_column_count(pQuery);
5663  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5664  shell_check_oom(zInsert);
5665  sqlite3_snprintf(200+nTable,zInsert,
5666                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5667  i = strlen30(zInsert);
5668  for(j=1; j<n; j++){
5669    memcpy(zInsert+i, ",?", 2);
5670    i += 2;
5671  }
5672  memcpy(zInsert+i, ");", 3);
5673  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5674  if( rc ){
5675    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5676            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5677            zQuery);
5678    goto end_data_xfer;
5679  }
5680  for(k=0; k<2; k++){
5681    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5682      for(i=0; i<n; i++){
5683        switch( sqlite3_column_type(pQuery, i) ){
5684          case SQLITE_NULL: {
5685            sqlite3_bind_null(pInsert, i+1);
5686            break;
5687          }
5688          case SQLITE_INTEGER: {
5689            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5690            break;
5691          }
5692          case SQLITE_FLOAT: {
5693            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5694            break;
5695          }
5696          case SQLITE_TEXT: {
5697            sqlite3_bind_text(pInsert, i+1,
5698                             (const char*)sqlite3_column_text(pQuery,i),
5699                             -1, SQLITE_STATIC);
5700            break;
5701          }
5702          case SQLITE_BLOB: {
5703            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5704                                            sqlite3_column_bytes(pQuery,i),
5705                                            SQLITE_STATIC);
5706            break;
5707          }
5708        }
5709      } /* End for */
5710      rc = sqlite3_step(pInsert);
5711      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5712        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5713                        sqlite3_errmsg(newDb));
5714      }
5715      sqlite3_reset(pInsert);
5716      cnt++;
5717      if( (cnt%spinRate)==0 ){
5718        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5719        fflush(stdout);
5720      }
5721    } /* End while */
5722    if( rc==SQLITE_DONE ) break;
5723    sqlite3_finalize(pQuery);
5724    sqlite3_free(zQuery);
5725    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5726                             zTable);
5727    shell_check_oom(zQuery);
5728    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5729    if( rc ){
5730      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5731      break;
5732    }
5733  } /* End for(k=0...) */
5734
5735end_data_xfer:
5736  sqlite3_finalize(pQuery);
5737  sqlite3_finalize(pInsert);
5738  sqlite3_free(zQuery);
5739  sqlite3_free(zInsert);
5740}
5741
5742
5743/*
5744** Try to transfer all rows of the schema that match zWhere.  For
5745** each row, invoke xForEach() on the object defined by that row.
5746** If an error is encountered while moving forward through the
5747** sqlite_schema table, try again moving backwards.
5748*/
5749static void tryToCloneSchema(
5750  ShellState *p,
5751  sqlite3 *newDb,
5752  const char *zWhere,
5753  void (*xForEach)(ShellState*,sqlite3*,const char*)
5754){
5755  sqlite3_stmt *pQuery = 0;
5756  char *zQuery = 0;
5757  int rc;
5758  const unsigned char *zName;
5759  const unsigned char *zSql;
5760  char *zErrMsg = 0;
5761
5762  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5763                           " WHERE %s", zWhere);
5764  shell_check_oom(zQuery);
5765  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5766  if( rc ){
5767    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5768                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5769                    zQuery);
5770    goto end_schema_xfer;
5771  }
5772  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5773    zName = sqlite3_column_text(pQuery, 0);
5774    zSql = sqlite3_column_text(pQuery, 1);
5775    if( zName==0 || zSql==0 ) continue;
5776    printf("%s... ", zName); fflush(stdout);
5777    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5778    if( zErrMsg ){
5779      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5780      sqlite3_free(zErrMsg);
5781      zErrMsg = 0;
5782    }
5783    if( xForEach ){
5784      xForEach(p, newDb, (const char*)zName);
5785    }
5786    printf("done\n");
5787  }
5788  if( rc!=SQLITE_DONE ){
5789    sqlite3_finalize(pQuery);
5790    sqlite3_free(zQuery);
5791    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5792                             " WHERE %s ORDER BY rowid DESC", zWhere);
5793    shell_check_oom(zQuery);
5794    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5795    if( rc ){
5796      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5797                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5798                      zQuery);
5799      goto end_schema_xfer;
5800    }
5801    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5802      zName = sqlite3_column_text(pQuery, 0);
5803      zSql = sqlite3_column_text(pQuery, 1);
5804      if( zName==0 || zSql==0 ) continue;
5805      printf("%s... ", zName); fflush(stdout);
5806      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5807      if( zErrMsg ){
5808        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5809        sqlite3_free(zErrMsg);
5810        zErrMsg = 0;
5811      }
5812      if( xForEach ){
5813        xForEach(p, newDb, (const char*)zName);
5814      }
5815      printf("done\n");
5816    }
5817  }
5818end_schema_xfer:
5819  sqlite3_finalize(pQuery);
5820  sqlite3_free(zQuery);
5821}
5822
5823/*
5824** Open a new database file named "zNewDb".  Try to recover as much information
5825** as possible out of the main database (which might be corrupt) and write it
5826** into zNewDb.
5827*/
5828static void tryToClone(ShellState *p, const char *zNewDb){
5829  int rc;
5830  sqlite3 *newDb = 0;
5831  if( access(zNewDb,0)==0 ){
5832    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5833    return;
5834  }
5835  rc = sqlite3_open(zNewDb, &newDb);
5836  if( rc ){
5837    utf8_printf(stderr, "Cannot create output database: %s\n",
5838            sqlite3_errmsg(newDb));
5839  }else{
5840    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5841    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5842    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5843    tryToCloneSchema(p, newDb, "type!='table'", 0);
5844    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5845    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5846  }
5847  close_db(newDb);
5848}
5849
5850/*
5851** Change the output file back to stdout.
5852**
5853** If the p->doXdgOpen flag is set, that means the output was being
5854** redirected to a temporary file named by p->zTempFile.  In that case,
5855** launch start/open/xdg-open on that temporary file.
5856*/
5857static void output_reset(ShellState *p){
5858  if( p->outfile[0]=='|' ){
5859#ifndef SQLITE_OMIT_POPEN
5860    pclose(p->out);
5861#endif
5862  }else{
5863    output_file_close(p->out);
5864#ifndef SQLITE_NOHAVE_SYSTEM
5865    if( p->doXdgOpen ){
5866      const char *zXdgOpenCmd =
5867#if defined(_WIN32)
5868      "start";
5869#elif defined(__APPLE__)
5870      "open";
5871#else
5872      "xdg-open";
5873#endif
5874      char *zCmd;
5875      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5876      if( system(zCmd) ){
5877        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5878      }else{
5879        /* Give the start/open/xdg-open command some time to get
5880        ** going before we continue, and potential delete the
5881        ** p->zTempFile data file out from under it */
5882        sqlite3_sleep(2000);
5883      }
5884      sqlite3_free(zCmd);
5885      outputModePop(p);
5886      p->doXdgOpen = 0;
5887    }
5888#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5889  }
5890  p->outfile[0] = 0;
5891  p->out = stdout;
5892}
5893
5894/*
5895** Run an SQL command and return the single integer result.
5896*/
5897static int db_int(sqlite3 *db, const char *zSql){
5898  sqlite3_stmt *pStmt;
5899  int res = 0;
5900  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5901  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5902    res = sqlite3_column_int(pStmt,0);
5903  }
5904  sqlite3_finalize(pStmt);
5905  return res;
5906}
5907
5908#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5909/*
5910** Convert a 2-byte or 4-byte big-endian integer into a native integer
5911*/
5912static unsigned int get2byteInt(unsigned char *a){
5913  return (a[0]<<8) + a[1];
5914}
5915static unsigned int get4byteInt(unsigned char *a){
5916  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5917}
5918
5919/*
5920** Implementation of the ".dbinfo" command.
5921**
5922** Return 1 on error, 2 to exit, and 0 otherwise.
5923*/
5924static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5925  static const struct { const char *zName; int ofst; } aField[] = {
5926     { "file change counter:",  24  },
5927     { "database page count:",  28  },
5928     { "freelist page count:",  36  },
5929     { "schema cookie:",        40  },
5930     { "schema format:",        44  },
5931     { "default cache size:",   48  },
5932     { "autovacuum top root:",  52  },
5933     { "incremental vacuum:",   64  },
5934     { "text encoding:",        56  },
5935     { "user version:",         60  },
5936     { "application id:",       68  },
5937     { "software version:",     96  },
5938  };
5939  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5940     { "number of tables:",
5941       "SELECT count(*) FROM %s WHERE type='table'" },
5942     { "number of indexes:",
5943       "SELECT count(*) FROM %s WHERE type='index'" },
5944     { "number of triggers:",
5945       "SELECT count(*) FROM %s WHERE type='trigger'" },
5946     { "number of views:",
5947       "SELECT count(*) FROM %s WHERE type='view'" },
5948     { "schema size:",
5949       "SELECT total(length(sql)) FROM %s" },
5950  };
5951  int i, rc;
5952  unsigned iDataVersion;
5953  char *zSchemaTab;
5954  char *zDb = nArg>=2 ? azArg[1] : "main";
5955  sqlite3_stmt *pStmt = 0;
5956  unsigned char aHdr[100];
5957  open_db(p, 0);
5958  if( p->db==0 ) return 1;
5959  rc = sqlite3_prepare_v2(p->db,
5960             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5961             -1, &pStmt, 0);
5962  if( rc ){
5963    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5964    sqlite3_finalize(pStmt);
5965    return 1;
5966  }
5967  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5968  if( sqlite3_step(pStmt)==SQLITE_ROW
5969   && sqlite3_column_bytes(pStmt,0)>100
5970  ){
5971    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5972    sqlite3_finalize(pStmt);
5973  }else{
5974    raw_printf(stderr, "unable to read database header\n");
5975    sqlite3_finalize(pStmt);
5976    return 1;
5977  }
5978  i = get2byteInt(aHdr+16);
5979  if( i==1 ) i = 65536;
5980  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5981  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5982  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5983  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5984  for(i=0; i<ArraySize(aField); i++){
5985    int ofst = aField[i].ofst;
5986    unsigned int val = get4byteInt(aHdr + ofst);
5987    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5988    switch( ofst ){
5989      case 56: {
5990        if( val==1 ) raw_printf(p->out, " (utf8)");
5991        if( val==2 ) raw_printf(p->out, " (utf16le)");
5992        if( val==3 ) raw_printf(p->out, " (utf16be)");
5993      }
5994    }
5995    raw_printf(p->out, "\n");
5996  }
5997  if( zDb==0 ){
5998    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5999  }else if( cli_strcmp(zDb,"temp")==0 ){
6000    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
6001  }else{
6002    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
6003  }
6004  for(i=0; i<ArraySize(aQuery); i++){
6005    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
6006    int val = db_int(p->db, zSql);
6007    sqlite3_free(zSql);
6008    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
6009  }
6010  sqlite3_free(zSchemaTab);
6011  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
6012  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
6013  return 0;
6014}
6015#endif /* SQLITE_SHELL_HAVE_RECOVER */
6016
6017/*
6018** Print the current sqlite3_errmsg() value to stderr and return 1.
6019*/
6020static int shellDatabaseError(sqlite3 *db){
6021  const char *zErr = sqlite3_errmsg(db);
6022  utf8_printf(stderr, "Error: %s\n", zErr);
6023  return 1;
6024}
6025
6026/*
6027** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
6028** if they match and FALSE (0) if they do not match.
6029**
6030** Globbing rules:
6031**
6032**      '*'       Matches any sequence of zero or more characters.
6033**
6034**      '?'       Matches exactly one character.
6035**
6036**     [...]      Matches one character from the enclosed list of
6037**                characters.
6038**
6039**     [^...]     Matches one character not in the enclosed list.
6040**
6041**      '#'       Matches any sequence of one or more digits with an
6042**                optional + or - sign in front
6043**
6044**      ' '       Any span of whitespace matches any other span of
6045**                whitespace.
6046**
6047** Extra whitespace at the end of z[] is ignored.
6048*/
6049static int testcase_glob(const char *zGlob, const char *z){
6050  int c, c2;
6051  int invert;
6052  int seen;
6053
6054  while( (c = (*(zGlob++)))!=0 ){
6055    if( IsSpace(c) ){
6056      if( !IsSpace(*z) ) return 0;
6057      while( IsSpace(*zGlob) ) zGlob++;
6058      while( IsSpace(*z) ) z++;
6059    }else if( c=='*' ){
6060      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6061        if( c=='?' && (*(z++))==0 ) return 0;
6062      }
6063      if( c==0 ){
6064        return 1;
6065      }else if( c=='[' ){
6066        while( *z && testcase_glob(zGlob-1,z)==0 ){
6067          z++;
6068        }
6069        return (*z)!=0;
6070      }
6071      while( (c2 = (*(z++)))!=0 ){
6072        while( c2!=c ){
6073          c2 = *(z++);
6074          if( c2==0 ) return 0;
6075        }
6076        if( testcase_glob(zGlob,z) ) return 1;
6077      }
6078      return 0;
6079    }else if( c=='?' ){
6080      if( (*(z++))==0 ) return 0;
6081    }else if( c=='[' ){
6082      int prior_c = 0;
6083      seen = 0;
6084      invert = 0;
6085      c = *(z++);
6086      if( c==0 ) return 0;
6087      c2 = *(zGlob++);
6088      if( c2=='^' ){
6089        invert = 1;
6090        c2 = *(zGlob++);
6091      }
6092      if( c2==']' ){
6093        if( c==']' ) seen = 1;
6094        c2 = *(zGlob++);
6095      }
6096      while( c2 && c2!=']' ){
6097        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6098          c2 = *(zGlob++);
6099          if( c>=prior_c && c<=c2 ) seen = 1;
6100          prior_c = 0;
6101        }else{
6102          if( c==c2 ){
6103            seen = 1;
6104          }
6105          prior_c = c2;
6106        }
6107        c2 = *(zGlob++);
6108      }
6109      if( c2==0 || (seen ^ invert)==0 ) return 0;
6110    }else if( c=='#' ){
6111      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6112      if( !IsDigit(z[0]) ) return 0;
6113      z++;
6114      while( IsDigit(z[0]) ){ z++; }
6115    }else{
6116      if( c!=(*(z++)) ) return 0;
6117    }
6118  }
6119  while( IsSpace(*z) ){ z++; }
6120  return *z==0;
6121}
6122
6123
6124/*
6125** Compare the string as a command-line option with either one or two
6126** initial "-" characters.
6127*/
6128static int optionMatch(const char *zStr, const char *zOpt){
6129  if( zStr[0]!='-' ) return 0;
6130  zStr++;
6131  if( zStr[0]=='-' ) zStr++;
6132  return cli_strcmp(zStr, zOpt)==0;
6133}
6134
6135/*
6136** Delete a file.
6137*/
6138int shellDeleteFile(const char *zFilename){
6139  int rc;
6140#ifdef _WIN32
6141  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6142  rc = _wunlink(z);
6143  sqlite3_free(z);
6144#else
6145  rc = unlink(zFilename);
6146#endif
6147  return rc;
6148}
6149
6150/*
6151** Try to delete the temporary file (if there is one) and free the
6152** memory used to hold the name of the temp file.
6153*/
6154static void clearTempFile(ShellState *p){
6155  if( p->zTempFile==0 ) return;
6156  if( p->doXdgOpen ) return;
6157  if( shellDeleteFile(p->zTempFile) ) return;
6158  sqlite3_free(p->zTempFile);
6159  p->zTempFile = 0;
6160}
6161
6162/*
6163** Create a new temp file name with the given suffix.
6164*/
6165static void newTempFile(ShellState *p, const char *zSuffix){
6166  clearTempFile(p);
6167  sqlite3_free(p->zTempFile);
6168  p->zTempFile = 0;
6169  if( p->db ){
6170    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6171  }
6172  if( p->zTempFile==0 ){
6173    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6174    ** will not work and we will need to fallback to guessing */
6175    char *zTemp;
6176    sqlite3_uint64 r;
6177    sqlite3_randomness(sizeof(r), &r);
6178    zTemp = getenv("TEMP");
6179    if( zTemp==0 ) zTemp = getenv("TMP");
6180    if( zTemp==0 ){
6181#ifdef _WIN32
6182      zTemp = "\\tmp";
6183#else
6184      zTemp = "/tmp";
6185#endif
6186    }
6187    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6188  }else{
6189    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6190  }
6191  shell_check_oom(p->zTempFile);
6192}
6193
6194
6195/*
6196** The implementation of SQL scalar function fkey_collate_clause(), used
6197** by the ".lint fkey-indexes" command. This scalar function is always
6198** called with four arguments - the parent table name, the parent column name,
6199** the child table name and the child column name.
6200**
6201**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6202**
6203** If either of the named tables or columns do not exist, this function
6204** returns an empty string. An empty string is also returned if both tables
6205** and columns exist but have the same default collation sequence. Or,
6206** if both exist but the default collation sequences are different, this
6207** function returns the string " COLLATE <parent-collation>", where
6208** <parent-collation> is the default collation sequence of the parent column.
6209*/
6210static void shellFkeyCollateClause(
6211  sqlite3_context *pCtx,
6212  int nVal,
6213  sqlite3_value **apVal
6214){
6215  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6216  const char *zParent;
6217  const char *zParentCol;
6218  const char *zParentSeq;
6219  const char *zChild;
6220  const char *zChildCol;
6221  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6222  int rc;
6223
6224  assert( nVal==4 );
6225  zParent = (const char*)sqlite3_value_text(apVal[0]);
6226  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6227  zChild = (const char*)sqlite3_value_text(apVal[2]);
6228  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6229
6230  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6231  rc = sqlite3_table_column_metadata(
6232      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6233  );
6234  if( rc==SQLITE_OK ){
6235    rc = sqlite3_table_column_metadata(
6236        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6237    );
6238  }
6239
6240  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6241    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6242    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6243    sqlite3_free(z);
6244  }
6245}
6246
6247
6248/*
6249** The implementation of dot-command ".lint fkey-indexes".
6250*/
6251static int lintFkeyIndexes(
6252  ShellState *pState,             /* Current shell tool state */
6253  char **azArg,                   /* Array of arguments passed to dot command */
6254  int nArg                        /* Number of entries in azArg[] */
6255){
6256  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6257  FILE *out = pState->out;        /* Stream to write non-error output to */
6258  int bVerbose = 0;               /* If -verbose is present */
6259  int bGroupByParent = 0;         /* If -groupbyparent is present */
6260  int i;                          /* To iterate through azArg[] */
6261  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6262  int rc;                         /* Return code */
6263  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6264
6265  /*
6266  ** This SELECT statement returns one row for each foreign key constraint
6267  ** in the schema of the main database. The column values are:
6268  **
6269  ** 0. The text of an SQL statement similar to:
6270  **
6271  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6272  **
6273  **    This SELECT is similar to the one that the foreign keys implementation
6274  **    needs to run internally on child tables. If there is an index that can
6275  **    be used to optimize this query, then it can also be used by the FK
6276  **    implementation to optimize DELETE or UPDATE statements on the parent
6277  **    table.
6278  **
6279  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6280  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6281  **    contains an index that can be used to optimize the query.
6282  **
6283  ** 2. Human readable text that describes the child table and columns. e.g.
6284  **
6285  **       "child_table(child_key1, child_key2)"
6286  **
6287  ** 3. Human readable text that describes the parent table and columns. e.g.
6288  **
6289  **       "parent_table(parent_key1, parent_key2)"
6290  **
6291  ** 4. A full CREATE INDEX statement for an index that could be used to
6292  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6293  **
6294  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6295  **
6296  ** 5. The name of the parent table.
6297  **
6298  ** These six values are used by the C logic below to generate the report.
6299  */
6300  const char *zSql =
6301  "SELECT "
6302    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6303    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6304    "  || fkey_collate_clause("
6305    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6306    ", "
6307    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6308    "  || group_concat('*=?', ' AND ') || ')'"
6309    ", "
6310    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6311    ", "
6312    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6313    ", "
6314    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6315    "  || ' ON ' || quote(s.name) || '('"
6316    "  || group_concat(quote(f.[from]) ||"
6317    "        fkey_collate_clause("
6318    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6319    "  || ');'"
6320    ", "
6321    "     f.[table] "
6322    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6323    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6324    "GROUP BY s.name, f.id "
6325    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6326  ;
6327  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6328
6329  for(i=2; i<nArg; i++){
6330    int n = strlen30(azArg[i]);
6331    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6332      bVerbose = 1;
6333    }
6334    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6335      bGroupByParent = 1;
6336      zIndent = "    ";
6337    }
6338    else{
6339      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6340          azArg[0], azArg[1]
6341      );
6342      return SQLITE_ERROR;
6343    }
6344  }
6345
6346  /* Register the fkey_collate_clause() SQL function */
6347  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6348      0, shellFkeyCollateClause, 0, 0
6349  );
6350
6351
6352  if( rc==SQLITE_OK ){
6353    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6354  }
6355  if( rc==SQLITE_OK ){
6356    sqlite3_bind_int(pSql, 1, bGroupByParent);
6357  }
6358
6359  if( rc==SQLITE_OK ){
6360    int rc2;
6361    char *zPrev = 0;
6362    while( SQLITE_ROW==sqlite3_step(pSql) ){
6363      int res = -1;
6364      sqlite3_stmt *pExplain = 0;
6365      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6366      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6367      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6368      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6369      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6370      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6371
6372      if( zEQP==0 ) continue;
6373      if( zGlob==0 ) continue;
6374      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6375      if( rc!=SQLITE_OK ) break;
6376      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6377        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6378        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6379                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6380      }
6381      rc = sqlite3_finalize(pExplain);
6382      if( rc!=SQLITE_OK ) break;
6383
6384      if( res<0 ){
6385        raw_printf(stderr, "Error: internal error");
6386        break;
6387      }else{
6388        if( bGroupByParent
6389        && (bVerbose || res==0)
6390        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6391        ){
6392          raw_printf(out, "-- Parent table %s\n", zParent);
6393          sqlite3_free(zPrev);
6394          zPrev = sqlite3_mprintf("%s", zParent);
6395        }
6396
6397        if( res==0 ){
6398          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6399        }else if( bVerbose ){
6400          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6401              zIndent, zFrom, zTarget
6402          );
6403        }
6404      }
6405    }
6406    sqlite3_free(zPrev);
6407
6408    if( rc!=SQLITE_OK ){
6409      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6410    }
6411
6412    rc2 = sqlite3_finalize(pSql);
6413    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6414      rc = rc2;
6415      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6416    }
6417  }else{
6418    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6419  }
6420
6421  return rc;
6422}
6423
6424/*
6425** Implementation of ".lint" dot command.
6426*/
6427static int lintDotCommand(
6428  ShellState *pState,             /* Current shell tool state */
6429  char **azArg,                   /* Array of arguments passed to dot command */
6430  int nArg                        /* Number of entries in azArg[] */
6431){
6432  int n;
6433  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6434  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6435  return lintFkeyIndexes(pState, azArg, nArg);
6436
6437 usage:
6438  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6439  raw_printf(stderr, "Where sub-commands are:\n");
6440  raw_printf(stderr, "    fkey-indexes\n");
6441  return SQLITE_ERROR;
6442}
6443
6444#if !defined SQLITE_OMIT_VIRTUALTABLE
6445static void shellPrepare(
6446  sqlite3 *db,
6447  int *pRc,
6448  const char *zSql,
6449  sqlite3_stmt **ppStmt
6450){
6451  *ppStmt = 0;
6452  if( *pRc==SQLITE_OK ){
6453    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6454    if( rc!=SQLITE_OK ){
6455      raw_printf(stderr, "sql error: %s (%d)\n",
6456          sqlite3_errmsg(db), sqlite3_errcode(db)
6457      );
6458      *pRc = rc;
6459    }
6460  }
6461}
6462
6463/*
6464** Create a prepared statement using printf-style arguments for the SQL.
6465**
6466** This routine is could be marked "static".  But it is not always used,
6467** depending on compile-time options.  By omitting the "static", we avoid
6468** nuisance compiler warnings about "defined but not used".
6469*/
6470void shellPreparePrintf(
6471  sqlite3 *db,
6472  int *pRc,
6473  sqlite3_stmt **ppStmt,
6474  const char *zFmt,
6475  ...
6476){
6477  *ppStmt = 0;
6478  if( *pRc==SQLITE_OK ){
6479    va_list ap;
6480    char *z;
6481    va_start(ap, zFmt);
6482    z = sqlite3_vmprintf(zFmt, ap);
6483    va_end(ap);
6484    if( z==0 ){
6485      *pRc = SQLITE_NOMEM;
6486    }else{
6487      shellPrepare(db, pRc, z, ppStmt);
6488      sqlite3_free(z);
6489    }
6490  }
6491}
6492
6493/* Finalize the prepared statement created using shellPreparePrintf().
6494**
6495** This routine is could be marked "static".  But it is not always used,
6496** depending on compile-time options.  By omitting the "static", we avoid
6497** nuisance compiler warnings about "defined but not used".
6498*/
6499void shellFinalize(
6500  int *pRc,
6501  sqlite3_stmt *pStmt
6502){
6503  if( pStmt ){
6504    sqlite3 *db = sqlite3_db_handle(pStmt);
6505    int rc = sqlite3_finalize(pStmt);
6506    if( *pRc==SQLITE_OK ){
6507      if( rc!=SQLITE_OK ){
6508        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6509      }
6510      *pRc = rc;
6511    }
6512  }
6513}
6514
6515/* Reset the prepared statement created using shellPreparePrintf().
6516**
6517** This routine is could be marked "static".  But it is not always used,
6518** depending on compile-time options.  By omitting the "static", we avoid
6519** nuisance compiler warnings about "defined but not used".
6520*/
6521void shellReset(
6522  int *pRc,
6523  sqlite3_stmt *pStmt
6524){
6525  int rc = sqlite3_reset(pStmt);
6526  if( *pRc==SQLITE_OK ){
6527    if( rc!=SQLITE_OK ){
6528      sqlite3 *db = sqlite3_db_handle(pStmt);
6529      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6530    }
6531    *pRc = rc;
6532  }
6533}
6534#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6535
6536#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6537/******************************************************************************
6538** The ".archive" or ".ar" command.
6539*/
6540/*
6541** Structure representing a single ".ar" command.
6542*/
6543typedef struct ArCommand ArCommand;
6544struct ArCommand {
6545  u8 eCmd;                        /* An AR_CMD_* value */
6546  u8 bVerbose;                    /* True if --verbose */
6547  u8 bZip;                        /* True if the archive is a ZIP */
6548  u8 bDryRun;                     /* True if --dry-run */
6549  u8 bAppend;                     /* True if --append */
6550  u8 bGlob;                       /* True if --glob */
6551  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6552  int nArg;                       /* Number of command arguments */
6553  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6554  const char *zFile;              /* --file argument, or NULL */
6555  const char *zDir;               /* --directory argument, or NULL */
6556  char **azArg;                   /* Array of command arguments */
6557  ShellState *p;                  /* Shell state */
6558  sqlite3 *db;                    /* Database containing the archive */
6559};
6560
6561/*
6562** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6563*/
6564static int arUsage(FILE *f){
6565  showHelp(f,"archive");
6566  return SQLITE_ERROR;
6567}
6568
6569/*
6570** Print an error message for the .ar command to stderr and return
6571** SQLITE_ERROR.
6572*/
6573static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6574  va_list ap;
6575  char *z;
6576  va_start(ap, zFmt);
6577  z = sqlite3_vmprintf(zFmt, ap);
6578  va_end(ap);
6579  utf8_printf(stderr, "Error: %s\n", z);
6580  if( pAr->fromCmdLine ){
6581    utf8_printf(stderr, "Use \"-A\" for more help\n");
6582  }else{
6583    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6584  }
6585  sqlite3_free(z);
6586  return SQLITE_ERROR;
6587}
6588
6589/*
6590** Values for ArCommand.eCmd.
6591*/
6592#define AR_CMD_CREATE       1
6593#define AR_CMD_UPDATE       2
6594#define AR_CMD_INSERT       3
6595#define AR_CMD_EXTRACT      4
6596#define AR_CMD_LIST         5
6597#define AR_CMD_HELP         6
6598#define AR_CMD_REMOVE       7
6599
6600/*
6601** Other (non-command) switches.
6602*/
6603#define AR_SWITCH_VERBOSE     8
6604#define AR_SWITCH_FILE        9
6605#define AR_SWITCH_DIRECTORY  10
6606#define AR_SWITCH_APPEND     11
6607#define AR_SWITCH_DRYRUN     12
6608#define AR_SWITCH_GLOB       13
6609
6610static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6611  switch( eSwitch ){
6612    case AR_CMD_CREATE:
6613    case AR_CMD_EXTRACT:
6614    case AR_CMD_LIST:
6615    case AR_CMD_REMOVE:
6616    case AR_CMD_UPDATE:
6617    case AR_CMD_INSERT:
6618    case AR_CMD_HELP:
6619      if( pAr->eCmd ){
6620        return arErrorMsg(pAr, "multiple command options");
6621      }
6622      pAr->eCmd = eSwitch;
6623      break;
6624
6625    case AR_SWITCH_DRYRUN:
6626      pAr->bDryRun = 1;
6627      break;
6628    case AR_SWITCH_GLOB:
6629      pAr->bGlob = 1;
6630      break;
6631    case AR_SWITCH_VERBOSE:
6632      pAr->bVerbose = 1;
6633      break;
6634    case AR_SWITCH_APPEND:
6635      pAr->bAppend = 1;
6636      /* Fall thru into --file */
6637    case AR_SWITCH_FILE:
6638      pAr->zFile = zArg;
6639      break;
6640    case AR_SWITCH_DIRECTORY:
6641      pAr->zDir = zArg;
6642      break;
6643  }
6644
6645  return SQLITE_OK;
6646}
6647
6648/*
6649** Parse the command line for an ".ar" command. The results are written into
6650** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6651** successfully, otherwise an error message is written to stderr and
6652** SQLITE_ERROR returned.
6653*/
6654static int arParseCommand(
6655  char **azArg,                   /* Array of arguments passed to dot command */
6656  int nArg,                       /* Number of entries in azArg[] */
6657  ArCommand *pAr                  /* Populate this object */
6658){
6659  struct ArSwitch {
6660    const char *zLong;
6661    char cShort;
6662    u8 eSwitch;
6663    u8 bArg;
6664  } aSwitch[] = {
6665    { "create",    'c', AR_CMD_CREATE,       0 },
6666    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6667    { "insert",    'i', AR_CMD_INSERT,       0 },
6668    { "list",      't', AR_CMD_LIST,         0 },
6669    { "remove",    'r', AR_CMD_REMOVE,       0 },
6670    { "update",    'u', AR_CMD_UPDATE,       0 },
6671    { "help",      'h', AR_CMD_HELP,         0 },
6672    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6673    { "file",      'f', AR_SWITCH_FILE,      1 },
6674    { "append",    'a', AR_SWITCH_APPEND,    1 },
6675    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6676    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6677    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6678  };
6679  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6680  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6681
6682  if( nArg<=1 ){
6683    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6684    return arUsage(stderr);
6685  }else{
6686    char *z = azArg[1];
6687    if( z[0]!='-' ){
6688      /* Traditional style [tar] invocation */
6689      int i;
6690      int iArg = 2;
6691      for(i=0; z[i]; i++){
6692        const char *zArg = 0;
6693        struct ArSwitch *pOpt;
6694        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6695          if( z[i]==pOpt->cShort ) break;
6696        }
6697        if( pOpt==pEnd ){
6698          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6699        }
6700        if( pOpt->bArg ){
6701          if( iArg>=nArg ){
6702            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6703          }
6704          zArg = azArg[iArg++];
6705        }
6706        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6707      }
6708      pAr->nArg = nArg-iArg;
6709      if( pAr->nArg>0 ){
6710        pAr->azArg = &azArg[iArg];
6711      }
6712    }else{
6713      /* Non-traditional invocation */
6714      int iArg;
6715      for(iArg=1; iArg<nArg; iArg++){
6716        int n;
6717        z = azArg[iArg];
6718        if( z[0]!='-' ){
6719          /* All remaining command line words are command arguments. */
6720          pAr->azArg = &azArg[iArg];
6721          pAr->nArg = nArg-iArg;
6722          break;
6723        }
6724        n = strlen30(z);
6725
6726        if( z[1]!='-' ){
6727          int i;
6728          /* One or more short options */
6729          for(i=1; i<n; i++){
6730            const char *zArg = 0;
6731            struct ArSwitch *pOpt;
6732            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6733              if( z[i]==pOpt->cShort ) break;
6734            }
6735            if( pOpt==pEnd ){
6736              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6737            }
6738            if( pOpt->bArg ){
6739              if( i<(n-1) ){
6740                zArg = &z[i+1];
6741                i = n;
6742              }else{
6743                if( iArg>=(nArg-1) ){
6744                  return arErrorMsg(pAr, "option requires an argument: %c",
6745                                    z[i]);
6746                }
6747                zArg = azArg[++iArg];
6748              }
6749            }
6750            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6751          }
6752        }else if( z[2]=='\0' ){
6753          /* A -- option, indicating that all remaining command line words
6754          ** are command arguments.  */
6755          pAr->azArg = &azArg[iArg+1];
6756          pAr->nArg = nArg-iArg-1;
6757          break;
6758        }else{
6759          /* A long option */
6760          const char *zArg = 0;             /* Argument for option, if any */
6761          struct ArSwitch *pMatch = 0;      /* Matching option */
6762          struct ArSwitch *pOpt;            /* Iterator */
6763          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6764            const char *zLong = pOpt->zLong;
6765            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6766              if( pMatch ){
6767                return arErrorMsg(pAr, "ambiguous option: %s",z);
6768              }else{
6769                pMatch = pOpt;
6770              }
6771            }
6772          }
6773
6774          if( pMatch==0 ){
6775            return arErrorMsg(pAr, "unrecognized option: %s", z);
6776          }
6777          if( pMatch->bArg ){
6778            if( iArg>=(nArg-1) ){
6779              return arErrorMsg(pAr, "option requires an argument: %s", z);
6780            }
6781            zArg = azArg[++iArg];
6782          }
6783          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6784        }
6785      }
6786    }
6787  }
6788
6789  return SQLITE_OK;
6790}
6791
6792/*
6793** This function assumes that all arguments within the ArCommand.azArg[]
6794** array refer to archive members, as for the --extract, --list or --remove
6795** commands. It checks that each of them are "present". If any specified
6796** file is not present in the archive, an error is printed to stderr and an
6797** error code returned. Otherwise, if all specified arguments are present
6798** in the archive, SQLITE_OK is returned. Here, "present" means either an
6799** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6800** when pAr->bGlob is true.
6801**
6802** This function strips any trailing '/' characters from each argument.
6803** This is consistent with the way the [tar] command seems to work on
6804** Linux.
6805*/
6806static int arCheckEntries(ArCommand *pAr){
6807  int rc = SQLITE_OK;
6808  if( pAr->nArg ){
6809    int i, j;
6810    sqlite3_stmt *pTest = 0;
6811    const char *zSel = (pAr->bGlob)
6812      ? "SELECT name FROM %s WHERE glob($name,name)"
6813      : "SELECT name FROM %s WHERE name=$name";
6814
6815    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6816    j = sqlite3_bind_parameter_index(pTest, "$name");
6817    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6818      char *z = pAr->azArg[i];
6819      int n = strlen30(z);
6820      int bOk = 0;
6821      while( n>0 && z[n-1]=='/' ) n--;
6822      z[n] = '\0';
6823      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6824      if( SQLITE_ROW==sqlite3_step(pTest) ){
6825        bOk = 1;
6826      }
6827      shellReset(&rc, pTest);
6828      if( rc==SQLITE_OK && bOk==0 ){
6829        utf8_printf(stderr, "not found in archive: %s\n", z);
6830        rc = SQLITE_ERROR;
6831      }
6832    }
6833    shellFinalize(&rc, pTest);
6834  }
6835  return rc;
6836}
6837
6838/*
6839** Format a WHERE clause that can be used against the "sqlar" table to
6840** identify all archive members that match the command arguments held
6841** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6842** The caller is responsible for eventually calling sqlite3_free() on
6843** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6844** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6845*/
6846static void arWhereClause(
6847  int *pRc,
6848  ArCommand *pAr,
6849  char **pzWhere                  /* OUT: New WHERE clause */
6850){
6851  char *zWhere = 0;
6852  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6853  if( *pRc==SQLITE_OK ){
6854    if( pAr->nArg==0 ){
6855      zWhere = sqlite3_mprintf("1");
6856    }else{
6857      int i;
6858      const char *zSep = "";
6859      for(i=0; i<pAr->nArg; i++){
6860        const char *z = pAr->azArg[i];
6861        zWhere = sqlite3_mprintf(
6862          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6863          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6864        );
6865        if( zWhere==0 ){
6866          *pRc = SQLITE_NOMEM;
6867          break;
6868        }
6869        zSep = " OR ";
6870      }
6871    }
6872  }
6873  *pzWhere = zWhere;
6874}
6875
6876/*
6877** Implementation of .ar "lisT" command.
6878*/
6879static int arListCommand(ArCommand *pAr){
6880  const char *zSql = "SELECT %s FROM %s WHERE %s";
6881  const char *azCols[] = {
6882    "name",
6883    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6884  };
6885
6886  char *zWhere = 0;
6887  sqlite3_stmt *pSql = 0;
6888  int rc;
6889
6890  rc = arCheckEntries(pAr);
6891  arWhereClause(&rc, pAr, &zWhere);
6892
6893  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6894                     pAr->zSrcTable, zWhere);
6895  if( pAr->bDryRun ){
6896    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6897  }else{
6898    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6899      if( pAr->bVerbose ){
6900        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6901            sqlite3_column_text(pSql, 0),
6902            sqlite3_column_int(pSql, 1),
6903            sqlite3_column_text(pSql, 2),
6904            sqlite3_column_text(pSql, 3)
6905        );
6906      }else{
6907        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6908      }
6909    }
6910  }
6911  shellFinalize(&rc, pSql);
6912  sqlite3_free(zWhere);
6913  return rc;
6914}
6915
6916
6917/*
6918** Implementation of .ar "Remove" command.
6919*/
6920static int arRemoveCommand(ArCommand *pAr){
6921  int rc = 0;
6922  char *zSql = 0;
6923  char *zWhere = 0;
6924
6925  if( pAr->nArg ){
6926    /* Verify that args actually exist within the archive before proceeding.
6927    ** And formulate a WHERE clause to match them.  */
6928    rc = arCheckEntries(pAr);
6929    arWhereClause(&rc, pAr, &zWhere);
6930  }
6931  if( rc==SQLITE_OK ){
6932    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6933                           pAr->zSrcTable, zWhere);
6934    if( pAr->bDryRun ){
6935      utf8_printf(pAr->p->out, "%s\n", zSql);
6936    }else{
6937      char *zErr = 0;
6938      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6939      if( rc==SQLITE_OK ){
6940        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6941        if( rc!=SQLITE_OK ){
6942          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6943        }else{
6944          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6945        }
6946      }
6947      if( zErr ){
6948        utf8_printf(stdout, "ERROR: %s\n", zErr);
6949        sqlite3_free(zErr);
6950      }
6951    }
6952  }
6953  sqlite3_free(zWhere);
6954  sqlite3_free(zSql);
6955  return rc;
6956}
6957
6958/*
6959** Implementation of .ar "eXtract" command.
6960*/
6961static int arExtractCommand(ArCommand *pAr){
6962  const char *zSql1 =
6963    "SELECT "
6964    " ($dir || name),"
6965    " writefile(($dir || name), %s, mode, mtime) "
6966    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6967    " AND name NOT GLOB '*..[/\\]*'";
6968
6969  const char *azExtraArg[] = {
6970    "sqlar_uncompress(data, sz)",
6971    "data"
6972  };
6973
6974  sqlite3_stmt *pSql = 0;
6975  int rc = SQLITE_OK;
6976  char *zDir = 0;
6977  char *zWhere = 0;
6978  int i, j;
6979
6980  /* If arguments are specified, check that they actually exist within
6981  ** the archive before proceeding. And formulate a WHERE clause to
6982  ** match them.  */
6983  rc = arCheckEntries(pAr);
6984  arWhereClause(&rc, pAr, &zWhere);
6985
6986  if( rc==SQLITE_OK ){
6987    if( pAr->zDir ){
6988      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6989    }else{
6990      zDir = sqlite3_mprintf("");
6991    }
6992    if( zDir==0 ) rc = SQLITE_NOMEM;
6993  }
6994
6995  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6996      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6997  );
6998
6999  if( rc==SQLITE_OK ){
7000    j = sqlite3_bind_parameter_index(pSql, "$dir");
7001    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
7002
7003    /* Run the SELECT statement twice. The first time, writefile() is called
7004    ** for all archive members that should be extracted. The second time,
7005    ** only for the directories. This is because the timestamps for
7006    ** extracted directories must be reset after they are populated (as
7007    ** populating them changes the timestamp).  */
7008    for(i=0; i<2; i++){
7009      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
7010      sqlite3_bind_int(pSql, j, i);
7011      if( pAr->bDryRun ){
7012        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
7013      }else{
7014        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
7015          if( i==0 && pAr->bVerbose ){
7016            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
7017          }
7018        }
7019      }
7020      shellReset(&rc, pSql);
7021    }
7022    shellFinalize(&rc, pSql);
7023  }
7024
7025  sqlite3_free(zDir);
7026  sqlite3_free(zWhere);
7027  return rc;
7028}
7029
7030/*
7031** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
7032*/
7033static int arExecSql(ArCommand *pAr, const char *zSql){
7034  int rc;
7035  if( pAr->bDryRun ){
7036    utf8_printf(pAr->p->out, "%s\n", zSql);
7037    rc = SQLITE_OK;
7038  }else{
7039    char *zErr = 0;
7040    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7041    if( zErr ){
7042      utf8_printf(stdout, "ERROR: %s\n", zErr);
7043      sqlite3_free(zErr);
7044    }
7045  }
7046  return rc;
7047}
7048
7049
7050/*
7051** Implementation of .ar "create", "insert", and "update" commands.
7052**
7053**     create    ->     Create a new SQL archive
7054**     insert    ->     Insert or reinsert all files listed
7055**     update    ->     Insert files that have changed or that were not
7056**                      previously in the archive
7057**
7058** Create the "sqlar" table in the database if it does not already exist.
7059** Then add each file in the azFile[] array to the archive. Directories
7060** are added recursively. If argument bVerbose is non-zero, a message is
7061** printed on stdout for each file archived.
7062**
7063** The create command is the same as update, except that it drops
7064** any existing "sqlar" table before beginning.  The "insert" command
7065** always overwrites every file named on the command-line, where as
7066** "update" only overwrites if the size or mtime or mode has changed.
7067*/
7068static int arCreateOrUpdateCommand(
7069  ArCommand *pAr,                 /* Command arguments and options */
7070  int bUpdate,                    /* true for a --create. */
7071  int bOnlyIfChanged              /* Only update if file has changed */
7072){
7073  const char *zCreate =
7074      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7075      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7076      "  mode INT,               -- access permissions\n"
7077      "  mtime INT,              -- last modification time\n"
7078      "  sz INT,                 -- original file size\n"
7079      "  data BLOB               -- compressed content\n"
7080      ")";
7081  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7082  const char *zInsertFmt[2] = {
7083     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7084     "  SELECT\n"
7085     "    %s,\n"
7086     "    mode,\n"
7087     "    mtime,\n"
7088     "    CASE substr(lsmode(mode),1,1)\n"
7089     "      WHEN '-' THEN length(data)\n"
7090     "      WHEN 'd' THEN 0\n"
7091     "      ELSE -1 END,\n"
7092     "    sqlar_compress(data)\n"
7093     "  FROM fsdir(%Q,%Q) AS disk\n"
7094     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7095     ,
7096     "REPLACE INTO %s(name,mode,mtime,data)\n"
7097     "  SELECT\n"
7098     "    %s,\n"
7099     "    mode,\n"
7100     "    mtime,\n"
7101     "    data\n"
7102     "  FROM fsdir(%Q,%Q) AS disk\n"
7103     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7104  };
7105  int i;                          /* For iterating through azFile[] */
7106  int rc;                         /* Return code */
7107  const char *zTab = 0;           /* SQL table into which to insert */
7108  char *zSql;
7109  char zTemp[50];
7110  char *zExists = 0;
7111
7112  arExecSql(pAr, "PRAGMA page_size=512");
7113  rc = arExecSql(pAr, "SAVEPOINT ar;");
7114  if( rc!=SQLITE_OK ) return rc;
7115  zTemp[0] = 0;
7116  if( pAr->bZip ){
7117    /* Initialize the zipfile virtual table, if necessary */
7118    if( pAr->zFile ){
7119      sqlite3_uint64 r;
7120      sqlite3_randomness(sizeof(r),&r);
7121      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7122      zTab = zTemp;
7123      zSql = sqlite3_mprintf(
7124         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7125         zTab, pAr->zFile
7126      );
7127      rc = arExecSql(pAr, zSql);
7128      sqlite3_free(zSql);
7129    }else{
7130      zTab = "zip";
7131    }
7132  }else{
7133    /* Initialize the table for an SQLAR */
7134    zTab = "sqlar";
7135    if( bUpdate==0 ){
7136      rc = arExecSql(pAr, zDrop);
7137      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7138    }
7139    rc = arExecSql(pAr, zCreate);
7140  }
7141  if( bOnlyIfChanged ){
7142    zExists = sqlite3_mprintf(
7143      " AND NOT EXISTS("
7144          "SELECT 1 FROM %s AS mem"
7145          " WHERE mem.name=disk.name"
7146          " AND mem.mtime=disk.mtime"
7147          " AND mem.mode=disk.mode)", zTab);
7148  }else{
7149    zExists = sqlite3_mprintf("");
7150  }
7151  if( zExists==0 ) rc = SQLITE_NOMEM;
7152  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7153    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7154        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7155        pAr->azArg[i], pAr->zDir, zExists);
7156    rc = arExecSql(pAr, zSql2);
7157    sqlite3_free(zSql2);
7158  }
7159end_ar_transaction:
7160  if( rc!=SQLITE_OK ){
7161    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7162  }else{
7163    rc = arExecSql(pAr, "RELEASE ar;");
7164    if( pAr->bZip && pAr->zFile ){
7165      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7166      arExecSql(pAr, zSql);
7167      sqlite3_free(zSql);
7168    }
7169  }
7170  sqlite3_free(zExists);
7171  return rc;
7172}
7173
7174/*
7175** Implementation of ".ar" dot command.
7176*/
7177static int arDotCommand(
7178  ShellState *pState,          /* Current shell tool state */
7179  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7180  char **azArg,                /* Array of arguments passed to dot command */
7181  int nArg                     /* Number of entries in azArg[] */
7182){
7183  ArCommand cmd;
7184  int rc;
7185  memset(&cmd, 0, sizeof(cmd));
7186  cmd.fromCmdLine = fromCmdLine;
7187  rc = arParseCommand(azArg, nArg, &cmd);
7188  if( rc==SQLITE_OK ){
7189    int eDbType = SHELL_OPEN_UNSPEC;
7190    cmd.p = pState;
7191    cmd.db = pState->db;
7192    if( cmd.zFile ){
7193      eDbType = deduceDatabaseType(cmd.zFile, 1);
7194    }else{
7195      eDbType = pState->openMode;
7196    }
7197    if( eDbType==SHELL_OPEN_ZIPFILE ){
7198      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7199        if( cmd.zFile==0 ){
7200          cmd.zSrcTable = sqlite3_mprintf("zip");
7201        }else{
7202          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7203        }
7204      }
7205      cmd.bZip = 1;
7206    }else if( cmd.zFile ){
7207      int flags;
7208      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7209      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7210           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7211        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7212      }else{
7213        flags = SQLITE_OPEN_READONLY;
7214      }
7215      cmd.db = 0;
7216      if( cmd.bDryRun ){
7217        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7218             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7219      }
7220      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7221             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7222      if( rc!=SQLITE_OK ){
7223        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7224            cmd.zFile, sqlite3_errmsg(cmd.db)
7225        );
7226        goto end_ar_command;
7227      }
7228      sqlite3_fileio_init(cmd.db, 0, 0);
7229      sqlite3_sqlar_init(cmd.db, 0, 0);
7230      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7231                              shellPutsFunc, 0, 0);
7232
7233    }
7234    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7235      if( cmd.eCmd!=AR_CMD_CREATE
7236       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7237      ){
7238        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7239        rc = SQLITE_ERROR;
7240        goto end_ar_command;
7241      }
7242      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7243    }
7244
7245    switch( cmd.eCmd ){
7246      case AR_CMD_CREATE:
7247        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7248        break;
7249
7250      case AR_CMD_EXTRACT:
7251        rc = arExtractCommand(&cmd);
7252        break;
7253
7254      case AR_CMD_LIST:
7255        rc = arListCommand(&cmd);
7256        break;
7257
7258      case AR_CMD_HELP:
7259        arUsage(pState->out);
7260        break;
7261
7262      case AR_CMD_INSERT:
7263        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7264        break;
7265
7266      case AR_CMD_REMOVE:
7267        rc = arRemoveCommand(&cmd);
7268        break;
7269
7270      default:
7271        assert( cmd.eCmd==AR_CMD_UPDATE );
7272        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7273        break;
7274    }
7275  }
7276end_ar_command:
7277  if( cmd.db!=pState->db ){
7278    close_db(cmd.db);
7279  }
7280  sqlite3_free(cmd.zSrcTable);
7281
7282  return rc;
7283}
7284/* End of the ".archive" or ".ar" command logic
7285*******************************************************************************/
7286#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7287
7288#if SQLITE_SHELL_HAVE_RECOVER
7289
7290/*
7291** This function is used as a callback by the recover extension. Simply
7292** print the supplied SQL statement to stdout.
7293*/
7294static int recoverSqlCb(void *pCtx, const char *zSql){
7295  ShellState *pState = (ShellState*)pCtx;
7296  utf8_printf(pState->out, "%s;\n", zSql);
7297  return SQLITE_OK;
7298}
7299
7300/*
7301** This function is called to recover data from the database. A script
7302** to construct a new database containing all recovered data is output
7303** on stream pState->out.
7304*/
7305static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7306  int rc = SQLITE_OK;
7307  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7308  const char *zLAF = "lost_and_found";
7309  int bFreelist = 1;              /* 0 if --ignore-freelist is specified */
7310  int bRowids = 1;                /* 0 if --no-rowids */
7311  sqlite3_recover *p = 0;
7312  int i = 0;
7313
7314  for(i=1; i<nArg; i++){
7315    char *z = azArg[i];
7316    int n;
7317    if( z[0]=='-' && z[1]=='-' ) z++;
7318    n = strlen30(z);
7319    if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
7320      bFreelist = 0;
7321    }else
7322    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7323      i++;
7324      zRecoveryDb = azArg[i];
7325    }else
7326    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7327      i++;
7328      zLAF = azArg[i];
7329    }else
7330    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7331      bRowids = 0;
7332    }
7333    else{
7334      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7335      showHelp(pState->out, azArg[0]);
7336      return 1;
7337    }
7338  }
7339
7340  p = sqlite3_recover_init_sql(
7341      pState->db, "main", recoverSqlCb, (void*)pState
7342  );
7343
7344  sqlite3_recover_config(p, 789, (void*)zRecoveryDb);
7345  sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
7346  sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
7347  sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
7348
7349  sqlite3_recover_run(p);
7350  if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
7351    const char *zErr = sqlite3_recover_errmsg(p);
7352    int errCode = sqlite3_recover_errcode(p);
7353    raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
7354  }
7355  rc = sqlite3_recover_finish(p);
7356  return rc;
7357}
7358#endif /* SQLITE_SHELL_HAVE_RECOVER */
7359
7360
7361/*
7362 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7363 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7364 *   close db and set it to 0, and return the columns spec, to later
7365 *   be sqlite3_free()'ed by the caller.
7366 * The return is 0 when either:
7367 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7368 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7369 * The 3rd argument, pRenamed, references an out parameter. If the
7370 * pointer is non-zero, its referent will be set to a summary of renames
7371 * done if renaming was necessary, or set to 0 if none was done. The out
7372 * string (if any) must be sqlite3_free()'ed by the caller.
7373 */
7374#ifdef SHELL_DEBUG
7375#define rc_err_oom_die(rc) \
7376  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7377  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7378    fprintf(stderr,"E:%d\n",rc), assert(0)
7379#else
7380static void rc_err_oom_die(int rc){
7381  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7382  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7383}
7384#endif
7385
7386#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7387static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7388#else  /* Otherwise, memory is faster/better for the transient DB. */
7389static const char *zCOL_DB = ":memory:";
7390#endif
7391
7392/* Define character (as C string) to separate generated column ordinal
7393 * from protected part of incoming column names. This defaults to "_"
7394 * so that incoming column identifiers that did not need not be quoted
7395 * remain usable without being quoted. It must be one character.
7396 */
7397#ifndef SHELL_AUTOCOLUMN_SEP
7398# define AUTOCOLUMN_SEP "_"
7399#else
7400# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7401#endif
7402
7403static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7404  /* Queries and D{D,M}L used here */
7405  static const char * const zTabMake = "\
7406CREATE TABLE ColNames(\
7407 cpos INTEGER PRIMARY KEY,\
7408 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7409CREATE VIEW RepeatedNames AS \
7410SELECT DISTINCT t.name FROM ColNames t \
7411WHERE t.name COLLATE NOCASE IN (\
7412 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7413);\
7414";
7415  static const char * const zTabFill = "\
7416INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7417 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7418";
7419  static const char * const zHasDupes = "\
7420SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7421 <count(name) FROM ColNames\
7422";
7423#ifdef SHELL_COLUMN_RENAME_CLEAN
7424  static const char * const zDedoctor = "\
7425UPDATE ColNames SET chop=iif(\
7426  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7427  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7428 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7429 0\
7430)\
7431";
7432#endif
7433  static const char * const zSetReps = "\
7434UPDATE ColNames AS t SET reps=\
7435(SELECT count(*) FROM ColNames d \
7436 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7437 COLLATE NOCASE\
7438)\
7439";
7440#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7441  static const char * const zColDigits = "\
7442SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7443";
7444#else
7445  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7446  static const char * const zColDigits = "\
7447SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7448 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7449 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7450";
7451#endif
7452  static const char * const zRenameRank =
7453#ifdef SHELL_COLUMN_RENAME_CLEAN
7454    "UPDATE ColNames AS t SET suff="
7455    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7456#else /* ...RENAME_MINIMAL_ONE_PASS */
7457"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7458"  SELECT 0 AS nlz"
7459"  UNION"
7460"  SELECT nlz+1 AS nlz FROM Lzn"
7461"  WHERE EXISTS("
7462"   SELECT 1"
7463"   FROM ColNames t, ColNames o"
7464"   WHERE"
7465"    iif(t.name IN (SELECT * FROM RepeatedNames),"
7466"     printf('%s"AUTOCOLUMN_SEP"%s',"
7467"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
7468"     t.name"
7469"    )"
7470"    ="
7471"    iif(o.name IN (SELECT * FROM RepeatedNames),"
7472"     printf('%s"AUTOCOLUMN_SEP"%s',"
7473"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
7474"     o.name"
7475"    )"
7476"    COLLATE NOCASE"
7477"    AND o.cpos<>t.cpos"
7478"   GROUP BY t.cpos"
7479"  )"
7480") UPDATE Colnames AS t SET"
7481" chop = 0," /* No chopping, never touch incoming names. */
7482" suff = iif(name IN (SELECT * FROM RepeatedNames),"
7483"  printf('"AUTOCOLUMN_SEP"%s', substring("
7484"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
7485"  ''"
7486" )"
7487#endif
7488    ;
7489  static const char * const zCollectVar = "\
7490SELECT\
7491 '('||x'0a'\
7492 || group_concat(\
7493  cname||' TEXT',\
7494  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
7495 ||')' AS ColsSpec \
7496FROM (\
7497 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
7498 FROM ColNames ORDER BY cpos\
7499)";
7500  static const char * const zRenamesDone =
7501    "SELECT group_concat("
7502    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
7503    " ','||x'0a')"
7504    "FROM ColNames WHERE suff<>'' OR chop!=0"
7505    ;
7506  int rc;
7507  sqlite3_stmt *pStmt = 0;
7508  assert(pDb!=0);
7509  if( zColNew ){
7510    /* Add initial or additional column. Init db if necessary. */
7511    if( *pDb==0 ){
7512      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
7513#ifdef SHELL_COLFIX_DB
7514      if(*zCOL_DB!=':')
7515        sqlite3_exec(*pDb,"drop table if exists ColNames;"
7516                     "drop view if exists RepeatedNames;",0,0,0);
7517#endif
7518      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
7519      rc_err_oom_die(rc);
7520    }
7521    assert(*pDb!=0);
7522    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
7523    rc_err_oom_die(rc);
7524    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
7525    rc_err_oom_die(rc);
7526    rc = sqlite3_step(pStmt);
7527    rc_err_oom_die(rc);
7528    sqlite3_finalize(pStmt);
7529    return 0;
7530  }else if( *pDb==0 ){
7531    return 0;
7532  }else{
7533    /* Formulate the columns spec, close the DB, zero *pDb. */
7534    char *zColsSpec = 0;
7535    int hasDupes = db_int(*pDb, zHasDupes);
7536    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
7537    if( hasDupes ){
7538#ifdef SHELL_COLUMN_RENAME_CLEAN
7539      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
7540      rc_err_oom_die(rc);
7541#endif
7542      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
7543      rc_err_oom_die(rc);
7544      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
7545      rc_err_oom_die(rc);
7546      sqlite3_bind_int(pStmt, 1, nDigits);
7547      rc = sqlite3_step(pStmt);
7548      sqlite3_finalize(pStmt);
7549      assert(rc==SQLITE_DONE);
7550    }
7551    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
7552    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
7553    rc_err_oom_die(rc);
7554    rc = sqlite3_step(pStmt);
7555    if( rc==SQLITE_ROW ){
7556      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7557    }else{
7558      zColsSpec = 0;
7559    }
7560    if( pzRenamed!=0 ){
7561      if( !hasDupes ) *pzRenamed = 0;
7562      else{
7563        sqlite3_finalize(pStmt);
7564        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
7565            && SQLITE_ROW==sqlite3_step(pStmt) ){
7566          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7567        }else
7568          *pzRenamed = 0;
7569      }
7570    }
7571    sqlite3_finalize(pStmt);
7572    sqlite3_close(*pDb);
7573    *pDb = 0;
7574    return zColsSpec;
7575  }
7576}
7577
7578/*
7579** If an input line begins with "." then invoke this routine to
7580** process that line.
7581**
7582** Return 1 on error, 2 to exit, and 0 otherwise.
7583*/
7584static int do_meta_command(char *zLine, ShellState *p){
7585  int h = 1;
7586  int nArg = 0;
7587  int n, c;
7588  int rc = 0;
7589  char *azArg[52];
7590
7591#ifndef SQLITE_OMIT_VIRTUALTABLE
7592  if( p->expert.pExpert ){
7593    expertFinish(p, 1, 0);
7594  }
7595#endif
7596
7597  /* Parse the input line into tokens.
7598  */
7599  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
7600    while( IsSpace(zLine[h]) ){ h++; }
7601    if( zLine[h]==0 ) break;
7602    if( zLine[h]=='\'' || zLine[h]=='"' ){
7603      int delim = zLine[h++];
7604      azArg[nArg++] = &zLine[h];
7605      while( zLine[h] && zLine[h]!=delim ){
7606        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
7607        h++;
7608      }
7609      if( zLine[h]==delim ){
7610        zLine[h++] = 0;
7611      }
7612      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
7613    }else{
7614      azArg[nArg++] = &zLine[h];
7615      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
7616      if( zLine[h] ) zLine[h++] = 0;
7617      resolve_backslashes(azArg[nArg-1]);
7618    }
7619  }
7620  azArg[nArg] = 0;
7621
7622  /* Process the input line.
7623  */
7624  if( nArg==0 ) return 0; /* no tokens, no error */
7625  n = strlen30(azArg[0]);
7626  c = azArg[0][0];
7627  clearTempFile(p);
7628
7629#ifndef SQLITE_OMIT_AUTHORIZATION
7630  if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){
7631    if( nArg!=2 ){
7632      raw_printf(stderr, "Usage: .auth ON|OFF\n");
7633      rc = 1;
7634      goto meta_command_exit;
7635    }
7636    open_db(p, 0);
7637    if( booleanValue(azArg[1]) ){
7638      sqlite3_set_authorizer(p->db, shellAuth, p);
7639    }else if( p->bSafeModePersist ){
7640      sqlite3_set_authorizer(p->db, safeModeAuth, p);
7641    }else{
7642      sqlite3_set_authorizer(p->db, 0, 0);
7643    }
7644  }else
7645#endif
7646
7647#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
7648  && !defined(SQLITE_SHELL_FIDDLE)
7649  if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){
7650    open_db(p, 0);
7651    failIfSafeMode(p, "cannot run .archive in safe mode");
7652    rc = arDotCommand(p, 0, azArg, nArg);
7653  }else
7654#endif
7655
7656#ifndef SQLITE_SHELL_FIDDLE
7657  if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0)
7658   || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0)
7659  ){
7660    const char *zDestFile = 0;
7661    const char *zDb = 0;
7662    sqlite3 *pDest;
7663    sqlite3_backup *pBackup;
7664    int j;
7665    int bAsync = 0;
7666    const char *zVfs = 0;
7667    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
7668    for(j=1; j<nArg; j++){
7669      const char *z = azArg[j];
7670      if( z[0]=='-' ){
7671        if( z[1]=='-' ) z++;
7672        if( cli_strcmp(z, "-append")==0 ){
7673          zVfs = "apndvfs";
7674        }else
7675        if( cli_strcmp(z, "-async")==0 ){
7676          bAsync = 1;
7677        }else
7678        {
7679          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
7680          return 1;
7681        }
7682      }else if( zDestFile==0 ){
7683        zDestFile = azArg[j];
7684      }else if( zDb==0 ){
7685        zDb = zDestFile;
7686        zDestFile = azArg[j];
7687      }else{
7688        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
7689        return 1;
7690      }
7691    }
7692    if( zDestFile==0 ){
7693      raw_printf(stderr, "missing FILENAME argument on .backup\n");
7694      return 1;
7695    }
7696    if( zDb==0 ) zDb = "main";
7697    rc = sqlite3_open_v2(zDestFile, &pDest,
7698                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
7699    if( rc!=SQLITE_OK ){
7700      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
7701      close_db(pDest);
7702      return 1;
7703    }
7704    if( bAsync ){
7705      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7706                   0, 0, 0);
7707    }
7708    open_db(p, 0);
7709    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7710    if( pBackup==0 ){
7711      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7712      close_db(pDest);
7713      return 1;
7714    }
7715    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7716    sqlite3_backup_finish(pBackup);
7717    if( rc==SQLITE_DONE ){
7718      rc = 0;
7719    }else{
7720      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7721      rc = 1;
7722    }
7723    close_db(pDest);
7724  }else
7725#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7726
7727  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){
7728    if( nArg==2 ){
7729      bail_on_error = booleanValue(azArg[1]);
7730    }else{
7731      raw_printf(stderr, "Usage: .bail on|off\n");
7732      rc = 1;
7733    }
7734  }else
7735
7736  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){
7737    if( nArg==2 ){
7738      if( booleanValue(azArg[1]) ){
7739        setBinaryMode(p->out, 1);
7740      }else{
7741        setTextMode(p->out, 1);
7742      }
7743    }else{
7744      raw_printf(stderr, "Usage: .binary on|off\n");
7745      rc = 1;
7746    }
7747  }else
7748
7749  /* The undocumented ".breakpoint" command causes a call to the no-op
7750  ** routine named test_breakpoint().
7751  */
7752  if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){
7753    test_breakpoint();
7754  }else
7755
7756#ifndef SQLITE_SHELL_FIDDLE
7757  if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){
7758    failIfSafeMode(p, "cannot run .cd in safe mode");
7759    if( nArg==2 ){
7760#if defined(_WIN32) || defined(WIN32)
7761      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7762      rc = !SetCurrentDirectoryW(z);
7763      sqlite3_free(z);
7764#else
7765      rc = chdir(azArg[1]);
7766#endif
7767      if( rc ){
7768        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7769        rc = 1;
7770      }
7771    }else{
7772      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7773      rc = 1;
7774    }
7775  }else
7776#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7777
7778  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){
7779    if( nArg==2 ){
7780      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7781    }else{
7782      raw_printf(stderr, "Usage: .changes on|off\n");
7783      rc = 1;
7784    }
7785  }else
7786
7787#ifndef SQLITE_SHELL_FIDDLE
7788  /* Cancel output redirection, if it is currently set (by .testcase)
7789  ** Then read the content of the testcase-out.txt file and compare against
7790  ** azArg[1].  If there are differences, report an error and exit.
7791  */
7792  if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){
7793    char *zRes = 0;
7794    output_reset(p);
7795    if( nArg!=2 ){
7796      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7797      rc = 2;
7798    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7799      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7800      rc = 2;
7801    }else if( testcase_glob(azArg[1],zRes)==0 ){
7802      utf8_printf(stderr,
7803                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
7804                 p->zTestcase, azArg[1], zRes);
7805      rc = 1;
7806    }else{
7807      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7808      p->nCheck++;
7809    }
7810    sqlite3_free(zRes);
7811  }else
7812#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7813
7814#ifndef SQLITE_SHELL_FIDDLE
7815  if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){
7816    failIfSafeMode(p, "cannot run .clone in safe mode");
7817    if( nArg==2 ){
7818      tryToClone(p, azArg[1]);
7819    }else{
7820      raw_printf(stderr, "Usage: .clone FILENAME\n");
7821      rc = 1;
7822    }
7823  }else
7824#endif /* !defined(SQLITE_SHELL_FIDDLE) */
7825
7826  if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){
7827    if( nArg==1 ){
7828      /* List available connections */
7829      int i;
7830      for(i=0; i<ArraySize(p->aAuxDb); i++){
7831        const char *zFile = p->aAuxDb[i].zDbFilename;
7832        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
7833          zFile = "(not open)";
7834        }else if( zFile==0 ){
7835          zFile = "(memory)";
7836        }else if( zFile[0]==0 ){
7837          zFile = "(temporary-file)";
7838        }
7839        if( p->pAuxDb == &p->aAuxDb[i] ){
7840          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
7841        }else if( p->aAuxDb[i].db!=0 ){
7842          utf8_printf(stdout, "       %d: %s\n", i, zFile);
7843        }
7844      }
7845    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
7846      int i = azArg[1][0] - '0';
7847      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
7848        p->pAuxDb->db = p->db;
7849        p->pAuxDb = &p->aAuxDb[i];
7850        globalDb = p->db = p->pAuxDb->db;
7851        p->pAuxDb->db = 0;
7852      }
7853    }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0
7854           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
7855      int i = azArg[2][0] - '0';
7856      if( i<0 || i>=ArraySize(p->aAuxDb) ){
7857        /* No-op */
7858      }else if( p->pAuxDb == &p->aAuxDb[i] ){
7859        raw_printf(stderr, "cannot close the active database connection\n");
7860        rc = 1;
7861      }else if( p->aAuxDb[i].db ){
7862        session_close_all(p, i);
7863        close_db(p->aAuxDb[i].db);
7864        p->aAuxDb[i].db = 0;
7865      }
7866    }else{
7867      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
7868      rc = 1;
7869    }
7870  }else
7871
7872  if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){
7873    char **azName = 0;
7874    int nName = 0;
7875    sqlite3_stmt *pStmt;
7876    int i;
7877    open_db(p, 0);
7878    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7879    if( rc ){
7880      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7881      rc = 1;
7882    }else{
7883      while( sqlite3_step(pStmt)==SQLITE_ROW ){
7884        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
7885        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
7886        if( zSchema==0 || zFile==0 ) continue;
7887        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
7888        shell_check_oom(azName);
7889        azName[nName*2] = strdup(zSchema);
7890        azName[nName*2+1] = strdup(zFile);
7891        nName++;
7892      }
7893    }
7894    sqlite3_finalize(pStmt);
7895    for(i=0; i<nName; i++){
7896      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
7897      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
7898      const char *z = azName[i*2+1];
7899      utf8_printf(p->out, "%s: %s %s%s\n",
7900         azName[i*2],
7901         z && z[0] ? z : "\"\"",
7902         bRdonly ? "r/o" : "r/w",
7903         eTxn==SQLITE_TXN_NONE ? "" :
7904            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
7905      free(azName[i*2]);
7906      free(azName[i*2+1]);
7907    }
7908    sqlite3_free(azName);
7909  }else
7910
7911  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){
7912    static const struct DbConfigChoices {
7913      const char *zName;
7914      int op;
7915    } aDbConfig[] = {
7916        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
7917        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
7918        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
7919        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
7920        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
7921        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
7922        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
7923        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7924        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
7925        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
7926        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7927        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
7928        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
7929        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
7930        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
7931        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
7932    };
7933    int ii, v;
7934    open_db(p, 0);
7935    for(ii=0; ii<ArraySize(aDbConfig); ii++){
7936      if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7937      if( nArg>=3 ){
7938        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7939      }
7940      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7941      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7942      if( nArg>1 ) break;
7943    }
7944    if( nArg>1 && ii==ArraySize(aDbConfig) ){
7945      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7946      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7947    }
7948  }else
7949
7950#if SQLITE_SHELL_HAVE_RECOVER
7951  if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){
7952    rc = shell_dbinfo_command(p, nArg, azArg);
7953  }else
7954
7955  if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){
7956    open_db(p, 0);
7957    rc = recoverDatabaseCmd(p, nArg, azArg);
7958  }else
7959#endif /* SQLITE_SHELL_HAVE_RECOVER */
7960
7961  if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){
7962    char *zLike = 0;
7963    char *zSql;
7964    int i;
7965    int savedShowHeader = p->showHeader;
7966    int savedShellFlags = p->shellFlgs;
7967    ShellClearFlag(p,
7968       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
7969       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
7970    for(i=1; i<nArg; i++){
7971      if( azArg[i][0]=='-' ){
7972        const char *z = azArg[i]+1;
7973        if( z[0]=='-' ) z++;
7974        if( cli_strcmp(z,"preserve-rowids")==0 ){
7975#ifdef SQLITE_OMIT_VIRTUALTABLE
7976          raw_printf(stderr, "The --preserve-rowids option is not compatible"
7977                             " with SQLITE_OMIT_VIRTUALTABLE\n");
7978          rc = 1;
7979          sqlite3_free(zLike);
7980          goto meta_command_exit;
7981#else
7982          ShellSetFlag(p, SHFLG_PreserveRowid);
7983#endif
7984        }else
7985        if( cli_strcmp(z,"newlines")==0 ){
7986          ShellSetFlag(p, SHFLG_Newlines);
7987        }else
7988        if( cli_strcmp(z,"data-only")==0 ){
7989          ShellSetFlag(p, SHFLG_DumpDataOnly);
7990        }else
7991        if( cli_strcmp(z,"nosys")==0 ){
7992          ShellSetFlag(p, SHFLG_DumpNoSys);
7993        }else
7994        {
7995          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7996          rc = 1;
7997          sqlite3_free(zLike);
7998          goto meta_command_exit;
7999        }
8000      }else{
8001        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8002        ** only dump data for tables for which either the table name matches
8003        ** the LIKE pattern, or the table appears to be a shadow table of
8004        ** a virtual table for which the name matches the LIKE pattern.
8005        */
8006        char *zExpr = sqlite3_mprintf(
8007            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8008            "  SELECT 1 FROM sqlite_schema WHERE "
8009            "    name LIKE %Q ESCAPE '\\' AND"
8010            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8011            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8012            ")", azArg[i], azArg[i]
8013        );
8014
8015        if( zLike ){
8016          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8017        }else{
8018          zLike = zExpr;
8019        }
8020      }
8021    }
8022
8023    open_db(p, 0);
8024
8025    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8026      /* When playing back a "dump", the content might appear in an order
8027      ** which causes immediate foreign key constraints to be violated.
8028      ** So disable foreign-key constraint enforcement to prevent problems. */
8029      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8030      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8031    }
8032    p->writableSchema = 0;
8033    p->showHeader = 0;
8034    /* Set writable_schema=ON since doing so forces SQLite to initialize
8035    ** as much of the schema as it can even if the sqlite_schema table is
8036    ** corrupt. */
8037    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8038    p->nErr = 0;
8039    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8040    zSql = sqlite3_mprintf(
8041      "SELECT name, type, sql FROM sqlite_schema AS o "
8042      "WHERE (%s) AND type=='table'"
8043      "  AND sql NOT NULL"
8044      " ORDER BY tbl_name='sqlite_sequence', rowid",
8045      zLike
8046    );
8047    run_schema_dump_query(p,zSql);
8048    sqlite3_free(zSql);
8049    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8050      zSql = sqlite3_mprintf(
8051        "SELECT sql FROM sqlite_schema AS o "
8052        "WHERE (%s) AND sql NOT NULL"
8053        "  AND type IN ('index','trigger','view')",
8054        zLike
8055      );
8056      run_table_dump_query(p, zSql);
8057      sqlite3_free(zSql);
8058    }
8059    sqlite3_free(zLike);
8060    if( p->writableSchema ){
8061      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8062      p->writableSchema = 0;
8063    }
8064    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8065    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8066    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8067      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8068    }
8069    p->showHeader = savedShowHeader;
8070    p->shellFlgs = savedShellFlags;
8071  }else
8072
8073  if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){
8074    if( nArg==2 ){
8075      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8076    }else{
8077      raw_printf(stderr, "Usage: .echo on|off\n");
8078      rc = 1;
8079    }
8080  }else
8081
8082  if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){
8083    if( nArg==2 ){
8084      p->autoEQPtest = 0;
8085      if( p->autoEQPtrace ){
8086        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8087        p->autoEQPtrace = 0;
8088      }
8089      if( cli_strcmp(azArg[1],"full")==0 ){
8090        p->autoEQP = AUTOEQP_full;
8091      }else if( cli_strcmp(azArg[1],"trigger")==0 ){
8092        p->autoEQP = AUTOEQP_trigger;
8093#ifdef SQLITE_DEBUG
8094      }else if( cli_strcmp(azArg[1],"test")==0 ){
8095        p->autoEQP = AUTOEQP_on;
8096        p->autoEQPtest = 1;
8097      }else if( cli_strcmp(azArg[1],"trace")==0 ){
8098        p->autoEQP = AUTOEQP_full;
8099        p->autoEQPtrace = 1;
8100        open_db(p, 0);
8101        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8102        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8103#endif
8104      }else{
8105        p->autoEQP = (u8)booleanValue(azArg[1]);
8106      }
8107    }else{
8108      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8109      rc = 1;
8110    }
8111  }else
8112
8113#ifndef SQLITE_SHELL_FIDDLE
8114  if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){
8115    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8116    rc = 2;
8117  }else
8118#endif
8119
8120  /* The ".explain" command is automatic now.  It is largely pointless.  It
8121  ** retained purely for backwards compatibility */
8122  if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){
8123    int val = 1;
8124    if( nArg>=2 ){
8125      if( cli_strcmp(azArg[1],"auto")==0 ){
8126        val = 99;
8127      }else{
8128        val =  booleanValue(azArg[1]);
8129      }
8130    }
8131    if( val==1 && p->mode!=MODE_Explain ){
8132      p->normalMode = p->mode;
8133      p->mode = MODE_Explain;
8134      p->autoExplain = 0;
8135    }else if( val==0 ){
8136      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8137      p->autoExplain = 0;
8138    }else if( val==99 ){
8139      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8140      p->autoExplain = 1;
8141    }
8142  }else
8143
8144#ifndef SQLITE_OMIT_VIRTUALTABLE
8145  if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){
8146    if( p->bSafeMode ){
8147      raw_printf(stderr,
8148        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8149        azArg[0]);
8150      rc = 1;
8151    }else{
8152      open_db(p, 0);
8153      expertDotCommand(p, azArg, nArg);
8154    }
8155  }else
8156#endif
8157
8158  if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){
8159    static const struct {
8160       const char *zCtrlName;   /* Name of a test-control option */
8161       int ctrlCode;            /* Integer code for that option */
8162       const char *zUsage;      /* Usage notes */
8163    } aCtrl[] = {
8164      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8165      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8166      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8167      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8168      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8169   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8170      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8171      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8172      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8173      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8174   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8175    };
8176    int filectrl = -1;
8177    int iCtrl = -1;
8178    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8179    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8180    int n2, i;
8181    const char *zCmd = 0;
8182    const char *zSchema = 0;
8183
8184    open_db(p, 0);
8185    zCmd = nArg>=2 ? azArg[1] : "help";
8186
8187    if( zCmd[0]=='-'
8188     && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0)
8189     && nArg>=4
8190    ){
8191      zSchema = azArg[2];
8192      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8193      nArg -= 2;
8194      zCmd = azArg[1];
8195    }
8196
8197    /* The argument can optionally begin with "-" or "--" */
8198    if( zCmd[0]=='-' && zCmd[1] ){
8199      zCmd++;
8200      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8201    }
8202
8203    /* --help lists all file-controls */
8204    if( cli_strcmp(zCmd,"help")==0 ){
8205      utf8_printf(p->out, "Available file-controls:\n");
8206      for(i=0; i<ArraySize(aCtrl); i++){
8207        utf8_printf(p->out, "  .filectrl %s %s\n",
8208                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8209      }
8210      rc = 1;
8211      goto meta_command_exit;
8212    }
8213
8214    /* convert filectrl text option to value. allow any unique prefix
8215    ** of the option name, or a numerical value. */
8216    n2 = strlen30(zCmd);
8217    for(i=0; i<ArraySize(aCtrl); i++){
8218      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8219        if( filectrl<0 ){
8220          filectrl = aCtrl[i].ctrlCode;
8221          iCtrl = i;
8222        }else{
8223          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8224                              "Use \".filectrl --help\" for help\n", zCmd);
8225          rc = 1;
8226          goto meta_command_exit;
8227        }
8228      }
8229    }
8230    if( filectrl<0 ){
8231      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8232                         "Use \".filectrl --help\" for help\n", zCmd);
8233    }else{
8234      switch(filectrl){
8235        case SQLITE_FCNTL_SIZE_LIMIT: {
8236          if( nArg!=2 && nArg!=3 ) break;
8237          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8238          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8239          isOk = 1;
8240          break;
8241        }
8242        case SQLITE_FCNTL_LOCK_TIMEOUT:
8243        case SQLITE_FCNTL_CHUNK_SIZE: {
8244          int x;
8245          if( nArg!=3 ) break;
8246          x = (int)integerValue(azArg[2]);
8247          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8248          isOk = 2;
8249          break;
8250        }
8251        case SQLITE_FCNTL_PERSIST_WAL:
8252        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8253          int x;
8254          if( nArg!=2 && nArg!=3 ) break;
8255          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8256          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8257          iRes = x;
8258          isOk = 1;
8259          break;
8260        }
8261        case SQLITE_FCNTL_DATA_VERSION:
8262        case SQLITE_FCNTL_HAS_MOVED: {
8263          int x;
8264          if( nArg!=2 ) break;
8265          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8266          iRes = x;
8267          isOk = 1;
8268          break;
8269        }
8270        case SQLITE_FCNTL_TEMPFILENAME: {
8271          char *z = 0;
8272          if( nArg!=2 ) break;
8273          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8274          if( z ){
8275            utf8_printf(p->out, "%s\n", z);
8276            sqlite3_free(z);
8277          }
8278          isOk = 2;
8279          break;
8280        }
8281        case SQLITE_FCNTL_RESERVE_BYTES: {
8282          int x;
8283          if( nArg>=3 ){
8284            x = atoi(azArg[2]);
8285            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8286          }
8287          x = -1;
8288          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8289          utf8_printf(p->out,"%d\n", x);
8290          isOk = 2;
8291          break;
8292        }
8293      }
8294    }
8295    if( isOk==0 && iCtrl>=0 ){
8296      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8297      rc = 1;
8298    }else if( isOk==1 ){
8299      char zBuf[100];
8300      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8301      raw_printf(p->out, "%s\n", zBuf);
8302    }
8303  }else
8304
8305  if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){
8306    ShellState data;
8307    int doStats = 0;
8308    memcpy(&data, p, sizeof(data));
8309    data.showHeader = 0;
8310    data.cMode = data.mode = MODE_Semi;
8311    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8312      data.cMode = data.mode = MODE_Pretty;
8313      nArg = 1;
8314    }
8315    if( nArg!=1 ){
8316      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8317      rc = 1;
8318      goto meta_command_exit;
8319    }
8320    open_db(p, 0);
8321    rc = sqlite3_exec(p->db,
8322       "SELECT sql FROM"
8323       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8324       "     FROM sqlite_schema UNION ALL"
8325       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8326       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8327       "ORDER BY x",
8328       callback, &data, 0
8329    );
8330    if( rc==SQLITE_OK ){
8331      sqlite3_stmt *pStmt;
8332      rc = sqlite3_prepare_v2(p->db,
8333               "SELECT rowid FROM sqlite_schema"
8334               " WHERE name GLOB 'sqlite_stat[134]'",
8335               -1, &pStmt, 0);
8336      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8337      sqlite3_finalize(pStmt);
8338    }
8339    if( doStats==0 ){
8340      raw_printf(p->out, "/* No STAT tables available */\n");
8341    }else{
8342      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8343      data.cMode = data.mode = MODE_Insert;
8344      data.zDestTable = "sqlite_stat1";
8345      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8346      data.zDestTable = "sqlite_stat4";
8347      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8348      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8349    }
8350  }else
8351
8352  if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
8353    if( nArg==2 ){
8354      p->showHeader = booleanValue(azArg[1]);
8355      p->shellFlgs |= SHFLG_HeaderSet;
8356    }else{
8357      raw_printf(stderr, "Usage: .headers on|off\n");
8358      rc = 1;
8359    }
8360  }else
8361
8362  if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
8363    if( nArg>=2 ){
8364      n = showHelp(p->out, azArg[1]);
8365      if( n==0 ){
8366        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8367      }
8368    }else{
8369      showHelp(p->out, 0);
8370    }
8371  }else
8372
8373#ifndef SQLITE_SHELL_FIDDLE
8374  if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){
8375    char *zTable = 0;           /* Insert data into this table */
8376    char *zSchema = 0;          /* within this schema (may default to "main") */
8377    char *zFile = 0;            /* Name of file to extra content from */
8378    sqlite3_stmt *pStmt = NULL; /* A statement */
8379    int nCol;                   /* Number of columns in the table */
8380    int nByte;                  /* Number of bytes in an SQL string */
8381    int i, j;                   /* Loop counters */
8382    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8383    int nSep;                   /* Number of bytes in p->colSeparator[] */
8384    char *zSql;                 /* An SQL statement */
8385    char *zFullTabName;         /* Table name with schema if applicable */
8386    ImportCtx sCtx;             /* Reader context */
8387    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8388    int eVerbose = 0;           /* Larger for more console output */
8389    int nSkip = 0;              /* Initial lines to skip */
8390    int useOutputMode = 1;      /* Use output mode to determine separators */
8391    char *zCreate = 0;          /* CREATE TABLE statement text */
8392
8393    failIfSafeMode(p, "cannot run .import in safe mode");
8394    memset(&sCtx, 0, sizeof(sCtx));
8395    if( p->mode==MODE_Ascii ){
8396      xRead = ascii_read_one_field;
8397    }else{
8398      xRead = csv_read_one_field;
8399    }
8400    rc = 1;
8401    for(i=1; i<nArg; i++){
8402      char *z = azArg[i];
8403      if( z[0]=='-' && z[1]=='-' ) z++;
8404      if( z[0]!='-' ){
8405        if( zFile==0 ){
8406          zFile = z;
8407        }else if( zTable==0 ){
8408          zTable = z;
8409        }else{
8410          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8411          showHelp(p->out, "import");
8412          goto meta_command_exit;
8413        }
8414      }else if( cli_strcmp(z,"-v")==0 ){
8415        eVerbose++;
8416      }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){
8417        zSchema = azArg[++i];
8418      }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){
8419        nSkip = integerValue(azArg[++i]);
8420      }else if( cli_strcmp(z,"-ascii")==0 ){
8421        sCtx.cColSep = SEP_Unit[0];
8422        sCtx.cRowSep = SEP_Record[0];
8423        xRead = ascii_read_one_field;
8424        useOutputMode = 0;
8425      }else if( cli_strcmp(z,"-csv")==0 ){
8426        sCtx.cColSep = ',';
8427        sCtx.cRowSep = '\n';
8428        xRead = csv_read_one_field;
8429        useOutputMode = 0;
8430      }else{
8431        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8432        showHelp(p->out, "import");
8433        goto meta_command_exit;
8434      }
8435    }
8436    if( zTable==0 ){
8437      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8438                  zFile==0 ? "FILE" : "TABLE");
8439      showHelp(p->out, "import");
8440      goto meta_command_exit;
8441    }
8442    seenInterrupt = 0;
8443    open_db(p, 0);
8444    if( useOutputMode ){
8445      /* If neither the --csv or --ascii options are specified, then set
8446      ** the column and row separator characters from the output mode. */
8447      nSep = strlen30(p->colSeparator);
8448      if( nSep==0 ){
8449        raw_printf(stderr,
8450                   "Error: non-null column separator required for import\n");
8451        goto meta_command_exit;
8452      }
8453      if( nSep>1 ){
8454        raw_printf(stderr,
8455              "Error: multi-character column separators not allowed"
8456              " for import\n");
8457        goto meta_command_exit;
8458      }
8459      nSep = strlen30(p->rowSeparator);
8460      if( nSep==0 ){
8461        raw_printf(stderr,
8462            "Error: non-null row separator required for import\n");
8463        goto meta_command_exit;
8464      }
8465      if( nSep==2 && p->mode==MODE_Csv
8466       && cli_strcmp(p->rowSeparator,SEP_CrLf)==0
8467      ){
8468        /* When importing CSV (only), if the row separator is set to the
8469        ** default output row separator, change it to the default input
8470        ** row separator.  This avoids having to maintain different input
8471        ** and output row separators. */
8472        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8473        nSep = strlen30(p->rowSeparator);
8474      }
8475      if( nSep>1 ){
8476        raw_printf(stderr, "Error: multi-character row separators not allowed"
8477                           " for import\n");
8478        goto meta_command_exit;
8479      }
8480      sCtx.cColSep = p->colSeparator[0];
8481      sCtx.cRowSep = p->rowSeparator[0];
8482    }
8483    sCtx.zFile = zFile;
8484    sCtx.nLine = 1;
8485    if( sCtx.zFile[0]=='|' ){
8486#ifdef SQLITE_OMIT_POPEN
8487      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8488      goto meta_command_exit;
8489#else
8490      sCtx.in = popen(sCtx.zFile+1, "r");
8491      sCtx.zFile = "<pipe>";
8492      sCtx.xCloser = pclose;
8493#endif
8494    }else{
8495      sCtx.in = fopen(sCtx.zFile, "rb");
8496      sCtx.xCloser = fclose;
8497    }
8498    if( sCtx.in==0 ){
8499      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
8500      goto meta_command_exit;
8501    }
8502    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
8503      char zSep[2];
8504      zSep[1] = 0;
8505      zSep[0] = sCtx.cColSep;
8506      utf8_printf(p->out, "Column separator ");
8507      output_c_string(p->out, zSep);
8508      utf8_printf(p->out, ", row separator ");
8509      zSep[0] = sCtx.cRowSep;
8510      output_c_string(p->out, zSep);
8511      utf8_printf(p->out, "\n");
8512    }
8513    sCtx.z = sqlite3_malloc64(120);
8514    if( sCtx.z==0 ){
8515      import_cleanup(&sCtx);
8516      shell_out_of_memory();
8517    }
8518    /* Below, resources must be freed before exit. */
8519    while( (nSkip--)>0 ){
8520      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
8521    }
8522    if( zSchema!=0 ){
8523      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
8524    }else{
8525      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
8526    }
8527    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
8528    if( zSql==0 || zFullTabName==0 ){
8529      import_cleanup(&sCtx);
8530      shell_out_of_memory();
8531    }
8532    nByte = strlen30(zSql);
8533    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8534    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
8535    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
8536      sqlite3 *dbCols = 0;
8537      char *zRenames = 0;
8538      char *zColDefs;
8539      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
8540      while( xRead(&sCtx) ){
8541        zAutoColumn(sCtx.z, &dbCols, 0);
8542        if( sCtx.cTerm!=sCtx.cColSep ) break;
8543      }
8544      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
8545      if( zRenames!=0 ){
8546        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
8547                    "Columns renamed during .import %s due to duplicates:\n"
8548                    "%s\n", sCtx.zFile, zRenames);
8549        sqlite3_free(zRenames);
8550      }
8551      assert(dbCols==0);
8552      if( zColDefs==0 ){
8553        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
8554      import_fail:
8555        sqlite3_free(zCreate);
8556        sqlite3_free(zSql);
8557        sqlite3_free(zFullTabName);
8558        import_cleanup(&sCtx);
8559        rc = 1;
8560        goto meta_command_exit;
8561      }
8562      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
8563      if( eVerbose>=1 ){
8564        utf8_printf(p->out, "%s\n", zCreate);
8565      }
8566      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
8567      if( rc ){
8568        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
8569        goto import_fail;
8570      }
8571      sqlite3_free(zCreate);
8572      zCreate = 0;
8573      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8574    }
8575    if( rc ){
8576      if (pStmt) sqlite3_finalize(pStmt);
8577      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
8578      goto import_fail;
8579    }
8580    sqlite3_free(zSql);
8581    nCol = sqlite3_column_count(pStmt);
8582    sqlite3_finalize(pStmt);
8583    pStmt = 0;
8584    if( nCol==0 ) return 0; /* no columns, no error */
8585    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
8586    if( zSql==0 ){
8587      import_cleanup(&sCtx);
8588      shell_out_of_memory();
8589    }
8590    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
8591    j = strlen30(zSql);
8592    for(i=1; i<nCol; i++){
8593      zSql[j++] = ',';
8594      zSql[j++] = '?';
8595    }
8596    zSql[j++] = ')';
8597    zSql[j] = 0;
8598    if( eVerbose>=2 ){
8599      utf8_printf(p->out, "Insert using: %s\n", zSql);
8600    }
8601    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8602    if( rc ){
8603      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8604      if (pStmt) sqlite3_finalize(pStmt);
8605      goto import_fail;
8606    }
8607    sqlite3_free(zSql);
8608    sqlite3_free(zFullTabName);
8609    needCommit = sqlite3_get_autocommit(p->db);
8610    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
8611    do{
8612      int startLine = sCtx.nLine;
8613      for(i=0; i<nCol; i++){
8614        char *z = xRead(&sCtx);
8615        /*
8616        ** Did we reach end-of-file before finding any columns?
8617        ** If so, stop instead of NULL filling the remaining columns.
8618        */
8619        if( z==0 && i==0 ) break;
8620        /*
8621        ** Did we reach end-of-file OR end-of-line before finding any
8622        ** columns in ASCII mode?  If so, stop instead of NULL filling
8623        ** the remaining columns.
8624        */
8625        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
8626        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
8627        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
8628          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8629                          "filling the rest with NULL\n",
8630                          sCtx.zFile, startLine, nCol, i+1);
8631          i += 2;
8632          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
8633        }
8634      }
8635      if( sCtx.cTerm==sCtx.cColSep ){
8636        do{
8637          xRead(&sCtx);
8638          i++;
8639        }while( sCtx.cTerm==sCtx.cColSep );
8640        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
8641                        "extras ignored\n",
8642                        sCtx.zFile, startLine, nCol, i);
8643      }
8644      if( i>=nCol ){
8645        sqlite3_step(pStmt);
8646        rc = sqlite3_reset(pStmt);
8647        if( rc!=SQLITE_OK ){
8648          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
8649                      startLine, sqlite3_errmsg(p->db));
8650          sCtx.nErr++;
8651        }else{
8652          sCtx.nRow++;
8653        }
8654      }
8655    }while( sCtx.cTerm!=EOF );
8656
8657    import_cleanup(&sCtx);
8658    sqlite3_finalize(pStmt);
8659    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
8660    if( eVerbose>0 ){
8661      utf8_printf(p->out,
8662          "Added %d rows with %d errors using %d lines of input\n",
8663          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
8664    }
8665  }else
8666#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8667
8668#ifndef SQLITE_UNTESTABLE
8669  if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){
8670    char *zSql;
8671    char *zCollist = 0;
8672    sqlite3_stmt *pStmt;
8673    int tnum = 0;
8674    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
8675    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
8676    int i;
8677    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
8678      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
8679                          "       .imposter off\n");
8680      /* Also allowed, but not documented:
8681      **
8682      **    .imposter TABLE IMPOSTER
8683      **
8684      ** where TABLE is a WITHOUT ROWID table.  In that case, the
8685      ** imposter is another WITHOUT ROWID table with the columns in
8686      ** storage order. */
8687      rc = 1;
8688      goto meta_command_exit;
8689    }
8690    open_db(p, 0);
8691    if( nArg==2 ){
8692      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
8693      goto meta_command_exit;
8694    }
8695    zSql = sqlite3_mprintf(
8696      "SELECT rootpage, 0 FROM sqlite_schema"
8697      " WHERE name='%q' AND type='index'"
8698      "UNION ALL "
8699      "SELECT rootpage, 1 FROM sqlite_schema"
8700      " WHERE name='%q' AND type='table'"
8701      "   AND sql LIKE '%%without%%rowid%%'",
8702      azArg[1], azArg[1]
8703    );
8704    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8705    sqlite3_free(zSql);
8706    if( sqlite3_step(pStmt)==SQLITE_ROW ){
8707      tnum = sqlite3_column_int(pStmt, 0);
8708      isWO = sqlite3_column_int(pStmt, 1);
8709    }
8710    sqlite3_finalize(pStmt);
8711    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
8712    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8713    sqlite3_free(zSql);
8714    i = 0;
8715    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8716      char zLabel[20];
8717      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
8718      i++;
8719      if( zCol==0 ){
8720        if( sqlite3_column_int(pStmt,1)==-1 ){
8721          zCol = "_ROWID_";
8722        }else{
8723          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
8724          zCol = zLabel;
8725        }
8726      }
8727      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
8728        lenPK = (int)strlen(zCollist);
8729      }
8730      if( zCollist==0 ){
8731        zCollist = sqlite3_mprintf("\"%w\"", zCol);
8732      }else{
8733        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
8734      }
8735    }
8736    sqlite3_finalize(pStmt);
8737    if( i==0 || tnum==0 ){
8738      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
8739      rc = 1;
8740      sqlite3_free(zCollist);
8741      goto meta_command_exit;
8742    }
8743    if( lenPK==0 ) lenPK = 100000;
8744    zSql = sqlite3_mprintf(
8745          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
8746          azArg[2], zCollist, lenPK, zCollist);
8747    sqlite3_free(zCollist);
8748    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
8749    if( rc==SQLITE_OK ){
8750      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
8751      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
8752      if( rc ){
8753        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
8754      }else{
8755        utf8_printf(stdout, "%s;\n", zSql);
8756        raw_printf(stdout,
8757          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
8758          azArg[1], isWO ? "table" : "index"
8759        );
8760      }
8761    }else{
8762      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
8763      rc = 1;
8764    }
8765    sqlite3_free(zSql);
8766  }else
8767#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
8768
8769#ifdef SQLITE_ENABLE_IOTRACE
8770  if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){
8771    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
8772    if( iotrace && iotrace!=stdout ) fclose(iotrace);
8773    iotrace = 0;
8774    if( nArg<2 ){
8775      sqlite3IoTrace = 0;
8776    }else if( cli_strcmp(azArg[1], "-")==0 ){
8777      sqlite3IoTrace = iotracePrintf;
8778      iotrace = stdout;
8779    }else{
8780      iotrace = fopen(azArg[1], "w");
8781      if( iotrace==0 ){
8782        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
8783        sqlite3IoTrace = 0;
8784        rc = 1;
8785      }else{
8786        sqlite3IoTrace = iotracePrintf;
8787      }
8788    }
8789  }else
8790#endif
8791
8792  if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){
8793    static const struct {
8794       const char *zLimitName;   /* Name of a limit */
8795       int limitCode;            /* Integer code for that limit */
8796    } aLimit[] = {
8797      { "length",                SQLITE_LIMIT_LENGTH                    },
8798      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
8799      { "column",                SQLITE_LIMIT_COLUMN                    },
8800      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
8801      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
8802      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
8803      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
8804      { "attached",              SQLITE_LIMIT_ATTACHED                  },
8805      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
8806      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
8807      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
8808      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
8809    };
8810    int i, n2;
8811    open_db(p, 0);
8812    if( nArg==1 ){
8813      for(i=0; i<ArraySize(aLimit); i++){
8814        printf("%20s %d\n", aLimit[i].zLimitName,
8815               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
8816      }
8817    }else if( nArg>3 ){
8818      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
8819      rc = 1;
8820      goto meta_command_exit;
8821    }else{
8822      int iLimit = -1;
8823      n2 = strlen30(azArg[1]);
8824      for(i=0; i<ArraySize(aLimit); i++){
8825        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
8826          if( iLimit<0 ){
8827            iLimit = i;
8828          }else{
8829            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
8830            rc = 1;
8831            goto meta_command_exit;
8832          }
8833        }
8834      }
8835      if( iLimit<0 ){
8836        utf8_printf(stderr, "unknown limit: \"%s\"\n"
8837                        "enter \".limits\" with no arguments for a list.\n",
8838                         azArg[1]);
8839        rc = 1;
8840        goto meta_command_exit;
8841      }
8842      if( nArg==3 ){
8843        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
8844                      (int)integerValue(azArg[2]));
8845      }
8846      printf("%20s %d\n", aLimit[iLimit].zLimitName,
8847             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
8848    }
8849  }else
8850
8851  if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){
8852    open_db(p, 0);
8853    lintDotCommand(p, azArg, nArg);
8854  }else
8855
8856#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
8857  if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){
8858    const char *zFile, *zProc;
8859    char *zErrMsg = 0;
8860    failIfSafeMode(p, "cannot run .load in safe mode");
8861    if( nArg<2 ){
8862      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
8863      rc = 1;
8864      goto meta_command_exit;
8865    }
8866    zFile = azArg[1];
8867    zProc = nArg>=3 ? azArg[2] : 0;
8868    open_db(p, 0);
8869    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
8870    if( rc!=SQLITE_OK ){
8871      utf8_printf(stderr, "Error: %s\n", zErrMsg);
8872      sqlite3_free(zErrMsg);
8873      rc = 1;
8874    }
8875  }else
8876#endif
8877
8878#ifndef SQLITE_SHELL_FIDDLE
8879  if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){
8880    failIfSafeMode(p, "cannot run .log in safe mode");
8881    if( nArg!=2 ){
8882      raw_printf(stderr, "Usage: .log FILENAME\n");
8883      rc = 1;
8884    }else{
8885      const char *zFile = azArg[1];
8886      output_file_close(p->pLog);
8887      p->pLog = output_file_open(zFile, 0);
8888    }
8889  }else
8890#endif
8891
8892  if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){
8893    const char *zMode = 0;
8894    const char *zTabname = 0;
8895    int i, n2;
8896    ColModeOpts cmOpts = ColModeOpts_default;
8897    for(i=1; i<nArg; i++){
8898      const char *z = azArg[i];
8899      if( optionMatch(z,"wrap") && i+1<nArg ){
8900        cmOpts.iWrap = integerValue(azArg[++i]);
8901      }else if( optionMatch(z,"ww") ){
8902        cmOpts.bWordWrap = 1;
8903      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
8904        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
8905      }else if( optionMatch(z,"quote") ){
8906        cmOpts.bQuote = 1;
8907      }else if( optionMatch(z,"noquote") ){
8908        cmOpts.bQuote = 0;
8909      }else if( zMode==0 ){
8910        zMode = z;
8911        /* Apply defaults for qbox pseudo-mode.  If that
8912         * overwrites already-set values, user was informed of this.
8913         */
8914        if( cli_strcmp(z, "qbox")==0 ){
8915          ColModeOpts cmo = ColModeOpts_default_qbox;
8916          zMode = "box";
8917          cmOpts = cmo;
8918        }
8919      }else if( zTabname==0 ){
8920        zTabname = z;
8921      }else if( z[0]=='-' ){
8922        utf8_printf(stderr, "unknown option: %s\n", z);
8923        utf8_printf(stderr, "options:\n"
8924                            "  --noquote\n"
8925                            "  --quote\n"
8926                            "  --wordwrap on/off\n"
8927                            "  --wrap N\n"
8928                            "  --ww\n");
8929        rc = 1;
8930        goto meta_command_exit;
8931      }else{
8932        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
8933        rc = 1;
8934        goto meta_command_exit;
8935      }
8936    }
8937    if( zMode==0 ){
8938      if( p->mode==MODE_Column
8939       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
8940      ){
8941        raw_printf
8942          (p->out,
8943           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
8944           modeDescr[p->mode], p->cmOpts.iWrap,
8945           p->cmOpts.bWordWrap ? "on" : "off",
8946           p->cmOpts.bQuote ? "" : "no");
8947      }else{
8948        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8949      }
8950      zMode = modeDescr[p->mode];
8951    }
8952    n2 = strlen30(zMode);
8953    if( cli_strncmp(zMode,"lines",n2)==0 ){
8954      p->mode = MODE_Line;
8955      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8956    }else if( cli_strncmp(zMode,"columns",n2)==0 ){
8957      p->mode = MODE_Column;
8958      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
8959        p->showHeader = 1;
8960      }
8961      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8962      p->cmOpts = cmOpts;
8963    }else if( cli_strncmp(zMode,"list",n2)==0 ){
8964      p->mode = MODE_List;
8965      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
8966      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8967    }else if( cli_strncmp(zMode,"html",n2)==0 ){
8968      p->mode = MODE_Html;
8969    }else if( cli_strncmp(zMode,"tcl",n2)==0 ){
8970      p->mode = MODE_Tcl;
8971      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
8972      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8973    }else if( cli_strncmp(zMode,"csv",n2)==0 ){
8974      p->mode = MODE_Csv;
8975      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8976      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8977    }else if( cli_strncmp(zMode,"tabs",n2)==0 ){
8978      p->mode = MODE_List;
8979      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8980    }else if( cli_strncmp(zMode,"insert",n2)==0 ){
8981      p->mode = MODE_Insert;
8982      set_table_name(p, zTabname ? zTabname : "table");
8983    }else if( cli_strncmp(zMode,"quote",n2)==0 ){
8984      p->mode = MODE_Quote;
8985      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8986      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
8987    }else if( cli_strncmp(zMode,"ascii",n2)==0 ){
8988      p->mode = MODE_Ascii;
8989      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8990      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8991    }else if( cli_strncmp(zMode,"markdown",n2)==0 ){
8992      p->mode = MODE_Markdown;
8993      p->cmOpts = cmOpts;
8994    }else if( cli_strncmp(zMode,"table",n2)==0 ){
8995      p->mode = MODE_Table;
8996      p->cmOpts = cmOpts;
8997    }else if( cli_strncmp(zMode,"box",n2)==0 ){
8998      p->mode = MODE_Box;
8999      p->cmOpts = cmOpts;
9000    }else if( cli_strncmp(zMode,"count",n2)==0 ){
9001      p->mode = MODE_Count;
9002    }else if( cli_strncmp(zMode,"off",n2)==0 ){
9003      p->mode = MODE_Off;
9004    }else if( cli_strncmp(zMode,"json",n2)==0 ){
9005      p->mode = MODE_Json;
9006    }else{
9007      raw_printf(stderr, "Error: mode should be one of: "
9008         "ascii box column csv html insert json line list markdown "
9009         "qbox quote table tabs tcl\n");
9010      rc = 1;
9011    }
9012    p->cMode = p->mode;
9013  }else
9014
9015#ifndef SQLITE_SHELL_FIDDLE
9016  if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){
9017    if( nArg!=2 ){
9018      raw_printf(stderr, "Usage: .nonce NONCE\n");
9019      rc = 1;
9020    }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){
9021      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9022                 p->lineno, azArg[1]);
9023      exit(1);
9024    }else{
9025      p->bSafeMode = 0;
9026      return 0;  /* Return immediately to bypass the safe mode reset
9027                 ** at the end of this procedure */
9028    }
9029  }else
9030#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9031
9032  if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){
9033    if( nArg==2 ){
9034      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9035                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9036    }else{
9037      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9038      rc = 1;
9039    }
9040  }else
9041
9042  if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){
9043    const char *zFN = 0;     /* Pointer to constant filename */
9044    char *zNewFilename = 0;  /* Name of the database file to open */
9045    int iName = 1;           /* Index in azArg[] of the filename */
9046    int newFlag = 0;         /* True to delete file before opening */
9047    int openMode = SHELL_OPEN_UNSPEC;
9048
9049    /* Check for command-line arguments */
9050    for(iName=1; iName<nArg; iName++){
9051      const char *z = azArg[iName];
9052#ifndef SQLITE_SHELL_FIDDLE
9053      if( optionMatch(z,"new") ){
9054        newFlag = 1;
9055#ifdef SQLITE_HAVE_ZLIB
9056      }else if( optionMatch(z, "zip") ){
9057        openMode = SHELL_OPEN_ZIPFILE;
9058#endif
9059      }else if( optionMatch(z, "append") ){
9060        openMode = SHELL_OPEN_APPENDVFS;
9061      }else if( optionMatch(z, "readonly") ){
9062        openMode = SHELL_OPEN_READONLY;
9063      }else if( optionMatch(z, "nofollow") ){
9064        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9065#ifndef SQLITE_OMIT_DESERIALIZE
9066      }else if( optionMatch(z, "deserialize") ){
9067        openMode = SHELL_OPEN_DESERIALIZE;
9068      }else if( optionMatch(z, "hexdb") ){
9069        openMode = SHELL_OPEN_HEXDB;
9070      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9071        p->szMax = integerValue(azArg[++iName]);
9072#endif /* SQLITE_OMIT_DESERIALIZE */
9073      }else
9074#endif /* !SQLITE_SHELL_FIDDLE */
9075      if( z[0]=='-' ){
9076        utf8_printf(stderr, "unknown option: %s\n", z);
9077        rc = 1;
9078        goto meta_command_exit;
9079      }else if( zFN ){
9080        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9081        rc = 1;
9082        goto meta_command_exit;
9083      }else{
9084        zFN = z;
9085      }
9086    }
9087
9088    /* Close the existing database */
9089    session_close_all(p, -1);
9090    close_db(p->db);
9091    p->db = 0;
9092    p->pAuxDb->zDbFilename = 0;
9093    sqlite3_free(p->pAuxDb->zFreeOnClose);
9094    p->pAuxDb->zFreeOnClose = 0;
9095    p->openMode = openMode;
9096    p->openFlags = 0;
9097    p->szMax = 0;
9098
9099    /* If a filename is specified, try to open it first */
9100    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9101      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9102#ifndef SQLITE_SHELL_FIDDLE
9103      if( p->bSafeMode
9104       && p->openMode!=SHELL_OPEN_HEXDB
9105       && zFN
9106       && cli_strcmp(zFN,":memory:")!=0
9107      ){
9108        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9109      }
9110#else
9111      /* WASM mode has its own sandboxed pseudo-filesystem. */
9112#endif
9113      if( zFN ){
9114        zNewFilename = sqlite3_mprintf("%s", zFN);
9115        shell_check_oom(zNewFilename);
9116      }else{
9117        zNewFilename = 0;
9118      }
9119      p->pAuxDb->zDbFilename = zNewFilename;
9120      open_db(p, OPEN_DB_KEEPALIVE);
9121      if( p->db==0 ){
9122        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9123        sqlite3_free(zNewFilename);
9124      }else{
9125        p->pAuxDb->zFreeOnClose = zNewFilename;
9126      }
9127    }
9128    if( p->db==0 ){
9129      /* As a fall-back open a TEMP database */
9130      p->pAuxDb->zDbFilename = 0;
9131      open_db(p, 0);
9132    }
9133  }else
9134
9135#ifndef SQLITE_SHELL_FIDDLE
9136  if( (c=='o'
9137        && (cli_strncmp(azArg[0], "output", n)==0
9138            || cli_strncmp(azArg[0], "once", n)==0))
9139   || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0)
9140  ){
9141    char *zFile = 0;
9142    int bTxtMode = 0;
9143    int i;
9144    int eMode = 0;
9145    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9146    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9147
9148    zBOM[0] = 0;
9149    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9150    if( c=='e' ){
9151      eMode = 'x';
9152      bOnce = 2;
9153    }else if( cli_strncmp(azArg[0],"once",n)==0 ){
9154      bOnce = 1;
9155    }
9156    for(i=1; i<nArg; i++){
9157      char *z = azArg[i];
9158      if( z[0]=='-' ){
9159        if( z[1]=='-' ) z++;
9160        if( cli_strcmp(z,"-bom")==0 ){
9161          zBOM[0] = 0xef;
9162          zBOM[1] = 0xbb;
9163          zBOM[2] = 0xbf;
9164          zBOM[3] = 0;
9165        }else if( c!='e' && cli_strcmp(z,"-x")==0 ){
9166          eMode = 'x';  /* spreadsheet */
9167        }else if( c!='e' && cli_strcmp(z,"-e")==0 ){
9168          eMode = 'e';  /* text editor */
9169        }else{
9170          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9171                      azArg[i]);
9172          showHelp(p->out, azArg[0]);
9173          rc = 1;
9174          goto meta_command_exit;
9175        }
9176      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9177        zFile = sqlite3_mprintf("%s", z);
9178        if( zFile && zFile[0]=='|' ){
9179          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9180          break;
9181        }
9182      }else{
9183        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9184                    azArg[i]);
9185        showHelp(p->out, azArg[0]);
9186        rc = 1;
9187        sqlite3_free(zFile);
9188        goto meta_command_exit;
9189      }
9190    }
9191    if( zFile==0 ){
9192      zFile = sqlite3_mprintf("stdout");
9193    }
9194    if( bOnce ){
9195      p->outCount = 2;
9196    }else{
9197      p->outCount = 0;
9198    }
9199    output_reset(p);
9200#ifndef SQLITE_NOHAVE_SYSTEM
9201    if( eMode=='e' || eMode=='x' ){
9202      p->doXdgOpen = 1;
9203      outputModePush(p);
9204      if( eMode=='x' ){
9205        /* spreadsheet mode.  Output as CSV. */
9206        newTempFile(p, "csv");
9207        ShellClearFlag(p, SHFLG_Echo);
9208        p->mode = MODE_Csv;
9209        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9210        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9211      }else{
9212        /* text editor mode */
9213        newTempFile(p, "txt");
9214        bTxtMode = 1;
9215      }
9216      sqlite3_free(zFile);
9217      zFile = sqlite3_mprintf("%s", p->zTempFile);
9218    }
9219#endif /* SQLITE_NOHAVE_SYSTEM */
9220    shell_check_oom(zFile);
9221    if( zFile[0]=='|' ){
9222#ifdef SQLITE_OMIT_POPEN
9223      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9224      rc = 1;
9225      p->out = stdout;
9226#else
9227      p->out = popen(zFile + 1, "w");
9228      if( p->out==0 ){
9229        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9230        p->out = stdout;
9231        rc = 1;
9232      }else{
9233        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9234        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9235      }
9236#endif
9237    }else{
9238      p->out = output_file_open(zFile, bTxtMode);
9239      if( p->out==0 ){
9240        if( cli_strcmp(zFile,"off")!=0 ){
9241          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9242        }
9243        p->out = stdout;
9244        rc = 1;
9245      } else {
9246        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9247        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9248      }
9249    }
9250    sqlite3_free(zFile);
9251  }else
9252#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9253
9254  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){
9255    open_db(p,0);
9256    if( nArg<=1 ) goto parameter_syntax_error;
9257
9258    /* .parameter clear
9259    ** Clear all bind parameters by dropping the TEMP table that holds them.
9260    */
9261    if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){
9262      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9263                   0, 0, 0);
9264    }else
9265
9266    /* .parameter list
9267    ** List all bind parameters.
9268    */
9269    if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){
9270      sqlite3_stmt *pStmt = 0;
9271      int rx;
9272      int len = 0;
9273      rx = sqlite3_prepare_v2(p->db,
9274             "SELECT max(length(key)) "
9275             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9276      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9277        len = sqlite3_column_int(pStmt, 0);
9278        if( len>40 ) len = 40;
9279      }
9280      sqlite3_finalize(pStmt);
9281      pStmt = 0;
9282      if( len ){
9283        rx = sqlite3_prepare_v2(p->db,
9284             "SELECT key, quote(value) "
9285             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9286        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9287          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9288                      sqlite3_column_text(pStmt,1));
9289        }
9290        sqlite3_finalize(pStmt);
9291      }
9292    }else
9293
9294    /* .parameter init
9295    ** Make sure the TEMP table used to hold bind parameters exists.
9296    ** Create it if necessary.
9297    */
9298    if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){
9299      bind_table_init(p);
9300    }else
9301
9302    /* .parameter set NAME VALUE
9303    ** Set or reset a bind parameter.  NAME should be the full parameter
9304    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9305    ** VALUE can be in either SQL literal notation, or if not it will be
9306    ** understood to be a text string.
9307    */
9308    if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){
9309      int rx;
9310      char *zSql;
9311      sqlite3_stmt *pStmt;
9312      const char *zKey = azArg[2];
9313      const char *zValue = azArg[3];
9314      bind_table_init(p);
9315      zSql = sqlite3_mprintf(
9316                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9317                  "VALUES(%Q,%s);", zKey, zValue);
9318      shell_check_oom(zSql);
9319      pStmt = 0;
9320      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9321      sqlite3_free(zSql);
9322      if( rx!=SQLITE_OK ){
9323        sqlite3_finalize(pStmt);
9324        pStmt = 0;
9325        zSql = sqlite3_mprintf(
9326                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9327                   "VALUES(%Q,%Q);", zKey, zValue);
9328        shell_check_oom(zSql);
9329        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9330        sqlite3_free(zSql);
9331        if( rx!=SQLITE_OK ){
9332          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9333          sqlite3_finalize(pStmt);
9334          pStmt = 0;
9335          rc = 1;
9336        }
9337      }
9338      sqlite3_step(pStmt);
9339      sqlite3_finalize(pStmt);
9340    }else
9341
9342    /* .parameter unset NAME
9343    ** Remove the NAME binding from the parameter binding table, if it
9344    ** exists.
9345    */
9346    if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){
9347      char *zSql = sqlite3_mprintf(
9348          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9349      shell_check_oom(zSql);
9350      sqlite3_exec(p->db, zSql, 0, 0, 0);
9351      sqlite3_free(zSql);
9352    }else
9353    /* If no command name matches, show a syntax error */
9354    parameter_syntax_error:
9355    showHelp(p->out, "parameter");
9356  }else
9357
9358  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){
9359    int i;
9360    for(i=1; i<nArg; i++){
9361      if( i>1 ) raw_printf(p->out, " ");
9362      utf8_printf(p->out, "%s", azArg[i]);
9363    }
9364    raw_printf(p->out, "\n");
9365  }else
9366
9367#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9368  if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){
9369    int i;
9370    int nn = 0;
9371    p->flgProgress = 0;
9372    p->mxProgress = 0;
9373    p->nProgress = 0;
9374    for(i=1; i<nArg; i++){
9375      const char *z = azArg[i];
9376      if( z[0]=='-' ){
9377        z++;
9378        if( z[0]=='-' ) z++;
9379        if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){
9380          p->flgProgress |= SHELL_PROGRESS_QUIET;
9381          continue;
9382        }
9383        if( cli_strcmp(z,"reset")==0 ){
9384          p->flgProgress |= SHELL_PROGRESS_RESET;
9385          continue;
9386        }
9387        if( cli_strcmp(z,"once")==0 ){
9388          p->flgProgress |= SHELL_PROGRESS_ONCE;
9389          continue;
9390        }
9391        if( cli_strcmp(z,"limit")==0 ){
9392          if( i+1>=nArg ){
9393            utf8_printf(stderr, "Error: missing argument on --limit\n");
9394            rc = 1;
9395            goto meta_command_exit;
9396          }else{
9397            p->mxProgress = (int)integerValue(azArg[++i]);
9398          }
9399          continue;
9400        }
9401        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9402        rc = 1;
9403        goto meta_command_exit;
9404      }else{
9405        nn = (int)integerValue(z);
9406      }
9407    }
9408    open_db(p, 0);
9409    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9410  }else
9411#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9412
9413  if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){
9414    if( nArg >= 2) {
9415      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9416    }
9417    if( nArg >= 3) {
9418      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9419    }
9420  }else
9421
9422#ifndef SQLITE_SHELL_FIDDLE
9423  if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){
9424    rc = 2;
9425  }else
9426#endif
9427
9428#ifndef SQLITE_SHELL_FIDDLE
9429  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){
9430    FILE *inSaved = p->in;
9431    int savedLineno = p->lineno;
9432    failIfSafeMode(p, "cannot run .read in safe mode");
9433    if( nArg!=2 ){
9434      raw_printf(stderr, "Usage: .read FILE\n");
9435      rc = 1;
9436      goto meta_command_exit;
9437    }
9438    if( azArg[1][0]=='|' ){
9439#ifdef SQLITE_OMIT_POPEN
9440      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9441      rc = 1;
9442      p->out = stdout;
9443#else
9444      p->in = popen(azArg[1]+1, "r");
9445      if( p->in==0 ){
9446        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9447        rc = 1;
9448      }else{
9449        rc = process_input(p);
9450        pclose(p->in);
9451      }
9452#endif
9453    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9454      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9455      rc = 1;
9456    }else{
9457      rc = process_input(p);
9458      fclose(p->in);
9459    }
9460    p->in = inSaved;
9461    p->lineno = savedLineno;
9462  }else
9463#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9464
9465#ifndef SQLITE_SHELL_FIDDLE
9466  if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){
9467    const char *zSrcFile;
9468    const char *zDb;
9469    sqlite3 *pSrc;
9470    sqlite3_backup *pBackup;
9471    int nTimeout = 0;
9472
9473    failIfSafeMode(p, "cannot run .restore in safe mode");
9474    if( nArg==2 ){
9475      zSrcFile = azArg[1];
9476      zDb = "main";
9477    }else if( nArg==3 ){
9478      zSrcFile = azArg[2];
9479      zDb = azArg[1];
9480    }else{
9481      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
9482      rc = 1;
9483      goto meta_command_exit;
9484    }
9485    rc = sqlite3_open(zSrcFile, &pSrc);
9486    if( rc!=SQLITE_OK ){
9487      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
9488      close_db(pSrc);
9489      return 1;
9490    }
9491    open_db(p, 0);
9492    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
9493    if( pBackup==0 ){
9494      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9495      close_db(pSrc);
9496      return 1;
9497    }
9498    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
9499          || rc==SQLITE_BUSY  ){
9500      if( rc==SQLITE_BUSY ){
9501        if( nTimeout++ >= 3 ) break;
9502        sqlite3_sleep(100);
9503      }
9504    }
9505    sqlite3_backup_finish(pBackup);
9506    if( rc==SQLITE_DONE ){
9507      rc = 0;
9508    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
9509      raw_printf(stderr, "Error: source database is busy\n");
9510      rc = 1;
9511    }else{
9512      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9513      rc = 1;
9514    }
9515    close_db(pSrc);
9516  }else
9517#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9518
9519  if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){
9520    if( nArg==2 ){
9521      p->scanstatsOn = (u8)booleanValue(azArg[1]);
9522#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
9523      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
9524#endif
9525    }else{
9526      raw_printf(stderr, "Usage: .scanstats on|off\n");
9527      rc = 1;
9528    }
9529  }else
9530
9531  if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){
9532    ShellText sSelect;
9533    ShellState data;
9534    char *zErrMsg = 0;
9535    const char *zDiv = "(";
9536    const char *zName = 0;
9537    int iSchema = 0;
9538    int bDebug = 0;
9539    int bNoSystemTabs = 0;
9540    int ii;
9541
9542    open_db(p, 0);
9543    memcpy(&data, p, sizeof(data));
9544    data.showHeader = 0;
9545    data.cMode = data.mode = MODE_Semi;
9546    initText(&sSelect);
9547    for(ii=1; ii<nArg; ii++){
9548      if( optionMatch(azArg[ii],"indent") ){
9549        data.cMode = data.mode = MODE_Pretty;
9550      }else if( optionMatch(azArg[ii],"debug") ){
9551        bDebug = 1;
9552      }else if( optionMatch(azArg[ii],"nosys") ){
9553        bNoSystemTabs = 1;
9554      }else if( azArg[ii][0]=='-' ){
9555        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
9556        rc = 1;
9557        goto meta_command_exit;
9558      }else if( zName==0 ){
9559        zName = azArg[ii];
9560      }else{
9561        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
9562        rc = 1;
9563        goto meta_command_exit;
9564      }
9565    }
9566    if( zName!=0 ){
9567      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
9568                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
9569                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
9570                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
9571      if( isSchema ){
9572        char *new_argv[2], *new_colv[2];
9573        new_argv[0] = sqlite3_mprintf(
9574                      "CREATE TABLE %s (\n"
9575                      "  type text,\n"
9576                      "  name text,\n"
9577                      "  tbl_name text,\n"
9578                      "  rootpage integer,\n"
9579                      "  sql text\n"
9580                      ")", zName);
9581        shell_check_oom(new_argv[0]);
9582        new_argv[1] = 0;
9583        new_colv[0] = "sql";
9584        new_colv[1] = 0;
9585        callback(&data, 1, new_argv, new_colv);
9586        sqlite3_free(new_argv[0]);
9587      }
9588    }
9589    if( zDiv ){
9590      sqlite3_stmt *pStmt = 0;
9591      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
9592                              -1, &pStmt, 0);
9593      if( rc ){
9594        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9595        sqlite3_finalize(pStmt);
9596        rc = 1;
9597        goto meta_command_exit;
9598      }
9599      appendText(&sSelect, "SELECT sql FROM", 0);
9600      iSchema = 0;
9601      while( sqlite3_step(pStmt)==SQLITE_ROW ){
9602        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
9603        char zScNum[30];
9604        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
9605        appendText(&sSelect, zDiv, 0);
9606        zDiv = " UNION ALL ";
9607        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
9608        if( sqlite3_stricmp(zDb, "main")!=0 ){
9609          appendText(&sSelect, zDb, '\'');
9610        }else{
9611          appendText(&sSelect, "NULL", 0);
9612        }
9613        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
9614        appendText(&sSelect, zScNum, 0);
9615        appendText(&sSelect, " AS snum, ", 0);
9616        appendText(&sSelect, zDb, '\'');
9617        appendText(&sSelect, " AS sname FROM ", 0);
9618        appendText(&sSelect, zDb, quoteChar(zDb));
9619        appendText(&sSelect, ".sqlite_schema", 0);
9620      }
9621      sqlite3_finalize(pStmt);
9622#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
9623      if( zName ){
9624        appendText(&sSelect,
9625           " UNION ALL SELECT shell_module_schema(name),"
9626           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
9627        0);
9628      }
9629#endif
9630      appendText(&sSelect, ") WHERE ", 0);
9631      if( zName ){
9632        char *zQarg = sqlite3_mprintf("%Q", zName);
9633        int bGlob;
9634        shell_check_oom(zQarg);
9635        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
9636                strchr(zName, '[') != 0;
9637        if( strchr(zName, '.') ){
9638          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
9639        }else{
9640          appendText(&sSelect, "lower(tbl_name)", 0);
9641        }
9642        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
9643        appendText(&sSelect, zQarg, 0);
9644        if( !bGlob ){
9645          appendText(&sSelect, " ESCAPE '\\' ", 0);
9646        }
9647        appendText(&sSelect, " AND ", 0);
9648        sqlite3_free(zQarg);
9649      }
9650      if( bNoSystemTabs ){
9651        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
9652      }
9653      appendText(&sSelect, "sql IS NOT NULL"
9654                           " ORDER BY snum, rowid", 0);
9655      if( bDebug ){
9656        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
9657      }else{
9658        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
9659      }
9660      freeText(&sSelect);
9661    }
9662    if( zErrMsg ){
9663      utf8_printf(stderr,"Error: %s\n", zErrMsg);
9664      sqlite3_free(zErrMsg);
9665      rc = 1;
9666    }else if( rc != SQLITE_OK ){
9667      raw_printf(stderr,"Error: querying schema information\n");
9668      rc = 1;
9669    }else{
9670      rc = 0;
9671    }
9672  }else
9673
9674  if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0)
9675   || (c=='t' && n==9  && cli_strncmp(azArg[0], "treetrace", n)==0)
9676  ){
9677    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
9678    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
9679  }else
9680
9681#if defined(SQLITE_ENABLE_SESSION)
9682  if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){
9683    struct AuxDb *pAuxDb = p->pAuxDb;
9684    OpenSession *pSession = &pAuxDb->aSession[0];
9685    char **azCmd = &azArg[1];
9686    int iSes = 0;
9687    int nCmd = nArg - 1;
9688    int i;
9689    if( nArg<=1 ) goto session_syntax_error;
9690    open_db(p, 0);
9691    if( nArg>=3 ){
9692      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
9693        if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
9694      }
9695      if( iSes<pAuxDb->nSession ){
9696        pSession = &pAuxDb->aSession[iSes];
9697        azCmd++;
9698        nCmd--;
9699      }else{
9700        pSession = &pAuxDb->aSession[0];
9701        iSes = 0;
9702      }
9703    }
9704
9705    /* .session attach TABLE
9706    ** Invoke the sqlite3session_attach() interface to attach a particular
9707    ** table so that it is never filtered.
9708    */
9709    if( cli_strcmp(azCmd[0],"attach")==0 ){
9710      if( nCmd!=2 ) goto session_syntax_error;
9711      if( pSession->p==0 ){
9712        session_not_open:
9713        raw_printf(stderr, "ERROR: No sessions are open\n");
9714      }else{
9715        rc = sqlite3session_attach(pSession->p, azCmd[1]);
9716        if( rc ){
9717          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
9718          rc = 0;
9719        }
9720      }
9721    }else
9722
9723    /* .session changeset FILE
9724    ** .session patchset FILE
9725    ** Write a changeset or patchset into a file.  The file is overwritten.
9726    */
9727    if( cli_strcmp(azCmd[0],"changeset")==0
9728     || cli_strcmp(azCmd[0],"patchset")==0
9729    ){
9730      FILE *out = 0;
9731      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
9732      if( nCmd!=2 ) goto session_syntax_error;
9733      if( pSession->p==0 ) goto session_not_open;
9734      out = fopen(azCmd[1], "wb");
9735      if( out==0 ){
9736        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
9737                    azCmd[1]);
9738      }else{
9739        int szChng;
9740        void *pChng;
9741        if( azCmd[0][0]=='c' ){
9742          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
9743        }else{
9744          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
9745        }
9746        if( rc ){
9747          printf("Error: error code %d\n", rc);
9748          rc = 0;
9749        }
9750        if( pChng
9751          && fwrite(pChng, szChng, 1, out)!=1 ){
9752          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
9753                  szChng);
9754        }
9755        sqlite3_free(pChng);
9756        fclose(out);
9757      }
9758    }else
9759
9760    /* .session close
9761    ** Close the identified session
9762    */
9763    if( cli_strcmp(azCmd[0], "close")==0 ){
9764      if( nCmd!=1 ) goto session_syntax_error;
9765      if( pAuxDb->nSession ){
9766        session_close(pSession);
9767        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
9768      }
9769    }else
9770
9771    /* .session enable ?BOOLEAN?
9772    ** Query or set the enable flag
9773    */
9774    if( cli_strcmp(azCmd[0], "enable")==0 ){
9775      int ii;
9776      if( nCmd>2 ) goto session_syntax_error;
9777      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9778      if( pAuxDb->nSession ){
9779        ii = sqlite3session_enable(pSession->p, ii);
9780        utf8_printf(p->out, "session %s enable flag = %d\n",
9781                    pSession->zName, ii);
9782      }
9783    }else
9784
9785    /* .session filter GLOB ....
9786    ** Set a list of GLOB patterns of table names to be excluded.
9787    */
9788    if( cli_strcmp(azCmd[0], "filter")==0 ){
9789      int ii, nByte;
9790      if( nCmd<2 ) goto session_syntax_error;
9791      if( pAuxDb->nSession ){
9792        for(ii=0; ii<pSession->nFilter; ii++){
9793          sqlite3_free(pSession->azFilter[ii]);
9794        }
9795        sqlite3_free(pSession->azFilter);
9796        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
9797        pSession->azFilter = sqlite3_malloc( nByte );
9798        if( pSession->azFilter==0 ){
9799          raw_printf(stderr, "Error: out or memory\n");
9800          exit(1);
9801        }
9802        for(ii=1; ii<nCmd; ii++){
9803          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
9804          shell_check_oom(x);
9805        }
9806        pSession->nFilter = ii-1;
9807      }
9808    }else
9809
9810    /* .session indirect ?BOOLEAN?
9811    ** Query or set the indirect flag
9812    */
9813    if( cli_strcmp(azCmd[0], "indirect")==0 ){
9814      int ii;
9815      if( nCmd>2 ) goto session_syntax_error;
9816      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
9817      if( pAuxDb->nSession ){
9818        ii = sqlite3session_indirect(pSession->p, ii);
9819        utf8_printf(p->out, "session %s indirect flag = %d\n",
9820                    pSession->zName, ii);
9821      }
9822    }else
9823
9824    /* .session isempty
9825    ** Determine if the session is empty
9826    */
9827    if( cli_strcmp(azCmd[0], "isempty")==0 ){
9828      int ii;
9829      if( nCmd!=1 ) goto session_syntax_error;
9830      if( pAuxDb->nSession ){
9831        ii = sqlite3session_isempty(pSession->p);
9832        utf8_printf(p->out, "session %s isempty flag = %d\n",
9833                    pSession->zName, ii);
9834      }
9835    }else
9836
9837    /* .session list
9838    ** List all currently open sessions
9839    */
9840    if( cli_strcmp(azCmd[0],"list")==0 ){
9841      for(i=0; i<pAuxDb->nSession; i++){
9842        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
9843      }
9844    }else
9845
9846    /* .session open DB NAME
9847    ** Open a new session called NAME on the attached database DB.
9848    ** DB is normally "main".
9849    */
9850    if( cli_strcmp(azCmd[0],"open")==0 ){
9851      char *zName;
9852      if( nCmd!=3 ) goto session_syntax_error;
9853      zName = azCmd[2];
9854      if( zName[0]==0 ) goto session_syntax_error;
9855      for(i=0; i<pAuxDb->nSession; i++){
9856        if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
9857          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
9858          goto meta_command_exit;
9859        }
9860      }
9861      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
9862        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
9863        goto meta_command_exit;
9864      }
9865      pSession = &pAuxDb->aSession[pAuxDb->nSession];
9866      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
9867      if( rc ){
9868        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
9869        rc = 0;
9870        goto meta_command_exit;
9871      }
9872      pSession->nFilter = 0;
9873      sqlite3session_table_filter(pSession->p, session_filter, pSession);
9874      pAuxDb->nSession++;
9875      pSession->zName = sqlite3_mprintf("%s", zName);
9876      shell_check_oom(pSession->zName);
9877    }else
9878    /* If no command name matches, show a syntax error */
9879    session_syntax_error:
9880    showHelp(p->out, "session");
9881  }else
9882#endif
9883
9884#ifdef SQLITE_DEBUG
9885  /* Undocumented commands for internal testing.  Subject to change
9886  ** without notice. */
9887  if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){
9888    if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){
9889      int i, v;
9890      for(i=1; i<nArg; i++){
9891        v = booleanValue(azArg[i]);
9892        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
9893      }
9894    }
9895    if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){
9896      int i; sqlite3_int64 v;
9897      for(i=1; i<nArg; i++){
9898        char zBuf[200];
9899        v = integerValue(azArg[i]);
9900        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
9901        utf8_printf(p->out, "%s", zBuf);
9902      }
9903    }
9904  }else
9905#endif
9906
9907  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){
9908    int bIsInit = 0;         /* True to initialize the SELFTEST table */
9909    int bVerbose = 0;        /* Verbose output */
9910    int bSelftestExists;     /* True if SELFTEST already exists */
9911    int i, k;                /* Loop counters */
9912    int nTest = 0;           /* Number of tests runs */
9913    int nErr = 0;            /* Number of errors seen */
9914    ShellText str;           /* Answer for a query */
9915    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
9916
9917    open_db(p,0);
9918    for(i=1; i<nArg; i++){
9919      const char *z = azArg[i];
9920      if( z[0]=='-' && z[1]=='-' ) z++;
9921      if( cli_strcmp(z,"-init")==0 ){
9922        bIsInit = 1;
9923      }else
9924      if( cli_strcmp(z,"-v")==0 ){
9925        bVerbose++;
9926      }else
9927      {
9928        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
9929                    azArg[i], azArg[0]);
9930        raw_printf(stderr, "Should be one of: --init -v\n");
9931        rc = 1;
9932        goto meta_command_exit;
9933      }
9934    }
9935    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
9936           != SQLITE_OK ){
9937      bSelftestExists = 0;
9938    }else{
9939      bSelftestExists = 1;
9940    }
9941    if( bIsInit ){
9942      createSelftestTable(p);
9943      bSelftestExists = 1;
9944    }
9945    initText(&str);
9946    appendText(&str, "x", 0);
9947    for(k=bSelftestExists; k>=0; k--){
9948      if( k==1 ){
9949        rc = sqlite3_prepare_v2(p->db,
9950            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
9951            -1, &pStmt, 0);
9952      }else{
9953        rc = sqlite3_prepare_v2(p->db,
9954          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
9955          "      (1,'run','PRAGMA integrity_check','ok')",
9956          -1, &pStmt, 0);
9957      }
9958      if( rc ){
9959        raw_printf(stderr, "Error querying the selftest table\n");
9960        rc = 1;
9961        sqlite3_finalize(pStmt);
9962        goto meta_command_exit;
9963      }
9964      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
9965        int tno = sqlite3_column_int(pStmt, 0);
9966        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
9967        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
9968        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
9969
9970        if( zOp==0 ) continue;
9971        if( zSql==0 ) continue;
9972        if( zAns==0 ) continue;
9973        k = 0;
9974        if( bVerbose>0 ){
9975          printf("%d: %s %s\n", tno, zOp, zSql);
9976        }
9977        if( cli_strcmp(zOp,"memo")==0 ){
9978          utf8_printf(p->out, "%s\n", zSql);
9979        }else
9980        if( cli_strcmp(zOp,"run")==0 ){
9981          char *zErrMsg = 0;
9982          str.n = 0;
9983          str.z[0] = 0;
9984          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
9985          nTest++;
9986          if( bVerbose ){
9987            utf8_printf(p->out, "Result: %s\n", str.z);
9988          }
9989          if( rc || zErrMsg ){
9990            nErr++;
9991            rc = 1;
9992            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
9993            sqlite3_free(zErrMsg);
9994          }else if( cli_strcmp(zAns,str.z)!=0 ){
9995            nErr++;
9996            rc = 1;
9997            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
9998            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
9999          }
10000        }else
10001        {
10002          utf8_printf(stderr,
10003            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10004          rc = 1;
10005          break;
10006        }
10007      } /* End loop over rows of content from SELFTEST */
10008      sqlite3_finalize(pStmt);
10009    } /* End loop over k */
10010    freeText(&str);
10011    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10012  }else
10013
10014  if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){
10015    if( nArg<2 || nArg>3 ){
10016      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10017      rc = 1;
10018    }
10019    if( nArg>=2 ){
10020      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10021                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10022    }
10023    if( nArg>=3 ){
10024      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10025                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10026    }
10027  }else
10028
10029  if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){
10030    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10031    int i;                   /* Loop counter */
10032    int bSchema = 0;         /* Also hash the schema */
10033    int bSeparate = 0;       /* Hash each table separately */
10034    int iSize = 224;         /* Hash algorithm to use */
10035    int bDebug = 0;          /* Only show the query that would have run */
10036    sqlite3_stmt *pStmt;     /* For querying tables names */
10037    char *zSql;              /* SQL to be run */
10038    char *zSep;              /* Separator */
10039    ShellText sSql;          /* Complete SQL for the query to run the hash */
10040    ShellText sQuery;        /* Set of queries used to read all content */
10041    open_db(p, 0);
10042    for(i=1; i<nArg; i++){
10043      const char *z = azArg[i];
10044      if( z[0]=='-' ){
10045        z++;
10046        if( z[0]=='-' ) z++;
10047        if( cli_strcmp(z,"schema")==0 ){
10048          bSchema = 1;
10049        }else
10050        if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0
10051         || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0
10052        ){
10053          iSize = atoi(&z[5]);
10054        }else
10055        if( cli_strcmp(z,"debug")==0 ){
10056          bDebug = 1;
10057        }else
10058        {
10059          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10060                      azArg[i], azArg[0]);
10061          showHelp(p->out, azArg[0]);
10062          rc = 1;
10063          goto meta_command_exit;
10064        }
10065      }else if( zLike ){
10066        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10067        rc = 1;
10068        goto meta_command_exit;
10069      }else{
10070        zLike = z;
10071        bSeparate = 1;
10072        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10073      }
10074    }
10075    if( bSchema ){
10076      zSql = "SELECT lower(name) FROM sqlite_schema"
10077             " WHERE type='table' AND coalesce(rootpage,0)>1"
10078             " UNION ALL SELECT 'sqlite_schema'"
10079             " ORDER BY 1 collate nocase";
10080    }else{
10081      zSql = "SELECT lower(name) FROM sqlite_schema"
10082             " WHERE type='table' AND coalesce(rootpage,0)>1"
10083             " AND name NOT LIKE 'sqlite_%'"
10084             " ORDER BY 1 collate nocase";
10085    }
10086    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10087    initText(&sQuery);
10088    initText(&sSql);
10089    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10090    zSep = "VALUES(";
10091    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10092      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10093      if( zTab==0 ) continue;
10094      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10095      if( cli_strncmp(zTab, "sqlite_",7)!=0 ){
10096        appendText(&sQuery,"SELECT * FROM ", 0);
10097        appendText(&sQuery,zTab,'"');
10098        appendText(&sQuery," NOT INDEXED;", 0);
10099      }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){
10100        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10101                           " ORDER BY name;", 0);
10102      }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){
10103        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10104                           " ORDER BY name;", 0);
10105      }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){
10106        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10107                           " ORDER BY tbl,idx;", 0);
10108      }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){
10109        appendText(&sQuery, "SELECT * FROM ", 0);
10110        appendText(&sQuery, zTab, 0);
10111        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10112      }
10113      appendText(&sSql, zSep, 0);
10114      appendText(&sSql, sQuery.z, '\'');
10115      sQuery.n = 0;
10116      appendText(&sSql, ",", 0);
10117      appendText(&sSql, zTab, '\'');
10118      zSep = "),(";
10119    }
10120    sqlite3_finalize(pStmt);
10121    if( bSeparate ){
10122      zSql = sqlite3_mprintf(
10123          "%s))"
10124          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10125          "   FROM [sha3sum$query]",
10126          sSql.z, iSize);
10127    }else{
10128      zSql = sqlite3_mprintf(
10129          "%s))"
10130          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10131          "   FROM [sha3sum$query]",
10132          sSql.z, iSize);
10133    }
10134    shell_check_oom(zSql);
10135    freeText(&sQuery);
10136    freeText(&sSql);
10137    if( bDebug ){
10138      utf8_printf(p->out, "%s\n", zSql);
10139    }else{
10140      shell_exec(p, zSql, 0);
10141    }
10142    sqlite3_free(zSql);
10143  }else
10144
10145#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10146  if( c=='s'
10147   && (cli_strncmp(azArg[0], "shell", n)==0
10148       || cli_strncmp(azArg[0],"system",n)==0)
10149  ){
10150    char *zCmd;
10151    int i, x;
10152    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10153    if( nArg<2 ){
10154      raw_printf(stderr, "Usage: .system COMMAND\n");
10155      rc = 1;
10156      goto meta_command_exit;
10157    }
10158    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10159    for(i=2; i<nArg && zCmd!=0; i++){
10160      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10161                             zCmd, azArg[i]);
10162    }
10163    x = zCmd!=0 ? system(zCmd) : 1;
10164    sqlite3_free(zCmd);
10165    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10166  }else
10167#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10168
10169  if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){
10170    static const char *azBool[] = { "off", "on", "trigger", "full"};
10171    const char *zOut;
10172    int i;
10173    if( nArg!=1 ){
10174      raw_printf(stderr, "Usage: .show\n");
10175      rc = 1;
10176      goto meta_command_exit;
10177    }
10178    utf8_printf(p->out, "%12.12s: %s\n","echo",
10179                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10180    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10181    utf8_printf(p->out, "%12.12s: %s\n","explain",
10182         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10183    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10184    if( p->mode==MODE_Column
10185     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10186    ){
10187      utf8_printf
10188        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10189         modeDescr[p->mode], p->cmOpts.iWrap,
10190         p->cmOpts.bWordWrap ? "on" : "off",
10191         p->cmOpts.bQuote ? "" : "no");
10192    }else{
10193      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10194    }
10195    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10196      output_c_string(p->out, p->nullValue);
10197      raw_printf(p->out, "\n");
10198    utf8_printf(p->out,"%12.12s: %s\n","output",
10199            strlen30(p->outfile) ? p->outfile : "stdout");
10200    utf8_printf(p->out,"%12.12s: ", "colseparator");
10201      output_c_string(p->out, p->colSeparator);
10202      raw_printf(p->out, "\n");
10203    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10204      output_c_string(p->out, p->rowSeparator);
10205      raw_printf(p->out, "\n");
10206    switch( p->statsOn ){
10207      case 0:  zOut = "off";     break;
10208      default: zOut = "on";      break;
10209      case 2:  zOut = "stmt";    break;
10210      case 3:  zOut = "vmstep";  break;
10211    }
10212    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10213    utf8_printf(p->out, "%12.12s: ", "width");
10214    for (i=0;i<p->nWidth;i++) {
10215      raw_printf(p->out, "%d ", p->colWidth[i]);
10216    }
10217    raw_printf(p->out, "\n");
10218    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10219                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10220  }else
10221
10222  if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){
10223    if( nArg==2 ){
10224      if( cli_strcmp(azArg[1],"stmt")==0 ){
10225        p->statsOn = 2;
10226      }else if( cli_strcmp(azArg[1],"vmstep")==0 ){
10227        p->statsOn = 3;
10228      }else{
10229        p->statsOn = (u8)booleanValue(azArg[1]);
10230      }
10231    }else if( nArg==1 ){
10232      display_stats(p->db, p, 0);
10233    }else{
10234      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10235      rc = 1;
10236    }
10237  }else
10238
10239  if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0)
10240   || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0
10241                 || cli_strncmp(azArg[0], "indexes", n)==0) )
10242  ){
10243    sqlite3_stmt *pStmt;
10244    char **azResult;
10245    int nRow, nAlloc;
10246    int ii;
10247    ShellText s;
10248    initText(&s);
10249    open_db(p, 0);
10250    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10251    if( rc ){
10252      sqlite3_finalize(pStmt);
10253      return shellDatabaseError(p->db);
10254    }
10255
10256    if( nArg>2 && c=='i' ){
10257      /* It is an historical accident that the .indexes command shows an error
10258      ** when called with the wrong number of arguments whereas the .tables
10259      ** command does not. */
10260      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10261      rc = 1;
10262      sqlite3_finalize(pStmt);
10263      goto meta_command_exit;
10264    }
10265    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10266      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10267      if( zDbName==0 ) continue;
10268      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10269      if( sqlite3_stricmp(zDbName, "main")==0 ){
10270        appendText(&s, "SELECT name FROM ", 0);
10271      }else{
10272        appendText(&s, "SELECT ", 0);
10273        appendText(&s, zDbName, '\'');
10274        appendText(&s, "||'.'||name FROM ", 0);
10275      }
10276      appendText(&s, zDbName, '"');
10277      appendText(&s, ".sqlite_schema ", 0);
10278      if( c=='t' ){
10279        appendText(&s," WHERE type IN ('table','view')"
10280                      "   AND name NOT LIKE 'sqlite_%'"
10281                      "   AND name LIKE ?1", 0);
10282      }else{
10283        appendText(&s," WHERE type='index'"
10284                      "   AND tbl_name LIKE ?1", 0);
10285      }
10286    }
10287    rc = sqlite3_finalize(pStmt);
10288    if( rc==SQLITE_OK ){
10289      appendText(&s, " ORDER BY 1", 0);
10290      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10291    }
10292    freeText(&s);
10293    if( rc ) return shellDatabaseError(p->db);
10294
10295    /* Run the SQL statement prepared by the above block. Store the results
10296    ** as an array of nul-terminated strings in azResult[].  */
10297    nRow = nAlloc = 0;
10298    azResult = 0;
10299    if( nArg>1 ){
10300      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10301    }else{
10302      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10303    }
10304    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10305      if( nRow>=nAlloc ){
10306        char **azNew;
10307        int n2 = nAlloc*2 + 10;
10308        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10309        shell_check_oom(azNew);
10310        nAlloc = n2;
10311        azResult = azNew;
10312      }
10313      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10314      shell_check_oom(azResult[nRow]);
10315      nRow++;
10316    }
10317    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10318      rc = shellDatabaseError(p->db);
10319    }
10320
10321    /* Pretty-print the contents of array azResult[] to the output */
10322    if( rc==0 && nRow>0 ){
10323      int len, maxlen = 0;
10324      int i, j;
10325      int nPrintCol, nPrintRow;
10326      for(i=0; i<nRow; i++){
10327        len = strlen30(azResult[i]);
10328        if( len>maxlen ) maxlen = len;
10329      }
10330      nPrintCol = 80/(maxlen+2);
10331      if( nPrintCol<1 ) nPrintCol = 1;
10332      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10333      for(i=0; i<nPrintRow; i++){
10334        for(j=i; j<nRow; j+=nPrintRow){
10335          char *zSp = j<nPrintRow ? "" : "  ";
10336          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10337                      azResult[j] ? azResult[j]:"");
10338        }
10339        raw_printf(p->out, "\n");
10340      }
10341    }
10342
10343    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10344    sqlite3_free(azResult);
10345  }else
10346
10347#ifndef SQLITE_SHELL_FIDDLE
10348  /* Begin redirecting output to the file "testcase-out.txt" */
10349  if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){
10350    output_reset(p);
10351    p->out = output_file_open("testcase-out.txt", 0);
10352    if( p->out==0 ){
10353      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10354    }
10355    if( nArg>=2 ){
10356      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10357    }else{
10358      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10359    }
10360  }else
10361#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10362
10363#ifndef SQLITE_UNTESTABLE
10364  if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){
10365    static const struct {
10366       const char *zCtrlName;   /* Name of a test-control option */
10367       int ctrlCode;            /* Integer code for that option */
10368       int unSafe;              /* Not valid for --safe mode */
10369       const char *zUsage;      /* Usage notes */
10370    } aCtrl[] = {
10371      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10372      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10373    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10374    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10375      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10376      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10377    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10378      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10379      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10380      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10381      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10382      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10383#ifdef YYCOVERAGE
10384      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10385#endif
10386      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10387      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10388      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10389      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10390      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10391      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10392      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10393    };
10394    int testctrl = -1;
10395    int iCtrl = -1;
10396    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10397    int isOk = 0;
10398    int i, n2;
10399    const char *zCmd = 0;
10400
10401    open_db(p, 0);
10402    zCmd = nArg>=2 ? azArg[1] : "help";
10403
10404    /* The argument can optionally begin with "-" or "--" */
10405    if( zCmd[0]=='-' && zCmd[1] ){
10406      zCmd++;
10407      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10408    }
10409
10410    /* --help lists all test-controls */
10411    if( cli_strcmp(zCmd,"help")==0 ){
10412      utf8_printf(p->out, "Available test-controls:\n");
10413      for(i=0; i<ArraySize(aCtrl); i++){
10414        utf8_printf(p->out, "  .testctrl %s %s\n",
10415                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10416      }
10417      rc = 1;
10418      goto meta_command_exit;
10419    }
10420
10421    /* convert testctrl text option to value. allow any unique prefix
10422    ** of the option name, or a numerical value. */
10423    n2 = strlen30(zCmd);
10424    for(i=0; i<ArraySize(aCtrl); i++){
10425      if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10426        if( testctrl<0 ){
10427          testctrl = aCtrl[i].ctrlCode;
10428          iCtrl = i;
10429        }else{
10430          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10431                              "Use \".testctrl --help\" for help\n", zCmd);
10432          rc = 1;
10433          goto meta_command_exit;
10434        }
10435      }
10436    }
10437    if( testctrl<0 ){
10438      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10439                         "Use \".testctrl --help\" for help\n", zCmd);
10440    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10441      utf8_printf(stderr,
10442         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10443         p->lineno, aCtrl[iCtrl].zCtrlName);
10444      exit(1);
10445    }else{
10446      switch(testctrl){
10447
10448        /* sqlite3_test_control(int, db, int) */
10449        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10450          if( nArg==3 ){
10451            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10452            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10453            isOk = 3;
10454          }
10455          break;
10456
10457        /* sqlite3_test_control(int) */
10458        case SQLITE_TESTCTRL_PRNG_SAVE:
10459        case SQLITE_TESTCTRL_PRNG_RESTORE:
10460        case SQLITE_TESTCTRL_BYTEORDER:
10461          if( nArg==2 ){
10462            rc2 = sqlite3_test_control(testctrl);
10463            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10464          }
10465          break;
10466
10467        /* sqlite3_test_control(int, uint) */
10468        case SQLITE_TESTCTRL_PENDING_BYTE:
10469          if( nArg==3 ){
10470            unsigned int opt = (unsigned int)integerValue(azArg[2]);
10471            rc2 = sqlite3_test_control(testctrl, opt);
10472            isOk = 3;
10473          }
10474          break;
10475
10476        /* sqlite3_test_control(int, int, sqlite3*) */
10477        case SQLITE_TESTCTRL_PRNG_SEED:
10478          if( nArg==3 || nArg==4 ){
10479            int ii = (int)integerValue(azArg[2]);
10480            sqlite3 *db;
10481            if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){
10482              sqlite3_randomness(sizeof(ii),&ii);
10483              printf("-- random seed: %d\n", ii);
10484            }
10485            if( nArg==3 ){
10486              db = 0;
10487            }else{
10488              db = p->db;
10489              /* Make sure the schema has been loaded */
10490              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
10491            }
10492            rc2 = sqlite3_test_control(testctrl, ii, db);
10493            isOk = 3;
10494          }
10495          break;
10496
10497        /* sqlite3_test_control(int, int) */
10498        case SQLITE_TESTCTRL_ASSERT:
10499        case SQLITE_TESTCTRL_ALWAYS:
10500          if( nArg==3 ){
10501            int opt = booleanValue(azArg[2]);
10502            rc2 = sqlite3_test_control(testctrl, opt);
10503            isOk = 1;
10504          }
10505          break;
10506
10507        /* sqlite3_test_control(int, int) */
10508        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
10509        case SQLITE_TESTCTRL_NEVER_CORRUPT:
10510          if( nArg==3 ){
10511            int opt = booleanValue(azArg[2]);
10512            rc2 = sqlite3_test_control(testctrl, opt);
10513            isOk = 3;
10514          }
10515          break;
10516
10517        /* sqlite3_test_control(sqlite3*) */
10518        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
10519          rc2 = sqlite3_test_control(testctrl, p->db);
10520          isOk = 3;
10521          break;
10522
10523        case SQLITE_TESTCTRL_IMPOSTER:
10524          if( nArg==5 ){
10525            rc2 = sqlite3_test_control(testctrl, p->db,
10526                          azArg[2],
10527                          integerValue(azArg[3]),
10528                          integerValue(azArg[4]));
10529            isOk = 3;
10530          }
10531          break;
10532
10533        case SQLITE_TESTCTRL_SEEK_COUNT: {
10534          u64 x = 0;
10535          rc2 = sqlite3_test_control(testctrl, p->db, &x);
10536          utf8_printf(p->out, "%llu\n", x);
10537          isOk = 3;
10538          break;
10539        }
10540
10541#ifdef YYCOVERAGE
10542        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
10543          if( nArg==2 ){
10544            sqlite3_test_control(testctrl, p->out);
10545            isOk = 3;
10546          }
10547          break;
10548        }
10549#endif
10550#ifdef SQLITE_DEBUG
10551        case SQLITE_TESTCTRL_TUNE: {
10552          if( nArg==4 ){
10553            int id = (int)integerValue(azArg[2]);
10554            int val = (int)integerValue(azArg[3]);
10555            sqlite3_test_control(testctrl, id, &val);
10556            isOk = 3;
10557          }else if( nArg==3 ){
10558            int id = (int)integerValue(azArg[2]);
10559            sqlite3_test_control(testctrl, -id, &rc2);
10560            isOk = 1;
10561          }else if( nArg==2 ){
10562            int id = 1;
10563            while(1){
10564              int val = 0;
10565              rc2 = sqlite3_test_control(testctrl, -id, &val);
10566              if( rc2!=SQLITE_OK ) break;
10567              if( id>1 ) utf8_printf(p->out, "  ");
10568              utf8_printf(p->out, "%d: %d", id, val);
10569              id++;
10570            }
10571            if( id>1 ) utf8_printf(p->out, "\n");
10572            isOk = 3;
10573          }
10574          break;
10575        }
10576#endif
10577        case SQLITE_TESTCTRL_SORTER_MMAP:
10578          if( nArg==3 ){
10579            int opt = (unsigned int)integerValue(azArg[2]);
10580            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10581            isOk = 3;
10582          }
10583          break;
10584      }
10585    }
10586    if( isOk==0 && iCtrl>=0 ){
10587      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
10588      rc = 1;
10589    }else if( isOk==1 ){
10590      raw_printf(p->out, "%d\n", rc2);
10591    }else if( isOk==2 ){
10592      raw_printf(p->out, "0x%08x\n", rc2);
10593    }
10594  }else
10595#endif /* !defined(SQLITE_UNTESTABLE) */
10596
10597  if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){
10598    open_db(p, 0);
10599    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
10600  }else
10601
10602  if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){
10603    if( nArg==2 ){
10604      enableTimer = booleanValue(azArg[1]);
10605      if( enableTimer && !HAS_TIMER ){
10606        raw_printf(stderr, "Error: timer not available on this system.\n");
10607        enableTimer = 0;
10608      }
10609    }else{
10610      raw_printf(stderr, "Usage: .timer on|off\n");
10611      rc = 1;
10612    }
10613  }else
10614
10615#ifndef SQLITE_OMIT_TRACE
10616  if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){
10617    int mType = 0;
10618    int jj;
10619    open_db(p, 0);
10620    for(jj=1; jj<nArg; jj++){
10621      const char *z = azArg[jj];
10622      if( z[0]=='-' ){
10623        if( optionMatch(z, "expanded") ){
10624          p->eTraceType = SHELL_TRACE_EXPANDED;
10625        }
10626#ifdef SQLITE_ENABLE_NORMALIZE
10627        else if( optionMatch(z, "normalized") ){
10628          p->eTraceType = SHELL_TRACE_NORMALIZED;
10629        }
10630#endif
10631        else if( optionMatch(z, "plain") ){
10632          p->eTraceType = SHELL_TRACE_PLAIN;
10633        }
10634        else if( optionMatch(z, "profile") ){
10635          mType |= SQLITE_TRACE_PROFILE;
10636        }
10637        else if( optionMatch(z, "row") ){
10638          mType |= SQLITE_TRACE_ROW;
10639        }
10640        else if( optionMatch(z, "stmt") ){
10641          mType |= SQLITE_TRACE_STMT;
10642        }
10643        else if( optionMatch(z, "close") ){
10644          mType |= SQLITE_TRACE_CLOSE;
10645        }
10646        else {
10647          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
10648          rc = 1;
10649          goto meta_command_exit;
10650        }
10651      }else{
10652        output_file_close(p->traceOut);
10653        p->traceOut = output_file_open(azArg[1], 0);
10654      }
10655    }
10656    if( p->traceOut==0 ){
10657      sqlite3_trace_v2(p->db, 0, 0, 0);
10658    }else{
10659      if( mType==0 ) mType = SQLITE_TRACE_STMT;
10660      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
10661    }
10662  }else
10663#endif /* !defined(SQLITE_OMIT_TRACE) */
10664
10665#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10666  if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){
10667    int ii;
10668    int lenOpt;
10669    char *zOpt;
10670    if( nArg<2 ){
10671      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
10672      rc = 1;
10673      goto meta_command_exit;
10674    }
10675    open_db(p, 0);
10676    zOpt = azArg[1];
10677    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
10678    lenOpt = (int)strlen(zOpt);
10679    if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){
10680      assert( azArg[nArg]==0 );
10681      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
10682    }else{
10683      for(ii=1; ii<nArg; ii++){
10684        sqlite3_create_module(p->db, azArg[ii], 0, 0);
10685      }
10686    }
10687  }else
10688#endif
10689
10690#if SQLITE_USER_AUTHENTICATION
10691  if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){
10692    if( nArg<2 ){
10693      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
10694      rc = 1;
10695      goto meta_command_exit;
10696    }
10697    open_db(p, 0);
10698    if( cli_strcmp(azArg[1],"login")==0 ){
10699      if( nArg!=4 ){
10700        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
10701        rc = 1;
10702        goto meta_command_exit;
10703      }
10704      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
10705                                     strlen30(azArg[3]));
10706      if( rc ){
10707        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
10708        rc = 1;
10709      }
10710    }else if( cli_strcmp(azArg[1],"add")==0 ){
10711      if( nArg!=5 ){
10712        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
10713        rc = 1;
10714        goto meta_command_exit;
10715      }
10716      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10717                            booleanValue(azArg[4]));
10718      if( rc ){
10719        raw_printf(stderr, "User-Add failed: %d\n", rc);
10720        rc = 1;
10721      }
10722    }else if( cli_strcmp(azArg[1],"edit")==0 ){
10723      if( nArg!=5 ){
10724        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
10725        rc = 1;
10726        goto meta_command_exit;
10727      }
10728      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
10729                              booleanValue(azArg[4]));
10730      if( rc ){
10731        raw_printf(stderr, "User-Edit failed: %d\n", rc);
10732        rc = 1;
10733      }
10734    }else if( cli_strcmp(azArg[1],"delete")==0 ){
10735      if( nArg!=3 ){
10736        raw_printf(stderr, "Usage: .user delete USER\n");
10737        rc = 1;
10738        goto meta_command_exit;
10739      }
10740      rc = sqlite3_user_delete(p->db, azArg[2]);
10741      if( rc ){
10742        raw_printf(stderr, "User-Delete failed: %d\n", rc);
10743        rc = 1;
10744      }
10745    }else{
10746      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
10747      rc = 1;
10748      goto meta_command_exit;
10749    }
10750  }else
10751#endif /* SQLITE_USER_AUTHENTICATION */
10752
10753  if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){
10754    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
10755        sqlite3_libversion(), sqlite3_sourceid());
10756#if SQLITE_HAVE_ZLIB
10757    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
10758#endif
10759#define CTIMEOPT_VAL_(opt) #opt
10760#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10761#if defined(__clang__) && defined(__clang_major__)
10762    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
10763                    CTIMEOPT_VAL(__clang_minor__) "."
10764                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
10765#elif defined(_MSC_VER)
10766    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
10767#elif defined(__GNUC__) && defined(__VERSION__)
10768    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
10769#endif
10770  }else
10771
10772  if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){
10773    const char *zDbName = nArg==2 ? azArg[1] : "main";
10774    sqlite3_vfs *pVfs = 0;
10775    if( p->db ){
10776      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
10777      if( pVfs ){
10778        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
10779        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10780        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10781        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10782      }
10783    }
10784  }else
10785
10786  if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){
10787    sqlite3_vfs *pVfs;
10788    sqlite3_vfs *pCurrent = 0;
10789    if( p->db ){
10790      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
10791    }
10792    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
10793      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
10794           pVfs==pCurrent ? "  <--- CURRENT" : "");
10795      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
10796      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
10797      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
10798      if( pVfs->pNext ){
10799        raw_printf(p->out, "-----------------------------------\n");
10800      }
10801    }
10802  }else
10803
10804  if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){
10805    const char *zDbName = nArg==2 ? azArg[1] : "main";
10806    char *zVfsName = 0;
10807    if( p->db ){
10808      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
10809      if( zVfsName ){
10810        utf8_printf(p->out, "%s\n", zVfsName);
10811        sqlite3_free(zVfsName);
10812      }
10813    }
10814  }else
10815
10816  if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){
10817    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10818    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
10819  }else
10820
10821  if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){
10822    int j;
10823    assert( nArg<=ArraySize(azArg) );
10824    p->nWidth = nArg-1;
10825    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
10826    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
10827    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
10828    for(j=1; j<nArg; j++){
10829      p->colWidth[j-1] = (int)integerValue(azArg[j]);
10830    }
10831  }else
10832
10833  {
10834    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
10835      " \"%s\". Enter \".help\" for help\n", azArg[0]);
10836    rc = 1;
10837  }
10838
10839meta_command_exit:
10840  if( p->outCount ){
10841    p->outCount--;
10842    if( p->outCount==0 ) output_reset(p);
10843  }
10844  p->bSafeMode = p->bSafeModePersist;
10845  return rc;
10846}
10847
10848/* Line scan result and intermediate states (supporting scan resumption)
10849*/
10850#ifndef CHAR_BIT
10851# define CHAR_BIT 8
10852#endif
10853typedef enum {
10854  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
10855  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
10856  QSS_Start = 0
10857} QuickScanState;
10858#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
10859#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
10860#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
10861#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
10862#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
10863
10864/*
10865** Scan line for classification to guide shell's handling.
10866** The scan is resumable for subsequent lines when prior
10867** return values are passed as the 2nd argument.
10868*/
10869static QuickScanState quickscan(char *zLine, QuickScanState qss){
10870  char cin;
10871  char cWait = (char)qss; /* intentional narrowing loss */
10872  if( cWait==0 ){
10873  PlainScan:
10874    assert( cWait==0 );
10875    while( (cin = *zLine++)!=0 ){
10876      if( IsSpace(cin) )
10877        continue;
10878      switch (cin){
10879      case '-':
10880        if( *zLine!='-' )
10881          break;
10882        while((cin = *++zLine)!=0 )
10883          if( cin=='\n')
10884            goto PlainScan;
10885        return qss;
10886      case ';':
10887        qss |= QSS_EndingSemi;
10888        continue;
10889      case '/':
10890        if( *zLine=='*' ){
10891          ++zLine;
10892          cWait = '*';
10893          qss = QSS_SETV(qss, cWait);
10894          goto TermScan;
10895        }
10896        break;
10897      case '[':
10898        cin = ']';
10899        /* fall thru */
10900      case '`': case '\'': case '"':
10901        cWait = cin;
10902        qss = QSS_HasDark | cWait;
10903        goto TermScan;
10904      default:
10905        break;
10906      }
10907      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
10908    }
10909  }else{
10910  TermScan:
10911    while( (cin = *zLine++)!=0 ){
10912      if( cin==cWait ){
10913        switch( cWait ){
10914        case '*':
10915          if( *zLine != '/' )
10916            continue;
10917          ++zLine;
10918          cWait = 0;
10919          qss = QSS_SETV(qss, 0);
10920          goto PlainScan;
10921        case '`': case '\'': case '"':
10922          if(*zLine==cWait){
10923            ++zLine;
10924            continue;
10925          }
10926          /* fall thru */
10927        case ']':
10928          cWait = 0;
10929          qss = QSS_SETV(qss, 0);
10930          goto PlainScan;
10931        default: assert(0);
10932        }
10933      }
10934    }
10935  }
10936  return qss;
10937}
10938
10939/*
10940** Return TRUE if the line typed in is an SQL command terminator other
10941** than a semi-colon.  The SQL Server style "go" command is understood
10942** as is the Oracle "/".
10943*/
10944static int line_is_command_terminator(char *zLine){
10945  while( IsSpace(zLine[0]) ){ zLine++; };
10946  if( zLine[0]=='/' )
10947    zLine += 1; /* Oracle */
10948  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
10949    zLine += 2; /* SQL Server */
10950  else
10951    return 0;
10952  return quickscan(zLine, QSS_Start)==QSS_Start;
10953}
10954
10955/*
10956** We need a default sqlite3_complete() implementation to use in case
10957** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
10958** any arbitrary text is a complete SQL statement.  This is not very
10959** user-friendly, but it does seem to work.
10960*/
10961#ifdef SQLITE_OMIT_COMPLETE
10962#define sqlite3_complete(x) 1
10963#endif
10964
10965/*
10966** Return true if zSql is a complete SQL statement.  Return false if it
10967** ends in the middle of a string literal or C-style comment.
10968*/
10969static int line_is_complete(char *zSql, int nSql){
10970  int rc;
10971  if( zSql==0 ) return 1;
10972  zSql[nSql] = ';';
10973  zSql[nSql+1] = 0;
10974  rc = sqlite3_complete(zSql);
10975  zSql[nSql] = 0;
10976  return rc;
10977}
10978
10979/*
10980** Run a single line of SQL.  Return the number of errors.
10981*/
10982static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
10983  int rc;
10984  char *zErrMsg = 0;
10985
10986  open_db(p, 0);
10987  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
10988  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
10989  BEGIN_TIMER;
10990  rc = shell_exec(p, zSql, &zErrMsg);
10991  END_TIMER;
10992  if( rc || zErrMsg ){
10993    char zPrefix[100];
10994    const char *zErrorTail;
10995    const char *zErrorType;
10996    if( zErrMsg==0 ){
10997      zErrorType = "Error";
10998      zErrorTail = sqlite3_errmsg(p->db);
10999    }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){
11000      zErrorType = "Parse error";
11001      zErrorTail = &zErrMsg[12];
11002    }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){
11003      zErrorType = "Runtime error";
11004      zErrorTail = &zErrMsg[10];
11005    }else{
11006      zErrorType = "Error";
11007      zErrorTail = zErrMsg;
11008    }
11009    if( in!=0 || !stdin_is_interactive ){
11010      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11011                       "%s near line %d:", zErrorType, startline);
11012    }else{
11013      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11014    }
11015    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11016    sqlite3_free(zErrMsg);
11017    zErrMsg = 0;
11018    return 1;
11019  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11020    char zLineBuf[2000];
11021    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11022            "changes: %lld   total_changes: %lld",
11023            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11024    raw_printf(p->out, "%s\n", zLineBuf);
11025  }
11026  return 0;
11027}
11028
11029static void echo_group_input(ShellState *p, const char *zDo){
11030  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11031}
11032
11033#ifdef SQLITE_SHELL_FIDDLE
11034/*
11035** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11036** because we need the global shellState and cannot access it from that function
11037** without moving lots of code around (creating a larger/messier diff).
11038*/
11039static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11040  /* Parse the next line from shellState.wasm.zInput. */
11041  const char *zBegin = shellState.wasm.zPos;
11042  const char *z = zBegin;
11043  char *zLine = 0;
11044  i64 nZ = 0;
11045
11046  UNUSED_PARAMETER(in);
11047  UNUSED_PARAMETER(isContinuation);
11048  if(!z || !*z){
11049    return 0;
11050  }
11051  while(*z && isspace(*z)) ++z;
11052  zBegin = z;
11053  for(; *z && '\n'!=*z; ++nZ, ++z){}
11054  if(nZ>0 && '\r'==zBegin[nZ-1]){
11055    --nZ;
11056  }
11057  shellState.wasm.zPos = z;
11058  zLine = realloc(zPrior, nZ+1);
11059  shell_check_oom(zLine);
11060  memcpy(zLine, zBegin, nZ);
11061  zLine[nZ] = 0;
11062  return zLine;
11063}
11064#endif /* SQLITE_SHELL_FIDDLE */
11065
11066/*
11067** Read input from *in and process it.  If *in==0 then input
11068** is interactive - the user is typing it it.  Otherwise, input
11069** is coming from a file or device.  A prompt is issued and history
11070** is saved only if input is interactive.  An interrupt signal will
11071** cause this routine to exit immediately, unless input is interactive.
11072**
11073** Return the number of errors.
11074*/
11075static int process_input(ShellState *p){
11076  char *zLine = 0;          /* A single input line */
11077  char *zSql = 0;           /* Accumulated SQL text */
11078  i64 nLine;                /* Length of current line */
11079  i64 nSql = 0;             /* Bytes of zSql[] used */
11080  i64 nAlloc = 0;           /* Allocated zSql[] space */
11081  int rc;                   /* Error code */
11082  int errCnt = 0;           /* Number of errors seen */
11083  i64 startline = 0;        /* Line number for start of current input */
11084  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11085
11086  if( p->inputNesting==MAX_INPUT_NESTING ){
11087    /* This will be more informative in a later version. */
11088    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11089                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11090    return 1;
11091  }
11092  ++p->inputNesting;
11093  p->lineno = 0;
11094  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11095    fflush(p->out);
11096    zLine = one_input_line(p->in, zLine, nSql>0);
11097    if( zLine==0 ){
11098      /* End of input */
11099      if( p->in==0 && stdin_is_interactive ) printf("\n");
11100      break;
11101    }
11102    if( seenInterrupt ){
11103      if( p->in!=0 ) break;
11104      seenInterrupt = 0;
11105    }
11106    p->lineno++;
11107    if( QSS_INPLAIN(qss)
11108        && line_is_command_terminator(zLine)
11109        && line_is_complete(zSql, nSql) ){
11110      memcpy(zLine,";",2);
11111    }
11112    qss = quickscan(zLine, qss);
11113    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11114      /* Just swallow single-line whitespace */
11115      echo_group_input(p, zLine);
11116      qss = QSS_Start;
11117      continue;
11118    }
11119    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11120      echo_group_input(p, zLine);
11121      if( zLine[0]=='.' ){
11122        rc = do_meta_command(zLine, p);
11123        if( rc==2 ){ /* exit requested */
11124          break;
11125        }else if( rc ){
11126          errCnt++;
11127        }
11128      }
11129      qss = QSS_Start;
11130      continue;
11131    }
11132    /* No single-line dispositions remain; accumulate line(s). */
11133    nLine = strlen(zLine);
11134    if( nSql+nLine+2>=nAlloc ){
11135      /* Grow buffer by half-again increments when big. */
11136      nAlloc = nSql+(nSql>>1)+nLine+100;
11137      zSql = realloc(zSql, nAlloc);
11138      shell_check_oom(zSql);
11139    }
11140    if( nSql==0 ){
11141      i64 i;
11142      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11143      assert( nAlloc>0 && zSql!=0 );
11144      memcpy(zSql, zLine+i, nLine+1-i);
11145      startline = p->lineno;
11146      nSql = nLine-i;
11147    }else{
11148      zSql[nSql++] = '\n';
11149      memcpy(zSql+nSql, zLine, nLine+1);
11150      nSql += nLine;
11151    }
11152    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11153      echo_group_input(p, zSql);
11154      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11155      nSql = 0;
11156      if( p->outCount ){
11157        output_reset(p);
11158        p->outCount = 0;
11159      }else{
11160        clearTempFile(p);
11161      }
11162      p->bSafeMode = p->bSafeModePersist;
11163      qss = QSS_Start;
11164    }else if( nSql && QSS_PLAINWHITE(qss) ){
11165      echo_group_input(p, zSql);
11166      nSql = 0;
11167      qss = QSS_Start;
11168    }
11169  }
11170  if( nSql ){
11171    /* This may be incomplete. Let the SQL parser deal with that. */
11172    echo_group_input(p, zSql);
11173    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11174  }
11175  free(zSql);
11176  free(zLine);
11177  --p->inputNesting;
11178  return errCnt>0;
11179}
11180
11181/*
11182** Return a pathname which is the user's home directory.  A
11183** 0 return indicates an error of some kind.
11184*/
11185static char *find_home_dir(int clearFlag){
11186  static char *home_dir = NULL;
11187  if( clearFlag ){
11188    free(home_dir);
11189    home_dir = 0;
11190    return 0;
11191  }
11192  if( home_dir ) return home_dir;
11193
11194#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11195     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11196  {
11197    struct passwd *pwent;
11198    uid_t uid = getuid();
11199    if( (pwent=getpwuid(uid)) != NULL) {
11200      home_dir = pwent->pw_dir;
11201    }
11202  }
11203#endif
11204
11205#if defined(_WIN32_WCE)
11206  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11207   */
11208  home_dir = "/";
11209#else
11210
11211#if defined(_WIN32) || defined(WIN32)
11212  if (!home_dir) {
11213    home_dir = getenv("USERPROFILE");
11214  }
11215#endif
11216
11217  if (!home_dir) {
11218    home_dir = getenv("HOME");
11219  }
11220
11221#if defined(_WIN32) || defined(WIN32)
11222  if (!home_dir) {
11223    char *zDrive, *zPath;
11224    int n;
11225    zDrive = getenv("HOMEDRIVE");
11226    zPath = getenv("HOMEPATH");
11227    if( zDrive && zPath ){
11228      n = strlen30(zDrive) + strlen30(zPath) + 1;
11229      home_dir = malloc( n );
11230      if( home_dir==0 ) return 0;
11231      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11232      return home_dir;
11233    }
11234    home_dir = "c:\\";
11235  }
11236#endif
11237
11238#endif /* !_WIN32_WCE */
11239
11240  if( home_dir ){
11241    i64 n = strlen(home_dir) + 1;
11242    char *z = malloc( n );
11243    if( z ) memcpy(z, home_dir, n);
11244    home_dir = z;
11245  }
11246
11247  return home_dir;
11248}
11249
11250/*
11251** Read input from the file given by sqliterc_override.  Or if that
11252** parameter is NULL, take input from ~/.sqliterc
11253**
11254** Returns the number of errors.
11255*/
11256static void process_sqliterc(
11257  ShellState *p,                  /* Configuration data */
11258  const char *sqliterc_override   /* Name of config file. NULL to use default */
11259){
11260  char *home_dir = NULL;
11261  const char *sqliterc = sqliterc_override;
11262  char *zBuf = 0;
11263  FILE *inSaved = p->in;
11264  int savedLineno = p->lineno;
11265
11266  if (sqliterc == NULL) {
11267    home_dir = find_home_dir(0);
11268    if( home_dir==0 ){
11269      raw_printf(stderr, "-- warning: cannot find home directory;"
11270                      " cannot read ~/.sqliterc\n");
11271      return;
11272    }
11273    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11274    shell_check_oom(zBuf);
11275    sqliterc = zBuf;
11276  }
11277  p->in = fopen(sqliterc,"rb");
11278  if( p->in ){
11279    if( stdin_is_interactive ){
11280      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11281    }
11282    if( process_input(p) && bail_on_error ) exit(1);
11283    fclose(p->in);
11284  }else if( sqliterc_override!=0 ){
11285    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11286    if( bail_on_error ) exit(1);
11287  }
11288  p->in = inSaved;
11289  p->lineno = savedLineno;
11290  sqlite3_free(zBuf);
11291}
11292
11293/*
11294** Show available command line options
11295*/
11296static const char zOptions[] =
11297#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11298  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11299#endif
11300  "   -append              append the database to the end of the file\n"
11301  "   -ascii               set output mode to 'ascii'\n"
11302  "   -bail                stop after hitting an error\n"
11303  "   -batch               force batch I/O\n"
11304  "   -box                 set output mode to 'box'\n"
11305  "   -column              set output mode to 'column'\n"
11306  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11307  "   -csv                 set output mode to 'csv'\n"
11308#if !defined(SQLITE_OMIT_DESERIALIZE)
11309  "   -deserialize         open the database using sqlite3_deserialize()\n"
11310#endif
11311  "   -echo                print inputs before execution\n"
11312  "   -init FILENAME       read/process named file\n"
11313  "   -[no]header          turn headers on or off\n"
11314#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11315  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11316#endif
11317  "   -help                show this message\n"
11318  "   -html                set output mode to HTML\n"
11319  "   -interactive         force interactive I/O\n"
11320  "   -json                set output mode to 'json'\n"
11321  "   -line                set output mode to 'line'\n"
11322  "   -list                set output mode to 'list'\n"
11323  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11324  "   -markdown            set output mode to 'markdown'\n"
11325#if !defined(SQLITE_OMIT_DESERIALIZE)
11326  "   -maxsize N           maximum size for a --deserialize database\n"
11327#endif
11328  "   -memtrace            trace all memory allocations and deallocations\n"
11329  "   -mmap N              default mmap size set to N\n"
11330#ifdef SQLITE_ENABLE_MULTIPLEX
11331  "   -multiplex           enable the multiplexor VFS\n"
11332#endif
11333  "   -newline SEP         set output row separator. Default: '\\n'\n"
11334  "   -nofollow            refuse to open symbolic links to database files\n"
11335  "   -nonce STRING        set the safe-mode escape nonce\n"
11336  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11337  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11338  "   -quote               set output mode to 'quote'\n"
11339  "   -readonly            open the database read-only\n"
11340  "   -safe                enable safe-mode\n"
11341  "   -separator SEP       set output column separator. Default: '|'\n"
11342#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11343  "   -sorterref SIZE      sorter references threshold size\n"
11344#endif
11345  "   -stats               print memory stats before each finalize\n"
11346  "   -table               set output mode to 'table'\n"
11347  "   -tabs                set output mode to 'tabs'\n"
11348  "   -version             show SQLite version\n"
11349  "   -vfs NAME            use NAME as the default VFS\n"
11350#ifdef SQLITE_ENABLE_VFSTRACE
11351  "   -vfstrace            enable tracing of all VFS calls\n"
11352#endif
11353#ifdef SQLITE_HAVE_ZLIB
11354  "   -zip                 open the file as a ZIP Archive\n"
11355#endif
11356;
11357static void usage(int showDetail){
11358  utf8_printf(stderr,
11359      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11360      "FILENAME is the name of an SQLite database. A new database is created\n"
11361      "if the file does not previously exist.\n", Argv0);
11362  if( showDetail ){
11363    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11364  }else{
11365    raw_printf(stderr, "Use the -help option for additional information\n");
11366  }
11367  exit(1);
11368}
11369
11370/*
11371** Internal check:  Verify that the SQLite is uninitialized.  Print a
11372** error message if it is initialized.
11373*/
11374static void verify_uninitialized(void){
11375  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11376    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11377                        " initialization.\n");
11378  }
11379}
11380
11381/*
11382** Initialize the state information in data
11383*/
11384static void main_init(ShellState *data) {
11385  memset(data, 0, sizeof(*data));
11386  data->normalMode = data->cMode = data->mode = MODE_List;
11387  data->autoExplain = 1;
11388  data->pAuxDb = &data->aAuxDb[0];
11389  memcpy(data->colSeparator,SEP_Column, 2);
11390  memcpy(data->rowSeparator,SEP_Row, 2);
11391  data->showHeader = 0;
11392  data->shellFlgs = SHFLG_Lookaside;
11393  verify_uninitialized();
11394  sqlite3_config(SQLITE_CONFIG_URI, 1);
11395  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11396  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11397  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11398  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11399}
11400
11401/*
11402** Output text to the console in a font that attracts extra attention.
11403*/
11404#ifdef _WIN32
11405static void printBold(const char *zText){
11406#if !SQLITE_OS_WINRT
11407  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11408  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11409  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11410  SetConsoleTextAttribute(out,
11411         FOREGROUND_RED|FOREGROUND_INTENSITY
11412  );
11413#endif
11414  printf("%s", zText);
11415#if !SQLITE_OS_WINRT
11416  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11417#endif
11418}
11419#else
11420static void printBold(const char *zText){
11421  printf("\033[1m%s\033[0m", zText);
11422}
11423#endif
11424
11425/*
11426** Get the argument to an --option.  Throw an error and die if no argument
11427** is available.
11428*/
11429static char *cmdline_option_value(int argc, char **argv, int i){
11430  if( i==argc ){
11431    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11432            argv[0], argv[argc-1]);
11433    exit(1);
11434  }
11435  return argv[i];
11436}
11437
11438#ifndef SQLITE_SHELL_IS_UTF8
11439#  if (defined(_WIN32) || defined(WIN32)) \
11440   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11441#    define SQLITE_SHELL_IS_UTF8          (0)
11442#  else
11443#    define SQLITE_SHELL_IS_UTF8          (1)
11444#  endif
11445#endif
11446
11447#ifdef SQLITE_SHELL_FIDDLE
11448#  define main fiddle_main
11449#endif
11450
11451#if SQLITE_SHELL_IS_UTF8
11452int SQLITE_CDECL main(int argc, char **argv){
11453#else
11454int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11455  char **argv;
11456#endif
11457#ifdef SQLITE_DEBUG
11458  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
11459#endif
11460  char *zErrMsg = 0;
11461#ifdef SQLITE_SHELL_FIDDLE
11462#  define data shellState
11463#else
11464  ShellState data;
11465#endif
11466  const char *zInitFile = 0;
11467  int i;
11468  int rc = 0;
11469  int warnInmemoryDb = 0;
11470  int readStdin = 1;
11471  int nCmd = 0;
11472  char **azCmd = 0;
11473  const char *zVfs = 0;           /* Value of -vfs command-line option */
11474#if !SQLITE_SHELL_IS_UTF8
11475  char **argvToFree = 0;
11476  int argcToFree = 0;
11477#endif
11478
11479  setBinaryMode(stdin, 0);
11480  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
11481#ifdef SQLITE_SHELL_FIDDLE
11482  stdin_is_interactive = 0;
11483  stdout_is_console = 1;
11484  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
11485#else
11486  stdin_is_interactive = isatty(0);
11487  stdout_is_console = isatty(1);
11488#endif
11489
11490#if !defined(_WIN32_WCE)
11491  if( getenv("SQLITE_DEBUG_BREAK") ){
11492    if( isatty(0) && isatty(2) ){
11493      fprintf(stderr,
11494          "attach debugger to process %d and press any key to continue.\n",
11495          GETPID());
11496      fgetc(stdin);
11497    }else{
11498#if defined(_WIN32) || defined(WIN32)
11499#if SQLITE_OS_WINRT
11500      __debugbreak();
11501#else
11502      DebugBreak();
11503#endif
11504#elif defined(SIGTRAP)
11505      raise(SIGTRAP);
11506#endif
11507    }
11508  }
11509#endif
11510
11511#if USE_SYSTEM_SQLITE+0!=1
11512  if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
11513    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
11514            sqlite3_sourceid(), SQLITE_SOURCE_ID);
11515    exit(1);
11516  }
11517#endif
11518  main_init(&data);
11519
11520  /* On Windows, we must translate command-line arguments into UTF-8.
11521  ** The SQLite memory allocator subsystem has to be enabled in order to
11522  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
11523  ** subsequent sqlite3_config() calls will work.  So copy all results into
11524  ** memory that does not come from the SQLite memory allocator.
11525  */
11526#if !SQLITE_SHELL_IS_UTF8
11527  sqlite3_initialize();
11528  argvToFree = malloc(sizeof(argv[0])*argc*2);
11529  shell_check_oom(argvToFree);
11530  argcToFree = argc;
11531  argv = argvToFree + argc;
11532  for(i=0; i<argc; i++){
11533    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
11534    i64 n;
11535    shell_check_oom(z);
11536    n = strlen(z);
11537    argv[i] = malloc( n+1 );
11538    shell_check_oom(argv[i]);
11539    memcpy(argv[i], z, n+1);
11540    argvToFree[i] = argv[i];
11541    sqlite3_free(z);
11542  }
11543  sqlite3_shutdown();
11544#endif
11545
11546  assert( argc>=1 && argv && argv[0] );
11547  Argv0 = argv[0];
11548
11549  /* Make sure we have a valid signal handler early, before anything
11550  ** else is done.
11551  */
11552#ifdef SIGINT
11553  signal(SIGINT, interrupt_handler);
11554#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
11555  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
11556#endif
11557
11558#ifdef SQLITE_SHELL_DBNAME_PROC
11559  {
11560    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
11561    ** of a C-function that will provide the name of the database file.  Use
11562    ** this compile-time option to embed this shell program in larger
11563    ** applications. */
11564    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
11565    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
11566    warnInmemoryDb = 0;
11567  }
11568#endif
11569
11570  /* Do an initial pass through the command-line argument to locate
11571  ** the name of the database file, the name of the initialization file,
11572  ** the size of the alternative malloc heap,
11573  ** and the first command to execute.
11574  */
11575  verify_uninitialized();
11576  for(i=1; i<argc; i++){
11577    char *z;
11578    z = argv[i];
11579    if( z[0]!='-' ){
11580      if( data.aAuxDb->zDbFilename==0 ){
11581        data.aAuxDb->zDbFilename = z;
11582      }else{
11583        /* Excesss arguments are interpreted as SQL (or dot-commands) and
11584        ** mean that nothing is read from stdin */
11585        readStdin = 0;
11586        nCmd++;
11587        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
11588        shell_check_oom(azCmd);
11589        azCmd[nCmd-1] = z;
11590      }
11591    }
11592    if( z[1]=='-' ) z++;
11593    if( cli_strcmp(z,"-separator")==0
11594     || cli_strcmp(z,"-nullvalue")==0
11595     || cli_strcmp(z,"-newline")==0
11596     || cli_strcmp(z,"-cmd")==0
11597    ){
11598      (void)cmdline_option_value(argc, argv, ++i);
11599    }else if( cli_strcmp(z,"-init")==0 ){
11600      zInitFile = cmdline_option_value(argc, argv, ++i);
11601    }else if( cli_strcmp(z,"-batch")==0 ){
11602      /* Need to check for batch mode here to so we can avoid printing
11603      ** informational messages (like from process_sqliterc) before
11604      ** we do the actual processing of arguments later in a second pass.
11605      */
11606      stdin_is_interactive = 0;
11607    }else if( cli_strcmp(z,"-heap")==0 ){
11608#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11609      const char *zSize;
11610      sqlite3_int64 szHeap;
11611
11612      zSize = cmdline_option_value(argc, argv, ++i);
11613      szHeap = integerValue(zSize);
11614      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
11615      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
11616#else
11617      (void)cmdline_option_value(argc, argv, ++i);
11618#endif
11619    }else if( cli_strcmp(z,"-pagecache")==0 ){
11620      sqlite3_int64 n, sz;
11621      sz = integerValue(cmdline_option_value(argc,argv,++i));
11622      if( sz>70000 ) sz = 70000;
11623      if( sz<0 ) sz = 0;
11624      n = integerValue(cmdline_option_value(argc,argv,++i));
11625      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
11626        n = 0xffffffffffffLL/sz;
11627      }
11628      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
11629                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
11630      data.shellFlgs |= SHFLG_Pagecache;
11631    }else if( cli_strcmp(z,"-lookaside")==0 ){
11632      int n, sz;
11633      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
11634      if( sz<0 ) sz = 0;
11635      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11636      if( n<0 ) n = 0;
11637      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
11638      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
11639    }else if( cli_strcmp(z,"-threadsafe")==0 ){
11640      int n;
11641      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
11642      switch( n ){
11643         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
11644         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
11645         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
11646      }
11647#ifdef SQLITE_ENABLE_VFSTRACE
11648    }else if( cli_strcmp(z,"-vfstrace")==0 ){
11649      extern int vfstrace_register(
11650         const char *zTraceName,
11651         const char *zOldVfsName,
11652         int (*xOut)(const char*,void*),
11653         void *pOutArg,
11654         int makeDefault
11655      );
11656      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
11657#endif
11658#ifdef SQLITE_ENABLE_MULTIPLEX
11659    }else if( cli_strcmp(z,"-multiplex")==0 ){
11660      extern int sqlite3_multiple_initialize(const char*,int);
11661      sqlite3_multiplex_initialize(0, 1);
11662#endif
11663    }else if( cli_strcmp(z,"-mmap")==0 ){
11664      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11665      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
11666#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11667    }else if( cli_strcmp(z,"-sorterref")==0 ){
11668      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
11669      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
11670#endif
11671    }else if( cli_strcmp(z,"-vfs")==0 ){
11672      zVfs = cmdline_option_value(argc, argv, ++i);
11673#ifdef SQLITE_HAVE_ZLIB
11674    }else if( cli_strcmp(z,"-zip")==0 ){
11675      data.openMode = SHELL_OPEN_ZIPFILE;
11676#endif
11677    }else if( cli_strcmp(z,"-append")==0 ){
11678      data.openMode = SHELL_OPEN_APPENDVFS;
11679#ifndef SQLITE_OMIT_DESERIALIZE
11680    }else if( cli_strcmp(z,"-deserialize")==0 ){
11681      data.openMode = SHELL_OPEN_DESERIALIZE;
11682    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
11683      data.szMax = integerValue(argv[++i]);
11684#endif
11685    }else if( cli_strcmp(z,"-readonly")==0 ){
11686      data.openMode = SHELL_OPEN_READONLY;
11687    }else if( cli_strcmp(z,"-nofollow")==0 ){
11688      data.openFlags = SQLITE_OPEN_NOFOLLOW;
11689#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11690    }else if( cli_strncmp(z, "-A",2)==0 ){
11691      /* All remaining command-line arguments are passed to the ".archive"
11692      ** command, so ignore them */
11693      break;
11694#endif
11695    }else if( cli_strcmp(z, "-memtrace")==0 ){
11696      sqlite3MemTraceActivate(stderr);
11697    }else if( cli_strcmp(z,"-bail")==0 ){
11698      bail_on_error = 1;
11699    }else if( cli_strcmp(z,"-nonce")==0 ){
11700      free(data.zNonce);
11701      data.zNonce = strdup(argv[++i]);
11702    }else if( cli_strcmp(z,"-safe")==0 ){
11703      /* no-op - catch this on the second pass */
11704    }
11705  }
11706  verify_uninitialized();
11707
11708
11709#ifdef SQLITE_SHELL_INIT_PROC
11710  {
11711    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
11712    ** of a C-function that will perform initialization actions on SQLite that
11713    ** occur just before or after sqlite3_initialize(). Use this compile-time
11714    ** option to embed this shell program in larger applications. */
11715    extern void SQLITE_SHELL_INIT_PROC(void);
11716    SQLITE_SHELL_INIT_PROC();
11717  }
11718#else
11719  /* All the sqlite3_config() calls have now been made. So it is safe
11720  ** to call sqlite3_initialize() and process any command line -vfs option. */
11721  sqlite3_initialize();
11722#endif
11723
11724  if( zVfs ){
11725    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
11726    if( pVfs ){
11727      sqlite3_vfs_register(pVfs, 1);
11728    }else{
11729      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
11730      exit(1);
11731    }
11732  }
11733
11734  if( data.pAuxDb->zDbFilename==0 ){
11735#ifndef SQLITE_OMIT_MEMORYDB
11736    data.pAuxDb->zDbFilename = ":memory:";
11737    warnInmemoryDb = argc==1;
11738#else
11739    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
11740    return 1;
11741#endif
11742  }
11743  data.out = stdout;
11744#ifndef SQLITE_SHELL_FIDDLE
11745  sqlite3_appendvfs_init(0,0,0);
11746#endif
11747
11748  /* Go ahead and open the database file if it already exists.  If the
11749  ** file does not exist, delay opening it.  This prevents empty database
11750  ** files from being created if a user mistypes the database name argument
11751  ** to the sqlite command-line tool.
11752  */
11753  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
11754    open_db(&data, 0);
11755  }
11756
11757  /* Process the initialization file if there is one.  If no -init option
11758  ** is given on the command line, look for a file named ~/.sqliterc and
11759  ** try to process it.
11760  */
11761  process_sqliterc(&data,zInitFile);
11762
11763  /* Make a second pass through the command-line argument and set
11764  ** options.  This second pass is delayed until after the initialization
11765  ** file is processed so that the command-line arguments will override
11766  ** settings in the initialization file.
11767  */
11768  for(i=1; i<argc; i++){
11769    char *z = argv[i];
11770    if( z[0]!='-' ) continue;
11771    if( z[1]=='-' ){ z++; }
11772    if( cli_strcmp(z,"-init")==0 ){
11773      i++;
11774    }else if( cli_strcmp(z,"-html")==0 ){
11775      data.mode = MODE_Html;
11776    }else if( cli_strcmp(z,"-list")==0 ){
11777      data.mode = MODE_List;
11778    }else if( cli_strcmp(z,"-quote")==0 ){
11779      data.mode = MODE_Quote;
11780      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
11781      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11782    }else if( cli_strcmp(z,"-line")==0 ){
11783      data.mode = MODE_Line;
11784    }else if( cli_strcmp(z,"-column")==0 ){
11785      data.mode = MODE_Column;
11786    }else if( cli_strcmp(z,"-json")==0 ){
11787      data.mode = MODE_Json;
11788    }else if( cli_strcmp(z,"-markdown")==0 ){
11789      data.mode = MODE_Markdown;
11790    }else if( cli_strcmp(z,"-table")==0 ){
11791      data.mode = MODE_Table;
11792    }else if( cli_strcmp(z,"-box")==0 ){
11793      data.mode = MODE_Box;
11794    }else if( cli_strcmp(z,"-csv")==0 ){
11795      data.mode = MODE_Csv;
11796      memcpy(data.colSeparator,",",2);
11797#ifdef SQLITE_HAVE_ZLIB
11798    }else if( cli_strcmp(z,"-zip")==0 ){
11799      data.openMode = SHELL_OPEN_ZIPFILE;
11800#endif
11801    }else if( cli_strcmp(z,"-append")==0 ){
11802      data.openMode = SHELL_OPEN_APPENDVFS;
11803#ifndef SQLITE_OMIT_DESERIALIZE
11804    }else if( cli_strcmp(z,"-deserialize")==0 ){
11805      data.openMode = SHELL_OPEN_DESERIALIZE;
11806    }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){
11807      data.szMax = integerValue(argv[++i]);
11808#endif
11809    }else if( cli_strcmp(z,"-readonly")==0 ){
11810      data.openMode = SHELL_OPEN_READONLY;
11811    }else if( cli_strcmp(z,"-nofollow")==0 ){
11812      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
11813    }else if( cli_strcmp(z,"-ascii")==0 ){
11814      data.mode = MODE_Ascii;
11815      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
11816      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
11817    }else if( cli_strcmp(z,"-tabs")==0 ){
11818      data.mode = MODE_List;
11819      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
11820      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
11821    }else if( cli_strcmp(z,"-separator")==0 ){
11822      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
11823                       "%s",cmdline_option_value(argc,argv,++i));
11824    }else if( cli_strcmp(z,"-newline")==0 ){
11825      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
11826                       "%s",cmdline_option_value(argc,argv,++i));
11827    }else if( cli_strcmp(z,"-nullvalue")==0 ){
11828      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
11829                       "%s",cmdline_option_value(argc,argv,++i));
11830    }else if( cli_strcmp(z,"-header")==0 ){
11831      data.showHeader = 1;
11832      ShellSetFlag(&data, SHFLG_HeaderSet);
11833     }else if( cli_strcmp(z,"-noheader")==0 ){
11834      data.showHeader = 0;
11835      ShellSetFlag(&data, SHFLG_HeaderSet);
11836    }else if( cli_strcmp(z,"-echo")==0 ){
11837      ShellSetFlag(&data, SHFLG_Echo);
11838    }else if( cli_strcmp(z,"-eqp")==0 ){
11839      data.autoEQP = AUTOEQP_on;
11840    }else if( cli_strcmp(z,"-eqpfull")==0 ){
11841      data.autoEQP = AUTOEQP_full;
11842    }else if( cli_strcmp(z,"-stats")==0 ){
11843      data.statsOn = 1;
11844    }else if( cli_strcmp(z,"-scanstats")==0 ){
11845      data.scanstatsOn = 1;
11846    }else if( cli_strcmp(z,"-backslash")==0 ){
11847      /* Undocumented command-line option: -backslash
11848      ** Causes C-style backslash escapes to be evaluated in SQL statements
11849      ** prior to sending the SQL into SQLite.  Useful for injecting
11850      ** crazy bytes in the middle of SQL statements for testing and debugging.
11851      */
11852      ShellSetFlag(&data, SHFLG_Backslash);
11853    }else if( cli_strcmp(z,"-bail")==0 ){
11854      /* No-op.  The bail_on_error flag should already be set. */
11855    }else if( cli_strcmp(z,"-version")==0 ){
11856      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
11857      return 0;
11858    }else if( cli_strcmp(z,"-interactive")==0 ){
11859      stdin_is_interactive = 1;
11860    }else if( cli_strcmp(z,"-batch")==0 ){
11861      stdin_is_interactive = 0;
11862    }else if( cli_strcmp(z,"-heap")==0 ){
11863      i++;
11864    }else if( cli_strcmp(z,"-pagecache")==0 ){
11865      i+=2;
11866    }else if( cli_strcmp(z,"-lookaside")==0 ){
11867      i+=2;
11868    }else if( cli_strcmp(z,"-threadsafe")==0 ){
11869      i+=2;
11870    }else if( cli_strcmp(z,"-nonce")==0 ){
11871      i += 2;
11872    }else if( cli_strcmp(z,"-mmap")==0 ){
11873      i++;
11874    }else if( cli_strcmp(z,"-memtrace")==0 ){
11875      i++;
11876#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11877    }else if( cli_strcmp(z,"-sorterref")==0 ){
11878      i++;
11879#endif
11880    }else if( cli_strcmp(z,"-vfs")==0 ){
11881      i++;
11882#ifdef SQLITE_ENABLE_VFSTRACE
11883    }else if( cli_strcmp(z,"-vfstrace")==0 ){
11884      i++;
11885#endif
11886#ifdef SQLITE_ENABLE_MULTIPLEX
11887    }else if( cli_strcmp(z,"-multiplex")==0 ){
11888      i++;
11889#endif
11890    }else if( cli_strcmp(z,"-help")==0 ){
11891      usage(1);
11892    }else if( cli_strcmp(z,"-cmd")==0 ){
11893      /* Run commands that follow -cmd first and separately from commands
11894      ** that simply appear on the command-line.  This seems goofy.  It would
11895      ** be better if all commands ran in the order that they appear.  But
11896      ** we retain the goofy behavior for historical compatibility. */
11897      if( i==argc-1 ) break;
11898      z = cmdline_option_value(argc,argv,++i);
11899      if( z[0]=='.' ){
11900        rc = do_meta_command(z, &data);
11901        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
11902      }else{
11903        open_db(&data, 0);
11904        rc = shell_exec(&data, z, &zErrMsg);
11905        if( zErrMsg!=0 ){
11906          utf8_printf(stderr,"Error: %s\n", zErrMsg);
11907          if( bail_on_error ) return rc!=0 ? rc : 1;
11908        }else if( rc!=0 ){
11909          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
11910          if( bail_on_error ) return rc;
11911        }
11912      }
11913#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
11914    }else if( cli_strncmp(z, "-A", 2)==0 ){
11915      if( nCmd>0 ){
11916        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
11917                            " with \"%s\"\n", z);
11918        return 1;
11919      }
11920      open_db(&data, OPEN_DB_ZIPFILE);
11921      if( z[2] ){
11922        argv[i] = &z[2];
11923        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
11924      }else{
11925        arDotCommand(&data, 1, argv+i, argc-i);
11926      }
11927      readStdin = 0;
11928      break;
11929#endif
11930    }else if( cli_strcmp(z,"-safe")==0 ){
11931      data.bSafeMode = data.bSafeModePersist = 1;
11932    }else{
11933      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
11934      raw_printf(stderr,"Use -help for a list of options.\n");
11935      return 1;
11936    }
11937    data.cMode = data.mode;
11938  }
11939
11940  if( !readStdin ){
11941    /* Run all arguments that do not begin with '-' as if they were separate
11942    ** command-line inputs, except for the argToSkip argument which contains
11943    ** the database filename.
11944    */
11945    for(i=0; i<nCmd; i++){
11946      if( azCmd[i][0]=='.' ){
11947        rc = do_meta_command(azCmd[i], &data);
11948        if( rc ){
11949          free(azCmd);
11950          return rc==2 ? 0 : rc;
11951        }
11952      }else{
11953        open_db(&data, 0);
11954        rc = shell_exec(&data, azCmd[i], &zErrMsg);
11955        if( zErrMsg || rc ){
11956          if( zErrMsg!=0 ){
11957            utf8_printf(stderr,"Error: %s\n", zErrMsg);
11958          }else{
11959            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
11960          }
11961          sqlite3_free(zErrMsg);
11962          free(azCmd);
11963          return rc!=0 ? rc : 1;
11964        }
11965      }
11966    }
11967  }else{
11968    /* Run commands received from standard input
11969    */
11970    if( stdin_is_interactive ){
11971      char *zHome;
11972      char *zHistory;
11973      int nHistory;
11974      printf(
11975        "SQLite version %s %.19s\n" /*extra-version-info*/
11976        "Enter \".help\" for usage hints.\n",
11977        sqlite3_libversion(), sqlite3_sourceid()
11978      );
11979      if( warnInmemoryDb ){
11980        printf("Connected to a ");
11981        printBold("transient in-memory database");
11982        printf(".\nUse \".open FILENAME\" to reopen on a "
11983               "persistent database.\n");
11984      }
11985      zHistory = getenv("SQLITE_HISTORY");
11986      if( zHistory ){
11987        zHistory = strdup(zHistory);
11988      }else if( (zHome = find_home_dir(0))!=0 ){
11989        nHistory = strlen30(zHome) + 20;
11990        if( (zHistory = malloc(nHistory))!=0 ){
11991          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
11992        }
11993      }
11994      if( zHistory ){ shell_read_history(zHistory); }
11995#if HAVE_READLINE || HAVE_EDITLINE
11996      rl_attempted_completion_function = readline_completion;
11997#elif HAVE_LINENOISE
11998      linenoiseSetCompletionCallback(linenoise_completion);
11999#endif
12000      data.in = 0;
12001      rc = process_input(&data);
12002      if( zHistory ){
12003        shell_stifle_history(2000);
12004        shell_write_history(zHistory);
12005        free(zHistory);
12006      }
12007    }else{
12008      data.in = stdin;
12009      rc = process_input(&data);
12010    }
12011  }
12012#ifndef SQLITE_SHELL_FIDDLE
12013  /* In WASM mode we have to leave the db state in place so that
12014  ** client code can "push" SQL into it after this call returns. */
12015  free(azCmd);
12016  set_table_name(&data, 0);
12017  if( data.db ){
12018    session_close_all(&data, -1);
12019    close_db(data.db);
12020  }
12021  for(i=0; i<ArraySize(data.aAuxDb); i++){
12022    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12023    if( data.aAuxDb[i].db ){
12024      session_close_all(&data, i);
12025      close_db(data.aAuxDb[i].db);
12026    }
12027  }
12028  find_home_dir(1);
12029  output_reset(&data);
12030  data.doXdgOpen = 0;
12031  clearTempFile(&data);
12032#if !SQLITE_SHELL_IS_UTF8
12033  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12034  free(argvToFree);
12035#endif
12036  free(data.colWidth);
12037  free(data.zNonce);
12038  /* Clear the global data structure so that valgrind will detect memory
12039  ** leaks */
12040  memset(&data, 0, sizeof(data));
12041#ifdef SQLITE_DEBUG
12042  if( sqlite3_memory_used()>mem_main_enter ){
12043    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12044                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12045  }
12046#endif
12047#endif /* !SQLITE_SHELL_FIDDLE */
12048  return rc;
12049}
12050
12051
12052#ifdef SQLITE_SHELL_FIDDLE
12053/* Only for emcc experimentation purposes. */
12054int fiddle_experiment(int a,int b){
12055  return a + b;
12056}
12057
12058/*
12059** Returns a pointer to the current DB handle.
12060*/
12061sqlite3 * fiddle_db_handle(){
12062  return globalDb;
12063}
12064
12065/*
12066** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12067** "main" is assumed. Returns 0 if no db with the given name is
12068** open.
12069*/
12070sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12071  sqlite3_vfs * pVfs = 0;
12072  if(globalDb){
12073    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12074                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
12075  }
12076  return pVfs;
12077}
12078
12079/* Only for emcc experimentation purposes. */
12080sqlite3 * fiddle_db_arg(sqlite3 *arg){
12081    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12082    return arg;
12083}
12084
12085/*
12086** Intended to be called via a SharedWorker() while a separate
12087** SharedWorker() (which manages the wasm module) is performing work
12088** which should be interrupted. Unfortunately, SharedWorker is not
12089** portable enough to make real use of.
12090*/
12091void fiddle_interrupt(void){
12092  if( globalDb ) sqlite3_interrupt(globalDb);
12093}
12094
12095/*
12096** Returns the filename of the given db name, assuming "main" if
12097** zDbName is NULL. Returns NULL if globalDb is not opened.
12098*/
12099const char * fiddle_db_filename(const char * zDbName){
12100    return globalDb
12101      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12102      : NULL;
12103}
12104
12105/*
12106** Completely wipes out the contents of the currently-opened database
12107** but leaves its storage intact for reuse.
12108*/
12109void fiddle_reset_db(void){
12110  if( globalDb ){
12111    int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12112    if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12113    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12114  }
12115}
12116
12117/*
12118** Uses the current database's VFS xRead to stream the db file's
12119** contents out to the given callback. The callback gets a single
12120** chunk of size n (its 2nd argument) on each call and must return 0
12121** on success, non-0 on error. This function returns 0 on success,
12122** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12123** code from the callback. Note that this is not thread-friendly: it
12124** expects that it will be the only thread reading the db file and
12125** takes no measures to ensure that is the case.
12126*/
12127int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12128  sqlite3_int64 nSize = 0;
12129  sqlite3_int64 nPos = 0;
12130  sqlite3_file * pFile = 0;
12131  unsigned char buf[1024 * 8];
12132  int nBuf = (int)sizeof(buf);
12133  int rc = shellState.db
12134    ? sqlite3_file_control(shellState.db, "main",
12135                           SQLITE_FCNTL_FILE_POINTER, &pFile)
12136    : SQLITE_NOTFOUND;
12137  if( rc ) return rc;
12138  rc = pFile->pMethods->xFileSize(pFile, &nSize);
12139  if( rc ) return rc;
12140  if(nSize % nBuf){
12141    /* DB size is not an even multiple of the buffer size. Reduce
12142    ** buffer size so that we do not unduly inflate the db size when
12143    ** exporting. */
12144    if(0 == nSize % 4096) nBuf = 4096;
12145    else if(0 == nSize % 2048) nBuf = 2048;
12146    else if(0 == nSize % 1024) nBuf = 1024;
12147    else nBuf = 512;
12148  }
12149  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12150    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12151    if(SQLITE_IOERR_SHORT_READ == rc){
12152      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12153    }
12154    if( 0==rc ) rc = xCallback(buf, nBuf);
12155  }
12156  return rc;
12157}
12158
12159/*
12160** Trivial exportable function for emscripten. It processes zSql as if
12161** it were input to the sqlite3 shell and redirects all output to the
12162** wasm binding. fiddle_main() must have been called before this
12163** is called, or results are undefined.
12164*/
12165void fiddle_exec(const char * zSql){
12166  if(zSql && *zSql){
12167    if('.'==*zSql) puts(zSql);
12168    shellState.wasm.zInput = zSql;
12169    shellState.wasm.zPos = zSql;
12170    process_input(&shellState);
12171    shellState.wasm.zInput = shellState.wasm.zPos = 0;
12172  }
12173}
12174#endif /* SQLITE_SHELL_FIDDLE */
12175