xref: /sqlite-3.40.0/src/shell.c.in (revision 181f7e86)
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/* Return the current wall-clock time */
253static sqlite3_int64 timeOfDay(void){
254  static sqlite3_vfs *clockVfs = 0;
255  sqlite3_int64 t;
256  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
257  if( clockVfs==0 ) return 0;  /* Never actually happens */
258  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
259    clockVfs->xCurrentTimeInt64(clockVfs, &t);
260  }else{
261    double r;
262    clockVfs->xCurrentTime(clockVfs, &r);
263    t = (sqlite3_int64)(r*86400000.0);
264  }
265  return t;
266}
267
268#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
269#include <sys/time.h>
270#include <sys/resource.h>
271
272/* VxWorks does not support getrusage() as far as we can determine */
273#if defined(_WRS_KERNEL) || defined(__RTP__)
274struct rusage {
275  struct timeval ru_utime; /* user CPU time used */
276  struct timeval ru_stime; /* system CPU time used */
277};
278#define getrusage(A,B) memset(B,0,sizeof(*B))
279#endif
280
281/* Saved resource information for the beginning of an operation */
282static struct rusage sBegin;  /* CPU time at start */
283static sqlite3_int64 iBegin;  /* Wall-clock time at start */
284
285/*
286** Begin timing an operation
287*/
288static void beginTimer(void){
289  if( enableTimer ){
290    getrusage(RUSAGE_SELF, &sBegin);
291    iBegin = timeOfDay();
292  }
293}
294
295/* Return the difference of two time_structs in seconds */
296static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
297  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
298         (double)(pEnd->tv_sec - pStart->tv_sec);
299}
300
301/*
302** Print the timing results.
303*/
304static void endTimer(void){
305  if( enableTimer ){
306    sqlite3_int64 iEnd = timeOfDay();
307    struct rusage sEnd;
308    getrusage(RUSAGE_SELF, &sEnd);
309    printf("Run Time: real %.3f user %f sys %f\n",
310       (iEnd - iBegin)*0.001,
311       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
312       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
313  }
314}
315
316#define BEGIN_TIMER beginTimer()
317#define END_TIMER endTimer()
318#define HAS_TIMER 1
319
320#elif (defined(_WIN32) || defined(WIN32))
321
322/* Saved resource information for the beginning of an operation */
323static HANDLE hProcess;
324static FILETIME ftKernelBegin;
325static FILETIME ftUserBegin;
326static sqlite3_int64 ftWallBegin;
327typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
328                                    LPFILETIME, LPFILETIME);
329static GETPROCTIMES getProcessTimesAddr = NULL;
330
331/*
332** Check to see if we have timer support.  Return 1 if necessary
333** support found (or found previously).
334*/
335static int hasTimer(void){
336  if( getProcessTimesAddr ){
337    return 1;
338  } else {
339#if !SQLITE_OS_WINRT
340    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
341    ** versions. See if the version we are running on has it, and if it
342    ** does, save off a pointer to it and the current process handle.
343    */
344    hProcess = GetCurrentProcess();
345    if( hProcess ){
346      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
347      if( NULL != hinstLib ){
348        getProcessTimesAddr =
349            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
350        if( NULL != getProcessTimesAddr ){
351          return 1;
352        }
353        FreeLibrary(hinstLib);
354      }
355    }
356#endif
357  }
358  return 0;
359}
360
361/*
362** Begin timing an operation
363*/
364static void beginTimer(void){
365  if( enableTimer && getProcessTimesAddr ){
366    FILETIME ftCreation, ftExit;
367    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
368                        &ftKernelBegin,&ftUserBegin);
369    ftWallBegin = timeOfDay();
370  }
371}
372
373/* Return the difference of two FILETIME structs in seconds */
374static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
375  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
376  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
377  return (double) ((i64End - i64Start) / 10000000.0);
378}
379
380/*
381** Print the timing results.
382*/
383static void endTimer(void){
384  if( enableTimer && getProcessTimesAddr){
385    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
386    sqlite3_int64 ftWallEnd = timeOfDay();
387    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
388    printf("Run Time: real %.3f user %f sys %f\n",
389       (ftWallEnd - ftWallBegin)*0.001,
390       timeDiff(&ftUserBegin, &ftUserEnd),
391       timeDiff(&ftKernelBegin, &ftKernelEnd));
392  }
393}
394
395#define BEGIN_TIMER beginTimer()
396#define END_TIMER endTimer()
397#define HAS_TIMER hasTimer()
398
399#else
400#define BEGIN_TIMER
401#define END_TIMER
402#define HAS_TIMER 0
403#endif
404
405/*
406** Used to prevent warnings about unused parameters
407*/
408#define UNUSED_PARAMETER(x) (void)(x)
409
410/*
411** Number of elements in an array
412*/
413#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
414
415/*
416** If the following flag is set, then command execution stops
417** at an error if we are not interactive.
418*/
419static int bail_on_error = 0;
420
421/*
422** Threat stdin as an interactive input if the following variable
423** is true.  Otherwise, assume stdin is connected to a file or pipe.
424*/
425static int stdin_is_interactive = 1;
426
427/*
428** On Windows systems we have to know if standard output is a console
429** in order to translate UTF-8 into MBCS.  The following variable is
430** true if translation is required.
431*/
432static int stdout_is_console = 1;
433
434/*
435** The following is the open SQLite database.  We make a pointer
436** to this database a static variable so that it can be accessed
437** by the SIGINT handler to interrupt database processing.
438*/
439static sqlite3 *globalDb = 0;
440
441/*
442** True if an interrupt (Control-C) has been received.
443*/
444static volatile int seenInterrupt = 0;
445
446/*
447** This is the name of our program. It is set in main(), used
448** in a number of other places, mostly for error messages.
449*/
450static char *Argv0;
451
452/*
453** Prompt strings. Initialized in main. Settable with
454**   .prompt main continue
455*/
456static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
457static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
458
459/*
460** Render output like fprintf().  Except, if the output is going to the
461** console and if this is running on a Windows machine, translate the
462** output from UTF-8 into MBCS.
463*/
464#if defined(_WIN32) || defined(WIN32)
465void utf8_printf(FILE *out, const char *zFormat, ...){
466  va_list ap;
467  va_start(ap, zFormat);
468  if( stdout_is_console && (out==stdout || out==stderr) ){
469    char *z1 = sqlite3_vmprintf(zFormat, ap);
470    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
471    sqlite3_free(z1);
472    fputs(z2, out);
473    sqlite3_free(z2);
474  }else{
475    vfprintf(out, zFormat, ap);
476  }
477  va_end(ap);
478}
479#elif !defined(utf8_printf)
480# define utf8_printf fprintf
481#endif
482
483/*
484** Render output like fprintf().  This should not be used on anything that
485** includes string formatting (e.g. "%s").
486*/
487#if !defined(raw_printf)
488# define raw_printf fprintf
489#endif
490
491/* Indicate out-of-memory and exit. */
492static void shell_out_of_memory(void){
493  raw_printf(stderr,"Error: out of memory\n");
494  exit(1);
495}
496
497/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
498** out-of-memory error.
499*/
500static void shell_check_oom(void *p){
501  if( p==0 ) shell_out_of_memory();
502}
503
504/*
505** Write I/O traces to the following stream.
506*/
507#ifdef SQLITE_ENABLE_IOTRACE
508static FILE *iotrace = 0;
509#endif
510
511/*
512** This routine works like printf in that its first argument is a
513** format string and subsequent arguments are values to be substituted
514** in place of % fields.  The result of formatting this string
515** is written to iotrace.
516*/
517#ifdef SQLITE_ENABLE_IOTRACE
518static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
519  va_list ap;
520  char *z;
521  if( iotrace==0 ) return;
522  va_start(ap, zFormat);
523  z = sqlite3_vmprintf(zFormat, ap);
524  va_end(ap);
525  utf8_printf(iotrace, "%s", z);
526  sqlite3_free(z);
527}
528#endif
529
530/*
531** Output string zUtf to stream pOut as w characters.  If w is negative,
532** then right-justify the text.  W is the width in UTF-8 characters, not
533** in bytes.  This is different from the %*.*s specification in printf
534** since with %*.*s the width is measured in bytes, not characters.
535*/
536static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
537  int i;
538  int n;
539  int aw = w<0 ? -w : w;
540  for(i=n=0; zUtf[i]; i++){
541    if( (zUtf[i]&0xc0)!=0x80 ){
542      n++;
543      if( n==aw ){
544        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
545        break;
546      }
547    }
548  }
549  if( n>=aw ){
550    utf8_printf(pOut, "%.*s", i, zUtf);
551  }else if( w<0 ){
552    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
553  }else{
554    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
555  }
556}
557
558
559/*
560** Determines if a string is a number of not.
561*/
562static int isNumber(const char *z, int *realnum){
563  if( *z=='-' || *z=='+' ) z++;
564  if( !IsDigit(*z) ){
565    return 0;
566  }
567  z++;
568  if( realnum ) *realnum = 0;
569  while( IsDigit(*z) ){ z++; }
570  if( *z=='.' ){
571    z++;
572    if( !IsDigit(*z) ) return 0;
573    while( IsDigit(*z) ){ z++; }
574    if( realnum ) *realnum = 1;
575  }
576  if( *z=='e' || *z=='E' ){
577    z++;
578    if( *z=='+' || *z=='-' ) z++;
579    if( !IsDigit(*z) ) return 0;
580    while( IsDigit(*z) ){ z++; }
581    if( realnum ) *realnum = 1;
582  }
583  return *z==0;
584}
585
586/*
587** Compute a string length that is limited to what can be stored in
588** lower 30 bits of a 32-bit signed integer.
589*/
590static int strlen30(const char *z){
591  const char *z2 = z;
592  while( *z2 ){ z2++; }
593  return 0x3fffffff & (int)(z2 - z);
594}
595
596/*
597** Return the length of a string in characters.  Multibyte UTF8 characters
598** count as a single character.
599*/
600static int strlenChar(const char *z){
601  int n = 0;
602  while( *z ){
603    if( (0xc0&*(z++))!=0x80 ) n++;
604  }
605  return n;
606}
607
608/*
609** Return open FILE * if zFile exists, can be opened for read
610** and is an ordinary file or a character stream source.
611** Otherwise return 0.
612*/
613static FILE * openChrSource(const char *zFile){
614#ifdef _WIN32
615  struct _stat x = {0};
616# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
617  /* On Windows, open first, then check the stream nature. This order
618  ** is necessary because _stat() and sibs, when checking a named pipe,
619  ** effectively break the pipe as its supplier sees it. */
620  FILE *rv = fopen(zFile, "rb");
621  if( rv==0 ) return 0;
622  if( _fstat(_fileno(rv), &x) != 0
623      || !STAT_CHR_SRC(x.st_mode)){
624    fclose(rv);
625    rv = 0;
626  }
627  return rv;
628#else
629  struct stat x = {0};
630  int rc = stat(zFile, &x);
631# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
632  if( rc!=0 ) return 0;
633  if( STAT_CHR_SRC(x.st_mode) ){
634    return fopen(zFile, "rb");
635  }else{
636    return 0;
637  }
638#endif
639#undef STAT_CHR_SRC
640}
641
642/*
643** This routine reads a line of text from FILE in, stores
644** the text in memory obtained from malloc() and returns a pointer
645** to the text.  NULL is returned at end of file, or if malloc()
646** fails.
647**
648** If zLine is not NULL then it is a malloced buffer returned from
649** a previous call to this routine that may be reused.
650*/
651static char *local_getline(char *zLine, FILE *in){
652  int nLine = zLine==0 ? 0 : 100;
653  int n = 0;
654
655  while( 1 ){
656    if( n+100>nLine ){
657      nLine = nLine*2 + 100;
658      zLine = realloc(zLine, nLine);
659      shell_check_oom(zLine);
660    }
661    if( fgets(&zLine[n], nLine - n, in)==0 ){
662      if( n==0 ){
663        free(zLine);
664        return 0;
665      }
666      zLine[n] = 0;
667      break;
668    }
669    while( zLine[n] ) n++;
670    if( n>0 && zLine[n-1]=='\n' ){
671      n--;
672      if( n>0 && zLine[n-1]=='\r' ) n--;
673      zLine[n] = 0;
674      break;
675    }
676  }
677#if defined(_WIN32) || defined(WIN32)
678  /* For interactive input on Windows systems, translate the
679  ** multi-byte characterset characters into UTF-8. */
680  if( stdin_is_interactive && in==stdin ){
681    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
682    if( zTrans ){
683      int nTrans = strlen30(zTrans)+1;
684      if( nTrans>nLine ){
685        zLine = realloc(zLine, nTrans);
686        shell_check_oom(zLine);
687      }
688      memcpy(zLine, zTrans, nTrans);
689      sqlite3_free(zTrans);
690    }
691  }
692#endif /* defined(_WIN32) || defined(WIN32) */
693  return zLine;
694}
695
696/*
697** Retrieve a single line of input text.
698**
699** If in==0 then read from standard input and prompt before each line.
700** If isContinuation is true, then a continuation prompt is appropriate.
701** If isContinuation is zero, then the main prompt should be used.
702**
703** If zPrior is not NULL then it is a buffer from a prior call to this
704** routine that can be reused.
705**
706** The result is stored in space obtained from malloc() and must either
707** be freed by the caller or else passed back into this routine via the
708** zPrior argument for reuse.
709*/
710#ifndef SQLITE_SHELL_FIDDLE
711static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
712  char *zPrompt;
713  char *zResult;
714  if( in!=0 ){
715    zResult = local_getline(zPrior, in);
716  }else{
717    zPrompt = isContinuation ? continuePrompt : mainPrompt;
718#if SHELL_USE_LOCAL_GETLINE
719    printf("%s", zPrompt);
720    fflush(stdout);
721    zResult = local_getline(zPrior, stdin);
722#else
723    free(zPrior);
724    zResult = shell_readline(zPrompt);
725    if( zResult && *zResult ) shell_add_history(zResult);
726#endif
727  }
728  return zResult;
729}
730#endif /* !SQLITE_SHELL_FIDDLE */
731
732/*
733** Return the value of a hexadecimal digit.  Return -1 if the input
734** is not a hex digit.
735*/
736static int hexDigitValue(char c){
737  if( c>='0' && c<='9' ) return c - '0';
738  if( c>='a' && c<='f' ) return c - 'a' + 10;
739  if( c>='A' && c<='F' ) return c - 'A' + 10;
740  return -1;
741}
742
743/*
744** Interpret zArg as an integer value, possibly with suffixes.
745*/
746static sqlite3_int64 integerValue(const char *zArg){
747  sqlite3_int64 v = 0;
748  static const struct { char *zSuffix; int iMult; } aMult[] = {
749    { "KiB", 1024 },
750    { "MiB", 1024*1024 },
751    { "GiB", 1024*1024*1024 },
752    { "KB",  1000 },
753    { "MB",  1000000 },
754    { "GB",  1000000000 },
755    { "K",   1000 },
756    { "M",   1000000 },
757    { "G",   1000000000 },
758  };
759  int i;
760  int isNeg = 0;
761  if( zArg[0]=='-' ){
762    isNeg = 1;
763    zArg++;
764  }else if( zArg[0]=='+' ){
765    zArg++;
766  }
767  if( zArg[0]=='0' && zArg[1]=='x' ){
768    int x;
769    zArg += 2;
770    while( (x = hexDigitValue(zArg[0]))>=0 ){
771      v = (v<<4) + x;
772      zArg++;
773    }
774  }else{
775    while( IsDigit(zArg[0]) ){
776      v = v*10 + zArg[0] - '0';
777      zArg++;
778    }
779  }
780  for(i=0; i<ArraySize(aMult); i++){
781    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
782      v *= aMult[i].iMult;
783      break;
784    }
785  }
786  return isNeg? -v : v;
787}
788
789/*
790** A variable length string to which one can append text.
791*/
792typedef struct ShellText ShellText;
793struct ShellText {
794  char *z;
795  int n;
796  int nAlloc;
797};
798
799/*
800** Initialize and destroy a ShellText object
801*/
802static void initText(ShellText *p){
803  memset(p, 0, sizeof(*p));
804}
805static void freeText(ShellText *p){
806  free(p->z);
807  initText(p);
808}
809
810/* zIn is either a pointer to a NULL-terminated string in memory obtained
811** from malloc(), or a NULL pointer. The string pointed to by zAppend is
812** added to zIn, and the result returned in memory obtained from malloc().
813** zIn, if it was not NULL, is freed.
814**
815** If the third argument, quote, is not '\0', then it is used as a
816** quote character for zAppend.
817*/
818static void appendText(ShellText *p, const char *zAppend, char quote){
819  int len;
820  int i;
821  int nAppend = strlen30(zAppend);
822
823  len = nAppend+p->n+1;
824  if( quote ){
825    len += 2;
826    for(i=0; i<nAppend; i++){
827      if( zAppend[i]==quote ) len++;
828    }
829  }
830
831  if( p->z==0 || p->n+len>=p->nAlloc ){
832    p->nAlloc = p->nAlloc*2 + len + 20;
833    p->z = realloc(p->z, p->nAlloc);
834    shell_check_oom(p->z);
835  }
836
837  if( quote ){
838    char *zCsr = p->z+p->n;
839    *zCsr++ = quote;
840    for(i=0; i<nAppend; i++){
841      *zCsr++ = zAppend[i];
842      if( zAppend[i]==quote ) *zCsr++ = quote;
843    }
844    *zCsr++ = quote;
845    p->n = (int)(zCsr - p->z);
846    *zCsr = '\0';
847  }else{
848    memcpy(p->z+p->n, zAppend, nAppend);
849    p->n += nAppend;
850    p->z[p->n] = '\0';
851  }
852}
853
854/*
855** Attempt to determine if identifier zName needs to be quoted, either
856** because it contains non-alphanumeric characters, or because it is an
857** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
858** that quoting is required.
859**
860** Return '"' if quoting is required.  Return 0 if no quoting is required.
861*/
862static char quoteChar(const char *zName){
863  int i;
864  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
865  for(i=0; zName[i]; i++){
866    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
867  }
868  return sqlite3_keyword_check(zName, i) ? '"' : 0;
869}
870
871/*
872** Construct a fake object name and column list to describe the structure
873** of the view, virtual table, or table valued function zSchema.zName.
874*/
875static char *shellFakeSchema(
876  sqlite3 *db,            /* The database connection containing the vtab */
877  const char *zSchema,    /* Schema of the database holding the vtab */
878  const char *zName       /* The name of the virtual table */
879){
880  sqlite3_stmt *pStmt = 0;
881  char *zSql;
882  ShellText s;
883  char cQuote;
884  char *zDiv = "(";
885  int nRow = 0;
886
887  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
888                         zSchema ? zSchema : "main", zName);
889  shell_check_oom(zSql);
890  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
891  sqlite3_free(zSql);
892  initText(&s);
893  if( zSchema ){
894    cQuote = quoteChar(zSchema);
895    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
896    appendText(&s, zSchema, cQuote);
897    appendText(&s, ".", 0);
898  }
899  cQuote = quoteChar(zName);
900  appendText(&s, zName, cQuote);
901  while( sqlite3_step(pStmt)==SQLITE_ROW ){
902    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
903    nRow++;
904    appendText(&s, zDiv, 0);
905    zDiv = ",";
906    if( zCol==0 ) zCol = "";
907    cQuote = quoteChar(zCol);
908    appendText(&s, zCol, cQuote);
909  }
910  appendText(&s, ")", 0);
911  sqlite3_finalize(pStmt);
912  if( nRow==0 ){
913    freeText(&s);
914    s.z = 0;
915  }
916  return s.z;
917}
918
919/*
920** SQL function:  shell_module_schema(X)
921**
922** Return a fake schema for the table-valued function or eponymous virtual
923** table X.
924*/
925static void shellModuleSchema(
926  sqlite3_context *pCtx,
927  int nVal,
928  sqlite3_value **apVal
929){
930  const char *zName;
931  char *zFake;
932  UNUSED_PARAMETER(nVal);
933  zName = (const char*)sqlite3_value_text(apVal[0]);
934  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
935  if( zFake ){
936    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
937                        -1, sqlite3_free);
938    free(zFake);
939  }
940}
941
942/*
943** SQL function:  shell_add_schema(S,X)
944**
945** Add the schema name X to the CREATE statement in S and return the result.
946** Examples:
947**
948**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
949**
950** Also works on
951**
952**    CREATE INDEX
953**    CREATE UNIQUE INDEX
954**    CREATE VIEW
955**    CREATE TRIGGER
956**    CREATE VIRTUAL TABLE
957**
958** This UDF is used by the .schema command to insert the schema name of
959** attached databases into the middle of the sqlite_schema.sql field.
960*/
961static void shellAddSchemaName(
962  sqlite3_context *pCtx,
963  int nVal,
964  sqlite3_value **apVal
965){
966  static const char *aPrefix[] = {
967     "TABLE",
968     "INDEX",
969     "UNIQUE INDEX",
970     "VIEW",
971     "TRIGGER",
972     "VIRTUAL TABLE"
973  };
974  int i = 0;
975  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
976  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
977  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
978  sqlite3 *db = sqlite3_context_db_handle(pCtx);
979  UNUSED_PARAMETER(nVal);
980  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
981    for(i=0; i<ArraySize(aPrefix); i++){
982      int n = strlen30(aPrefix[i]);
983      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
984        char *z = 0;
985        char *zFake = 0;
986        if( zSchema ){
987          char cQuote = quoteChar(zSchema);
988          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
989            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
990          }else{
991            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
992          }
993        }
994        if( zName
995         && aPrefix[i][0]=='V'
996         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
997        ){
998          if( z==0 ){
999            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
1000          }else{
1001            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
1002          }
1003          free(zFake);
1004        }
1005        if( z ){
1006          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1007          return;
1008        }
1009      }
1010    }
1011  }
1012  sqlite3_result_value(pCtx, apVal[0]);
1013}
1014
1015/*
1016** The source code for several run-time loadable extensions is inserted
1017** below by the ../tool/mkshellc.tcl script.  Before processing that included
1018** code, we need to override some macros to make the included program code
1019** work here in the middle of this regular program.
1020*/
1021#define SQLITE_EXTENSION_INIT1
1022#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1023
1024#if defined(_WIN32) && defined(_MSC_VER)
1025INCLUDE test_windirent.h
1026INCLUDE test_windirent.c
1027#define dirent DIRENT
1028#endif
1029INCLUDE ../ext/misc/memtrace.c
1030INCLUDE ../ext/misc/shathree.c
1031INCLUDE ../ext/misc/uint.c
1032INCLUDE ../ext/misc/decimal.c
1033INCLUDE ../ext/misc/ieee754.c
1034INCLUDE ../ext/misc/series.c
1035INCLUDE ../ext/misc/regexp.c
1036#ifndef SQLITE_SHELL_FIDDLE
1037INCLUDE ../ext/misc/fileio.c
1038INCLUDE ../ext/misc/completion.c
1039INCLUDE ../ext/misc/appendvfs.c
1040#endif
1041#ifdef SQLITE_HAVE_ZLIB
1042INCLUDE ../ext/misc/zipfile.c
1043INCLUDE ../ext/misc/sqlar.c
1044#endif
1045INCLUDE ../ext/expert/sqlite3expert.h
1046INCLUDE ../ext/expert/sqlite3expert.c
1047
1048#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1049INCLUDE ../ext/misc/dbdata.c
1050#endif
1051
1052#if defined(SQLITE_ENABLE_SESSION)
1053/*
1054** State information for a single open session
1055*/
1056typedef struct OpenSession OpenSession;
1057struct OpenSession {
1058  char *zName;             /* Symbolic name for this session */
1059  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1060  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1061  sqlite3_session *p;      /* The open session */
1062};
1063#endif
1064
1065typedef struct ExpertInfo ExpertInfo;
1066struct ExpertInfo {
1067  sqlite3expert *pExpert;
1068  int bVerbose;
1069};
1070
1071/* A single line in the EQP output */
1072typedef struct EQPGraphRow EQPGraphRow;
1073struct EQPGraphRow {
1074  int iEqpId;           /* ID for this row */
1075  int iParentId;        /* ID of the parent row */
1076  EQPGraphRow *pNext;   /* Next row in sequence */
1077  char zText[1];        /* Text to display for this row */
1078};
1079
1080/* All EQP output is collected into an instance of the following */
1081typedef struct EQPGraph EQPGraph;
1082struct EQPGraph {
1083  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1084  EQPGraphRow *pLast;   /* Last element of the pRow list */
1085  char zPrefix[100];    /* Graph prefix */
1086};
1087
1088/* Parameters affecting columnar mode result display (defaulting together) */
1089typedef struct ColModeOpts {
1090  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1091  u8 bQuote;            /* Quote results for .mode box and table */
1092  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1093} ColModeOpts;
1094#define ColModeOpts_default { 60, 0, 0 }
1095#define ColModeOpts_default_qbox { 60, 1, 0 }
1096
1097/*
1098** State information about the database connection is contained in an
1099** instance of the following structure.
1100*/
1101typedef struct ShellState ShellState;
1102struct ShellState {
1103  sqlite3 *db;           /* The database */
1104  u8 autoExplain;        /* Automatically turn on .explain mode */
1105  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1106  u8 autoEQPtest;        /* autoEQP is in test mode */
1107  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1108  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1109  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1110  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1111  u8 nEqpLevel;          /* Depth of the EQP output graph */
1112  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1113  u8 bSafeMode;          /* True to prohibit unsafe operations */
1114  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1115  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1116  unsigned statsOn;      /* True to display memory stats before each finalize */
1117  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1118  int inputNesting;      /* Track nesting level of .read and other redirects */
1119  int outCount;          /* Revert to stdout when reaching zero */
1120  int cnt;               /* Number of records displayed so far */
1121  int lineno;            /* Line number of last line read from in */
1122  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1123  FILE *in;              /* Read commands from this stream */
1124  FILE *out;             /* Write results here */
1125  FILE *traceOut;        /* Output for sqlite3_trace() */
1126  int nErr;              /* Number of errors seen */
1127  int mode;              /* An output mode setting */
1128  int modePrior;         /* Saved mode */
1129  int cMode;             /* temporary output mode for the current query */
1130  int normalMode;        /* Output mode before ".explain on" */
1131  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1132  int showHeader;        /* True to show column names in List or Column mode */
1133  int nCheck;            /* Number of ".check" commands run */
1134  unsigned nProgress;    /* Number of progress callbacks encountered */
1135  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1136  unsigned flgProgress;  /* Flags for the progress callback */
1137  unsigned shellFlgs;    /* Various flags */
1138  unsigned priorShFlgs;  /* Saved copy of flags */
1139  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1140  char *zDestTable;      /* Name of destination table when MODE_Insert */
1141  char *zTempFile;       /* Temporary file that might need deleting */
1142  char zTestcase[30];    /* Name of current test case */
1143  char colSeparator[20]; /* Column separator character for several modes */
1144  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1145  char colSepPrior[20];  /* Saved column separator */
1146  char rowSepPrior[20];  /* Saved row separator */
1147  int *colWidth;         /* Requested width of each column in columnar modes */
1148  int *actualWidth;      /* Actual width of each column */
1149  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1150  char nullValue[20];    /* The text to print when a NULL comes back from
1151                         ** the database */
1152  char outfile[FILENAME_MAX]; /* Filename for *out */
1153  sqlite3_stmt *pStmt;   /* Current statement if any. */
1154  FILE *pLog;            /* Write log output here */
1155  struct AuxDb {         /* Storage space for auxiliary database connections */
1156    sqlite3 *db;               /* Connection pointer */
1157    const char *zDbFilename;   /* Filename used to open the connection */
1158    char *zFreeOnClose;        /* Free this memory allocation on close */
1159#if defined(SQLITE_ENABLE_SESSION)
1160    int nSession;              /* Number of active sessions */
1161    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1162#endif
1163  } aAuxDb[5],           /* Array of all database connections */
1164    *pAuxDb;             /* Currently active database connection */
1165  int *aiIndent;         /* Array of indents used in MODE_Explain */
1166  int nIndent;           /* Size of array aiIndent[] */
1167  int iIndent;           /* Index of current op in aiIndent[] */
1168  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1169  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1170  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1171#ifdef SQLITE_SHELL_FIDDLE
1172  struct {
1173    const char * zInput; /* Input string from wasm/JS proxy */
1174    const char * zPos;   /* Cursor pos into zInput */
1175    const char * zDefaultDbName; /* Default name for db file */
1176  } wasm;
1177#endif
1178};
1179
1180#ifdef SQLITE_SHELL_FIDDLE
1181static ShellState shellState;
1182#endif
1183
1184
1185/* Allowed values for ShellState.autoEQP
1186*/
1187#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1188#define AUTOEQP_on       1           /* Automatic EQP is on */
1189#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1190#define AUTOEQP_full     3           /* Show full EXPLAIN */
1191
1192/* Allowed values for ShellState.openMode
1193*/
1194#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1195#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1196#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1197#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1198#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1199#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1200#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1201
1202/* Allowed values for ShellState.eTraceType
1203*/
1204#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1205#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1206#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1207
1208/* Bits in the ShellState.flgProgress variable */
1209#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1210#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1211                                   ** callback limit is reached, and for each
1212                                   ** top-level SQL statement */
1213#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1214
1215/*
1216** These are the allowed shellFlgs values
1217*/
1218#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1219#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1220#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1221#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1222#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1223#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1224#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1225#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1226#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1227#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1228
1229/*
1230** Macros for testing and setting shellFlgs
1231*/
1232#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1233#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1234#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1235
1236/*
1237** These are the allowed modes.
1238*/
1239#define MODE_Line     0  /* One column per line.  Blank line between records */
1240#define MODE_Column   1  /* One record per line in neat columns */
1241#define MODE_List     2  /* One record per line with a separator */
1242#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1243#define MODE_Html     4  /* Generate an XHTML table */
1244#define MODE_Insert   5  /* Generate SQL "insert" statements */
1245#define MODE_Quote    6  /* Quote values as for SQL */
1246#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1247#define MODE_Csv      8  /* Quote strings, numbers are plain */
1248#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1249#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1250#define MODE_Pretty  11  /* Pretty-print schemas */
1251#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1252#define MODE_Json    13  /* Output JSON */
1253#define MODE_Markdown 14 /* Markdown formatting */
1254#define MODE_Table   15  /* MySQL-style table formatting */
1255#define MODE_Box     16  /* Unicode box-drawing characters */
1256#define MODE_Count   17  /* Output only a count of the rows of output */
1257#define MODE_Off     18  /* No query output shown */
1258
1259static const char *modeDescr[] = {
1260  "line",
1261  "column",
1262  "list",
1263  "semi",
1264  "html",
1265  "insert",
1266  "quote",
1267  "tcl",
1268  "csv",
1269  "explain",
1270  "ascii",
1271  "prettyprint",
1272  "eqp",
1273  "json",
1274  "markdown",
1275  "table",
1276  "box",
1277  "count",
1278  "off"
1279};
1280
1281/*
1282** These are the column/row/line separators used by the various
1283** import/export modes.
1284*/
1285#define SEP_Column    "|"
1286#define SEP_Row       "\n"
1287#define SEP_Tab       "\t"
1288#define SEP_Space     " "
1289#define SEP_Comma     ","
1290#define SEP_CrLf      "\r\n"
1291#define SEP_Unit      "\x1F"
1292#define SEP_Record    "\x1E"
1293
1294/*
1295** Limit input nesting via .read or any other input redirect.
1296** It's not too expensive, so a generous allowance can be made.
1297*/
1298#define MAX_INPUT_NESTING 25
1299
1300/*
1301** A callback for the sqlite3_log() interface.
1302*/
1303static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1304  ShellState *p = (ShellState*)pArg;
1305  if( p->pLog==0 ) return;
1306  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1307  fflush(p->pLog);
1308}
1309
1310/*
1311** SQL function:  shell_putsnl(X)
1312**
1313** Write the text X to the screen (or whatever output is being directed)
1314** adding a newline at the end, and then return X.
1315*/
1316static void shellPutsFunc(
1317  sqlite3_context *pCtx,
1318  int nVal,
1319  sqlite3_value **apVal
1320){
1321  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1322  (void)nVal;
1323  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1324  sqlite3_result_value(pCtx, apVal[0]);
1325}
1326
1327/*
1328** If in safe mode, print an error message described by the arguments
1329** and exit immediately.
1330*/
1331static void failIfSafeMode(
1332  ShellState *p,
1333  const char *zErrMsg,
1334  ...
1335){
1336  if( p->bSafeMode ){
1337    va_list ap;
1338    char *zMsg;
1339    va_start(ap, zErrMsg);
1340    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1341    va_end(ap);
1342    raw_printf(stderr, "line %d: ", p->lineno);
1343    utf8_printf(stderr, "%s\n", zMsg);
1344    exit(1);
1345  }
1346}
1347
1348/*
1349** SQL function:   edit(VALUE)
1350**                 edit(VALUE,EDITOR)
1351**
1352** These steps:
1353**
1354**     (1) Write VALUE into a temporary file.
1355**     (2) Run program EDITOR on that temporary file.
1356**     (3) Read the temporary file back and return its content as the result.
1357**     (4) Delete the temporary file
1358**
1359** If the EDITOR argument is omitted, use the value in the VISUAL
1360** environment variable.  If still there is no EDITOR, through an error.
1361**
1362** Also throw an error if the EDITOR program returns a non-zero exit code.
1363*/
1364#ifndef SQLITE_NOHAVE_SYSTEM
1365static void editFunc(
1366  sqlite3_context *context,
1367  int argc,
1368  sqlite3_value **argv
1369){
1370  const char *zEditor;
1371  char *zTempFile = 0;
1372  sqlite3 *db;
1373  char *zCmd = 0;
1374  int bBin;
1375  int rc;
1376  int hasCRNL = 0;
1377  FILE *f = 0;
1378  sqlite3_int64 sz;
1379  sqlite3_int64 x;
1380  unsigned char *p = 0;
1381
1382  if( argc==2 ){
1383    zEditor = (const char*)sqlite3_value_text(argv[1]);
1384  }else{
1385    zEditor = getenv("VISUAL");
1386  }
1387  if( zEditor==0 ){
1388    sqlite3_result_error(context, "no editor for edit()", -1);
1389    return;
1390  }
1391  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1392    sqlite3_result_error(context, "NULL input to edit()", -1);
1393    return;
1394  }
1395  db = sqlite3_context_db_handle(context);
1396  zTempFile = 0;
1397  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1398  if( zTempFile==0 ){
1399    sqlite3_uint64 r = 0;
1400    sqlite3_randomness(sizeof(r), &r);
1401    zTempFile = sqlite3_mprintf("temp%llx", r);
1402    if( zTempFile==0 ){
1403      sqlite3_result_error_nomem(context);
1404      return;
1405    }
1406  }
1407  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1408  /* When writing the file to be edited, do \n to \r\n conversions on systems
1409  ** that want \r\n line endings */
1410  f = fopen(zTempFile, bBin ? "wb" : "w");
1411  if( f==0 ){
1412    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1413    goto edit_func_end;
1414  }
1415  sz = sqlite3_value_bytes(argv[0]);
1416  if( bBin ){
1417    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1418  }else{
1419    const char *z = (const char*)sqlite3_value_text(argv[0]);
1420    /* Remember whether or not the value originally contained \r\n */
1421    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1422    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1423  }
1424  fclose(f);
1425  f = 0;
1426  if( x!=sz ){
1427    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1428    goto edit_func_end;
1429  }
1430  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1431  if( zCmd==0 ){
1432    sqlite3_result_error_nomem(context);
1433    goto edit_func_end;
1434  }
1435  rc = system(zCmd);
1436  sqlite3_free(zCmd);
1437  if( rc ){
1438    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1439    goto edit_func_end;
1440  }
1441  f = fopen(zTempFile, "rb");
1442  if( f==0 ){
1443    sqlite3_result_error(context,
1444      "edit() cannot reopen temp file after edit", -1);
1445    goto edit_func_end;
1446  }
1447  fseek(f, 0, SEEK_END);
1448  sz = ftell(f);
1449  rewind(f);
1450  p = sqlite3_malloc64( sz+1 );
1451  if( p==0 ){
1452    sqlite3_result_error_nomem(context);
1453    goto edit_func_end;
1454  }
1455  x = fread(p, 1, (size_t)sz, f);
1456  fclose(f);
1457  f = 0;
1458  if( x!=sz ){
1459    sqlite3_result_error(context, "could not read back the whole file", -1);
1460    goto edit_func_end;
1461  }
1462  if( bBin ){
1463    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1464  }else{
1465    sqlite3_int64 i, j;
1466    if( hasCRNL ){
1467      /* If the original contains \r\n then do no conversions back to \n */
1468    }else{
1469      /* If the file did not originally contain \r\n then convert any new
1470      ** \r\n back into \n */
1471      for(i=j=0; i<sz; i++){
1472        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1473        p[j++] = p[i];
1474      }
1475      sz = j;
1476      p[sz] = 0;
1477    }
1478    sqlite3_result_text64(context, (const char*)p, sz,
1479                          sqlite3_free, SQLITE_UTF8);
1480  }
1481  p = 0;
1482
1483edit_func_end:
1484  if( f ) fclose(f);
1485  unlink(zTempFile);
1486  sqlite3_free(zTempFile);
1487  sqlite3_free(p);
1488}
1489#endif /* SQLITE_NOHAVE_SYSTEM */
1490
1491/*
1492** Save or restore the current output mode
1493*/
1494static void outputModePush(ShellState *p){
1495  p->modePrior = p->mode;
1496  p->priorShFlgs = p->shellFlgs;
1497  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1498  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1499}
1500static void outputModePop(ShellState *p){
1501  p->mode = p->modePrior;
1502  p->shellFlgs = p->priorShFlgs;
1503  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1504  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1505}
1506
1507/*
1508** Output the given string as a hex-encoded blob (eg. X'1234' )
1509*/
1510static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1511  int i;
1512  unsigned char *aBlob = (unsigned char*)pBlob;
1513
1514  char *zStr = sqlite3_malloc(nBlob*2 + 1);
1515  shell_check_oom(zStr);
1516
1517  for(i=0; i<nBlob; i++){
1518    static const char aHex[] = {
1519        '0', '1', '2', '3', '4', '5', '6', '7',
1520        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1521    };
1522    zStr[i*2] = aHex[ (aBlob[i] >> 4) ];
1523    zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ];
1524  }
1525  zStr[i*2] = '\0';
1526
1527  raw_printf(out,"X'%s'", zStr);
1528  sqlite3_free(zStr);
1529}
1530
1531/*
1532** Find a string that is not found anywhere in z[].  Return a pointer
1533** to that string.
1534**
1535** Try to use zA and zB first.  If both of those are already found in z[]
1536** then make up some string and store it in the buffer zBuf.
1537*/
1538static const char *unused_string(
1539  const char *z,                    /* Result must not appear anywhere in z */
1540  const char *zA, const char *zB,   /* Try these first */
1541  char *zBuf                        /* Space to store a generated string */
1542){
1543  unsigned i = 0;
1544  if( strstr(z, zA)==0 ) return zA;
1545  if( strstr(z, zB)==0 ) return zB;
1546  do{
1547    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1548  }while( strstr(z,zBuf)!=0 );
1549  return zBuf;
1550}
1551
1552/*
1553** Output the given string as a quoted string using SQL quoting conventions.
1554**
1555** See also: output_quoted_escaped_string()
1556*/
1557static void output_quoted_string(FILE *out, const char *z){
1558  int i;
1559  char c;
1560  setBinaryMode(out, 1);
1561  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1562  if( c==0 ){
1563    utf8_printf(out,"'%s'",z);
1564  }else{
1565    raw_printf(out, "'");
1566    while( *z ){
1567      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1568      if( c=='\'' ) i++;
1569      if( i ){
1570        utf8_printf(out, "%.*s", i, z);
1571        z += i;
1572      }
1573      if( c=='\'' ){
1574        raw_printf(out, "'");
1575        continue;
1576      }
1577      if( c==0 ){
1578        break;
1579      }
1580      z++;
1581    }
1582    raw_printf(out, "'");
1583  }
1584  setTextMode(out, 1);
1585}
1586
1587/*
1588** Output the given string as a quoted string using SQL quoting conventions.
1589** Additionallly , escape the "\n" and "\r" characters so that they do not
1590** get corrupted by end-of-line translation facilities in some operating
1591** systems.
1592**
1593** This is like output_quoted_string() but with the addition of the \r\n
1594** escape mechanism.
1595*/
1596static void output_quoted_escaped_string(FILE *out, const char *z){
1597  int i;
1598  char c;
1599  setBinaryMode(out, 1);
1600  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1601  if( c==0 ){
1602    utf8_printf(out,"'%s'",z);
1603  }else{
1604    const char *zNL = 0;
1605    const char *zCR = 0;
1606    int nNL = 0;
1607    int nCR = 0;
1608    char zBuf1[20], zBuf2[20];
1609    for(i=0; z[i]; i++){
1610      if( z[i]=='\n' ) nNL++;
1611      if( z[i]=='\r' ) nCR++;
1612    }
1613    if( nNL ){
1614      raw_printf(out, "replace(");
1615      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1616    }
1617    if( nCR ){
1618      raw_printf(out, "replace(");
1619      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1620    }
1621    raw_printf(out, "'");
1622    while( *z ){
1623      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1624      if( c=='\'' ) i++;
1625      if( i ){
1626        utf8_printf(out, "%.*s", i, z);
1627        z += i;
1628      }
1629      if( c=='\'' ){
1630        raw_printf(out, "'");
1631        continue;
1632      }
1633      if( c==0 ){
1634        break;
1635      }
1636      z++;
1637      if( c=='\n' ){
1638        raw_printf(out, "%s", zNL);
1639        continue;
1640      }
1641      raw_printf(out, "%s", zCR);
1642    }
1643    raw_printf(out, "'");
1644    if( nCR ){
1645      raw_printf(out, ",'%s',char(13))", zCR);
1646    }
1647    if( nNL ){
1648      raw_printf(out, ",'%s',char(10))", zNL);
1649    }
1650  }
1651  setTextMode(out, 1);
1652}
1653
1654/*
1655** Output the given string as a quoted according to C or TCL quoting rules.
1656*/
1657static void output_c_string(FILE *out, const char *z){
1658  unsigned int c;
1659  fputc('"', out);
1660  while( (c = *(z++))!=0 ){
1661    if( c=='\\' ){
1662      fputc(c, out);
1663      fputc(c, out);
1664    }else if( c=='"' ){
1665      fputc('\\', out);
1666      fputc('"', out);
1667    }else if( c=='\t' ){
1668      fputc('\\', out);
1669      fputc('t', out);
1670    }else if( c=='\n' ){
1671      fputc('\\', out);
1672      fputc('n', out);
1673    }else if( c=='\r' ){
1674      fputc('\\', out);
1675      fputc('r', out);
1676    }else if( !isprint(c&0xff) ){
1677      raw_printf(out, "\\%03o", c&0xff);
1678    }else{
1679      fputc(c, out);
1680    }
1681  }
1682  fputc('"', out);
1683}
1684
1685/*
1686** Output the given string as a quoted according to JSON quoting rules.
1687*/
1688static void output_json_string(FILE *out, const char *z, int n){
1689  unsigned int c;
1690  if( n<0 ) n = (int)strlen(z);
1691  fputc('"', out);
1692  while( n-- ){
1693    c = *(z++);
1694    if( c=='\\' || c=='"' ){
1695      fputc('\\', out);
1696      fputc(c, out);
1697    }else if( c<=0x1f ){
1698      fputc('\\', out);
1699      if( c=='\b' ){
1700        fputc('b', out);
1701      }else if( c=='\f' ){
1702        fputc('f', out);
1703      }else if( c=='\n' ){
1704        fputc('n', out);
1705      }else if( c=='\r' ){
1706        fputc('r', out);
1707      }else if( c=='\t' ){
1708        fputc('t', out);
1709      }else{
1710         raw_printf(out, "u%04x",c);
1711      }
1712    }else{
1713      fputc(c, out);
1714    }
1715  }
1716  fputc('"', out);
1717}
1718
1719/*
1720** Output the given string with characters that are special to
1721** HTML escaped.
1722*/
1723static void output_html_string(FILE *out, const char *z){
1724  int i;
1725  if( z==0 ) z = "";
1726  while( *z ){
1727    for(i=0;   z[i]
1728            && z[i]!='<'
1729            && z[i]!='&'
1730            && z[i]!='>'
1731            && z[i]!='\"'
1732            && z[i]!='\'';
1733        i++){}
1734    if( i>0 ){
1735      utf8_printf(out,"%.*s",i,z);
1736    }
1737    if( z[i]=='<' ){
1738      raw_printf(out,"&lt;");
1739    }else if( z[i]=='&' ){
1740      raw_printf(out,"&amp;");
1741    }else if( z[i]=='>' ){
1742      raw_printf(out,"&gt;");
1743    }else if( z[i]=='\"' ){
1744      raw_printf(out,"&quot;");
1745    }else if( z[i]=='\'' ){
1746      raw_printf(out,"&#39;");
1747    }else{
1748      break;
1749    }
1750    z += i + 1;
1751  }
1752}
1753
1754/*
1755** If a field contains any character identified by a 1 in the following
1756** array, then the string must be quoted for CSV.
1757*/
1758static const char needCsvQuote[] = {
1759  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1760  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1761  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1762  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1763  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1764  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1765  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1766  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1767  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1768  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1769  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1770  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1771  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1772  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1773  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1774  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1775};
1776
1777/*
1778** Output a single term of CSV.  Actually, p->colSeparator is used for
1779** the separator, which may or may not be a comma.  p->nullValue is
1780** the null value.  Strings are quoted if necessary.  The separator
1781** is only issued if bSep is true.
1782*/
1783static void output_csv(ShellState *p, const char *z, int bSep){
1784  FILE *out = p->out;
1785  if( z==0 ){
1786    utf8_printf(out,"%s",p->nullValue);
1787  }else{
1788    unsigned i;
1789    for(i=0; z[i]; i++){
1790      if( needCsvQuote[((unsigned char*)z)[i]] ){
1791        i = 0;
1792        break;
1793      }
1794    }
1795    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1796      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1797      shell_check_oom(zQuoted);
1798      utf8_printf(out, "%s", zQuoted);
1799      sqlite3_free(zQuoted);
1800    }else{
1801      utf8_printf(out, "%s", z);
1802    }
1803  }
1804  if( bSep ){
1805    utf8_printf(p->out, "%s", p->colSeparator);
1806  }
1807}
1808
1809/*
1810** This routine runs when the user presses Ctrl-C
1811*/
1812static void interrupt_handler(int NotUsed){
1813  UNUSED_PARAMETER(NotUsed);
1814  seenInterrupt++;
1815  if( seenInterrupt>2 ) exit(1);
1816  if( globalDb ) sqlite3_interrupt(globalDb);
1817}
1818
1819#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1820/*
1821** This routine runs for console events (e.g. Ctrl-C) on Win32
1822*/
1823static BOOL WINAPI ConsoleCtrlHandler(
1824  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1825){
1826  if( dwCtrlType==CTRL_C_EVENT ){
1827    interrupt_handler(0);
1828    return TRUE;
1829  }
1830  return FALSE;
1831}
1832#endif
1833
1834#ifndef SQLITE_OMIT_AUTHORIZATION
1835/*
1836** This authorizer runs in safe mode.
1837*/
1838static int safeModeAuth(
1839  void *pClientData,
1840  int op,
1841  const char *zA1,
1842  const char *zA2,
1843  const char *zA3,
1844  const char *zA4
1845){
1846  ShellState *p = (ShellState*)pClientData;
1847  static const char *azProhibitedFunctions[] = {
1848    "edit",
1849    "fts3_tokenizer",
1850    "load_extension",
1851    "readfile",
1852    "writefile",
1853    "zipfile",
1854    "zipfile_cds",
1855  };
1856  UNUSED_PARAMETER(zA2);
1857  UNUSED_PARAMETER(zA3);
1858  UNUSED_PARAMETER(zA4);
1859  switch( op ){
1860    case SQLITE_ATTACH: {
1861#ifndef SQLITE_SHELL_FIDDLE
1862      /* In WASM builds the filesystem is a virtual sandbox, so
1863      ** there's no harm in using ATTACH. */
1864      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1865#endif
1866      break;
1867    }
1868    case SQLITE_FUNCTION: {
1869      int i;
1870      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1871        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1872          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1873                         azProhibitedFunctions[i]);
1874        }
1875      }
1876      break;
1877    }
1878  }
1879  return SQLITE_OK;
1880}
1881
1882/*
1883** When the ".auth ON" is set, the following authorizer callback is
1884** invoked.  It always returns SQLITE_OK.
1885*/
1886static int shellAuth(
1887  void *pClientData,
1888  int op,
1889  const char *zA1,
1890  const char *zA2,
1891  const char *zA3,
1892  const char *zA4
1893){
1894  ShellState *p = (ShellState*)pClientData;
1895  static const char *azAction[] = { 0,
1896     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1897     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1898     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1899     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1900     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1901     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1902     "PRAGMA",               "READ",                 "SELECT",
1903     "TRANSACTION",          "UPDATE",               "ATTACH",
1904     "DETACH",               "ALTER_TABLE",          "REINDEX",
1905     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1906     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1907  };
1908  int i;
1909  const char *az[4];
1910  az[0] = zA1;
1911  az[1] = zA2;
1912  az[2] = zA3;
1913  az[3] = zA4;
1914  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1915  for(i=0; i<4; i++){
1916    raw_printf(p->out, " ");
1917    if( az[i] ){
1918      output_c_string(p->out, az[i]);
1919    }else{
1920      raw_printf(p->out, "NULL");
1921    }
1922  }
1923  raw_printf(p->out, "\n");
1924  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1925  return SQLITE_OK;
1926}
1927#endif
1928
1929/*
1930** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1931**
1932** This routine converts some CREATE TABLE statements for shadow tables
1933** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1934**
1935** If the schema statement in z[] contains a start-of-comment and if
1936** sqlite3_complete() returns false, try to terminate the comment before
1937** printing the result.  https://sqlite.org/forum/forumpost/d7be961c5c
1938*/
1939static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1940  char *zToFree = 0;
1941  if( z==0 ) return;
1942  if( zTail==0 ) return;
1943  if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){
1944    const char *zOrig = z;
1945    static const char *azTerm[] = { "", "*/", "\n" };
1946    int i;
1947    for(i=0; i<ArraySize(azTerm); i++){
1948      char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]);
1949      if( sqlite3_complete(zNew) ){
1950        size_t n = strlen(zNew);
1951        zNew[n-1] = 0;
1952        zToFree = zNew;
1953        z = zNew;
1954        break;
1955      }
1956      sqlite3_free(zNew);
1957    }
1958  }
1959  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1960    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1961  }else{
1962    utf8_printf(out, "%s%s", z, zTail);
1963  }
1964  sqlite3_free(zToFree);
1965}
1966static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1967  char c = z[n];
1968  z[n] = 0;
1969  printSchemaLine(out, z, zTail);
1970  z[n] = c;
1971}
1972
1973/*
1974** Return true if string z[] has nothing but whitespace and comments to the
1975** end of the first line.
1976*/
1977static int wsToEol(const char *z){
1978  int i;
1979  for(i=0; z[i]; i++){
1980    if( z[i]=='\n' ) return 1;
1981    if( IsSpace(z[i]) ) continue;
1982    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1983    return 0;
1984  }
1985  return 1;
1986}
1987
1988/*
1989** Add a new entry to the EXPLAIN QUERY PLAN data
1990*/
1991static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1992  EQPGraphRow *pNew;
1993  int nText = strlen30(zText);
1994  if( p->autoEQPtest ){
1995    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1996  }
1997  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1998  shell_check_oom(pNew);
1999  pNew->iEqpId = iEqpId;
2000  pNew->iParentId = p2;
2001  memcpy(pNew->zText, zText, nText+1);
2002  pNew->pNext = 0;
2003  if( p->sGraph.pLast ){
2004    p->sGraph.pLast->pNext = pNew;
2005  }else{
2006    p->sGraph.pRow = pNew;
2007  }
2008  p->sGraph.pLast = pNew;
2009}
2010
2011/*
2012** Free and reset the EXPLAIN QUERY PLAN data that has been collected
2013** in p->sGraph.
2014*/
2015static void eqp_reset(ShellState *p){
2016  EQPGraphRow *pRow, *pNext;
2017  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
2018    pNext = pRow->pNext;
2019    sqlite3_free(pRow);
2020  }
2021  memset(&p->sGraph, 0, sizeof(p->sGraph));
2022}
2023
2024/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
2025** pOld, or return the first such line if pOld is NULL
2026*/
2027static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
2028  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
2029  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
2030  return pRow;
2031}
2032
2033/* Render a single level of the graph that has iEqpId as its parent.  Called
2034** recursively to render sublevels.
2035*/
2036static void eqp_render_level(ShellState *p, int iEqpId){
2037  EQPGraphRow *pRow, *pNext;
2038  int n = strlen30(p->sGraph.zPrefix);
2039  char *z;
2040  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
2041    pNext = eqp_next_row(p, iEqpId, pRow);
2042    z = pRow->zText;
2043    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2044                pNext ? "|--" : "`--", z);
2045    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2046      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2047      eqp_render_level(p, pRow->iEqpId);
2048      p->sGraph.zPrefix[n] = 0;
2049    }
2050  }
2051}
2052
2053/*
2054** Display and reset the EXPLAIN QUERY PLAN data
2055*/
2056static void eqp_render(ShellState *p){
2057  EQPGraphRow *pRow = p->sGraph.pRow;
2058  if( pRow ){
2059    if( pRow->zText[0]=='-' ){
2060      if( pRow->pNext==0 ){
2061        eqp_reset(p);
2062        return;
2063      }
2064      utf8_printf(p->out, "%s\n", pRow->zText+3);
2065      p->sGraph.pRow = pRow->pNext;
2066      sqlite3_free(pRow);
2067    }else{
2068      utf8_printf(p->out, "QUERY PLAN\n");
2069    }
2070    p->sGraph.zPrefix[0] = 0;
2071    eqp_render_level(p, 0);
2072    eqp_reset(p);
2073  }
2074}
2075
2076#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2077/*
2078** Progress handler callback.
2079*/
2080static int progress_handler(void *pClientData) {
2081  ShellState *p = (ShellState*)pClientData;
2082  p->nProgress++;
2083  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2084    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2085    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2086    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2087    return 1;
2088  }
2089  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2090    raw_printf(p->out, "Progress %u\n", p->nProgress);
2091  }
2092  return 0;
2093}
2094#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2095
2096/*
2097** Print N dashes
2098*/
2099static void print_dashes(FILE *out, int N){
2100  const char zDash[] = "--------------------------------------------------";
2101  const int nDash = sizeof(zDash) - 1;
2102  while( N>nDash ){
2103    fputs(zDash, out);
2104    N -= nDash;
2105  }
2106  raw_printf(out, "%.*s", N, zDash);
2107}
2108
2109/*
2110** Print a markdown or table-style row separator using ascii-art
2111*/
2112static void print_row_separator(
2113  ShellState *p,
2114  int nArg,
2115  const char *zSep
2116){
2117  int i;
2118  if( nArg>0 ){
2119    fputs(zSep, p->out);
2120    print_dashes(p->out, p->actualWidth[0]+2);
2121    for(i=1; i<nArg; i++){
2122      fputs(zSep, p->out);
2123      print_dashes(p->out, p->actualWidth[i]+2);
2124    }
2125    fputs(zSep, p->out);
2126  }
2127  fputs("\n", p->out);
2128}
2129
2130/*
2131** This is the callback routine that the shell
2132** invokes for each row of a query result.
2133*/
2134static int shell_callback(
2135  void *pArg,
2136  int nArg,        /* Number of result columns */
2137  char **azArg,    /* Text of each result column */
2138  char **azCol,    /* Column names */
2139  int *aiType      /* Column types.  Might be NULL */
2140){
2141  int i;
2142  ShellState *p = (ShellState*)pArg;
2143
2144  if( azArg==0 ) return 0;
2145  switch( p->cMode ){
2146    case MODE_Count:
2147    case MODE_Off: {
2148      break;
2149    }
2150    case MODE_Line: {
2151      int w = 5;
2152      if( azArg==0 ) break;
2153      for(i=0; i<nArg; i++){
2154        int len = strlen30(azCol[i] ? azCol[i] : "");
2155        if( len>w ) w = len;
2156      }
2157      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2158      for(i=0; i<nArg; i++){
2159        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2160                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2161      }
2162      break;
2163    }
2164    case MODE_Explain: {
2165      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2166      if( nArg>ArraySize(aExplainWidth) ){
2167        nArg = ArraySize(aExplainWidth);
2168      }
2169      if( p->cnt++==0 ){
2170        for(i=0; i<nArg; i++){
2171          int w = aExplainWidth[i];
2172          utf8_width_print(p->out, w, azCol[i]);
2173          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2174        }
2175        for(i=0; i<nArg; i++){
2176          int w = aExplainWidth[i];
2177          print_dashes(p->out, w);
2178          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2179        }
2180      }
2181      if( azArg==0 ) break;
2182      for(i=0; i<nArg; i++){
2183        int w = aExplainWidth[i];
2184        if( i==nArg-1 ) w = 0;
2185        if( azArg[i] && strlenChar(azArg[i])>w ){
2186          w = strlenChar(azArg[i]);
2187        }
2188        if( i==1 && p->aiIndent && p->pStmt ){
2189          if( p->iIndent<p->nIndent ){
2190            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2191          }
2192          p->iIndent++;
2193        }
2194        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2195        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2196      }
2197      break;
2198    }
2199    case MODE_Semi: {   /* .schema and .fullschema output */
2200      printSchemaLine(p->out, azArg[0], ";\n");
2201      break;
2202    }
2203    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2204      char *z;
2205      int j;
2206      int nParen = 0;
2207      char cEnd = 0;
2208      char c;
2209      int nLine = 0;
2210      assert( nArg==1 );
2211      if( azArg[0]==0 ) break;
2212      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2213       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2214      ){
2215        utf8_printf(p->out, "%s;\n", azArg[0]);
2216        break;
2217      }
2218      z = sqlite3_mprintf("%s", azArg[0]);
2219      shell_check_oom(z);
2220      j = 0;
2221      for(i=0; IsSpace(z[i]); i++){}
2222      for(; (c = z[i])!=0; i++){
2223        if( IsSpace(c) ){
2224          if( z[j-1]=='\r' ) z[j-1] = '\n';
2225          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2226        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2227          j--;
2228        }
2229        z[j++] = c;
2230      }
2231      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2232      z[j] = 0;
2233      if( strlen30(z)>=79 ){
2234        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2235          if( c==cEnd ){
2236            cEnd = 0;
2237          }else if( c=='"' || c=='\'' || c=='`' ){
2238            cEnd = c;
2239          }else if( c=='[' ){
2240            cEnd = ']';
2241          }else if( c=='-' && z[i+1]=='-' ){
2242            cEnd = '\n';
2243          }else if( c=='(' ){
2244            nParen++;
2245          }else if( c==')' ){
2246            nParen--;
2247            if( nLine>0 && nParen==0 && j>0 ){
2248              printSchemaLineN(p->out, z, j, "\n");
2249              j = 0;
2250            }
2251          }
2252          z[j++] = c;
2253          if( nParen==1 && cEnd==0
2254           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2255          ){
2256            if( c=='\n' ) j--;
2257            printSchemaLineN(p->out, z, j, "\n  ");
2258            j = 0;
2259            nLine++;
2260            while( IsSpace(z[i+1]) ){ i++; }
2261          }
2262        }
2263        z[j] = 0;
2264      }
2265      printSchemaLine(p->out, z, ";\n");
2266      sqlite3_free(z);
2267      break;
2268    }
2269    case MODE_List: {
2270      if( p->cnt++==0 && p->showHeader ){
2271        for(i=0; i<nArg; i++){
2272          utf8_printf(p->out,"%s%s",azCol[i],
2273                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2274        }
2275      }
2276      if( azArg==0 ) break;
2277      for(i=0; i<nArg; i++){
2278        char *z = azArg[i];
2279        if( z==0 ) z = p->nullValue;
2280        utf8_printf(p->out, "%s", z);
2281        if( i<nArg-1 ){
2282          utf8_printf(p->out, "%s", p->colSeparator);
2283        }else{
2284          utf8_printf(p->out, "%s", p->rowSeparator);
2285        }
2286      }
2287      break;
2288    }
2289    case MODE_Html: {
2290      if( p->cnt++==0 && p->showHeader ){
2291        raw_printf(p->out,"<TR>");
2292        for(i=0; i<nArg; i++){
2293          raw_printf(p->out,"<TH>");
2294          output_html_string(p->out, azCol[i]);
2295          raw_printf(p->out,"</TH>\n");
2296        }
2297        raw_printf(p->out,"</TR>\n");
2298      }
2299      if( azArg==0 ) break;
2300      raw_printf(p->out,"<TR>");
2301      for(i=0; i<nArg; i++){
2302        raw_printf(p->out,"<TD>");
2303        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2304        raw_printf(p->out,"</TD>\n");
2305      }
2306      raw_printf(p->out,"</TR>\n");
2307      break;
2308    }
2309    case MODE_Tcl: {
2310      if( p->cnt++==0 && p->showHeader ){
2311        for(i=0; i<nArg; i++){
2312          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2313          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2314        }
2315        utf8_printf(p->out, "%s", p->rowSeparator);
2316      }
2317      if( azArg==0 ) break;
2318      for(i=0; i<nArg; i++){
2319        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2320        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2321      }
2322      utf8_printf(p->out, "%s", p->rowSeparator);
2323      break;
2324    }
2325    case MODE_Csv: {
2326      setBinaryMode(p->out, 1);
2327      if( p->cnt++==0 && p->showHeader ){
2328        for(i=0; i<nArg; i++){
2329          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2330        }
2331        utf8_printf(p->out, "%s", p->rowSeparator);
2332      }
2333      if( nArg>0 ){
2334        for(i=0; i<nArg; i++){
2335          output_csv(p, azArg[i], i<nArg-1);
2336        }
2337        utf8_printf(p->out, "%s", p->rowSeparator);
2338      }
2339      setTextMode(p->out, 1);
2340      break;
2341    }
2342    case MODE_Insert: {
2343      if( azArg==0 ) break;
2344      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2345      if( p->showHeader ){
2346        raw_printf(p->out,"(");
2347        for(i=0; i<nArg; i++){
2348          if( i>0 ) raw_printf(p->out, ",");
2349          if( quoteChar(azCol[i]) ){
2350            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2351            shell_check_oom(z);
2352            utf8_printf(p->out, "%s", z);
2353            sqlite3_free(z);
2354          }else{
2355            raw_printf(p->out, "%s", azCol[i]);
2356          }
2357        }
2358        raw_printf(p->out,")");
2359      }
2360      p->cnt++;
2361      for(i=0; i<nArg; i++){
2362        raw_printf(p->out, i>0 ? "," : " VALUES(");
2363        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2364          utf8_printf(p->out,"NULL");
2365        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2366          if( ShellHasFlag(p, SHFLG_Newlines) ){
2367            output_quoted_string(p->out, azArg[i]);
2368          }else{
2369            output_quoted_escaped_string(p->out, azArg[i]);
2370          }
2371        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2372          utf8_printf(p->out,"%s", azArg[i]);
2373        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2374          char z[50];
2375          double r = sqlite3_column_double(p->pStmt, i);
2376          sqlite3_uint64 ur;
2377          memcpy(&ur,&r,sizeof(r));
2378          if( ur==0x7ff0000000000000LL ){
2379            raw_printf(p->out, "1e999");
2380          }else if( ur==0xfff0000000000000LL ){
2381            raw_printf(p->out, "-1e999");
2382          }else{
2383            sqlite3_int64 ir = (sqlite3_int64)r;
2384            if( r==(double)ir ){
2385              sqlite3_snprintf(50,z,"%lld.0", ir);
2386            }else{
2387              sqlite3_snprintf(50,z,"%!.20g", r);
2388            }
2389            raw_printf(p->out, "%s", z);
2390          }
2391        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2392          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2393          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2394          output_hex_blob(p->out, pBlob, nBlob);
2395        }else if( isNumber(azArg[i], 0) ){
2396          utf8_printf(p->out,"%s", azArg[i]);
2397        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2398          output_quoted_string(p->out, azArg[i]);
2399        }else{
2400          output_quoted_escaped_string(p->out, azArg[i]);
2401        }
2402      }
2403      raw_printf(p->out,");\n");
2404      break;
2405    }
2406    case MODE_Json: {
2407      if( azArg==0 ) break;
2408      if( p->cnt==0 ){
2409        fputs("[{", p->out);
2410      }else{
2411        fputs(",\n{", p->out);
2412      }
2413      p->cnt++;
2414      for(i=0; i<nArg; i++){
2415        output_json_string(p->out, azCol[i], -1);
2416        putc(':', p->out);
2417        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2418          fputs("null",p->out);
2419        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2420          char z[50];
2421          double r = sqlite3_column_double(p->pStmt, i);
2422          sqlite3_uint64 ur;
2423          memcpy(&ur,&r,sizeof(r));
2424          if( ur==0x7ff0000000000000LL ){
2425            raw_printf(p->out, "1e999");
2426          }else if( ur==0xfff0000000000000LL ){
2427            raw_printf(p->out, "-1e999");
2428          }else{
2429            sqlite3_snprintf(50,z,"%!.20g", r);
2430            raw_printf(p->out, "%s", z);
2431          }
2432        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2433          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2434          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2435          output_json_string(p->out, pBlob, nBlob);
2436        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2437          output_json_string(p->out, azArg[i], -1);
2438        }else{
2439          utf8_printf(p->out,"%s", azArg[i]);
2440        }
2441        if( i<nArg-1 ){
2442          putc(',', p->out);
2443        }
2444      }
2445      putc('}', p->out);
2446      break;
2447    }
2448    case MODE_Quote: {
2449      if( azArg==0 ) break;
2450      if( p->cnt==0 && p->showHeader ){
2451        for(i=0; i<nArg; i++){
2452          if( i>0 ) fputs(p->colSeparator, p->out);
2453          output_quoted_string(p->out, azCol[i]);
2454        }
2455        fputs(p->rowSeparator, p->out);
2456      }
2457      p->cnt++;
2458      for(i=0; i<nArg; i++){
2459        if( i>0 ) fputs(p->colSeparator, p->out);
2460        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2461          utf8_printf(p->out,"NULL");
2462        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2463          output_quoted_string(p->out, azArg[i]);
2464        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2465          utf8_printf(p->out,"%s", azArg[i]);
2466        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2467          char z[50];
2468          double r = sqlite3_column_double(p->pStmt, i);
2469          sqlite3_snprintf(50,z,"%!.20g", r);
2470          raw_printf(p->out, "%s", z);
2471        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2472          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2473          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2474          output_hex_blob(p->out, pBlob, nBlob);
2475        }else if( isNumber(azArg[i], 0) ){
2476          utf8_printf(p->out,"%s", azArg[i]);
2477        }else{
2478          output_quoted_string(p->out, azArg[i]);
2479        }
2480      }
2481      fputs(p->rowSeparator, p->out);
2482      break;
2483    }
2484    case MODE_Ascii: {
2485      if( p->cnt++==0 && p->showHeader ){
2486        for(i=0; i<nArg; i++){
2487          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2488          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2489        }
2490        utf8_printf(p->out, "%s", p->rowSeparator);
2491      }
2492      if( azArg==0 ) break;
2493      for(i=0; i<nArg; i++){
2494        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2495        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2496      }
2497      utf8_printf(p->out, "%s", p->rowSeparator);
2498      break;
2499    }
2500    case MODE_EQP: {
2501      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2502      break;
2503    }
2504  }
2505  return 0;
2506}
2507
2508/*
2509** This is the callback routine that the SQLite library
2510** invokes for each row of a query result.
2511*/
2512static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2513  /* since we don't have type info, call the shell_callback with a NULL value */
2514  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2515}
2516
2517/*
2518** This is the callback routine from sqlite3_exec() that appends all
2519** output onto the end of a ShellText object.
2520*/
2521static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2522  ShellText *p = (ShellText*)pArg;
2523  int i;
2524  UNUSED_PARAMETER(az);
2525  if( azArg==0 ) return 0;
2526  if( p->n ) appendText(p, "|", 0);
2527  for(i=0; i<nArg; i++){
2528    if( i ) appendText(p, ",", 0);
2529    if( azArg[i] ) appendText(p, azArg[i], 0);
2530  }
2531  return 0;
2532}
2533
2534/*
2535** Generate an appropriate SELFTEST table in the main database.
2536*/
2537static void createSelftestTable(ShellState *p){
2538  char *zErrMsg = 0;
2539  sqlite3_exec(p->db,
2540    "SAVEPOINT selftest_init;\n"
2541    "CREATE TABLE IF NOT EXISTS selftest(\n"
2542    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2543    "  op TEXT,\n"                   /* Operator:  memo run */
2544    "  cmd TEXT,\n"                  /* Command text */
2545    "  ans TEXT\n"                   /* Desired answer */
2546    ");"
2547    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2548    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2549    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2550    "         'memo','Tests generated by --init');\n"
2551    "INSERT INTO [_shell$self]\n"
2552    "  SELECT 'run',\n"
2553    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2554                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2555    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2556                          "FROM sqlite_schema ORDER BY 2',224));\n"
2557    "INSERT INTO [_shell$self]\n"
2558    "  SELECT 'run',"
2559    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2560    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2561    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2562    "  FROM (\n"
2563    "    SELECT name FROM sqlite_schema\n"
2564    "     WHERE type='table'\n"
2565    "       AND name<>'selftest'\n"
2566    "       AND coalesce(rootpage,0)>0\n"
2567    "  )\n"
2568    " ORDER BY name;\n"
2569    "INSERT INTO [_shell$self]\n"
2570    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2571    "INSERT INTO selftest(tno,op,cmd,ans)"
2572    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2573    "DROP TABLE [_shell$self];"
2574    ,0,0,&zErrMsg);
2575  if( zErrMsg ){
2576    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2577    sqlite3_free(zErrMsg);
2578  }
2579  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2580}
2581
2582
2583/*
2584** Set the destination table field of the ShellState structure to
2585** the name of the table given.  Escape any quote characters in the
2586** table name.
2587*/
2588static void set_table_name(ShellState *p, const char *zName){
2589  int i, n;
2590  char cQuote;
2591  char *z;
2592
2593  if( p->zDestTable ){
2594    free(p->zDestTable);
2595    p->zDestTable = 0;
2596  }
2597  if( zName==0 ) return;
2598  cQuote = quoteChar(zName);
2599  n = strlen30(zName);
2600  if( cQuote ) n += n+2;
2601  z = p->zDestTable = malloc( n+1 );
2602  shell_check_oom(z);
2603  n = 0;
2604  if( cQuote ) z[n++] = cQuote;
2605  for(i=0; zName[i]; i++){
2606    z[n++] = zName[i];
2607    if( zName[i]==cQuote ) z[n++] = cQuote;
2608  }
2609  if( cQuote ) z[n++] = cQuote;
2610  z[n] = 0;
2611}
2612
2613/*
2614** Maybe construct two lines of text that point out the position of a
2615** syntax error.  Return a pointer to the text, in memory obtained from
2616** sqlite3_malloc().  Or, if the most recent error does not involve a
2617** specific token that we can point to, return an empty string.
2618**
2619** In all cases, the memory returned is obtained from sqlite3_malloc64()
2620** and should be released by the caller invoking sqlite3_free().
2621*/
2622static char *shell_error_context(const char *zSql, sqlite3 *db){
2623  int iOffset;
2624  size_t len;
2625  char *zCode;
2626  char *zMsg;
2627  int i;
2628  if( db==0
2629   || zSql==0
2630   || (iOffset = sqlite3_error_offset(db))<0
2631  ){
2632    return sqlite3_mprintf("");
2633  }
2634  while( iOffset>50 ){
2635    iOffset--;
2636    zSql++;
2637    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2638  }
2639  len = strlen(zSql);
2640  if( len>78 ){
2641    len = 78;
2642    while( (zSql[len]&0xc0)==0x80 ) len--;
2643  }
2644  zCode = sqlite3_mprintf("%.*s", len, zSql);
2645  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2646  if( iOffset<25 ){
2647    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2648  }else{
2649    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2650  }
2651  return zMsg;
2652}
2653
2654
2655/*
2656** Execute a query statement that will generate SQL output.  Print
2657** the result columns, comma-separated, on a line and then add a
2658** semicolon terminator to the end of that line.
2659**
2660** If the number of columns is 1 and that column contains text "--"
2661** then write the semicolon on a separate line.  That way, if a
2662** "--" comment occurs at the end of the statement, the comment
2663** won't consume the semicolon terminator.
2664*/
2665static int run_table_dump_query(
2666  ShellState *p,           /* Query context */
2667  const char *zSelect      /* SELECT statement to extract content */
2668){
2669  sqlite3_stmt *pSelect;
2670  int rc;
2671  int nResult;
2672  int i;
2673  const char *z;
2674  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2675  if( rc!=SQLITE_OK || !pSelect ){
2676    char *zContext = shell_error_context(zSelect, p->db);
2677    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2678                sqlite3_errmsg(p->db), zContext);
2679    sqlite3_free(zContext);
2680    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2681    return rc;
2682  }
2683  rc = sqlite3_step(pSelect);
2684  nResult = sqlite3_column_count(pSelect);
2685  while( rc==SQLITE_ROW ){
2686    z = (const char*)sqlite3_column_text(pSelect, 0);
2687    utf8_printf(p->out, "%s", z);
2688    for(i=1; i<nResult; i++){
2689      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2690    }
2691    if( z==0 ) z = "";
2692    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2693    if( z[0] ){
2694      raw_printf(p->out, "\n;\n");
2695    }else{
2696      raw_printf(p->out, ";\n");
2697    }
2698    rc = sqlite3_step(pSelect);
2699  }
2700  rc = sqlite3_finalize(pSelect);
2701  if( rc!=SQLITE_OK ){
2702    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2703                sqlite3_errmsg(p->db));
2704    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2705  }
2706  return rc;
2707}
2708
2709/*
2710** Allocate space and save off string indicating current error.
2711*/
2712static char *save_err_msg(
2713  sqlite3 *db,           /* Database to query */
2714  const char *zPhase,    /* When the error occcurs */
2715  int rc,                /* Error code returned from API */
2716  const char *zSql       /* SQL string, or NULL */
2717){
2718  char *zErr;
2719  char *zContext;
2720  sqlite3_str *pStr = sqlite3_str_new(0);
2721  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2722  if( rc>1 ){
2723    sqlite3_str_appendf(pStr, " (%d)", rc);
2724  }
2725  zContext = shell_error_context(zSql, db);
2726  if( zContext ){
2727    sqlite3_str_appendall(pStr, zContext);
2728    sqlite3_free(zContext);
2729  }
2730  zErr = sqlite3_str_finish(pStr);
2731  shell_check_oom(zErr);
2732  return zErr;
2733}
2734
2735#ifdef __linux__
2736/*
2737** Attempt to display I/O stats on Linux using /proc/PID/io
2738*/
2739static void displayLinuxIoStats(FILE *out){
2740  FILE *in;
2741  char z[200];
2742  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2743  in = fopen(z, "rb");
2744  if( in==0 ) return;
2745  while( fgets(z, sizeof(z), in)!=0 ){
2746    static const struct {
2747      const char *zPattern;
2748      const char *zDesc;
2749    } aTrans[] = {
2750      { "rchar: ",                  "Bytes received by read():" },
2751      { "wchar: ",                  "Bytes sent to write():"    },
2752      { "syscr: ",                  "Read() system calls:"      },
2753      { "syscw: ",                  "Write() system calls:"     },
2754      { "read_bytes: ",             "Bytes read from storage:"  },
2755      { "write_bytes: ",            "Bytes written to storage:" },
2756      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2757    };
2758    int i;
2759    for(i=0; i<ArraySize(aTrans); i++){
2760      int n = strlen30(aTrans[i].zPattern);
2761      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2762        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2763        break;
2764      }
2765    }
2766  }
2767  fclose(in);
2768}
2769#endif
2770
2771/*
2772** Display a single line of status using 64-bit values.
2773*/
2774static void displayStatLine(
2775  ShellState *p,            /* The shell context */
2776  char *zLabel,             /* Label for this one line */
2777  char *zFormat,            /* Format for the result */
2778  int iStatusCtrl,          /* Which status to display */
2779  int bReset                /* True to reset the stats */
2780){
2781  sqlite3_int64 iCur = -1;
2782  sqlite3_int64 iHiwtr = -1;
2783  int i, nPercent;
2784  char zLine[200];
2785  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2786  for(i=0, nPercent=0; zFormat[i]; i++){
2787    if( zFormat[i]=='%' ) nPercent++;
2788  }
2789  if( nPercent>1 ){
2790    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2791  }else{
2792    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2793  }
2794  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2795}
2796
2797/*
2798** Display memory stats.
2799*/
2800static int display_stats(
2801  sqlite3 *db,                /* Database to query */
2802  ShellState *pArg,           /* Pointer to ShellState */
2803  int bReset                  /* True to reset the stats */
2804){
2805  int iCur;
2806  int iHiwtr;
2807  FILE *out;
2808  if( pArg==0 || pArg->out==0 ) return 0;
2809  out = pArg->out;
2810
2811  if( pArg->pStmt && pArg->statsOn==2 ){
2812    int nCol, i, x;
2813    sqlite3_stmt *pStmt = pArg->pStmt;
2814    char z[100];
2815    nCol = sqlite3_column_count(pStmt);
2816    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2817    for(i=0; i<nCol; i++){
2818      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2819      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2820#ifndef SQLITE_OMIT_DECLTYPE
2821      sqlite3_snprintf(30, z+x, "declared type:");
2822      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2823#endif
2824#ifdef SQLITE_ENABLE_COLUMN_METADATA
2825      sqlite3_snprintf(30, z+x, "database name:");
2826      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2827      sqlite3_snprintf(30, z+x, "table name:");
2828      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2829      sqlite3_snprintf(30, z+x, "origin name:");
2830      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2831#endif
2832    }
2833  }
2834
2835  if( pArg->statsOn==3 ){
2836    if( pArg->pStmt ){
2837      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2838      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2839    }
2840    return 0;
2841  }
2842
2843  displayStatLine(pArg, "Memory Used:",
2844     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2845  displayStatLine(pArg, "Number of Outstanding Allocations:",
2846     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2847  if( pArg->shellFlgs & SHFLG_Pagecache ){
2848    displayStatLine(pArg, "Number of Pcache Pages Used:",
2849       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2850  }
2851  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2852     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2853  displayStatLine(pArg, "Largest Allocation:",
2854     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2855  displayStatLine(pArg, "Largest Pcache Allocation:",
2856     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2857#ifdef YYTRACKMAXSTACKDEPTH
2858  displayStatLine(pArg, "Deepest Parser Stack:",
2859     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2860#endif
2861
2862  if( db ){
2863    if( pArg->shellFlgs & SHFLG_Lookaside ){
2864      iHiwtr = iCur = -1;
2865      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2866                        &iCur, &iHiwtr, bReset);
2867      raw_printf(pArg->out,
2868              "Lookaside Slots Used:                %d (max %d)\n",
2869              iCur, iHiwtr);
2870      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2871                        &iCur, &iHiwtr, bReset);
2872      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2873              iHiwtr);
2874      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2875                        &iCur, &iHiwtr, bReset);
2876      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2877              iHiwtr);
2878      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2879                        &iCur, &iHiwtr, bReset);
2880      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2881              iHiwtr);
2882    }
2883    iHiwtr = iCur = -1;
2884    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2885    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2886            iCur);
2887    iHiwtr = iCur = -1;
2888    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2889    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2890    iHiwtr = iCur = -1;
2891    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2892    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2893    iHiwtr = iCur = -1;
2894    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2895    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2896    iHiwtr = iCur = -1;
2897    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2898    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2899    iHiwtr = iCur = -1;
2900    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2901    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2902            iCur);
2903    iHiwtr = iCur = -1;
2904    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2905    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2906            iCur);
2907  }
2908
2909  if( pArg->pStmt ){
2910    int iHit, iMiss;
2911    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2912                               bReset);
2913    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2914    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2915    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2916    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2917    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2918    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2919    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2920    if( iHit || iMiss ){
2921      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2922            iHit, iHit+iMiss);
2923    }
2924    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2925    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2926    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2927    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2928    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2929    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2930    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2931    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2932  }
2933
2934#ifdef __linux__
2935  displayLinuxIoStats(pArg->out);
2936#endif
2937
2938  /* Do not remove this machine readable comment: extra-stats-output-here */
2939
2940  return 0;
2941}
2942
2943/*
2944** Display scan stats.
2945*/
2946static void display_scanstats(
2947  sqlite3 *db,                    /* Database to query */
2948  ShellState *pArg                /* Pointer to ShellState */
2949){
2950#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2951  UNUSED_PARAMETER(db);
2952  UNUSED_PARAMETER(pArg);
2953#else
2954  int i, k, n, mx;
2955  raw_printf(pArg->out, "-------- scanstats --------\n");
2956  mx = 0;
2957  for(k=0; k<=mx; k++){
2958    double rEstLoop = 1.0;
2959    for(i=n=0; 1; i++){
2960      sqlite3_stmt *p = pArg->pStmt;
2961      sqlite3_int64 nLoop, nVisit;
2962      double rEst;
2963      int iSid;
2964      const char *zExplain;
2965      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2966        break;
2967      }
2968      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2969      if( iSid>mx ) mx = iSid;
2970      if( iSid!=k ) continue;
2971      if( n==0 ){
2972        rEstLoop = (double)nLoop;
2973        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2974      }
2975      n++;
2976      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2977      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2978      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2979      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2980      rEstLoop *= rEst;
2981      raw_printf(pArg->out,
2982          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2983          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2984      );
2985    }
2986  }
2987  raw_printf(pArg->out, "---------------------------\n");
2988#endif
2989}
2990
2991/*
2992** Parameter azArray points to a zero-terminated array of strings. zStr
2993** points to a single nul-terminated string. Return non-zero if zStr
2994** is equal, according to strcmp(), to any of the strings in the array.
2995** Otherwise, return zero.
2996*/
2997static int str_in_array(const char *zStr, const char **azArray){
2998  int i;
2999  for(i=0; azArray[i]; i++){
3000    if( 0==strcmp(zStr, azArray[i]) ) return 1;
3001  }
3002  return 0;
3003}
3004
3005/*
3006** If compiled statement pSql appears to be an EXPLAIN statement, allocate
3007** and populate the ShellState.aiIndent[] array with the number of
3008** spaces each opcode should be indented before it is output.
3009**
3010** The indenting rules are:
3011**
3012**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3013**       all opcodes that occur between the p2 jump destination and the opcode
3014**       itself by 2 spaces.
3015**
3016**     * Do the previous for "Return" instructions for when P2 is positive.
3017**       See tag-20220407a in wherecode.c and vdbe.c.
3018**
3019**     * For each "Goto", if the jump destination is earlier in the program
3020**       and ends on one of:
3021**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
3022**       or if the P1 parameter is one instead of zero,
3023**       then indent all opcodes between the earlier instruction
3024**       and "Goto" by 2 spaces.
3025*/
3026static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
3027  const char *zSql;               /* The text of the SQL statement */
3028  const char *z;                  /* Used to check if this is an EXPLAIN */
3029  int *abYield = 0;               /* True if op is an OP_Yield */
3030  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
3031  int iOp;                        /* Index of operation in p->aiIndent[] */
3032
3033  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3034                           "Return", 0 };
3035  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3036                            "Rewind", 0 };
3037  const char *azGoto[] = { "Goto", 0 };
3038
3039  /* Try to figure out if this is really an EXPLAIN statement. If this
3040  ** cannot be verified, return early.  */
3041  if( sqlite3_column_count(pSql)!=8 ){
3042    p->cMode = p->mode;
3043    return;
3044  }
3045  zSql = sqlite3_sql(pSql);
3046  if( zSql==0 ) return;
3047  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3048  if( sqlite3_strnicmp(z, "explain", 7) ){
3049    p->cMode = p->mode;
3050    return;
3051  }
3052
3053  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3054    int i;
3055    int iAddr = sqlite3_column_int(pSql, 0);
3056    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3057
3058    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3059    ** p2 is an instruction address, set variable p2op to the index of that
3060    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3061    ** the current instruction is part of a sub-program generated by an
3062    ** SQL trigger or foreign key.  */
3063    int p2 = sqlite3_column_int(pSql, 3);
3064    int p2op = (p2 + (iOp-iAddr));
3065
3066    /* Grow the p->aiIndent array as required */
3067    if( iOp>=nAlloc ){
3068      if( iOp==0 ){
3069        /* Do further verfication that this is explain output.  Abort if
3070        ** it is not */
3071        static const char *explainCols[] = {
3072           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3073        int jj;
3074        for(jj=0; jj<ArraySize(explainCols); jj++){
3075          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3076            p->cMode = p->mode;
3077            sqlite3_reset(pSql);
3078            return;
3079          }
3080        }
3081      }
3082      nAlloc += 100;
3083      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3084      shell_check_oom(p->aiIndent);
3085      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3086      shell_check_oom(abYield);
3087    }
3088    abYield[iOp] = str_in_array(zOp, azYield);
3089    p->aiIndent[iOp] = 0;
3090    p->nIndent = iOp+1;
3091
3092    if( str_in_array(zOp, azNext) && p2op>0 ){
3093      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3094    }
3095    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3096     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3097    ){
3098      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3099    }
3100  }
3101
3102  p->iIndent = 0;
3103  sqlite3_free(abYield);
3104  sqlite3_reset(pSql);
3105}
3106
3107/*
3108** Free the array allocated by explain_data_prepare().
3109*/
3110static void explain_data_delete(ShellState *p){
3111  sqlite3_free(p->aiIndent);
3112  p->aiIndent = 0;
3113  p->nIndent = 0;
3114  p->iIndent = 0;
3115}
3116
3117/*
3118** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3119*/
3120static unsigned int savedSelectTrace;
3121static unsigned int savedWhereTrace;
3122static void disable_debug_trace_modes(void){
3123  unsigned int zero = 0;
3124  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3125  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3126  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3127  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3128}
3129static void restore_debug_trace_modes(void){
3130  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3131  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3132}
3133
3134/* Create the TEMP table used to store parameter bindings */
3135static void bind_table_init(ShellState *p){
3136  int wrSchema = 0;
3137  int defensiveMode = 0;
3138  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3139  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3140  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3141  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3142  sqlite3_exec(p->db,
3143    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3144    "  key TEXT PRIMARY KEY,\n"
3145    "  value\n"
3146    ") WITHOUT ROWID;",
3147    0, 0, 0);
3148  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3149  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3150}
3151
3152/*
3153** Bind parameters on a prepared statement.
3154**
3155** Parameter bindings are taken from a TEMP table of the form:
3156**
3157**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3158**    WITHOUT ROWID;
3159**
3160** No bindings occur if this table does not exist.  The name of the table
3161** begins with "sqlite_" so that it will not collide with ordinary application
3162** tables.  The table must be in the TEMP schema.
3163*/
3164static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3165  int nVar;
3166  int i;
3167  int rc;
3168  sqlite3_stmt *pQ = 0;
3169
3170  nVar = sqlite3_bind_parameter_count(pStmt);
3171  if( nVar==0 ) return;  /* Nothing to do */
3172  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3173                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3174    return; /* Parameter table does not exist */
3175  }
3176  rc = sqlite3_prepare_v2(pArg->db,
3177          "SELECT value FROM temp.sqlite_parameters"
3178          " WHERE key=?1", -1, &pQ, 0);
3179  if( rc || pQ==0 ) return;
3180  for(i=1; i<=nVar; i++){
3181    char zNum[30];
3182    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3183    if( zVar==0 ){
3184      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3185      zVar = zNum;
3186    }
3187    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3188    if( sqlite3_step(pQ)==SQLITE_ROW ){
3189      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3190    }else{
3191      sqlite3_bind_null(pStmt, i);
3192    }
3193    sqlite3_reset(pQ);
3194  }
3195  sqlite3_finalize(pQ);
3196}
3197
3198/*
3199** UTF8 box-drawing characters.  Imagine box lines like this:
3200**
3201**           1
3202**           |
3203**       4 --+-- 2
3204**           |
3205**           3
3206**
3207** Each box characters has between 2 and 4 of the lines leading from
3208** the center.  The characters are here identified by the numbers of
3209** their corresponding lines.
3210*/
3211#define BOX_24   "\342\224\200"  /* U+2500 --- */
3212#define BOX_13   "\342\224\202"  /* U+2502  |  */
3213#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3214#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3215#define BOX_12   "\342\224\224"  /* U+2514  '- */
3216#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3217#define BOX_123  "\342\224\234"  /* U+251c  |- */
3218#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3219#define BOX_234  "\342\224\254"  /* U+252c -,- */
3220#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3221#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3222
3223/* Draw horizontal line N characters long using unicode box
3224** characters
3225*/
3226static void print_box_line(FILE *out, int N){
3227  const char zDash[] =
3228      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3229      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3230  const int nDash = sizeof(zDash) - 1;
3231  N *= 3;
3232  while( N>nDash ){
3233    utf8_printf(out, zDash);
3234    N -= nDash;
3235  }
3236  utf8_printf(out, "%.*s", N, zDash);
3237}
3238
3239/*
3240** Draw a horizontal separator for a MODE_Box table.
3241*/
3242static void print_box_row_separator(
3243  ShellState *p,
3244  int nArg,
3245  const char *zSep1,
3246  const char *zSep2,
3247  const char *zSep3
3248){
3249  int i;
3250  if( nArg>0 ){
3251    utf8_printf(p->out, "%s", zSep1);
3252    print_box_line(p->out, p->actualWidth[0]+2);
3253    for(i=1; i<nArg; i++){
3254      utf8_printf(p->out, "%s", zSep2);
3255      print_box_line(p->out, p->actualWidth[i]+2);
3256    }
3257    utf8_printf(p->out, "%s", zSep3);
3258  }
3259  fputs("\n", p->out);
3260}
3261
3262/*
3263** z[] is a line of text that is to be displayed the .mode box or table or
3264** similar tabular formats.  z[] might contain control characters such
3265** as \n, \t, \f, or \r.
3266**
3267** Compute characters to display on the first line of z[].  Stop at the
3268** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3269** from malloc()) of that first line, which caller should free sometime.
3270** Write anything to display on the next line into *pzTail.  If this is
3271** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3272*/
3273static char *translateForDisplayAndDup(
3274  const unsigned char *z,            /* Input text to be transformed */
3275  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3276  int mxWidth,                       /* Max width.  0 means no limit */
3277  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3278){
3279  int i;                 /* Input bytes consumed */
3280  int j;                 /* Output bytes generated */
3281  int k;                 /* Input bytes to be displayed */
3282  int n;                 /* Output column number */
3283  unsigned char *zOut;   /* Output text */
3284
3285  if( z==0 ){
3286    *pzTail = 0;
3287    return 0;
3288  }
3289  if( mxWidth<0 ) mxWidth = -mxWidth;
3290  if( mxWidth==0 ) mxWidth = 1000000;
3291  i = j = n = 0;
3292  while( n<mxWidth ){
3293    if( z[i]>=' ' ){
3294      n++;
3295      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3296      continue;
3297    }
3298    if( z[i]=='\t' ){
3299      do{
3300        n++;
3301        j++;
3302      }while( (n&7)!=0 && n<mxWidth );
3303      i++;
3304      continue;
3305    }
3306    break;
3307  }
3308  if( n>=mxWidth && bWordWrap  ){
3309    /* Perhaps try to back up to a better place to break the line */
3310    for(k=i; k>i/2; k--){
3311      if( isspace(z[k-1]) ) break;
3312    }
3313    if( k<=i/2 ){
3314      for(k=i; k>i/2; k--){
3315        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3316      }
3317    }
3318    if( k<=i/2 ){
3319      k = i;
3320    }else{
3321      i = k;
3322      while( z[i]==' ' ) i++;
3323    }
3324  }else{
3325    k = i;
3326  }
3327  if( n>=mxWidth && z[i]>=' ' ){
3328   *pzTail = &z[i];
3329  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3330    *pzTail = z[i+2] ? &z[i+2] : 0;
3331  }else if( z[i]==0 || z[i+1]==0 ){
3332    *pzTail = 0;
3333  }else{
3334    *pzTail = &z[i+1];
3335  }
3336  zOut = malloc( j+1 );
3337  shell_check_oom(zOut);
3338  i = j = n = 0;
3339  while( i<k ){
3340    if( z[i]>=' ' ){
3341      n++;
3342      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3343      continue;
3344    }
3345    if( z[i]=='\t' ){
3346      do{
3347        n++;
3348        zOut[j++] = ' ';
3349      }while( (n&7)!=0 && n<mxWidth );
3350      i++;
3351      continue;
3352    }
3353    break;
3354  }
3355  zOut[j] = 0;
3356  return (char*)zOut;
3357}
3358
3359/* Extract the value of the i-th current column for pStmt as an SQL literal
3360** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3361** the caller.
3362*/
3363static char *quoted_column(sqlite3_stmt *pStmt, int i){
3364  switch( sqlite3_column_type(pStmt, i) ){
3365    case SQLITE_NULL: {
3366      return sqlite3_mprintf("NULL");
3367    }
3368    case SQLITE_INTEGER:
3369    case SQLITE_FLOAT: {
3370      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3371    }
3372    case SQLITE_TEXT: {
3373      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3374    }
3375    case SQLITE_BLOB: {
3376      int j;
3377      sqlite3_str *pStr = sqlite3_str_new(0);
3378      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3379      int n = sqlite3_column_bytes(pStmt,i);
3380      sqlite3_str_append(pStr, "x'", 2);
3381      for(j=0; j<n; j++){
3382        sqlite3_str_appendf(pStr, "%02x", a[j]);
3383      }
3384      sqlite3_str_append(pStr, "'", 1);
3385      return sqlite3_str_finish(pStr);
3386    }
3387  }
3388  return 0; /* Not reached */
3389}
3390
3391/*
3392** Run a prepared statement and output the result in one of the
3393** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3394** or MODE_Box.
3395**
3396** This is different from ordinary exec_prepared_stmt() in that
3397** it has to run the entire query and gather the results into memory
3398** first, in order to determine column widths, before providing
3399** any output.
3400*/
3401static void exec_prepared_stmt_columnar(
3402  ShellState *p,                        /* Pointer to ShellState */
3403  sqlite3_stmt *pStmt                   /* Statment to run */
3404){
3405  sqlite3_int64 nRow = 0;
3406  int nColumn = 0;
3407  char **azData = 0;
3408  sqlite3_int64 nAlloc = 0;
3409  char *abRowDiv = 0;
3410  const unsigned char *uz;
3411  const char *z;
3412  char **azQuoted = 0;
3413  int rc;
3414  sqlite3_int64 i, nData;
3415  int j, nTotal, w, n;
3416  const char *colSep = 0;
3417  const char *rowSep = 0;
3418  const unsigned char **azNextLine = 0;
3419  int bNextLine = 0;
3420  int bMultiLineRowExists = 0;
3421  int bw = p->cmOpts.bWordWrap;
3422  const char *zEmpty = "";
3423  const char *zShowNull = p->nullValue;
3424
3425  rc = sqlite3_step(pStmt);
3426  if( rc!=SQLITE_ROW ) return;
3427  nColumn = sqlite3_column_count(pStmt);
3428  nAlloc = nColumn*4;
3429  if( nAlloc<=0 ) nAlloc = 1;
3430  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3431  shell_check_oom(azData);
3432  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3433  shell_check_oom((void*)azNextLine);
3434  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3435  if( p->cmOpts.bQuote ){
3436    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3437    shell_check_oom(azQuoted);
3438    memset(azQuoted, 0, nColumn*sizeof(char*) );
3439  }
3440  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3441  shell_check_oom(abRowDiv);
3442  if( nColumn>p->nWidth ){
3443    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3444    shell_check_oom(p->colWidth);
3445    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3446    p->nWidth = nColumn;
3447    p->actualWidth = &p->colWidth[nColumn];
3448  }
3449  memset(p->actualWidth, 0, nColumn*sizeof(int));
3450  for(i=0; i<nColumn; i++){
3451    w = p->colWidth[i];
3452    if( w<0 ) w = -w;
3453    p->actualWidth[i] = w;
3454  }
3455  for(i=0; i<nColumn; i++){
3456    const unsigned char *zNotUsed;
3457    int wx = p->colWidth[i];
3458    if( wx==0 ){
3459      wx = p->cmOpts.iWrap;
3460    }
3461    if( wx<0 ) wx = -wx;
3462    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3463    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3464  }
3465  do{
3466    int useNextLine = bNextLine;
3467    bNextLine = 0;
3468    if( (nRow+2)*nColumn >= nAlloc ){
3469      nAlloc *= 2;
3470      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3471      shell_check_oom(azData);
3472      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3473      shell_check_oom(abRowDiv);
3474    }
3475    abRowDiv[nRow] = 1;
3476    nRow++;
3477    for(i=0; i<nColumn; i++){
3478      int wx = p->colWidth[i];
3479      if( wx==0 ){
3480        wx = p->cmOpts.iWrap;
3481      }
3482      if( wx<0 ) wx = -wx;
3483      if( useNextLine ){
3484        uz = azNextLine[i];
3485        if( uz==0 ) uz = (u8*)zEmpty;
3486      }else if( p->cmOpts.bQuote ){
3487        sqlite3_free(azQuoted[i]);
3488        azQuoted[i] = quoted_column(pStmt,i);
3489        uz = (const unsigned char*)azQuoted[i];
3490      }else{
3491        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3492        if( uz==0 ) uz = (u8*)zShowNull;
3493      }
3494      azData[nRow*nColumn + i]
3495        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3496      if( azNextLine[i] ){
3497        bNextLine = 1;
3498        abRowDiv[nRow-1] = 0;
3499        bMultiLineRowExists = 1;
3500      }
3501    }
3502  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3503  nTotal = nColumn*(nRow+1);
3504  for(i=0; i<nTotal; i++){
3505    z = azData[i];
3506    if( z==0 ) z = (char*)zEmpty;
3507    n = strlenChar(z);
3508    j = i%nColumn;
3509    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3510  }
3511  if( seenInterrupt ) goto columnar_end;
3512  if( nColumn==0 ) goto columnar_end;
3513  switch( p->cMode ){
3514    case MODE_Column: {
3515      colSep = "  ";
3516      rowSep = "\n";
3517      if( p->showHeader ){
3518        for(i=0; i<nColumn; i++){
3519          w = p->actualWidth[i];
3520          if( p->colWidth[i]<0 ) w = -w;
3521          utf8_width_print(p->out, w, azData[i]);
3522          fputs(i==nColumn-1?"\n":"  ", p->out);
3523        }
3524        for(i=0; i<nColumn; i++){
3525          print_dashes(p->out, p->actualWidth[i]);
3526          fputs(i==nColumn-1?"\n":"  ", p->out);
3527        }
3528      }
3529      break;
3530    }
3531    case MODE_Table: {
3532      colSep = " | ";
3533      rowSep = " |\n";
3534      print_row_separator(p, nColumn, "+");
3535      fputs("| ", p->out);
3536      for(i=0; i<nColumn; i++){
3537        w = p->actualWidth[i];
3538        n = strlenChar(azData[i]);
3539        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3540        fputs(i==nColumn-1?" |\n":" | ", p->out);
3541      }
3542      print_row_separator(p, nColumn, "+");
3543      break;
3544    }
3545    case MODE_Markdown: {
3546      colSep = " | ";
3547      rowSep = " |\n";
3548      fputs("| ", p->out);
3549      for(i=0; i<nColumn; i++){
3550        w = p->actualWidth[i];
3551        n = strlenChar(azData[i]);
3552        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3553        fputs(i==nColumn-1?" |\n":" | ", p->out);
3554      }
3555      print_row_separator(p, nColumn, "|");
3556      break;
3557    }
3558    case MODE_Box: {
3559      colSep = " " BOX_13 " ";
3560      rowSep = " " BOX_13 "\n";
3561      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3562      utf8_printf(p->out, BOX_13 " ");
3563      for(i=0; i<nColumn; i++){
3564        w = p->actualWidth[i];
3565        n = strlenChar(azData[i]);
3566        utf8_printf(p->out, "%*s%s%*s%s",
3567            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3568            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3569      }
3570      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3571      break;
3572    }
3573  }
3574  for(i=nColumn, j=0; i<nTotal; i++, j++){
3575    if( j==0 && p->cMode!=MODE_Column ){
3576      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3577    }
3578    z = azData[i];
3579    if( z==0 ) z = p->nullValue;
3580    w = p->actualWidth[j];
3581    if( p->colWidth[j]<0 ) w = -w;
3582    utf8_width_print(p->out, w, z);
3583    if( j==nColumn-1 ){
3584      utf8_printf(p->out, "%s", rowSep);
3585      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3586        if( p->cMode==MODE_Table ){
3587          print_row_separator(p, nColumn, "+");
3588        }else if( p->cMode==MODE_Box ){
3589          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3590        }else if( p->cMode==MODE_Column ){
3591          raw_printf(p->out, "\n");
3592        }
3593      }
3594      j = -1;
3595      if( seenInterrupt ) goto columnar_end;
3596    }else{
3597      utf8_printf(p->out, "%s", colSep);
3598    }
3599  }
3600  if( p->cMode==MODE_Table ){
3601    print_row_separator(p, nColumn, "+");
3602  }else if( p->cMode==MODE_Box ){
3603    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3604  }
3605columnar_end:
3606  if( seenInterrupt ){
3607    utf8_printf(p->out, "Interrupt\n");
3608  }
3609  nData = (nRow+1)*nColumn;
3610  for(i=0; i<nData; i++){
3611    z = azData[i];
3612    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3613  }
3614  sqlite3_free(azData);
3615  sqlite3_free((void*)azNextLine);
3616  sqlite3_free(abRowDiv);
3617  if( azQuoted ){
3618    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3619    sqlite3_free(azQuoted);
3620  }
3621}
3622
3623/*
3624** Run a prepared statement
3625*/
3626static void exec_prepared_stmt(
3627  ShellState *pArg,                                /* Pointer to ShellState */
3628  sqlite3_stmt *pStmt                              /* Statment to run */
3629){
3630  int rc;
3631  sqlite3_uint64 nRow = 0;
3632
3633  if( pArg->cMode==MODE_Column
3634   || pArg->cMode==MODE_Table
3635   || pArg->cMode==MODE_Box
3636   || pArg->cMode==MODE_Markdown
3637  ){
3638    exec_prepared_stmt_columnar(pArg, pStmt);
3639    return;
3640  }
3641
3642  /* perform the first step.  this will tell us if we
3643  ** have a result set or not and how wide it is.
3644  */
3645  rc = sqlite3_step(pStmt);
3646  /* if we have a result set... */
3647  if( SQLITE_ROW == rc ){
3648    /* allocate space for col name ptr, value ptr, and type */
3649    int nCol = sqlite3_column_count(pStmt);
3650    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3651    if( !pData ){
3652      shell_out_of_memory();
3653    }else{
3654      char **azCols = (char **)pData;      /* Names of result columns */
3655      char **azVals = &azCols[nCol];       /* Results */
3656      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3657      int i, x;
3658      assert(sizeof(int) <= sizeof(char *));
3659      /* save off ptrs to column names */
3660      for(i=0; i<nCol; i++){
3661        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3662      }
3663      do{
3664        nRow++;
3665        /* extract the data and data types */
3666        for(i=0; i<nCol; i++){
3667          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3668          if( x==SQLITE_BLOB
3669           && pArg
3670           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3671          ){
3672            azVals[i] = "";
3673          }else{
3674            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3675          }
3676          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3677            rc = SQLITE_NOMEM;
3678            break; /* from for */
3679          }
3680        } /* end for */
3681
3682        /* if data and types extracted successfully... */
3683        if( SQLITE_ROW == rc ){
3684          /* call the supplied callback with the result row data */
3685          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3686            rc = SQLITE_ABORT;
3687          }else{
3688            rc = sqlite3_step(pStmt);
3689          }
3690        }
3691      } while( SQLITE_ROW == rc );
3692      sqlite3_free(pData);
3693      if( pArg->cMode==MODE_Json ){
3694        fputs("]\n", pArg->out);
3695      }else if( pArg->cMode==MODE_Count ){
3696        char zBuf[200];
3697        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3698                         nRow, nRow!=1 ? "s" : "");
3699        printf("%s", zBuf);
3700      }
3701    }
3702  }
3703}
3704
3705#ifndef SQLITE_OMIT_VIRTUALTABLE
3706/*
3707** This function is called to process SQL if the previous shell command
3708** was ".expert". It passes the SQL in the second argument directly to
3709** the sqlite3expert object.
3710**
3711** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3712** code. In this case, (*pzErr) may be set to point to a buffer containing
3713** an English language error message. It is the responsibility of the
3714** caller to eventually free this buffer using sqlite3_free().
3715*/
3716static int expertHandleSQL(
3717  ShellState *pState,
3718  const char *zSql,
3719  char **pzErr
3720){
3721  assert( pState->expert.pExpert );
3722  assert( pzErr==0 || *pzErr==0 );
3723  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3724}
3725
3726/*
3727** This function is called either to silently clean up the object
3728** created by the ".expert" command (if bCancel==1), or to generate a
3729** report from it and then clean it up (if bCancel==0).
3730**
3731** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3732** code. In this case, (*pzErr) may be set to point to a buffer containing
3733** an English language error message. It is the responsibility of the
3734** caller to eventually free this buffer using sqlite3_free().
3735*/
3736static int expertFinish(
3737  ShellState *pState,
3738  int bCancel,
3739  char **pzErr
3740){
3741  int rc = SQLITE_OK;
3742  sqlite3expert *p = pState->expert.pExpert;
3743  assert( p );
3744  assert( bCancel || pzErr==0 || *pzErr==0 );
3745  if( bCancel==0 ){
3746    FILE *out = pState->out;
3747    int bVerbose = pState->expert.bVerbose;
3748
3749    rc = sqlite3_expert_analyze(p, pzErr);
3750    if( rc==SQLITE_OK ){
3751      int nQuery = sqlite3_expert_count(p);
3752      int i;
3753
3754      if( bVerbose ){
3755        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3756        raw_printf(out, "-- Candidates -----------------------------\n");
3757        raw_printf(out, "%s\n", zCand);
3758      }
3759      for(i=0; i<nQuery; i++){
3760        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3761        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3762        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3763        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3764        if( bVerbose ){
3765          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3766          raw_printf(out, "%s\n\n", zSql);
3767        }
3768        raw_printf(out, "%s\n", zIdx);
3769        raw_printf(out, "%s\n", zEQP);
3770      }
3771    }
3772  }
3773  sqlite3_expert_destroy(p);
3774  pState->expert.pExpert = 0;
3775  return rc;
3776}
3777
3778/*
3779** Implementation of ".expert" dot command.
3780*/
3781static int expertDotCommand(
3782  ShellState *pState,             /* Current shell tool state */
3783  char **azArg,                   /* Array of arguments passed to dot command */
3784  int nArg                        /* Number of entries in azArg[] */
3785){
3786  int rc = SQLITE_OK;
3787  char *zErr = 0;
3788  int i;
3789  int iSample = 0;
3790
3791  assert( pState->expert.pExpert==0 );
3792  memset(&pState->expert, 0, sizeof(ExpertInfo));
3793
3794  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3795    char *z = azArg[i];
3796    int n;
3797    if( z[0]=='-' && z[1]=='-' ) z++;
3798    n = strlen30(z);
3799    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3800      pState->expert.bVerbose = 1;
3801    }
3802    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3803      if( i==(nArg-1) ){
3804        raw_printf(stderr, "option requires an argument: %s\n", z);
3805        rc = SQLITE_ERROR;
3806      }else{
3807        iSample = (int)integerValue(azArg[++i]);
3808        if( iSample<0 || iSample>100 ){
3809          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3810          rc = SQLITE_ERROR;
3811        }
3812      }
3813    }
3814    else{
3815      raw_printf(stderr, "unknown option: %s\n", z);
3816      rc = SQLITE_ERROR;
3817    }
3818  }
3819
3820  if( rc==SQLITE_OK ){
3821    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3822    if( pState->expert.pExpert==0 ){
3823      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3824      rc = SQLITE_ERROR;
3825    }else{
3826      sqlite3_expert_config(
3827          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3828      );
3829    }
3830  }
3831  sqlite3_free(zErr);
3832
3833  return rc;
3834}
3835#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3836
3837/*
3838** Execute a statement or set of statements.  Print
3839** any result rows/columns depending on the current mode
3840** set via the supplied callback.
3841**
3842** This is very similar to SQLite's built-in sqlite3_exec()
3843** function except it takes a slightly different callback
3844** and callback data argument.
3845*/
3846static int shell_exec(
3847  ShellState *pArg,                         /* Pointer to ShellState */
3848  const char *zSql,                         /* SQL to be evaluated */
3849  char **pzErrMsg                           /* Error msg written here */
3850){
3851  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3852  int rc = SQLITE_OK;             /* Return Code */
3853  int rc2;
3854  const char *zLeftover;          /* Tail of unprocessed SQL */
3855  sqlite3 *db = pArg->db;
3856
3857  if( pzErrMsg ){
3858    *pzErrMsg = NULL;
3859  }
3860
3861#ifndef SQLITE_OMIT_VIRTUALTABLE
3862  if( pArg->expert.pExpert ){
3863    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3864    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3865  }
3866#endif
3867
3868  while( zSql[0] && (SQLITE_OK == rc) ){
3869    static const char *zStmtSql;
3870    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3871    if( SQLITE_OK != rc ){
3872      if( pzErrMsg ){
3873        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3874      }
3875    }else{
3876      if( !pStmt ){
3877        /* this happens for a comment or white-space */
3878        zSql = zLeftover;
3879        while( IsSpace(zSql[0]) ) zSql++;
3880        continue;
3881      }
3882      zStmtSql = sqlite3_sql(pStmt);
3883      if( zStmtSql==0 ) zStmtSql = "";
3884      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3885
3886      /* save off the prepared statment handle and reset row count */
3887      if( pArg ){
3888        pArg->pStmt = pStmt;
3889        pArg->cnt = 0;
3890      }
3891
3892      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3893      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3894        sqlite3_stmt *pExplain;
3895        char *zEQP;
3896        int triggerEQP = 0;
3897        disable_debug_trace_modes();
3898        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3899        if( pArg->autoEQP>=AUTOEQP_trigger ){
3900          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3901        }
3902        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3903        shell_check_oom(zEQP);
3904        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3905        if( rc==SQLITE_OK ){
3906          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3907            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3908            int iEqpId = sqlite3_column_int(pExplain, 0);
3909            int iParentId = sqlite3_column_int(pExplain, 1);
3910            if( zEQPLine==0 ) zEQPLine = "";
3911            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3912            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3913          }
3914          eqp_render(pArg);
3915        }
3916        sqlite3_finalize(pExplain);
3917        sqlite3_free(zEQP);
3918        if( pArg->autoEQP>=AUTOEQP_full ){
3919          /* Also do an EXPLAIN for ".eqp full" mode */
3920          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3921          shell_check_oom(zEQP);
3922          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3923          if( rc==SQLITE_OK ){
3924            pArg->cMode = MODE_Explain;
3925            explain_data_prepare(pArg, pExplain);
3926            exec_prepared_stmt(pArg, pExplain);
3927            explain_data_delete(pArg);
3928          }
3929          sqlite3_finalize(pExplain);
3930          sqlite3_free(zEQP);
3931        }
3932        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3933          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3934          /* Reprepare pStmt before reactiving trace modes */
3935          sqlite3_finalize(pStmt);
3936          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3937          if( pArg ) pArg->pStmt = pStmt;
3938        }
3939        restore_debug_trace_modes();
3940      }
3941
3942      if( pArg ){
3943        pArg->cMode = pArg->mode;
3944        if( pArg->autoExplain ){
3945          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3946            pArg->cMode = MODE_Explain;
3947          }
3948          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3949            pArg->cMode = MODE_EQP;
3950          }
3951        }
3952
3953        /* If the shell is currently in ".explain" mode, gather the extra
3954        ** data required to add indents to the output.*/
3955        if( pArg->cMode==MODE_Explain ){
3956          explain_data_prepare(pArg, pStmt);
3957        }
3958      }
3959
3960      bind_prepared_stmt(pArg, pStmt);
3961      exec_prepared_stmt(pArg, pStmt);
3962      explain_data_delete(pArg);
3963      eqp_render(pArg);
3964
3965      /* print usage stats if stats on */
3966      if( pArg && pArg->statsOn ){
3967        display_stats(db, pArg, 0);
3968      }
3969
3970      /* print loop-counters if required */
3971      if( pArg && pArg->scanstatsOn ){
3972        display_scanstats(db, pArg);
3973      }
3974
3975      /* Finalize the statement just executed. If this fails, save a
3976      ** copy of the error message. Otherwise, set zSql to point to the
3977      ** next statement to execute. */
3978      rc2 = sqlite3_finalize(pStmt);
3979      if( rc!=SQLITE_NOMEM ) rc = rc2;
3980      if( rc==SQLITE_OK ){
3981        zSql = zLeftover;
3982        while( IsSpace(zSql[0]) ) zSql++;
3983      }else if( pzErrMsg ){
3984        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3985      }
3986
3987      /* clear saved stmt handle */
3988      if( pArg ){
3989        pArg->pStmt = NULL;
3990      }
3991    }
3992  } /* end while */
3993
3994  return rc;
3995}
3996
3997/*
3998** Release memory previously allocated by tableColumnList().
3999*/
4000static void freeColumnList(char **azCol){
4001  int i;
4002  for(i=1; azCol[i]; i++){
4003    sqlite3_free(azCol[i]);
4004  }
4005  /* azCol[0] is a static string */
4006  sqlite3_free(azCol);
4007}
4008
4009/*
4010** Return a list of pointers to strings which are the names of all
4011** columns in table zTab.   The memory to hold the names is dynamically
4012** allocated and must be released by the caller using a subsequent call
4013** to freeColumnList().
4014**
4015** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
4016** value that needs to be preserved, then azCol[0] is filled in with the
4017** name of the rowid column.
4018**
4019** The first regular column in the table is azCol[1].  The list is terminated
4020** by an entry with azCol[i]==0.
4021*/
4022static char **tableColumnList(ShellState *p, const char *zTab){
4023  char **azCol = 0;
4024  sqlite3_stmt *pStmt;
4025  char *zSql;
4026  int nCol = 0;
4027  int nAlloc = 0;
4028  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
4029  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
4030  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
4031  int rc;
4032
4033  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
4034  shell_check_oom(zSql);
4035  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4036  sqlite3_free(zSql);
4037  if( rc ) return 0;
4038  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4039    if( nCol>=nAlloc-2 ){
4040      nAlloc = nAlloc*2 + nCol + 10;
4041      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4042      shell_check_oom(azCol);
4043    }
4044    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4045    shell_check_oom(azCol[nCol]);
4046    if( sqlite3_column_int(pStmt, 5) ){
4047      nPK++;
4048      if( nPK==1
4049       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4050                          "INTEGER")==0
4051      ){
4052        isIPK = 1;
4053      }else{
4054        isIPK = 0;
4055      }
4056    }
4057  }
4058  sqlite3_finalize(pStmt);
4059  if( azCol==0 ) return 0;
4060  azCol[0] = 0;
4061  azCol[nCol+1] = 0;
4062
4063  /* The decision of whether or not a rowid really needs to be preserved
4064  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4065  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4066  ** rowids on tables where the rowid is inaccessible because there are other
4067  ** columns in the table named "rowid", "_rowid_", and "oid".
4068  */
4069  if( preserveRowid && isIPK ){
4070    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4071    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4072    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4073    ** ROWID aliases.  To distinguish these cases, check to see if
4074    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4075    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4076    */
4077    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4078                           " WHERE origin='pk'", zTab);
4079    shell_check_oom(zSql);
4080    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4081    sqlite3_free(zSql);
4082    if( rc ){
4083      freeColumnList(azCol);
4084      return 0;
4085    }
4086    rc = sqlite3_step(pStmt);
4087    sqlite3_finalize(pStmt);
4088    preserveRowid = rc==SQLITE_ROW;
4089  }
4090  if( preserveRowid ){
4091    /* Only preserve the rowid if we can find a name to use for the
4092    ** rowid */
4093    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4094    int i, j;
4095    for(j=0; j<3; j++){
4096      for(i=1; i<=nCol; i++){
4097        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4098      }
4099      if( i>nCol ){
4100        /* At this point, we know that azRowid[j] is not the name of any
4101        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4102        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4103        ** tables will fail this last check */
4104        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4105        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4106        break;
4107      }
4108    }
4109  }
4110  return azCol;
4111}
4112
4113/*
4114** Toggle the reverse_unordered_selects setting.
4115*/
4116static void toggleSelectOrder(sqlite3 *db){
4117  sqlite3_stmt *pStmt = 0;
4118  int iSetting = 0;
4119  char zStmt[100];
4120  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4121  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4122    iSetting = sqlite3_column_int(pStmt, 0);
4123  }
4124  sqlite3_finalize(pStmt);
4125  sqlite3_snprintf(sizeof(zStmt), zStmt,
4126       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4127  sqlite3_exec(db, zStmt, 0, 0, 0);
4128}
4129
4130/*
4131** This is a different callback routine used for dumping the database.
4132** Each row received by this callback consists of a table name,
4133** the table type ("index" or "table") and SQL to create the table.
4134** This routine should print text sufficient to recreate the table.
4135*/
4136static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4137  int rc;
4138  const char *zTable;
4139  const char *zType;
4140  const char *zSql;
4141  ShellState *p = (ShellState *)pArg;
4142  int dataOnly;
4143  int noSys;
4144
4145  UNUSED_PARAMETER(azNotUsed);
4146  if( nArg!=3 || azArg==0 ) return 0;
4147  zTable = azArg[0];
4148  zType = azArg[1];
4149  zSql = azArg[2];
4150  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4151  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4152
4153  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4154    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4155  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4156    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4157  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4158    return 0;
4159  }else if( dataOnly ){
4160    /* no-op */
4161  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4162    char *zIns;
4163    if( !p->writableSchema ){
4164      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4165      p->writableSchema = 1;
4166    }
4167    zIns = sqlite3_mprintf(
4168       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4169       "VALUES('table','%q','%q',0,'%q');",
4170       zTable, zTable, zSql);
4171    shell_check_oom(zIns);
4172    utf8_printf(p->out, "%s\n", zIns);
4173    sqlite3_free(zIns);
4174    return 0;
4175  }else{
4176    printSchemaLine(p->out, zSql, ";\n");
4177  }
4178
4179  if( strcmp(zType, "table")==0 ){
4180    ShellText sSelect;
4181    ShellText sTable;
4182    char **azCol;
4183    int i;
4184    char *savedDestTable;
4185    int savedMode;
4186
4187    azCol = tableColumnList(p, zTable);
4188    if( azCol==0 ){
4189      p->nErr++;
4190      return 0;
4191    }
4192
4193    /* Always quote the table name, even if it appears to be pure ascii,
4194    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4195    initText(&sTable);
4196    appendText(&sTable, zTable, quoteChar(zTable));
4197    /* If preserving the rowid, add a column list after the table name.
4198    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4199    ** instead of the usual "INSERT INTO tab VALUES(...)".
4200    */
4201    if( azCol[0] ){
4202      appendText(&sTable, "(", 0);
4203      appendText(&sTable, azCol[0], 0);
4204      for(i=1; azCol[i]; i++){
4205        appendText(&sTable, ",", 0);
4206        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4207      }
4208      appendText(&sTable, ")", 0);
4209    }
4210
4211    /* Build an appropriate SELECT statement */
4212    initText(&sSelect);
4213    appendText(&sSelect, "SELECT ", 0);
4214    if( azCol[0] ){
4215      appendText(&sSelect, azCol[0], 0);
4216      appendText(&sSelect, ",", 0);
4217    }
4218    for(i=1; azCol[i]; i++){
4219      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4220      if( azCol[i+1] ){
4221        appendText(&sSelect, ",", 0);
4222      }
4223    }
4224    freeColumnList(azCol);
4225    appendText(&sSelect, " FROM ", 0);
4226    appendText(&sSelect, zTable, quoteChar(zTable));
4227
4228    savedDestTable = p->zDestTable;
4229    savedMode = p->mode;
4230    p->zDestTable = sTable.z;
4231    p->mode = p->cMode = MODE_Insert;
4232    rc = shell_exec(p, sSelect.z, 0);
4233    if( (rc&0xff)==SQLITE_CORRUPT ){
4234      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4235      toggleSelectOrder(p->db);
4236      shell_exec(p, sSelect.z, 0);
4237      toggleSelectOrder(p->db);
4238    }
4239    p->zDestTable = savedDestTable;
4240    p->mode = savedMode;
4241    freeText(&sTable);
4242    freeText(&sSelect);
4243    if( rc ) p->nErr++;
4244  }
4245  return 0;
4246}
4247
4248/*
4249** Run zQuery.  Use dump_callback() as the callback routine so that
4250** the contents of the query are output as SQL statements.
4251**
4252** If we get a SQLITE_CORRUPT error, rerun the query after appending
4253** "ORDER BY rowid DESC" to the end.
4254*/
4255static int run_schema_dump_query(
4256  ShellState *p,
4257  const char *zQuery
4258){
4259  int rc;
4260  char *zErr = 0;
4261  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4262  if( rc==SQLITE_CORRUPT ){
4263    char *zQ2;
4264    int len = strlen30(zQuery);
4265    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4266    if( zErr ){
4267      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4268      sqlite3_free(zErr);
4269      zErr = 0;
4270    }
4271    zQ2 = malloc( len+100 );
4272    if( zQ2==0 ) return rc;
4273    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4274    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4275    if( rc ){
4276      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4277    }else{
4278      rc = SQLITE_CORRUPT;
4279    }
4280    sqlite3_free(zErr);
4281    free(zQ2);
4282  }
4283  return rc;
4284}
4285
4286/*
4287** Text of help messages.
4288**
4289** The help text for each individual command begins with a line that starts
4290** with ".".  Subsequent lines are supplemental information.
4291**
4292** There must be two or more spaces between the end of the command and the
4293** start of the description of what that command does.
4294*/
4295static const char *(azHelp[]) = {
4296#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4297  && !defined(SQLITE_SHELL_FIDDLE)
4298  ".archive ...             Manage SQL archives",
4299  "   Each command must have exactly one of the following options:",
4300  "     -c, --create               Create a new archive",
4301  "     -u, --update               Add or update files with changed mtime",
4302  "     -i, --insert               Like -u but always add even if unchanged",
4303  "     -r, --remove               Remove files from archive",
4304  "     -t, --list                 List contents of archive",
4305  "     -x, --extract              Extract files from archive",
4306  "   Optional arguments:",
4307  "     -v, --verbose              Print each filename as it is processed",
4308  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4309  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4310  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4311  "     -g, --glob                 Use glob matching for names in archive",
4312  "     -n, --dryrun               Show the SQL that would have occurred",
4313  "   Examples:",
4314  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4315  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4316  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4317  "   See also:",
4318  "      http://sqlite.org/cli.html#sqlite_archive_support",
4319#endif
4320#ifndef SQLITE_OMIT_AUTHORIZATION
4321  ".auth ON|OFF             Show authorizer callbacks",
4322#endif
4323#ifndef SQLITE_SHELL_FIDDLE
4324  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4325  "   Options:",
4326  "       --append            Use the appendvfs",
4327  "       --async             Write to FILE without journal and fsync()",
4328#endif
4329  ".bail on|off             Stop after hitting an error.  Default OFF",
4330  ".binary on|off           Turn binary output on or off.  Default OFF",
4331#ifndef SQLITE_SHELL_FIDDLE
4332  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4333#endif
4334  ".changes on|off          Show number of rows changed by SQL",
4335#ifndef SQLITE_SHELL_FIDDLE
4336  ".check GLOB              Fail if output since .testcase does not match",
4337  ".clone NEWDB             Clone data into NEWDB from the existing database",
4338#endif
4339  ".connection [close] [#]  Open or close an auxiliary database connection",
4340  ".databases               List names and files of attached databases",
4341  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4342#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4343  ".dbinfo ?DB?             Show status information about the database",
4344#endif
4345  ".dump ?OBJECTS?          Render database content as SQL",
4346  "   Options:",
4347  "     --data-only            Output only INSERT statements",
4348  "     --newlines             Allow unescaped newline characters in output",
4349  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4350  "     --preserve-rowids      Include ROWID values in the output",
4351  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4352  "   Additional LIKE patterns can be given in subsequent arguments",
4353  ".echo on|off             Turn command echo on or off",
4354  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4355  "   Other Modes:",
4356#ifdef SQLITE_DEBUG
4357  "      test                  Show raw EXPLAIN QUERY PLAN output",
4358  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4359#endif
4360  "      trigger               Like \"full\" but also show trigger bytecode",
4361#ifndef SQLITE_SHELL_FIDDLE
4362  ".excel                   Display the output of next command in spreadsheet",
4363  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4364#endif
4365#ifndef SQLITE_SHELL_FIDDLE
4366  ".exit ?CODE?             Exit this program with return-code CODE",
4367#endif
4368  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4369  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4370  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4371  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4372  "   --help                  Show CMD details",
4373  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4374  ".headers on|off          Turn display of headers on or off",
4375  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4376#ifndef SQLITE_SHELL_FIDDLE
4377  ".import FILE TABLE       Import data from FILE into TABLE",
4378  "   Options:",
4379  "     --ascii               Use \\037 and \\036 as column and row separators",
4380  "     --csv                 Use , and \\n as column and row separators",
4381  "     --skip N              Skip the first N rows of input",
4382  "     --schema S            Target table to be S.TABLE",
4383  "     -v                    \"Verbose\" - increase auxiliary output",
4384  "   Notes:",
4385  "     *  If TABLE does not exist, it is created.  The first row of input",
4386  "        determines the column names.",
4387  "     *  If neither --csv or --ascii are used, the input mode is derived",
4388  "        from the \".mode\" output mode",
4389  "     *  If FILE begins with \"|\" then it is a command that generates the",
4390  "        input text.",
4391#endif
4392#ifndef SQLITE_OMIT_TEST_CONTROL
4393  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4394#endif
4395  ".indexes ?TABLE?         Show names of indexes",
4396  "                           If TABLE is specified, only show indexes for",
4397  "                           tables matching TABLE using the LIKE operator.",
4398#ifdef SQLITE_ENABLE_IOTRACE
4399  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4400#endif
4401  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4402  ".lint OPTIONS            Report potential schema issues.",
4403  "     Options:",
4404  "        fkey-indexes     Find missing foreign key indexes",
4405#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4406  ".load FILE ?ENTRY?       Load an extension library",
4407#endif
4408#ifndef SQLITE_SHELL_FIDDLE
4409  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4410#endif
4411  ".mode MODE ?OPTIONS?     Set output mode",
4412  "   MODE is one of:",
4413  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4414  "     box         Tables using unicode box-drawing characters",
4415  "     csv         Comma-separated values",
4416  "     column      Output in columns.  (See .width)",
4417  "     html        HTML <table> code",
4418  "     insert      SQL insert statements for TABLE",
4419  "     json        Results in a JSON array",
4420  "     line        One value per line",
4421  "     list        Values delimited by \"|\"",
4422  "     markdown    Markdown table format",
4423  "     qbox        Shorthand for \"box --width 60 --quote\"",
4424  "     quote       Escape answers as for SQL",
4425  "     table       ASCII-art table",
4426  "     tabs        Tab-separated values",
4427  "     tcl         TCL list elements",
4428  "   OPTIONS: (for columnar modes or insert mode):",
4429  "     --wrap N       Wrap output lines to no longer than N characters",
4430  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4431  "     --ww           Shorthand for \"--wordwrap 1\"",
4432  "     --quote        Quote output text as SQL literals",
4433  "     --noquote      Do not quote output text",
4434  "     TABLE          The name of SQL table used for \"insert\" mode",
4435#ifndef SQLITE_SHELL_FIDDLE
4436  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4437#endif
4438  ".nullvalue STRING        Use STRING in place of NULL values",
4439#ifndef SQLITE_SHELL_FIDDLE
4440  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4441  "     If FILE begins with '|' then open as a pipe",
4442  "       --bom  Put a UTF8 byte-order mark at the beginning",
4443  "       -e     Send output to the system text editor",
4444  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4445  /* Note that .open is (partially) available in WASM builds but is
4446  ** currently only intended to be used by the fiddle tool, not
4447  ** end users, so is "undocumented." */
4448  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4449  "     Options:",
4450  "        --append        Use appendvfs to append database to the end of FILE",
4451#endif
4452#ifndef SQLITE_OMIT_DESERIALIZE
4453  "        --deserialize   Load into memory using sqlite3_deserialize()",
4454  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4455  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4456#endif
4457  "        --new           Initialize FILE to an empty database",
4458  "        --nofollow      Do not follow symbolic links",
4459  "        --readonly      Open FILE readonly",
4460  "        --zip           FILE is a ZIP archive",
4461#ifndef SQLITE_SHELL_FIDDLE
4462  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4463  "   If FILE begins with '|' then open it as a pipe.",
4464  "   Options:",
4465  "     --bom                 Prefix output with a UTF8 byte-order mark",
4466  "     -e                    Send output to the system text editor",
4467  "     -x                    Send output as CSV to a spreadsheet",
4468#endif
4469  ".parameter CMD ...       Manage SQL parameter bindings",
4470  "   clear                   Erase all bindings",
4471  "   init                    Initialize the TEMP table that holds bindings",
4472  "   list                    List the current parameter bindings",
4473  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4474  "                           PARAMETER should start with one of: $ : @ ?",
4475  "   unset PARAMETER         Remove PARAMETER from the binding table",
4476  ".print STRING...         Print literal STRING",
4477#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4478  ".progress N              Invoke progress handler after every N opcodes",
4479  "   --limit N                 Interrupt after N progress callbacks",
4480  "   --once                    Do no more than one progress interrupt",
4481  "   --quiet|-q                No output except at interrupts",
4482  "   --reset                   Reset the count for each input and interrupt",
4483#endif
4484  ".prompt MAIN CONTINUE    Replace the standard prompts",
4485#ifndef SQLITE_SHELL_FIDDLE
4486  ".quit                    Exit this program",
4487  ".read FILE               Read input from FILE or command output",
4488  "    If FILE begins with \"|\", it is a command that generates the input.",
4489#endif
4490#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4491  ".recover                 Recover as much data as possible from corrupt db.",
4492  "   --freelist-corrupt       Assume the freelist is corrupt",
4493  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4494  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4495  "   --no-rowids              Do not attempt to recover rowid values",
4496  "                            that are not also INTEGER PRIMARY KEYs",
4497#endif
4498#ifndef SQLITE_SHELL_FIDDLE
4499  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4500  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4501#endif
4502  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4503  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4504  "   Options:",
4505  "      --indent             Try to pretty-print the schema",
4506  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4507  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4508  "    Options:",
4509  "       --init               Create a new SELFTEST table",
4510  "       -v                   Verbose output",
4511  ".separator COL ?ROW?     Change the column and row separators",
4512#if defined(SQLITE_ENABLE_SESSION)
4513  ".session ?NAME? CMD ...  Create or control sessions",
4514  "   Subcommands:",
4515  "     attach TABLE             Attach TABLE",
4516  "     changeset FILE           Write a changeset into FILE",
4517  "     close                    Close one session",
4518  "     enable ?BOOLEAN?         Set or query the enable bit",
4519  "     filter GLOB...           Reject tables matching GLOBs",
4520  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4521  "     isempty                  Query whether the session is empty",
4522  "     list                     List currently open session names",
4523  "     open DB NAME             Open a new session on DB",
4524  "     patchset FILE            Write a patchset into FILE",
4525  "   If ?NAME? is omitted, the first defined session is used.",
4526#endif
4527  ".sha3sum ...             Compute a SHA3 hash of database content",
4528  "    Options:",
4529  "      --schema              Also hash the sqlite_schema table",
4530  "      --sha3-224            Use the sha3-224 algorithm",
4531  "      --sha3-256            Use the sha3-256 algorithm (default)",
4532  "      --sha3-384            Use the sha3-384 algorithm",
4533  "      --sha3-512            Use the sha3-512 algorithm",
4534  "    Any other argument is a LIKE pattern for tables to hash",
4535#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4536  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4537#endif
4538  ".show                    Show the current values for various settings",
4539  ".stats ?ARG?             Show stats or turn stats on or off",
4540  "   off                      Turn off automatic stat display",
4541  "   on                       Turn on automatic stat display",
4542  "   stmt                     Show statement stats",
4543  "   vmstep                   Show the virtual machine step count only",
4544#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4545  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4546#endif
4547  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4548#ifndef SQLITE_SHELL_FIDDLE
4549  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4550#endif
4551  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4552  "                           Run \".testctrl\" with no arguments for details",
4553  ".timeout MS              Try opening locked tables for MS milliseconds",
4554  ".timer on|off            Turn SQL timer on or off",
4555#ifndef SQLITE_OMIT_TRACE
4556  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4557  "    FILE                    Send output to FILE",
4558  "    stdout                  Send output to stdout",
4559  "    stderr                  Send output to stderr",
4560  "    off                     Disable tracing",
4561  "    --expanded              Expand query parameters",
4562#ifdef SQLITE_ENABLE_NORMALIZE
4563  "    --normalized            Normal the SQL statements",
4564#endif
4565  "    --plain                 Show SQL as it is input",
4566  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4567  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4568  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4569  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4570#endif /* SQLITE_OMIT_TRACE */
4571#ifdef SQLITE_DEBUG
4572  ".unmodule NAME ...       Unregister virtual table modules",
4573  "    --allexcept             Unregister everything except those named",
4574#endif
4575  ".vfsinfo ?AUX?           Information about the top-level VFS",
4576  ".vfslist                 List all available VFSes",
4577  ".vfsname ?AUX?           Print the name of the VFS stack",
4578  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4579  "     Negative values right-justify",
4580};
4581
4582/*
4583** Output help text.
4584**
4585** zPattern describes the set of commands for which help text is provided.
4586** If zPattern is NULL, then show all commands, but only give a one-line
4587** description of each.
4588**
4589** Return the number of matches.
4590*/
4591static int showHelp(FILE *out, const char *zPattern){
4592  int i = 0;
4593  int j = 0;
4594  int n = 0;
4595  char *zPat;
4596  if( zPattern==0
4597   || zPattern[0]=='0'
4598   || strcmp(zPattern,"-a")==0
4599   || strcmp(zPattern,"-all")==0
4600   || strcmp(zPattern,"--all")==0
4601  ){
4602    /* Show all commands, but only one line per command */
4603    if( zPattern==0 ) zPattern = "";
4604    for(i=0; i<ArraySize(azHelp); i++){
4605      if( azHelp[i][0]=='.' || zPattern[0] ){
4606        utf8_printf(out, "%s\n", azHelp[i]);
4607        n++;
4608      }
4609    }
4610  }else{
4611    /* Look for commands that for which zPattern is an exact prefix */
4612    zPat = sqlite3_mprintf(".%s*", zPattern);
4613    shell_check_oom(zPat);
4614    for(i=0; i<ArraySize(azHelp); i++){
4615      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4616        utf8_printf(out, "%s\n", azHelp[i]);
4617        j = i+1;
4618        n++;
4619      }
4620    }
4621    sqlite3_free(zPat);
4622    if( n ){
4623      if( n==1 ){
4624        /* when zPattern is a prefix of exactly one command, then include the
4625        ** details of that command, which should begin at offset j */
4626        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4627          utf8_printf(out, "%s\n", azHelp[j]);
4628          j++;
4629        }
4630      }
4631      return n;
4632    }
4633    /* Look for commands that contain zPattern anywhere.  Show the complete
4634    ** text of all commands that match. */
4635    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4636    shell_check_oom(zPat);
4637    for(i=0; i<ArraySize(azHelp); i++){
4638      if( azHelp[i][0]=='.' ) j = i;
4639      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4640        utf8_printf(out, "%s\n", azHelp[j]);
4641        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4642          j++;
4643          utf8_printf(out, "%s\n", azHelp[j]);
4644        }
4645        i = j;
4646        n++;
4647      }
4648    }
4649    sqlite3_free(zPat);
4650  }
4651  return n;
4652}
4653
4654/* Forward reference */
4655static int process_input(ShellState *p);
4656
4657/*
4658** Read the content of file zName into memory obtained from sqlite3_malloc64()
4659** and return a pointer to the buffer. The caller is responsible for freeing
4660** the memory.
4661**
4662** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4663** read.
4664**
4665** For convenience, a nul-terminator byte is always appended to the data read
4666** from the file before the buffer is returned. This byte is not included in
4667** the final value of (*pnByte), if applicable.
4668**
4669** NULL is returned if any error is encountered. The final value of *pnByte
4670** is undefined in this case.
4671*/
4672static char *readFile(const char *zName, int *pnByte){
4673  FILE *in = fopen(zName, "rb");
4674  long nIn;
4675  size_t nRead;
4676  char *pBuf;
4677  if( in==0 ) return 0;
4678  fseek(in, 0, SEEK_END);
4679  nIn = ftell(in);
4680  rewind(in);
4681  pBuf = sqlite3_malloc64( nIn+1 );
4682  if( pBuf==0 ){ fclose(in); return 0; }
4683  nRead = fread(pBuf, nIn, 1, in);
4684  fclose(in);
4685  if( nRead!=1 ){
4686    sqlite3_free(pBuf);
4687    return 0;
4688  }
4689  pBuf[nIn] = 0;
4690  if( pnByte ) *pnByte = nIn;
4691  return pBuf;
4692}
4693
4694#if defined(SQLITE_ENABLE_SESSION)
4695/*
4696** Close a single OpenSession object and release all of its associated
4697** resources.
4698*/
4699static void session_close(OpenSession *pSession){
4700  int i;
4701  sqlite3session_delete(pSession->p);
4702  sqlite3_free(pSession->zName);
4703  for(i=0; i<pSession->nFilter; i++){
4704    sqlite3_free(pSession->azFilter[i]);
4705  }
4706  sqlite3_free(pSession->azFilter);
4707  memset(pSession, 0, sizeof(OpenSession));
4708}
4709#endif
4710
4711/*
4712** Close all OpenSession objects and release all associated resources.
4713*/
4714#if defined(SQLITE_ENABLE_SESSION)
4715static void session_close_all(ShellState *p, int i){
4716  int j;
4717  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4718  for(j=0; j<pAuxDb->nSession; j++){
4719    session_close(&pAuxDb->aSession[j]);
4720  }
4721  pAuxDb->nSession = 0;
4722}
4723#else
4724# define session_close_all(X,Y)
4725#endif
4726
4727/*
4728** Implementation of the xFilter function for an open session.  Omit
4729** any tables named by ".session filter" but let all other table through.
4730*/
4731#if defined(SQLITE_ENABLE_SESSION)
4732static int session_filter(void *pCtx, const char *zTab){
4733  OpenSession *pSession = (OpenSession*)pCtx;
4734  int i;
4735  for(i=0; i<pSession->nFilter; i++){
4736    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4737  }
4738  return 1;
4739}
4740#endif
4741
4742/*
4743** Try to deduce the type of file for zName based on its content.  Return
4744** one of the SHELL_OPEN_* constants.
4745**
4746** If the file does not exist or is empty but its name looks like a ZIP
4747** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4748** Otherwise, assume an ordinary database regardless of the filename if
4749** the type cannot be determined from content.
4750*/
4751int deduceDatabaseType(const char *zName, int dfltZip){
4752  FILE *f = fopen(zName, "rb");
4753  size_t n;
4754  int rc = SHELL_OPEN_UNSPEC;
4755  char zBuf[100];
4756  if( f==0 ){
4757    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4758       return SHELL_OPEN_ZIPFILE;
4759    }else{
4760       return SHELL_OPEN_NORMAL;
4761    }
4762  }
4763  n = fread(zBuf, 16, 1, f);
4764  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4765    fclose(f);
4766    return SHELL_OPEN_NORMAL;
4767  }
4768  fseek(f, -25, SEEK_END);
4769  n = fread(zBuf, 25, 1, f);
4770  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4771    rc = SHELL_OPEN_APPENDVFS;
4772  }else{
4773    fseek(f, -22, SEEK_END);
4774    n = fread(zBuf, 22, 1, f);
4775    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4776       && zBuf[3]==0x06 ){
4777      rc = SHELL_OPEN_ZIPFILE;
4778    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4779      rc = SHELL_OPEN_ZIPFILE;
4780    }
4781  }
4782  fclose(f);
4783  return rc;
4784}
4785
4786#ifndef SQLITE_OMIT_DESERIALIZE
4787/*
4788** Reconstruct an in-memory database using the output from the "dbtotxt"
4789** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4790** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4791*/
4792static unsigned char *readHexDb(ShellState *p, int *pnData){
4793  unsigned char *a = 0;
4794  int nLine;
4795  int n = 0;
4796  int pgsz = 0;
4797  int iOffset = 0;
4798  int j, k;
4799  int rc;
4800  FILE *in;
4801  const char *zDbFilename = p->pAuxDb->zDbFilename;
4802  unsigned int x[16];
4803  char zLine[1000];
4804  if( zDbFilename ){
4805    in = fopen(zDbFilename, "r");
4806    if( in==0 ){
4807      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4808      return 0;
4809    }
4810    nLine = 0;
4811  }else{
4812    in = p->in;
4813    nLine = p->lineno;
4814    if( in==0 ) in = stdin;
4815  }
4816  *pnData = 0;
4817  nLine++;
4818  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4819  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4820  if( rc!=2 ) goto readHexDb_error;
4821  if( n<0 ) goto readHexDb_error;
4822  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4823  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4824  a = sqlite3_malloc( n ? n : 1 );
4825  shell_check_oom(a);
4826  memset(a, 0, n);
4827  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4828    utf8_printf(stderr, "invalid pagesize\n");
4829    goto readHexDb_error;
4830  }
4831  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4832    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4833    if( rc==2 ){
4834      iOffset = k;
4835      continue;
4836    }
4837    if( strncmp(zLine, "| end ", 6)==0 ){
4838      break;
4839    }
4840    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4841                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4842                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4843    if( rc==17 ){
4844      k = iOffset+j;
4845      if( k+16<=n && k>=0 ){
4846        int ii;
4847        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4848      }
4849    }
4850  }
4851  *pnData = n;
4852  if( in!=p->in ){
4853    fclose(in);
4854  }else{
4855    p->lineno = nLine;
4856  }
4857  return a;
4858
4859readHexDb_error:
4860  if( in!=p->in ){
4861    fclose(in);
4862  }else{
4863    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4864      nLine++;
4865      if(strncmp(zLine, "| end ", 6)==0 ) break;
4866    }
4867    p->lineno = nLine;
4868  }
4869  sqlite3_free(a);
4870  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4871  return 0;
4872}
4873#endif /* SQLITE_OMIT_DESERIALIZE */
4874
4875/*
4876** Scalar function "shell_int32". The first argument to this function
4877** must be a blob. The second a non-negative integer. This function
4878** reads and returns a 32-bit big-endian integer from byte
4879** offset (4*<arg2>) of the blob.
4880*/
4881static void shellInt32(
4882  sqlite3_context *context,
4883  int argc,
4884  sqlite3_value **argv
4885){
4886  const unsigned char *pBlob;
4887  int nBlob;
4888  int iInt;
4889
4890  UNUSED_PARAMETER(argc);
4891  nBlob = sqlite3_value_bytes(argv[0]);
4892  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4893  iInt = sqlite3_value_int(argv[1]);
4894
4895  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4896    const unsigned char *a = &pBlob[iInt*4];
4897    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4898                       + ((sqlite3_int64)a[1]<<16)
4899                       + ((sqlite3_int64)a[2]<< 8)
4900                       + ((sqlite3_int64)a[3]<< 0);
4901    sqlite3_result_int64(context, iVal);
4902  }
4903}
4904
4905/*
4906** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4907** using "..." with internal double-quote characters doubled.
4908*/
4909static void shellIdQuote(
4910  sqlite3_context *context,
4911  int argc,
4912  sqlite3_value **argv
4913){
4914  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4915  UNUSED_PARAMETER(argc);
4916  if( zName ){
4917    char *z = sqlite3_mprintf("\"%w\"", zName);
4918    sqlite3_result_text(context, z, -1, sqlite3_free);
4919  }
4920}
4921
4922/*
4923** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4924*/
4925static void shellUSleepFunc(
4926  sqlite3_context *context,
4927  int argcUnused,
4928  sqlite3_value **argv
4929){
4930  int sleep = sqlite3_value_int(argv[0]);
4931  (void)argcUnused;
4932  sqlite3_sleep(sleep/1000);
4933  sqlite3_result_int(context, sleep);
4934}
4935
4936/*
4937** Scalar function "shell_escape_crnl" used by the .recover command.
4938** The argument passed to this function is the output of built-in
4939** function quote(). If the first character of the input is "'",
4940** indicating that the value passed to quote() was a text value,
4941** then this function searches the input for "\n" and "\r" characters
4942** and adds a wrapper similar to the following:
4943**
4944**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4945**
4946** Or, if the first character of the input is not "'", then a copy
4947** of the input is returned.
4948*/
4949static void shellEscapeCrnl(
4950  sqlite3_context *context,
4951  int argc,
4952  sqlite3_value **argv
4953){
4954  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4955  UNUSED_PARAMETER(argc);
4956  if( zText && zText[0]=='\'' ){
4957    int nText = sqlite3_value_bytes(argv[0]);
4958    int i;
4959    char zBuf1[20];
4960    char zBuf2[20];
4961    const char *zNL = 0;
4962    const char *zCR = 0;
4963    int nCR = 0;
4964    int nNL = 0;
4965
4966    for(i=0; zText[i]; i++){
4967      if( zNL==0 && zText[i]=='\n' ){
4968        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4969        nNL = (int)strlen(zNL);
4970      }
4971      if( zCR==0 && zText[i]=='\r' ){
4972        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4973        nCR = (int)strlen(zCR);
4974      }
4975    }
4976
4977    if( zNL || zCR ){
4978      int iOut = 0;
4979      i64 nMax = (nNL > nCR) ? nNL : nCR;
4980      i64 nAlloc = nMax * nText + (nMax+64)*2;
4981      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4982      if( zOut==0 ){
4983        sqlite3_result_error_nomem(context);
4984        return;
4985      }
4986
4987      if( zNL && zCR ){
4988        memcpy(&zOut[iOut], "replace(replace(", 16);
4989        iOut += 16;
4990      }else{
4991        memcpy(&zOut[iOut], "replace(", 8);
4992        iOut += 8;
4993      }
4994      for(i=0; zText[i]; i++){
4995        if( zText[i]=='\n' ){
4996          memcpy(&zOut[iOut], zNL, nNL);
4997          iOut += nNL;
4998        }else if( zText[i]=='\r' ){
4999          memcpy(&zOut[iOut], zCR, nCR);
5000          iOut += nCR;
5001        }else{
5002          zOut[iOut] = zText[i];
5003          iOut++;
5004        }
5005      }
5006
5007      if( zNL ){
5008        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5009        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
5010        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
5011      }
5012      if( zCR ){
5013        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
5014        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
5015        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
5016      }
5017
5018      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
5019      sqlite3_free(zOut);
5020      return;
5021    }
5022  }
5023
5024  sqlite3_result_value(context, argv[0]);
5025}
5026
5027/* Flags for open_db().
5028**
5029** The default behavior of open_db() is to exit(1) if the database fails to
5030** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
5031** but still returns without calling exit.
5032**
5033** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
5034** ZIP archive if the file does not exist or is empty and its name matches
5035** the *.zip pattern.
5036*/
5037#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
5038#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
5039
5040/*
5041** Make sure the database is open.  If it is not, then open it.  If
5042** the database fails to open, print an error message and exit.
5043*/
5044static void open_db(ShellState *p, int openFlags){
5045  if( p->db==0 ){
5046    const char *zDbFilename = p->pAuxDb->zDbFilename;
5047    if( p->openMode==SHELL_OPEN_UNSPEC ){
5048      if( zDbFilename==0 || zDbFilename[0]==0 ){
5049        p->openMode = SHELL_OPEN_NORMAL;
5050      }else{
5051        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5052                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5053      }
5054    }
5055    switch( p->openMode ){
5056      case SHELL_OPEN_APPENDVFS: {
5057        sqlite3_open_v2(zDbFilename, &p->db,
5058           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5059        break;
5060      }
5061      case SHELL_OPEN_HEXDB:
5062      case SHELL_OPEN_DESERIALIZE: {
5063        sqlite3_open(0, &p->db);
5064        break;
5065      }
5066      case SHELL_OPEN_ZIPFILE: {
5067        sqlite3_open(":memory:", &p->db);
5068        break;
5069      }
5070      case SHELL_OPEN_READONLY: {
5071        sqlite3_open_v2(zDbFilename, &p->db,
5072            SQLITE_OPEN_READONLY|p->openFlags, 0);
5073        break;
5074      }
5075      case SHELL_OPEN_UNSPEC:
5076      case SHELL_OPEN_NORMAL: {
5077        sqlite3_open_v2(zDbFilename, &p->db,
5078           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5079        break;
5080      }
5081    }
5082    globalDb = p->db;
5083    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5084      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5085          zDbFilename, sqlite3_errmsg(p->db));
5086      if( openFlags & OPEN_DB_KEEPALIVE ){
5087        sqlite3_open(":memory:", &p->db);
5088        return;
5089      }
5090      exit(1);
5091    }
5092#ifndef SQLITE_OMIT_LOAD_EXTENSION
5093    sqlite3_enable_load_extension(p->db, 1);
5094#endif
5095    sqlite3_shathree_init(p->db, 0, 0);
5096    sqlite3_uint_init(p->db, 0, 0);
5097    sqlite3_decimal_init(p->db, 0, 0);
5098    sqlite3_regexp_init(p->db, 0, 0);
5099    sqlite3_ieee_init(p->db, 0, 0);
5100    sqlite3_series_init(p->db, 0, 0);
5101#ifndef SQLITE_SHELL_FIDDLE
5102    sqlite3_fileio_init(p->db, 0, 0);
5103    sqlite3_completion_init(p->db, 0, 0);
5104#endif
5105#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5106    sqlite3_dbdata_init(p->db, 0, 0);
5107#endif
5108#ifdef SQLITE_HAVE_ZLIB
5109    if( !p->bSafeModePersist ){
5110      sqlite3_zipfile_init(p->db, 0, 0);
5111      sqlite3_sqlar_init(p->db, 0, 0);
5112    }
5113#endif
5114    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5115                            shellAddSchemaName, 0, 0);
5116    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5117                            shellModuleSchema, 0, 0);
5118    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5119                            shellPutsFunc, 0, 0);
5120    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5121                            shellEscapeCrnl, 0, 0);
5122    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5123                            shellInt32, 0, 0);
5124    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5125                            shellIdQuote, 0, 0);
5126    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5127                            shellUSleepFunc, 0, 0);
5128#ifndef SQLITE_NOHAVE_SYSTEM
5129    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5130                            editFunc, 0, 0);
5131    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5132                            editFunc, 0, 0);
5133#endif
5134    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5135      char *zSql = sqlite3_mprintf(
5136         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5137      shell_check_oom(zSql);
5138      sqlite3_exec(p->db, zSql, 0, 0, 0);
5139      sqlite3_free(zSql);
5140    }
5141#ifndef SQLITE_OMIT_DESERIALIZE
5142    else
5143    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5144      int rc;
5145      int nData = 0;
5146      unsigned char *aData;
5147      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5148        aData = (unsigned char*)readFile(zDbFilename, &nData);
5149      }else{
5150        aData = readHexDb(p, &nData);
5151        if( aData==0 ){
5152          return;
5153        }
5154      }
5155      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5156                   SQLITE_DESERIALIZE_RESIZEABLE |
5157                   SQLITE_DESERIALIZE_FREEONCLOSE);
5158      if( rc ){
5159        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5160      }
5161      if( p->szMax>0 ){
5162        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5163      }
5164    }
5165#endif
5166  }
5167  if( p->bSafeModePersist && p->db!=0 ){
5168    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5169  }
5170}
5171
5172/*
5173** Attempt to close the databaes connection.  Report errors.
5174*/
5175void close_db(sqlite3 *db){
5176  int rc = sqlite3_close(db);
5177  if( rc ){
5178    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5179        rc, sqlite3_errmsg(db));
5180  }
5181}
5182
5183#if HAVE_READLINE || HAVE_EDITLINE
5184/*
5185** Readline completion callbacks
5186*/
5187static char *readline_completion_generator(const char *text, int state){
5188  static sqlite3_stmt *pStmt = 0;
5189  char *zRet;
5190  if( state==0 ){
5191    char *zSql;
5192    sqlite3_finalize(pStmt);
5193    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5194                           "  FROM completion(%Q) ORDER BY 1", text);
5195    shell_check_oom(zSql);
5196    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5197    sqlite3_free(zSql);
5198  }
5199  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5200    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5201    zRet = z ? strdup(z) : 0;
5202  }else{
5203    sqlite3_finalize(pStmt);
5204    pStmt = 0;
5205    zRet = 0;
5206  }
5207  return zRet;
5208}
5209static char **readline_completion(const char *zText, int iStart, int iEnd){
5210  rl_attempted_completion_over = 1;
5211  return rl_completion_matches(zText, readline_completion_generator);
5212}
5213
5214#elif HAVE_LINENOISE
5215/*
5216** Linenoise completion callback
5217*/
5218static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5219  int nLine = strlen30(zLine);
5220  int i, iStart;
5221  sqlite3_stmt *pStmt = 0;
5222  char *zSql;
5223  char zBuf[1000];
5224
5225  if( nLine>sizeof(zBuf)-30 ) return;
5226  if( zLine[0]=='.' || zLine[0]=='#') return;
5227  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5228  if( i==nLine-1 ) return;
5229  iStart = i+1;
5230  memcpy(zBuf, zLine, iStart);
5231  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5232                         "  FROM completion(%Q,%Q) ORDER BY 1",
5233                         &zLine[iStart], zLine);
5234  shell_check_oom(zSql);
5235  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5236  sqlite3_free(zSql);
5237  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5238  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5239    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5240    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5241    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5242      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5243      linenoiseAddCompletion(lc, zBuf);
5244    }
5245  }
5246  sqlite3_finalize(pStmt);
5247}
5248#endif
5249
5250/*
5251** Do C-language style dequoting.
5252**
5253**    \a    -> alarm
5254**    \b    -> backspace
5255**    \t    -> tab
5256**    \n    -> newline
5257**    \v    -> vertical tab
5258**    \f    -> form feed
5259**    \r    -> carriage return
5260**    \s    -> space
5261**    \"    -> "
5262**    \'    -> '
5263**    \\    -> backslash
5264**    \NNN  -> ascii character NNN in octal
5265*/
5266static void resolve_backslashes(char *z){
5267  int i, j;
5268  char c;
5269  while( *z && *z!='\\' ) z++;
5270  for(i=j=0; (c = z[i])!=0; i++, j++){
5271    if( c=='\\' && z[i+1]!=0 ){
5272      c = z[++i];
5273      if( c=='a' ){
5274        c = '\a';
5275      }else if( c=='b' ){
5276        c = '\b';
5277      }else if( c=='t' ){
5278        c = '\t';
5279      }else if( c=='n' ){
5280        c = '\n';
5281      }else if( c=='v' ){
5282        c = '\v';
5283      }else if( c=='f' ){
5284        c = '\f';
5285      }else if( c=='r' ){
5286        c = '\r';
5287      }else if( c=='"' ){
5288        c = '"';
5289      }else if( c=='\'' ){
5290        c = '\'';
5291      }else if( c=='\\' ){
5292        c = '\\';
5293      }else if( c>='0' && c<='7' ){
5294        c -= '0';
5295        if( z[i+1]>='0' && z[i+1]<='7' ){
5296          i++;
5297          c = (c<<3) + z[i] - '0';
5298          if( z[i+1]>='0' && z[i+1]<='7' ){
5299            i++;
5300            c = (c<<3) + z[i] - '0';
5301          }
5302        }
5303      }
5304    }
5305    z[j] = c;
5306  }
5307  if( j<i ) z[j] = 0;
5308}
5309
5310/*
5311** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5312** for TRUE and FALSE.  Return the integer value if appropriate.
5313*/
5314static int booleanValue(const char *zArg){
5315  int i;
5316  if( zArg[0]=='0' && zArg[1]=='x' ){
5317    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5318  }else{
5319    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5320  }
5321  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5322  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5323    return 1;
5324  }
5325  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5326    return 0;
5327  }
5328  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5329          zArg);
5330  return 0;
5331}
5332
5333/*
5334** Set or clear a shell flag according to a boolean value.
5335*/
5336static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5337  if( booleanValue(zArg) ){
5338    ShellSetFlag(p, mFlag);
5339  }else{
5340    ShellClearFlag(p, mFlag);
5341  }
5342}
5343
5344/*
5345** Close an output file, assuming it is not stderr or stdout
5346*/
5347static void output_file_close(FILE *f){
5348  if( f && f!=stdout && f!=stderr ) fclose(f);
5349}
5350
5351/*
5352** Try to open an output file.   The names "stdout" and "stderr" are
5353** recognized and do the right thing.  NULL is returned if the output
5354** filename is "off".
5355*/
5356static FILE *output_file_open(const char *zFile, int bTextMode){
5357  FILE *f;
5358  if( strcmp(zFile,"stdout")==0 ){
5359    f = stdout;
5360  }else if( strcmp(zFile, "stderr")==0 ){
5361    f = stderr;
5362  }else if( strcmp(zFile, "off")==0 ){
5363    f = 0;
5364  }else{
5365    f = fopen(zFile, bTextMode ? "w" : "wb");
5366    if( f==0 ){
5367      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5368    }
5369  }
5370  return f;
5371}
5372
5373#ifndef SQLITE_OMIT_TRACE
5374/*
5375** A routine for handling output from sqlite3_trace().
5376*/
5377static int sql_trace_callback(
5378  unsigned mType,         /* The trace type */
5379  void *pArg,             /* The ShellState pointer */
5380  void *pP,               /* Usually a pointer to sqlite_stmt */
5381  void *pX                /* Auxiliary output */
5382){
5383  ShellState *p = (ShellState*)pArg;
5384  sqlite3_stmt *pStmt;
5385  const char *zSql;
5386  int nSql;
5387  if( p->traceOut==0 ) return 0;
5388  if( mType==SQLITE_TRACE_CLOSE ){
5389    utf8_printf(p->traceOut, "-- closing database connection\n");
5390    return 0;
5391  }
5392  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5393    zSql = (const char*)pX;
5394  }else{
5395    pStmt = (sqlite3_stmt*)pP;
5396    switch( p->eTraceType ){
5397      case SHELL_TRACE_EXPANDED: {
5398        zSql = sqlite3_expanded_sql(pStmt);
5399        break;
5400      }
5401#ifdef SQLITE_ENABLE_NORMALIZE
5402      case SHELL_TRACE_NORMALIZED: {
5403        zSql = sqlite3_normalized_sql(pStmt);
5404        break;
5405      }
5406#endif
5407      default: {
5408        zSql = sqlite3_sql(pStmt);
5409        break;
5410      }
5411    }
5412  }
5413  if( zSql==0 ) return 0;
5414  nSql = strlen30(zSql);
5415  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5416  switch( mType ){
5417    case SQLITE_TRACE_ROW:
5418    case SQLITE_TRACE_STMT: {
5419      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5420      break;
5421    }
5422    case SQLITE_TRACE_PROFILE: {
5423      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5424      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5425      break;
5426    }
5427  }
5428  return 0;
5429}
5430#endif
5431
5432/*
5433** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5434** a useful spot to set a debugger breakpoint.
5435*/
5436static void test_breakpoint(void){
5437  static int nCall = 0;
5438  nCall++;
5439}
5440
5441/*
5442** An object used to read a CSV and other files for import.
5443*/
5444typedef struct ImportCtx ImportCtx;
5445struct ImportCtx {
5446  const char *zFile;  /* Name of the input file */
5447  FILE *in;           /* Read the CSV text from this input stream */
5448  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5449  char *z;            /* Accumulated text for a field */
5450  int n;              /* Number of bytes in z */
5451  int nAlloc;         /* Space allocated for z[] */
5452  int nLine;          /* Current line number */
5453  int nRow;           /* Number of rows imported */
5454  int nErr;           /* Number of errors encountered */
5455  int bNotFirst;      /* True if one or more bytes already read */
5456  int cTerm;          /* Character that terminated the most recent field */
5457  int cColSep;        /* The column separator character.  (Usually ",") */
5458  int cRowSep;        /* The row separator character.  (Usually "\n") */
5459};
5460
5461/* Clean up resourced used by an ImportCtx */
5462static void import_cleanup(ImportCtx *p){
5463  if( p->in!=0 && p->xCloser!=0 ){
5464    p->xCloser(p->in);
5465    p->in = 0;
5466  }
5467  sqlite3_free(p->z);
5468  p->z = 0;
5469}
5470
5471/* Append a single byte to z[] */
5472static void import_append_char(ImportCtx *p, int c){
5473  if( p->n+1>=p->nAlloc ){
5474    p->nAlloc += p->nAlloc + 100;
5475    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5476    shell_check_oom(p->z);
5477  }
5478  p->z[p->n++] = (char)c;
5479}
5480
5481/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5482** with the option of having a separator other than ",".
5483**
5484**   +  Input comes from p->in.
5485**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5486**      from sqlite3_malloc64().
5487**   +  Use p->cSep as the column separator.  The default is ",".
5488**   +  Use p->rSep as the row separator.  The default is "\n".
5489**   +  Keep track of the line number in p->nLine.
5490**   +  Store the character that terminates the field in p->cTerm.  Store
5491**      EOF on end-of-file.
5492**   +  Report syntax errors on stderr
5493*/
5494static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5495  int c;
5496  int cSep = p->cColSep;
5497  int rSep = p->cRowSep;
5498  p->n = 0;
5499  c = fgetc(p->in);
5500  if( c==EOF || seenInterrupt ){
5501    p->cTerm = EOF;
5502    return 0;
5503  }
5504  if( c=='"' ){
5505    int pc, ppc;
5506    int startLine = p->nLine;
5507    int cQuote = c;
5508    pc = ppc = 0;
5509    while( 1 ){
5510      c = fgetc(p->in);
5511      if( c==rSep ) p->nLine++;
5512      if( c==cQuote ){
5513        if( pc==cQuote ){
5514          pc = 0;
5515          continue;
5516        }
5517      }
5518      if( (c==cSep && pc==cQuote)
5519       || (c==rSep && pc==cQuote)
5520       || (c==rSep && pc=='\r' && ppc==cQuote)
5521       || (c==EOF && pc==cQuote)
5522      ){
5523        do{ p->n--; }while( p->z[p->n]!=cQuote );
5524        p->cTerm = c;
5525        break;
5526      }
5527      if( pc==cQuote && c!='\r' ){
5528        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5529                p->zFile, p->nLine, cQuote);
5530      }
5531      if( c==EOF ){
5532        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5533                p->zFile, startLine, cQuote);
5534        p->cTerm = c;
5535        break;
5536      }
5537      import_append_char(p, c);
5538      ppc = pc;
5539      pc = c;
5540    }
5541  }else{
5542    /* If this is the first field being parsed and it begins with the
5543    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5544    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5545      import_append_char(p, c);
5546      c = fgetc(p->in);
5547      if( (c&0xff)==0xbb ){
5548        import_append_char(p, c);
5549        c = fgetc(p->in);
5550        if( (c&0xff)==0xbf ){
5551          p->bNotFirst = 1;
5552          p->n = 0;
5553          return csv_read_one_field(p);
5554        }
5555      }
5556    }
5557    while( c!=EOF && c!=cSep && c!=rSep ){
5558      import_append_char(p, c);
5559      c = fgetc(p->in);
5560    }
5561    if( c==rSep ){
5562      p->nLine++;
5563      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5564    }
5565    p->cTerm = c;
5566  }
5567  if( p->z ) p->z[p->n] = 0;
5568  p->bNotFirst = 1;
5569  return p->z;
5570}
5571
5572/* Read a single field of ASCII delimited text.
5573**
5574**   +  Input comes from p->in.
5575**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5576**      from sqlite3_malloc64().
5577**   +  Use p->cSep as the column separator.  The default is "\x1F".
5578**   +  Use p->rSep as the row separator.  The default is "\x1E".
5579**   +  Keep track of the row number in p->nLine.
5580**   +  Store the character that terminates the field in p->cTerm.  Store
5581**      EOF on end-of-file.
5582**   +  Report syntax errors on stderr
5583*/
5584static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5585  int c;
5586  int cSep = p->cColSep;
5587  int rSep = p->cRowSep;
5588  p->n = 0;
5589  c = fgetc(p->in);
5590  if( c==EOF || seenInterrupt ){
5591    p->cTerm = EOF;
5592    return 0;
5593  }
5594  while( c!=EOF && c!=cSep && c!=rSep ){
5595    import_append_char(p, c);
5596    c = fgetc(p->in);
5597  }
5598  if( c==rSep ){
5599    p->nLine++;
5600  }
5601  p->cTerm = c;
5602  if( p->z ) p->z[p->n] = 0;
5603  return p->z;
5604}
5605
5606/*
5607** Try to transfer data for table zTable.  If an error is seen while
5608** moving forward, try to go backwards.  The backwards movement won't
5609** work for WITHOUT ROWID tables.
5610*/
5611static void tryToCloneData(
5612  ShellState *p,
5613  sqlite3 *newDb,
5614  const char *zTable
5615){
5616  sqlite3_stmt *pQuery = 0;
5617  sqlite3_stmt *pInsert = 0;
5618  char *zQuery = 0;
5619  char *zInsert = 0;
5620  int rc;
5621  int i, j, n;
5622  int nTable = strlen30(zTable);
5623  int k = 0;
5624  int cnt = 0;
5625  const int spinRate = 10000;
5626
5627  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5628  shell_check_oom(zQuery);
5629  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5630  if( rc ){
5631    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5632            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5633            zQuery);
5634    goto end_data_xfer;
5635  }
5636  n = sqlite3_column_count(pQuery);
5637  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5638  shell_check_oom(zInsert);
5639  sqlite3_snprintf(200+nTable,zInsert,
5640                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5641  i = strlen30(zInsert);
5642  for(j=1; j<n; j++){
5643    memcpy(zInsert+i, ",?", 2);
5644    i += 2;
5645  }
5646  memcpy(zInsert+i, ");", 3);
5647  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5648  if( rc ){
5649    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5650            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5651            zQuery);
5652    goto end_data_xfer;
5653  }
5654  for(k=0; k<2; k++){
5655    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5656      for(i=0; i<n; i++){
5657        switch( sqlite3_column_type(pQuery, i) ){
5658          case SQLITE_NULL: {
5659            sqlite3_bind_null(pInsert, i+1);
5660            break;
5661          }
5662          case SQLITE_INTEGER: {
5663            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5664            break;
5665          }
5666          case SQLITE_FLOAT: {
5667            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5668            break;
5669          }
5670          case SQLITE_TEXT: {
5671            sqlite3_bind_text(pInsert, i+1,
5672                             (const char*)sqlite3_column_text(pQuery,i),
5673                             -1, SQLITE_STATIC);
5674            break;
5675          }
5676          case SQLITE_BLOB: {
5677            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5678                                            sqlite3_column_bytes(pQuery,i),
5679                                            SQLITE_STATIC);
5680            break;
5681          }
5682        }
5683      } /* End for */
5684      rc = sqlite3_step(pInsert);
5685      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5686        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5687                        sqlite3_errmsg(newDb));
5688      }
5689      sqlite3_reset(pInsert);
5690      cnt++;
5691      if( (cnt%spinRate)==0 ){
5692        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5693        fflush(stdout);
5694      }
5695    } /* End while */
5696    if( rc==SQLITE_DONE ) break;
5697    sqlite3_finalize(pQuery);
5698    sqlite3_free(zQuery);
5699    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5700                             zTable);
5701    shell_check_oom(zQuery);
5702    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5703    if( rc ){
5704      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5705      break;
5706    }
5707  } /* End for(k=0...) */
5708
5709end_data_xfer:
5710  sqlite3_finalize(pQuery);
5711  sqlite3_finalize(pInsert);
5712  sqlite3_free(zQuery);
5713  sqlite3_free(zInsert);
5714}
5715
5716
5717/*
5718** Try to transfer all rows of the schema that match zWhere.  For
5719** each row, invoke xForEach() on the object defined by that row.
5720** If an error is encountered while moving forward through the
5721** sqlite_schema table, try again moving backwards.
5722*/
5723static void tryToCloneSchema(
5724  ShellState *p,
5725  sqlite3 *newDb,
5726  const char *zWhere,
5727  void (*xForEach)(ShellState*,sqlite3*,const char*)
5728){
5729  sqlite3_stmt *pQuery = 0;
5730  char *zQuery = 0;
5731  int rc;
5732  const unsigned char *zName;
5733  const unsigned char *zSql;
5734  char *zErrMsg = 0;
5735
5736  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5737                           " WHERE %s", zWhere);
5738  shell_check_oom(zQuery);
5739  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5740  if( rc ){
5741    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5742                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5743                    zQuery);
5744    goto end_schema_xfer;
5745  }
5746  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5747    zName = sqlite3_column_text(pQuery, 0);
5748    zSql = sqlite3_column_text(pQuery, 1);
5749    if( zName==0 || zSql==0 ) continue;
5750    printf("%s... ", zName); fflush(stdout);
5751    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5752    if( zErrMsg ){
5753      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5754      sqlite3_free(zErrMsg);
5755      zErrMsg = 0;
5756    }
5757    if( xForEach ){
5758      xForEach(p, newDb, (const char*)zName);
5759    }
5760    printf("done\n");
5761  }
5762  if( rc!=SQLITE_DONE ){
5763    sqlite3_finalize(pQuery);
5764    sqlite3_free(zQuery);
5765    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5766                             " WHERE %s ORDER BY rowid DESC", zWhere);
5767    shell_check_oom(zQuery);
5768    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5769    if( rc ){
5770      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5771                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5772                      zQuery);
5773      goto end_schema_xfer;
5774    }
5775    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5776      zName = sqlite3_column_text(pQuery, 0);
5777      zSql = sqlite3_column_text(pQuery, 1);
5778      if( zName==0 || zSql==0 ) continue;
5779      printf("%s... ", zName); fflush(stdout);
5780      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5781      if( zErrMsg ){
5782        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5783        sqlite3_free(zErrMsg);
5784        zErrMsg = 0;
5785      }
5786      if( xForEach ){
5787        xForEach(p, newDb, (const char*)zName);
5788      }
5789      printf("done\n");
5790    }
5791  }
5792end_schema_xfer:
5793  sqlite3_finalize(pQuery);
5794  sqlite3_free(zQuery);
5795}
5796
5797/*
5798** Open a new database file named "zNewDb".  Try to recover as much information
5799** as possible out of the main database (which might be corrupt) and write it
5800** into zNewDb.
5801*/
5802static void tryToClone(ShellState *p, const char *zNewDb){
5803  int rc;
5804  sqlite3 *newDb = 0;
5805  if( access(zNewDb,0)==0 ){
5806    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5807    return;
5808  }
5809  rc = sqlite3_open(zNewDb, &newDb);
5810  if( rc ){
5811    utf8_printf(stderr, "Cannot create output database: %s\n",
5812            sqlite3_errmsg(newDb));
5813  }else{
5814    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5815    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5816    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5817    tryToCloneSchema(p, newDb, "type!='table'", 0);
5818    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5819    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5820  }
5821  close_db(newDb);
5822}
5823
5824/*
5825** Change the output file back to stdout.
5826**
5827** If the p->doXdgOpen flag is set, that means the output was being
5828** redirected to a temporary file named by p->zTempFile.  In that case,
5829** launch start/open/xdg-open on that temporary file.
5830*/
5831static void output_reset(ShellState *p){
5832  if( p->outfile[0]=='|' ){
5833#ifndef SQLITE_OMIT_POPEN
5834    pclose(p->out);
5835#endif
5836  }else{
5837    output_file_close(p->out);
5838#ifndef SQLITE_NOHAVE_SYSTEM
5839    if( p->doXdgOpen ){
5840      const char *zXdgOpenCmd =
5841#if defined(_WIN32)
5842      "start";
5843#elif defined(__APPLE__)
5844      "open";
5845#else
5846      "xdg-open";
5847#endif
5848      char *zCmd;
5849      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5850      if( system(zCmd) ){
5851        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5852      }else{
5853        /* Give the start/open/xdg-open command some time to get
5854        ** going before we continue, and potential delete the
5855        ** p->zTempFile data file out from under it */
5856        sqlite3_sleep(2000);
5857      }
5858      sqlite3_free(zCmd);
5859      outputModePop(p);
5860      p->doXdgOpen = 0;
5861    }
5862#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5863  }
5864  p->outfile[0] = 0;
5865  p->out = stdout;
5866}
5867
5868/*
5869** Run an SQL command and return the single integer result.
5870*/
5871static int db_int(sqlite3 *db, const char *zSql){
5872  sqlite3_stmt *pStmt;
5873  int res = 0;
5874  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5875  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5876    res = sqlite3_column_int(pStmt,0);
5877  }
5878  sqlite3_finalize(pStmt);
5879  return res;
5880}
5881
5882#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5883/*
5884** Convert a 2-byte or 4-byte big-endian integer into a native integer
5885*/
5886static unsigned int get2byteInt(unsigned char *a){
5887  return (a[0]<<8) + a[1];
5888}
5889static unsigned int get4byteInt(unsigned char *a){
5890  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5891}
5892
5893/*
5894** Implementation of the ".dbinfo" command.
5895**
5896** Return 1 on error, 2 to exit, and 0 otherwise.
5897*/
5898static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5899  static const struct { const char *zName; int ofst; } aField[] = {
5900     { "file change counter:",  24  },
5901     { "database page count:",  28  },
5902     { "freelist page count:",  36  },
5903     { "schema cookie:",        40  },
5904     { "schema format:",        44  },
5905     { "default cache size:",   48  },
5906     { "autovacuum top root:",  52  },
5907     { "incremental vacuum:",   64  },
5908     { "text encoding:",        56  },
5909     { "user version:",         60  },
5910     { "application id:",       68  },
5911     { "software version:",     96  },
5912  };
5913  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5914     { "number of tables:",
5915       "SELECT count(*) FROM %s WHERE type='table'" },
5916     { "number of indexes:",
5917       "SELECT count(*) FROM %s WHERE type='index'" },
5918     { "number of triggers:",
5919       "SELECT count(*) FROM %s WHERE type='trigger'" },
5920     { "number of views:",
5921       "SELECT count(*) FROM %s WHERE type='view'" },
5922     { "schema size:",
5923       "SELECT total(length(sql)) FROM %s" },
5924  };
5925  int i, rc;
5926  unsigned iDataVersion;
5927  char *zSchemaTab;
5928  char *zDb = nArg>=2 ? azArg[1] : "main";
5929  sqlite3_stmt *pStmt = 0;
5930  unsigned char aHdr[100];
5931  open_db(p, 0);
5932  if( p->db==0 ) return 1;
5933  rc = sqlite3_prepare_v2(p->db,
5934             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5935             -1, &pStmt, 0);
5936  if( rc ){
5937    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5938    sqlite3_finalize(pStmt);
5939    return 1;
5940  }
5941  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5942  if( sqlite3_step(pStmt)==SQLITE_ROW
5943   && sqlite3_column_bytes(pStmt,0)>100
5944  ){
5945    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5946    sqlite3_finalize(pStmt);
5947  }else{
5948    raw_printf(stderr, "unable to read database header\n");
5949    sqlite3_finalize(pStmt);
5950    return 1;
5951  }
5952  i = get2byteInt(aHdr+16);
5953  if( i==1 ) i = 65536;
5954  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5955  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5956  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5957  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5958  for(i=0; i<ArraySize(aField); i++){
5959    int ofst = aField[i].ofst;
5960    unsigned int val = get4byteInt(aHdr + ofst);
5961    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5962    switch( ofst ){
5963      case 56: {
5964        if( val==1 ) raw_printf(p->out, " (utf8)");
5965        if( val==2 ) raw_printf(p->out, " (utf16le)");
5966        if( val==3 ) raw_printf(p->out, " (utf16be)");
5967      }
5968    }
5969    raw_printf(p->out, "\n");
5970  }
5971  if( zDb==0 ){
5972    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5973  }else if( strcmp(zDb,"temp")==0 ){
5974    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5975  }else{
5976    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5977  }
5978  for(i=0; i<ArraySize(aQuery); i++){
5979    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5980    int val = db_int(p->db, zSql);
5981    sqlite3_free(zSql);
5982    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5983  }
5984  sqlite3_free(zSchemaTab);
5985  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5986  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5987  return 0;
5988}
5989#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5990          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5991
5992/*
5993** Print the current sqlite3_errmsg() value to stderr and return 1.
5994*/
5995static int shellDatabaseError(sqlite3 *db){
5996  const char *zErr = sqlite3_errmsg(db);
5997  utf8_printf(stderr, "Error: %s\n", zErr);
5998  return 1;
5999}
6000
6001/*
6002** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
6003** if they match and FALSE (0) if they do not match.
6004**
6005** Globbing rules:
6006**
6007**      '*'       Matches any sequence of zero or more characters.
6008**
6009**      '?'       Matches exactly one character.
6010**
6011**     [...]      Matches one character from the enclosed list of
6012**                characters.
6013**
6014**     [^...]     Matches one character not in the enclosed list.
6015**
6016**      '#'       Matches any sequence of one or more digits with an
6017**                optional + or - sign in front
6018**
6019**      ' '       Any span of whitespace matches any other span of
6020**                whitespace.
6021**
6022** Extra whitespace at the end of z[] is ignored.
6023*/
6024static int testcase_glob(const char *zGlob, const char *z){
6025  int c, c2;
6026  int invert;
6027  int seen;
6028
6029  while( (c = (*(zGlob++)))!=0 ){
6030    if( IsSpace(c) ){
6031      if( !IsSpace(*z) ) return 0;
6032      while( IsSpace(*zGlob) ) zGlob++;
6033      while( IsSpace(*z) ) z++;
6034    }else if( c=='*' ){
6035      while( (c=(*(zGlob++))) == '*' || c=='?' ){
6036        if( c=='?' && (*(z++))==0 ) return 0;
6037      }
6038      if( c==0 ){
6039        return 1;
6040      }else if( c=='[' ){
6041        while( *z && testcase_glob(zGlob-1,z)==0 ){
6042          z++;
6043        }
6044        return (*z)!=0;
6045      }
6046      while( (c2 = (*(z++)))!=0 ){
6047        while( c2!=c ){
6048          c2 = *(z++);
6049          if( c2==0 ) return 0;
6050        }
6051        if( testcase_glob(zGlob,z) ) return 1;
6052      }
6053      return 0;
6054    }else if( c=='?' ){
6055      if( (*(z++))==0 ) return 0;
6056    }else if( c=='[' ){
6057      int prior_c = 0;
6058      seen = 0;
6059      invert = 0;
6060      c = *(z++);
6061      if( c==0 ) return 0;
6062      c2 = *(zGlob++);
6063      if( c2=='^' ){
6064        invert = 1;
6065        c2 = *(zGlob++);
6066      }
6067      if( c2==']' ){
6068        if( c==']' ) seen = 1;
6069        c2 = *(zGlob++);
6070      }
6071      while( c2 && c2!=']' ){
6072        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6073          c2 = *(zGlob++);
6074          if( c>=prior_c && c<=c2 ) seen = 1;
6075          prior_c = 0;
6076        }else{
6077          if( c==c2 ){
6078            seen = 1;
6079          }
6080          prior_c = c2;
6081        }
6082        c2 = *(zGlob++);
6083      }
6084      if( c2==0 || (seen ^ invert)==0 ) return 0;
6085    }else if( c=='#' ){
6086      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6087      if( !IsDigit(z[0]) ) return 0;
6088      z++;
6089      while( IsDigit(z[0]) ){ z++; }
6090    }else{
6091      if( c!=(*(z++)) ) return 0;
6092    }
6093  }
6094  while( IsSpace(*z) ){ z++; }
6095  return *z==0;
6096}
6097
6098
6099/*
6100** Compare the string as a command-line option with either one or two
6101** initial "-" characters.
6102*/
6103static int optionMatch(const char *zStr, const char *zOpt){
6104  if( zStr[0]!='-' ) return 0;
6105  zStr++;
6106  if( zStr[0]=='-' ) zStr++;
6107  return strcmp(zStr, zOpt)==0;
6108}
6109
6110/*
6111** Delete a file.
6112*/
6113int shellDeleteFile(const char *zFilename){
6114  int rc;
6115#ifdef _WIN32
6116  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6117  rc = _wunlink(z);
6118  sqlite3_free(z);
6119#else
6120  rc = unlink(zFilename);
6121#endif
6122  return rc;
6123}
6124
6125/*
6126** Try to delete the temporary file (if there is one) and free the
6127** memory used to hold the name of the temp file.
6128*/
6129static void clearTempFile(ShellState *p){
6130  if( p->zTempFile==0 ) return;
6131  if( p->doXdgOpen ) return;
6132  if( shellDeleteFile(p->zTempFile) ) return;
6133  sqlite3_free(p->zTempFile);
6134  p->zTempFile = 0;
6135}
6136
6137/*
6138** Create a new temp file name with the given suffix.
6139*/
6140static void newTempFile(ShellState *p, const char *zSuffix){
6141  clearTempFile(p);
6142  sqlite3_free(p->zTempFile);
6143  p->zTempFile = 0;
6144  if( p->db ){
6145    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6146  }
6147  if( p->zTempFile==0 ){
6148    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6149    ** will not work and we will need to fallback to guessing */
6150    char *zTemp;
6151    sqlite3_uint64 r;
6152    sqlite3_randomness(sizeof(r), &r);
6153    zTemp = getenv("TEMP");
6154    if( zTemp==0 ) zTemp = getenv("TMP");
6155    if( zTemp==0 ){
6156#ifdef _WIN32
6157      zTemp = "\\tmp";
6158#else
6159      zTemp = "/tmp";
6160#endif
6161    }
6162    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6163  }else{
6164    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6165  }
6166  shell_check_oom(p->zTempFile);
6167}
6168
6169
6170/*
6171** The implementation of SQL scalar function fkey_collate_clause(), used
6172** by the ".lint fkey-indexes" command. This scalar function is always
6173** called with four arguments - the parent table name, the parent column name,
6174** the child table name and the child column name.
6175**
6176**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6177**
6178** If either of the named tables or columns do not exist, this function
6179** returns an empty string. An empty string is also returned if both tables
6180** and columns exist but have the same default collation sequence. Or,
6181** if both exist but the default collation sequences are different, this
6182** function returns the string " COLLATE <parent-collation>", where
6183** <parent-collation> is the default collation sequence of the parent column.
6184*/
6185static void shellFkeyCollateClause(
6186  sqlite3_context *pCtx,
6187  int nVal,
6188  sqlite3_value **apVal
6189){
6190  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6191  const char *zParent;
6192  const char *zParentCol;
6193  const char *zParentSeq;
6194  const char *zChild;
6195  const char *zChildCol;
6196  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6197  int rc;
6198
6199  assert( nVal==4 );
6200  zParent = (const char*)sqlite3_value_text(apVal[0]);
6201  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6202  zChild = (const char*)sqlite3_value_text(apVal[2]);
6203  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6204
6205  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6206  rc = sqlite3_table_column_metadata(
6207      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6208  );
6209  if( rc==SQLITE_OK ){
6210    rc = sqlite3_table_column_metadata(
6211        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6212    );
6213  }
6214
6215  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6216    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6217    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6218    sqlite3_free(z);
6219  }
6220}
6221
6222
6223/*
6224** The implementation of dot-command ".lint fkey-indexes".
6225*/
6226static int lintFkeyIndexes(
6227  ShellState *pState,             /* Current shell tool state */
6228  char **azArg,                   /* Array of arguments passed to dot command */
6229  int nArg                        /* Number of entries in azArg[] */
6230){
6231  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6232  FILE *out = pState->out;        /* Stream to write non-error output to */
6233  int bVerbose = 0;               /* If -verbose is present */
6234  int bGroupByParent = 0;         /* If -groupbyparent is present */
6235  int i;                          /* To iterate through azArg[] */
6236  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6237  int rc;                         /* Return code */
6238  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6239
6240  /*
6241  ** This SELECT statement returns one row for each foreign key constraint
6242  ** in the schema of the main database. The column values are:
6243  **
6244  ** 0. The text of an SQL statement similar to:
6245  **
6246  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6247  **
6248  **    This SELECT is similar to the one that the foreign keys implementation
6249  **    needs to run internally on child tables. If there is an index that can
6250  **    be used to optimize this query, then it can also be used by the FK
6251  **    implementation to optimize DELETE or UPDATE statements on the parent
6252  **    table.
6253  **
6254  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6255  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6256  **    contains an index that can be used to optimize the query.
6257  **
6258  ** 2. Human readable text that describes the child table and columns. e.g.
6259  **
6260  **       "child_table(child_key1, child_key2)"
6261  **
6262  ** 3. Human readable text that describes the parent table and columns. e.g.
6263  **
6264  **       "parent_table(parent_key1, parent_key2)"
6265  **
6266  ** 4. A full CREATE INDEX statement for an index that could be used to
6267  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6268  **
6269  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6270  **
6271  ** 5. The name of the parent table.
6272  **
6273  ** These six values are used by the C logic below to generate the report.
6274  */
6275  const char *zSql =
6276  "SELECT "
6277    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6278    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6279    "  || fkey_collate_clause("
6280    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6281    ", "
6282    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6283    "  || group_concat('*=?', ' AND ') || ')'"
6284    ", "
6285    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6286    ", "
6287    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6288    ", "
6289    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6290    "  || ' ON ' || quote(s.name) || '('"
6291    "  || group_concat(quote(f.[from]) ||"
6292    "        fkey_collate_clause("
6293    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6294    "  || ');'"
6295    ", "
6296    "     f.[table] "
6297    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6298    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6299    "GROUP BY s.name, f.id "
6300    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6301  ;
6302  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6303
6304  for(i=2; i<nArg; i++){
6305    int n = strlen30(azArg[i]);
6306    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6307      bVerbose = 1;
6308    }
6309    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6310      bGroupByParent = 1;
6311      zIndent = "    ";
6312    }
6313    else{
6314      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6315          azArg[0], azArg[1]
6316      );
6317      return SQLITE_ERROR;
6318    }
6319  }
6320
6321  /* Register the fkey_collate_clause() SQL function */
6322  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6323      0, shellFkeyCollateClause, 0, 0
6324  );
6325
6326
6327  if( rc==SQLITE_OK ){
6328    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6329  }
6330  if( rc==SQLITE_OK ){
6331    sqlite3_bind_int(pSql, 1, bGroupByParent);
6332  }
6333
6334  if( rc==SQLITE_OK ){
6335    int rc2;
6336    char *zPrev = 0;
6337    while( SQLITE_ROW==sqlite3_step(pSql) ){
6338      int res = -1;
6339      sqlite3_stmt *pExplain = 0;
6340      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6341      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6342      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6343      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6344      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6345      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6346
6347      if( zEQP==0 ) continue;
6348      if( zGlob==0 ) continue;
6349      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6350      if( rc!=SQLITE_OK ) break;
6351      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6352        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6353        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6354                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6355      }
6356      rc = sqlite3_finalize(pExplain);
6357      if( rc!=SQLITE_OK ) break;
6358
6359      if( res<0 ){
6360        raw_printf(stderr, "Error: internal error");
6361        break;
6362      }else{
6363        if( bGroupByParent
6364        && (bVerbose || res==0)
6365        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6366        ){
6367          raw_printf(out, "-- Parent table %s\n", zParent);
6368          sqlite3_free(zPrev);
6369          zPrev = sqlite3_mprintf("%s", zParent);
6370        }
6371
6372        if( res==0 ){
6373          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6374        }else if( bVerbose ){
6375          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6376              zIndent, zFrom, zTarget
6377          );
6378        }
6379      }
6380    }
6381    sqlite3_free(zPrev);
6382
6383    if( rc!=SQLITE_OK ){
6384      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6385    }
6386
6387    rc2 = sqlite3_finalize(pSql);
6388    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6389      rc = rc2;
6390      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6391    }
6392  }else{
6393    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6394  }
6395
6396  return rc;
6397}
6398
6399/*
6400** Implementation of ".lint" dot command.
6401*/
6402static int lintDotCommand(
6403  ShellState *pState,             /* Current shell tool state */
6404  char **azArg,                   /* Array of arguments passed to dot command */
6405  int nArg                        /* Number of entries in azArg[] */
6406){
6407  int n;
6408  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6409  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6410  return lintFkeyIndexes(pState, azArg, nArg);
6411
6412 usage:
6413  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6414  raw_printf(stderr, "Where sub-commands are:\n");
6415  raw_printf(stderr, "    fkey-indexes\n");
6416  return SQLITE_ERROR;
6417}
6418
6419#if !defined SQLITE_OMIT_VIRTUALTABLE
6420static void shellPrepare(
6421  sqlite3 *db,
6422  int *pRc,
6423  const char *zSql,
6424  sqlite3_stmt **ppStmt
6425){
6426  *ppStmt = 0;
6427  if( *pRc==SQLITE_OK ){
6428    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6429    if( rc!=SQLITE_OK ){
6430      raw_printf(stderr, "sql error: %s (%d)\n",
6431          sqlite3_errmsg(db), sqlite3_errcode(db)
6432      );
6433      *pRc = rc;
6434    }
6435  }
6436}
6437
6438/*
6439** Create a prepared statement using printf-style arguments for the SQL.
6440**
6441** This routine is could be marked "static".  But it is not always used,
6442** depending on compile-time options.  By omitting the "static", we avoid
6443** nuisance compiler warnings about "defined but not used".
6444*/
6445void shellPreparePrintf(
6446  sqlite3 *db,
6447  int *pRc,
6448  sqlite3_stmt **ppStmt,
6449  const char *zFmt,
6450  ...
6451){
6452  *ppStmt = 0;
6453  if( *pRc==SQLITE_OK ){
6454    va_list ap;
6455    char *z;
6456    va_start(ap, zFmt);
6457    z = sqlite3_vmprintf(zFmt, ap);
6458    va_end(ap);
6459    if( z==0 ){
6460      *pRc = SQLITE_NOMEM;
6461    }else{
6462      shellPrepare(db, pRc, z, ppStmt);
6463      sqlite3_free(z);
6464    }
6465  }
6466}
6467
6468/* Finalize the prepared statement created using shellPreparePrintf().
6469**
6470** This routine is could be marked "static".  But it is not always used,
6471** depending on compile-time options.  By omitting the "static", we avoid
6472** nuisance compiler warnings about "defined but not used".
6473*/
6474void shellFinalize(
6475  int *pRc,
6476  sqlite3_stmt *pStmt
6477){
6478  if( pStmt ){
6479    sqlite3 *db = sqlite3_db_handle(pStmt);
6480    int rc = sqlite3_finalize(pStmt);
6481    if( *pRc==SQLITE_OK ){
6482      if( rc!=SQLITE_OK ){
6483        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6484      }
6485      *pRc = rc;
6486    }
6487  }
6488}
6489
6490/* Reset the prepared statement created using shellPreparePrintf().
6491**
6492** This routine is could be marked "static".  But it is not always used,
6493** depending on compile-time options.  By omitting the "static", we avoid
6494** nuisance compiler warnings about "defined but not used".
6495*/
6496void shellReset(
6497  int *pRc,
6498  sqlite3_stmt *pStmt
6499){
6500  int rc = sqlite3_reset(pStmt);
6501  if( *pRc==SQLITE_OK ){
6502    if( rc!=SQLITE_OK ){
6503      sqlite3 *db = sqlite3_db_handle(pStmt);
6504      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6505    }
6506    *pRc = rc;
6507  }
6508}
6509#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6510
6511#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6512/******************************************************************************
6513** The ".archive" or ".ar" command.
6514*/
6515/*
6516** Structure representing a single ".ar" command.
6517*/
6518typedef struct ArCommand ArCommand;
6519struct ArCommand {
6520  u8 eCmd;                        /* An AR_CMD_* value */
6521  u8 bVerbose;                    /* True if --verbose */
6522  u8 bZip;                        /* True if the archive is a ZIP */
6523  u8 bDryRun;                     /* True if --dry-run */
6524  u8 bAppend;                     /* True if --append */
6525  u8 bGlob;                       /* True if --glob */
6526  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6527  int nArg;                       /* Number of command arguments */
6528  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6529  const char *zFile;              /* --file argument, or NULL */
6530  const char *zDir;               /* --directory argument, or NULL */
6531  char **azArg;                   /* Array of command arguments */
6532  ShellState *p;                  /* Shell state */
6533  sqlite3 *db;                    /* Database containing the archive */
6534};
6535
6536/*
6537** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6538*/
6539static int arUsage(FILE *f){
6540  showHelp(f,"archive");
6541  return SQLITE_ERROR;
6542}
6543
6544/*
6545** Print an error message for the .ar command to stderr and return
6546** SQLITE_ERROR.
6547*/
6548static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6549  va_list ap;
6550  char *z;
6551  va_start(ap, zFmt);
6552  z = sqlite3_vmprintf(zFmt, ap);
6553  va_end(ap);
6554  utf8_printf(stderr, "Error: %s\n", z);
6555  if( pAr->fromCmdLine ){
6556    utf8_printf(stderr, "Use \"-A\" for more help\n");
6557  }else{
6558    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6559  }
6560  sqlite3_free(z);
6561  return SQLITE_ERROR;
6562}
6563
6564/*
6565** Values for ArCommand.eCmd.
6566*/
6567#define AR_CMD_CREATE       1
6568#define AR_CMD_UPDATE       2
6569#define AR_CMD_INSERT       3
6570#define AR_CMD_EXTRACT      4
6571#define AR_CMD_LIST         5
6572#define AR_CMD_HELP         6
6573#define AR_CMD_REMOVE       7
6574
6575/*
6576** Other (non-command) switches.
6577*/
6578#define AR_SWITCH_VERBOSE     8
6579#define AR_SWITCH_FILE        9
6580#define AR_SWITCH_DIRECTORY  10
6581#define AR_SWITCH_APPEND     11
6582#define AR_SWITCH_DRYRUN     12
6583#define AR_SWITCH_GLOB       13
6584
6585static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6586  switch( eSwitch ){
6587    case AR_CMD_CREATE:
6588    case AR_CMD_EXTRACT:
6589    case AR_CMD_LIST:
6590    case AR_CMD_REMOVE:
6591    case AR_CMD_UPDATE:
6592    case AR_CMD_INSERT:
6593    case AR_CMD_HELP:
6594      if( pAr->eCmd ){
6595        return arErrorMsg(pAr, "multiple command options");
6596      }
6597      pAr->eCmd = eSwitch;
6598      break;
6599
6600    case AR_SWITCH_DRYRUN:
6601      pAr->bDryRun = 1;
6602      break;
6603    case AR_SWITCH_GLOB:
6604      pAr->bGlob = 1;
6605      break;
6606    case AR_SWITCH_VERBOSE:
6607      pAr->bVerbose = 1;
6608      break;
6609    case AR_SWITCH_APPEND:
6610      pAr->bAppend = 1;
6611      /* Fall thru into --file */
6612    case AR_SWITCH_FILE:
6613      pAr->zFile = zArg;
6614      break;
6615    case AR_SWITCH_DIRECTORY:
6616      pAr->zDir = zArg;
6617      break;
6618  }
6619
6620  return SQLITE_OK;
6621}
6622
6623/*
6624** Parse the command line for an ".ar" command. The results are written into
6625** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6626** successfully, otherwise an error message is written to stderr and
6627** SQLITE_ERROR returned.
6628*/
6629static int arParseCommand(
6630  char **azArg,                   /* Array of arguments passed to dot command */
6631  int nArg,                       /* Number of entries in azArg[] */
6632  ArCommand *pAr                  /* Populate this object */
6633){
6634  struct ArSwitch {
6635    const char *zLong;
6636    char cShort;
6637    u8 eSwitch;
6638    u8 bArg;
6639  } aSwitch[] = {
6640    { "create",    'c', AR_CMD_CREATE,       0 },
6641    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6642    { "insert",    'i', AR_CMD_INSERT,       0 },
6643    { "list",      't', AR_CMD_LIST,         0 },
6644    { "remove",    'r', AR_CMD_REMOVE,       0 },
6645    { "update",    'u', AR_CMD_UPDATE,       0 },
6646    { "help",      'h', AR_CMD_HELP,         0 },
6647    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6648    { "file",      'f', AR_SWITCH_FILE,      1 },
6649    { "append",    'a', AR_SWITCH_APPEND,    1 },
6650    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6651    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6652    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6653  };
6654  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6655  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6656
6657  if( nArg<=1 ){
6658    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6659    return arUsage(stderr);
6660  }else{
6661    char *z = azArg[1];
6662    if( z[0]!='-' ){
6663      /* Traditional style [tar] invocation */
6664      int i;
6665      int iArg = 2;
6666      for(i=0; z[i]; i++){
6667        const char *zArg = 0;
6668        struct ArSwitch *pOpt;
6669        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6670          if( z[i]==pOpt->cShort ) break;
6671        }
6672        if( pOpt==pEnd ){
6673          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6674        }
6675        if( pOpt->bArg ){
6676          if( iArg>=nArg ){
6677            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6678          }
6679          zArg = azArg[iArg++];
6680        }
6681        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6682      }
6683      pAr->nArg = nArg-iArg;
6684      if( pAr->nArg>0 ){
6685        pAr->azArg = &azArg[iArg];
6686      }
6687    }else{
6688      /* Non-traditional invocation */
6689      int iArg;
6690      for(iArg=1; iArg<nArg; iArg++){
6691        int n;
6692        z = azArg[iArg];
6693        if( z[0]!='-' ){
6694          /* All remaining command line words are command arguments. */
6695          pAr->azArg = &azArg[iArg];
6696          pAr->nArg = nArg-iArg;
6697          break;
6698        }
6699        n = strlen30(z);
6700
6701        if( z[1]!='-' ){
6702          int i;
6703          /* One or more short options */
6704          for(i=1; i<n; i++){
6705            const char *zArg = 0;
6706            struct ArSwitch *pOpt;
6707            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6708              if( z[i]==pOpt->cShort ) break;
6709            }
6710            if( pOpt==pEnd ){
6711              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6712            }
6713            if( pOpt->bArg ){
6714              if( i<(n-1) ){
6715                zArg = &z[i+1];
6716                i = n;
6717              }else{
6718                if( iArg>=(nArg-1) ){
6719                  return arErrorMsg(pAr, "option requires an argument: %c",
6720                                    z[i]);
6721                }
6722                zArg = azArg[++iArg];
6723              }
6724            }
6725            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6726          }
6727        }else if( z[2]=='\0' ){
6728          /* A -- option, indicating that all remaining command line words
6729          ** are command arguments.  */
6730          pAr->azArg = &azArg[iArg+1];
6731          pAr->nArg = nArg-iArg-1;
6732          break;
6733        }else{
6734          /* A long option */
6735          const char *zArg = 0;             /* Argument for option, if any */
6736          struct ArSwitch *pMatch = 0;      /* Matching option */
6737          struct ArSwitch *pOpt;            /* Iterator */
6738          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6739            const char *zLong = pOpt->zLong;
6740            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6741              if( pMatch ){
6742                return arErrorMsg(pAr, "ambiguous option: %s",z);
6743              }else{
6744                pMatch = pOpt;
6745              }
6746            }
6747          }
6748
6749          if( pMatch==0 ){
6750            return arErrorMsg(pAr, "unrecognized option: %s", z);
6751          }
6752          if( pMatch->bArg ){
6753            if( iArg>=(nArg-1) ){
6754              return arErrorMsg(pAr, "option requires an argument: %s", z);
6755            }
6756            zArg = azArg[++iArg];
6757          }
6758          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6759        }
6760      }
6761    }
6762  }
6763
6764  return SQLITE_OK;
6765}
6766
6767/*
6768** This function assumes that all arguments within the ArCommand.azArg[]
6769** array refer to archive members, as for the --extract, --list or --remove
6770** commands. It checks that each of them are "present". If any specified
6771** file is not present in the archive, an error is printed to stderr and an
6772** error code returned. Otherwise, if all specified arguments are present
6773** in the archive, SQLITE_OK is returned. Here, "present" means either an
6774** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6775** when pAr->bGlob is true.
6776**
6777** This function strips any trailing '/' characters from each argument.
6778** This is consistent with the way the [tar] command seems to work on
6779** Linux.
6780*/
6781static int arCheckEntries(ArCommand *pAr){
6782  int rc = SQLITE_OK;
6783  if( pAr->nArg ){
6784    int i, j;
6785    sqlite3_stmt *pTest = 0;
6786    const char *zSel = (pAr->bGlob)
6787      ? "SELECT name FROM %s WHERE glob($name,name)"
6788      : "SELECT name FROM %s WHERE name=$name";
6789
6790    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6791    j = sqlite3_bind_parameter_index(pTest, "$name");
6792    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6793      char *z = pAr->azArg[i];
6794      int n = strlen30(z);
6795      int bOk = 0;
6796      while( n>0 && z[n-1]=='/' ) n--;
6797      z[n] = '\0';
6798      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6799      if( SQLITE_ROW==sqlite3_step(pTest) ){
6800        bOk = 1;
6801      }
6802      shellReset(&rc, pTest);
6803      if( rc==SQLITE_OK && bOk==0 ){
6804        utf8_printf(stderr, "not found in archive: %s\n", z);
6805        rc = SQLITE_ERROR;
6806      }
6807    }
6808    shellFinalize(&rc, pTest);
6809  }
6810  return rc;
6811}
6812
6813/*
6814** Format a WHERE clause that can be used against the "sqlar" table to
6815** identify all archive members that match the command arguments held
6816** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6817** The caller is responsible for eventually calling sqlite3_free() on
6818** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6819** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6820*/
6821static void arWhereClause(
6822  int *pRc,
6823  ArCommand *pAr,
6824  char **pzWhere                  /* OUT: New WHERE clause */
6825){
6826  char *zWhere = 0;
6827  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6828  if( *pRc==SQLITE_OK ){
6829    if( pAr->nArg==0 ){
6830      zWhere = sqlite3_mprintf("1");
6831    }else{
6832      int i;
6833      const char *zSep = "";
6834      for(i=0; i<pAr->nArg; i++){
6835        const char *z = pAr->azArg[i];
6836        zWhere = sqlite3_mprintf(
6837          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6838          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6839        );
6840        if( zWhere==0 ){
6841          *pRc = SQLITE_NOMEM;
6842          break;
6843        }
6844        zSep = " OR ";
6845      }
6846    }
6847  }
6848  *pzWhere = zWhere;
6849}
6850
6851/*
6852** Implementation of .ar "lisT" command.
6853*/
6854static int arListCommand(ArCommand *pAr){
6855  const char *zSql = "SELECT %s FROM %s WHERE %s";
6856  const char *azCols[] = {
6857    "name",
6858    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6859  };
6860
6861  char *zWhere = 0;
6862  sqlite3_stmt *pSql = 0;
6863  int rc;
6864
6865  rc = arCheckEntries(pAr);
6866  arWhereClause(&rc, pAr, &zWhere);
6867
6868  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6869                     pAr->zSrcTable, zWhere);
6870  if( pAr->bDryRun ){
6871    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6872  }else{
6873    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6874      if( pAr->bVerbose ){
6875        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6876            sqlite3_column_text(pSql, 0),
6877            sqlite3_column_int(pSql, 1),
6878            sqlite3_column_text(pSql, 2),
6879            sqlite3_column_text(pSql, 3)
6880        );
6881      }else{
6882        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6883      }
6884    }
6885  }
6886  shellFinalize(&rc, pSql);
6887  sqlite3_free(zWhere);
6888  return rc;
6889}
6890
6891
6892/*
6893** Implementation of .ar "Remove" command.
6894*/
6895static int arRemoveCommand(ArCommand *pAr){
6896  int rc = 0;
6897  char *zSql = 0;
6898  char *zWhere = 0;
6899
6900  if( pAr->nArg ){
6901    /* Verify that args actually exist within the archive before proceeding.
6902    ** And formulate a WHERE clause to match them.  */
6903    rc = arCheckEntries(pAr);
6904    arWhereClause(&rc, pAr, &zWhere);
6905  }
6906  if( rc==SQLITE_OK ){
6907    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6908                           pAr->zSrcTable, zWhere);
6909    if( pAr->bDryRun ){
6910      utf8_printf(pAr->p->out, "%s\n", zSql);
6911    }else{
6912      char *zErr = 0;
6913      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6914      if( rc==SQLITE_OK ){
6915        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6916        if( rc!=SQLITE_OK ){
6917          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6918        }else{
6919          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6920        }
6921      }
6922      if( zErr ){
6923        utf8_printf(stdout, "ERROR: %s\n", zErr);
6924        sqlite3_free(zErr);
6925      }
6926    }
6927  }
6928  sqlite3_free(zWhere);
6929  sqlite3_free(zSql);
6930  return rc;
6931}
6932
6933/*
6934** Implementation of .ar "eXtract" command.
6935*/
6936static int arExtractCommand(ArCommand *pAr){
6937  const char *zSql1 =
6938    "SELECT "
6939    " ($dir || name),"
6940    " writefile(($dir || name), %s, mode, mtime) "
6941    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6942    " AND name NOT GLOB '*..[/\\]*'";
6943
6944  const char *azExtraArg[] = {
6945    "sqlar_uncompress(data, sz)",
6946    "data"
6947  };
6948
6949  sqlite3_stmt *pSql = 0;
6950  int rc = SQLITE_OK;
6951  char *zDir = 0;
6952  char *zWhere = 0;
6953  int i, j;
6954
6955  /* If arguments are specified, check that they actually exist within
6956  ** the archive before proceeding. And formulate a WHERE clause to
6957  ** match them.  */
6958  rc = arCheckEntries(pAr);
6959  arWhereClause(&rc, pAr, &zWhere);
6960
6961  if( rc==SQLITE_OK ){
6962    if( pAr->zDir ){
6963      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6964    }else{
6965      zDir = sqlite3_mprintf("");
6966    }
6967    if( zDir==0 ) rc = SQLITE_NOMEM;
6968  }
6969
6970  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6971      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6972  );
6973
6974  if( rc==SQLITE_OK ){
6975    j = sqlite3_bind_parameter_index(pSql, "$dir");
6976    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6977
6978    /* Run the SELECT statement twice. The first time, writefile() is called
6979    ** for all archive members that should be extracted. The second time,
6980    ** only for the directories. This is because the timestamps for
6981    ** extracted directories must be reset after they are populated (as
6982    ** populating them changes the timestamp).  */
6983    for(i=0; i<2; i++){
6984      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6985      sqlite3_bind_int(pSql, j, i);
6986      if( pAr->bDryRun ){
6987        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6988      }else{
6989        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6990          if( i==0 && pAr->bVerbose ){
6991            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6992          }
6993        }
6994      }
6995      shellReset(&rc, pSql);
6996    }
6997    shellFinalize(&rc, pSql);
6998  }
6999
7000  sqlite3_free(zDir);
7001  sqlite3_free(zWhere);
7002  return rc;
7003}
7004
7005/*
7006** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
7007*/
7008static int arExecSql(ArCommand *pAr, const char *zSql){
7009  int rc;
7010  if( pAr->bDryRun ){
7011    utf8_printf(pAr->p->out, "%s\n", zSql);
7012    rc = SQLITE_OK;
7013  }else{
7014    char *zErr = 0;
7015    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
7016    if( zErr ){
7017      utf8_printf(stdout, "ERROR: %s\n", zErr);
7018      sqlite3_free(zErr);
7019    }
7020  }
7021  return rc;
7022}
7023
7024
7025/*
7026** Implementation of .ar "create", "insert", and "update" commands.
7027**
7028**     create    ->     Create a new SQL archive
7029**     insert    ->     Insert or reinsert all files listed
7030**     update    ->     Insert files that have changed or that were not
7031**                      previously in the archive
7032**
7033** Create the "sqlar" table in the database if it does not already exist.
7034** Then add each file in the azFile[] array to the archive. Directories
7035** are added recursively. If argument bVerbose is non-zero, a message is
7036** printed on stdout for each file archived.
7037**
7038** The create command is the same as update, except that it drops
7039** any existing "sqlar" table before beginning.  The "insert" command
7040** always overwrites every file named on the command-line, where as
7041** "update" only overwrites if the size or mtime or mode has changed.
7042*/
7043static int arCreateOrUpdateCommand(
7044  ArCommand *pAr,                 /* Command arguments and options */
7045  int bUpdate,                    /* true for a --create. */
7046  int bOnlyIfChanged              /* Only update if file has changed */
7047){
7048  const char *zCreate =
7049      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7050      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7051      "  mode INT,               -- access permissions\n"
7052      "  mtime INT,              -- last modification time\n"
7053      "  sz INT,                 -- original file size\n"
7054      "  data BLOB               -- compressed content\n"
7055      ")";
7056  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7057  const char *zInsertFmt[2] = {
7058     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7059     "  SELECT\n"
7060     "    %s,\n"
7061     "    mode,\n"
7062     "    mtime,\n"
7063     "    CASE substr(lsmode(mode),1,1)\n"
7064     "      WHEN '-' THEN length(data)\n"
7065     "      WHEN 'd' THEN 0\n"
7066     "      ELSE -1 END,\n"
7067     "    sqlar_compress(data)\n"
7068     "  FROM fsdir(%Q,%Q) AS disk\n"
7069     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7070     ,
7071     "REPLACE INTO %s(name,mode,mtime,data)\n"
7072     "  SELECT\n"
7073     "    %s,\n"
7074     "    mode,\n"
7075     "    mtime,\n"
7076     "    data\n"
7077     "  FROM fsdir(%Q,%Q) AS disk\n"
7078     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7079  };
7080  int i;                          /* For iterating through azFile[] */
7081  int rc;                         /* Return code */
7082  const char *zTab = 0;           /* SQL table into which to insert */
7083  char *zSql;
7084  char zTemp[50];
7085  char *zExists = 0;
7086
7087  arExecSql(pAr, "PRAGMA page_size=512");
7088  rc = arExecSql(pAr, "SAVEPOINT ar;");
7089  if( rc!=SQLITE_OK ) return rc;
7090  zTemp[0] = 0;
7091  if( pAr->bZip ){
7092    /* Initialize the zipfile virtual table, if necessary */
7093    if( pAr->zFile ){
7094      sqlite3_uint64 r;
7095      sqlite3_randomness(sizeof(r),&r);
7096      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7097      zTab = zTemp;
7098      zSql = sqlite3_mprintf(
7099         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7100         zTab, pAr->zFile
7101      );
7102      rc = arExecSql(pAr, zSql);
7103      sqlite3_free(zSql);
7104    }else{
7105      zTab = "zip";
7106    }
7107  }else{
7108    /* Initialize the table for an SQLAR */
7109    zTab = "sqlar";
7110    if( bUpdate==0 ){
7111      rc = arExecSql(pAr, zDrop);
7112      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7113    }
7114    rc = arExecSql(pAr, zCreate);
7115  }
7116  if( bOnlyIfChanged ){
7117    zExists = sqlite3_mprintf(
7118      " AND NOT EXISTS("
7119          "SELECT 1 FROM %s AS mem"
7120          " WHERE mem.name=disk.name"
7121          " AND mem.mtime=disk.mtime"
7122          " AND mem.mode=disk.mode)", zTab);
7123  }else{
7124    zExists = sqlite3_mprintf("");
7125  }
7126  if( zExists==0 ) rc = SQLITE_NOMEM;
7127  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7128    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7129        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7130        pAr->azArg[i], pAr->zDir, zExists);
7131    rc = arExecSql(pAr, zSql2);
7132    sqlite3_free(zSql2);
7133  }
7134end_ar_transaction:
7135  if( rc!=SQLITE_OK ){
7136    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7137  }else{
7138    rc = arExecSql(pAr, "RELEASE ar;");
7139    if( pAr->bZip && pAr->zFile ){
7140      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7141      arExecSql(pAr, zSql);
7142      sqlite3_free(zSql);
7143    }
7144  }
7145  sqlite3_free(zExists);
7146  return rc;
7147}
7148
7149/*
7150** Implementation of ".ar" dot command.
7151*/
7152static int arDotCommand(
7153  ShellState *pState,          /* Current shell tool state */
7154  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7155  char **azArg,                /* Array of arguments passed to dot command */
7156  int nArg                     /* Number of entries in azArg[] */
7157){
7158  ArCommand cmd;
7159  int rc;
7160  memset(&cmd, 0, sizeof(cmd));
7161  cmd.fromCmdLine = fromCmdLine;
7162  rc = arParseCommand(azArg, nArg, &cmd);
7163  if( rc==SQLITE_OK ){
7164    int eDbType = SHELL_OPEN_UNSPEC;
7165    cmd.p = pState;
7166    cmd.db = pState->db;
7167    if( cmd.zFile ){
7168      eDbType = deduceDatabaseType(cmd.zFile, 1);
7169    }else{
7170      eDbType = pState->openMode;
7171    }
7172    if( eDbType==SHELL_OPEN_ZIPFILE ){
7173      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7174        if( cmd.zFile==0 ){
7175          cmd.zSrcTable = sqlite3_mprintf("zip");
7176        }else{
7177          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7178        }
7179      }
7180      cmd.bZip = 1;
7181    }else if( cmd.zFile ){
7182      int flags;
7183      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7184      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7185           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7186        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7187      }else{
7188        flags = SQLITE_OPEN_READONLY;
7189      }
7190      cmd.db = 0;
7191      if( cmd.bDryRun ){
7192        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7193             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7194      }
7195      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7196             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7197      if( rc!=SQLITE_OK ){
7198        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7199            cmd.zFile, sqlite3_errmsg(cmd.db)
7200        );
7201        goto end_ar_command;
7202      }
7203      sqlite3_fileio_init(cmd.db, 0, 0);
7204      sqlite3_sqlar_init(cmd.db, 0, 0);
7205      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7206                              shellPutsFunc, 0, 0);
7207
7208    }
7209    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7210      if( cmd.eCmd!=AR_CMD_CREATE
7211       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7212      ){
7213        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7214        rc = SQLITE_ERROR;
7215        goto end_ar_command;
7216      }
7217      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7218    }
7219
7220    switch( cmd.eCmd ){
7221      case AR_CMD_CREATE:
7222        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7223        break;
7224
7225      case AR_CMD_EXTRACT:
7226        rc = arExtractCommand(&cmd);
7227        break;
7228
7229      case AR_CMD_LIST:
7230        rc = arListCommand(&cmd);
7231        break;
7232
7233      case AR_CMD_HELP:
7234        arUsage(pState->out);
7235        break;
7236
7237      case AR_CMD_INSERT:
7238        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7239        break;
7240
7241      case AR_CMD_REMOVE:
7242        rc = arRemoveCommand(&cmd);
7243        break;
7244
7245      default:
7246        assert( cmd.eCmd==AR_CMD_UPDATE );
7247        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7248        break;
7249    }
7250  }
7251end_ar_command:
7252  if( cmd.db!=pState->db ){
7253    close_db(cmd.db);
7254  }
7255  sqlite3_free(cmd.zSrcTable);
7256
7257  return rc;
7258}
7259/* End of the ".archive" or ".ar" command logic
7260*******************************************************************************/
7261#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7262
7263#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7264/*
7265** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7266** Otherwise, the SQL statement or statements in zSql are executed using
7267** database connection db and the error code written to *pRc before
7268** this function returns.
7269*/
7270static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7271  int rc = *pRc;
7272  if( rc==SQLITE_OK ){
7273    char *zErr = 0;
7274    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7275    if( rc!=SQLITE_OK ){
7276      raw_printf(stderr, "SQL error: %s\n", zErr);
7277    }
7278    sqlite3_free(zErr);
7279    *pRc = rc;
7280  }
7281}
7282
7283/*
7284** Like shellExec(), except that zFmt is a printf() style format string.
7285*/
7286static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7287  char *z = 0;
7288  if( *pRc==SQLITE_OK ){
7289    va_list ap;
7290    va_start(ap, zFmt);
7291    z = sqlite3_vmprintf(zFmt, ap);
7292    va_end(ap);
7293    if( z==0 ){
7294      *pRc = SQLITE_NOMEM;
7295    }else{
7296      shellExec(db, pRc, z);
7297    }
7298    sqlite3_free(z);
7299  }
7300}
7301
7302/*
7303** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7304** Otherwise, an attempt is made to allocate, zero and return a pointer
7305** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7306** to SQLITE_NOMEM and NULL returned.
7307*/
7308static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7309  void *pRet = 0;
7310  if( *pRc==SQLITE_OK ){
7311    pRet = sqlite3_malloc64(nByte);
7312    if( pRet==0 ){
7313      *pRc = SQLITE_NOMEM;
7314    }else{
7315      memset(pRet, 0, nByte);
7316    }
7317  }
7318  return pRet;
7319}
7320
7321/*
7322** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7323** Otherwise, zFmt is treated as a printf() style string. The result of
7324** formatting it along with any trailing arguments is written into a
7325** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7326** It is the responsibility of the caller to eventually free this buffer
7327** using a call to sqlite3_free().
7328**
7329** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7330** pointer returned.
7331*/
7332static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7333  char *z = 0;
7334  if( *pRc==SQLITE_OK ){
7335    va_list ap;
7336    va_start(ap, zFmt);
7337    z = sqlite3_vmprintf(zFmt, ap);
7338    va_end(ap);
7339    if( z==0 ){
7340      *pRc = SQLITE_NOMEM;
7341    }
7342  }
7343  return z;
7344}
7345
7346
7347/*
7348** When running the ".recover" command, each output table, and the special
7349** orphaned row table if it is required, is represented by an instance
7350** of the following struct.
7351*/
7352typedef struct RecoverTable RecoverTable;
7353struct RecoverTable {
7354  char *zQuoted;                  /* Quoted version of table name */
7355  int nCol;                       /* Number of columns in table */
7356  char **azlCol;                  /* Array of column lists */
7357  int iPk;                        /* Index of IPK column */
7358};
7359
7360/*
7361** Free a RecoverTable object allocated by recoverFindTable() or
7362** recoverOrphanTable().
7363*/
7364static void recoverFreeTable(RecoverTable *pTab){
7365  if( pTab ){
7366    sqlite3_free(pTab->zQuoted);
7367    if( pTab->azlCol ){
7368      int i;
7369      for(i=0; i<=pTab->nCol; i++){
7370        sqlite3_free(pTab->azlCol[i]);
7371      }
7372      sqlite3_free(pTab->azlCol);
7373    }
7374    sqlite3_free(pTab);
7375  }
7376}
7377
7378/*
7379** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7380** Otherwise, it allocates and returns a RecoverTable object based on the
7381** final four arguments passed to this function. It is the responsibility
7382** of the caller to eventually free the returned object using
7383** recoverFreeTable().
7384*/
7385static RecoverTable *recoverNewTable(
7386  int *pRc,                       /* IN/OUT: Error code */
7387  const char *zName,              /* Name of table */
7388  const char *zSql,               /* CREATE TABLE statement */
7389  int bIntkey,
7390  int nCol
7391){
7392  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7393  int rc = *pRc;
7394  RecoverTable *pTab = 0;
7395
7396  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7397  if( rc==SQLITE_OK ){
7398    int nSqlCol = 0;
7399    int bSqlIntkey = 0;
7400    sqlite3_stmt *pStmt = 0;
7401
7402    rc = sqlite3_open("", &dbtmp);
7403    if( rc==SQLITE_OK ){
7404      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7405                              shellIdQuote, 0, 0);
7406    }
7407    if( rc==SQLITE_OK ){
7408      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7409    }
7410    if( rc==SQLITE_OK ){
7411      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7412      if( rc==SQLITE_ERROR ){
7413        rc = SQLITE_OK;
7414        goto finished;
7415      }
7416    }
7417    shellPreparePrintf(dbtmp, &rc, &pStmt,
7418        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7419    );
7420    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7421      nSqlCol = sqlite3_column_int(pStmt, 0);
7422    }
7423    shellFinalize(&rc, pStmt);
7424
7425    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7426      goto finished;
7427    }
7428
7429    shellPreparePrintf(dbtmp, &rc, &pStmt,
7430      "SELECT ("
7431      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7432      ") FROM sqlite_schema WHERE name = %Q", zName
7433    );
7434    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7435      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7436    }
7437    shellFinalize(&rc, pStmt);
7438
7439    if( bIntkey==bSqlIntkey ){
7440      int i;
7441      const char *zPk = "_rowid_";
7442      sqlite3_stmt *pPkFinder = 0;
7443
7444      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7445      ** set zPk to the name of the PK column, and pTab->iPk to the index
7446      ** of the column, where columns are 0-numbered from left to right.
7447      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7448      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7449      pTab->iPk = -2;
7450      if( bIntkey ){
7451        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7452          "SELECT cid, name FROM pragma_table_info(%Q) "
7453          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7454          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7455          , zName, zName
7456        );
7457        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7458          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7459          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7460          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7461        }
7462      }
7463
7464      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7465      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7466      pTab->nCol = nSqlCol;
7467
7468      if( bIntkey ){
7469        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7470      }else{
7471        pTab->azlCol[0] = shellMPrintf(&rc, "");
7472      }
7473      i = 1;
7474      shellPreparePrintf(dbtmp, &rc, &pStmt,
7475          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7476          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7477          "FROM pragma_table_info(%Q)",
7478          bIntkey ? ", " : "", pTab->iPk,
7479          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7480          zName
7481      );
7482      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7483        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7484        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7485        i++;
7486      }
7487      shellFinalize(&rc, pStmt);
7488
7489      shellFinalize(&rc, pPkFinder);
7490    }
7491  }
7492
7493 finished:
7494  sqlite3_close(dbtmp);
7495  *pRc = rc;
7496  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7497    recoverFreeTable(pTab);
7498    pTab = 0;
7499  }
7500  return pTab;
7501}
7502
7503/*
7504** This function is called to search the schema recovered from the
7505** sqlite_schema table of the (possibly) corrupt database as part
7506** of a ".recover" command. Specifically, for a table with root page
7507** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7508** table must be a WITHOUT ROWID table, or if non-zero, not one of
7509** those.
7510**
7511** If a table is found, a (RecoverTable*) object is returned. Or, if
7512** no such table is found, but bIntkey is false and iRoot is the
7513** root page of an index in the recovered schema, then (*pbNoop) is
7514** set to true and NULL returned. Or, if there is no such table or
7515** index, NULL is returned and (*pbNoop) set to 0, indicating that
7516** the caller should write data to the orphans table.
7517*/
7518static RecoverTable *recoverFindTable(
7519  ShellState *pState,             /* Shell state object */
7520  int *pRc,                       /* IN/OUT: Error code */
7521  int iRoot,                      /* Root page of table */
7522  int bIntkey,                    /* True for an intkey table */
7523  int nCol,                       /* Number of columns in table */
7524  int *pbNoop                     /* OUT: True if iRoot is root of index */
7525){
7526  sqlite3_stmt *pStmt = 0;
7527  RecoverTable *pRet = 0;
7528  int bNoop = 0;
7529  const char *zSql = 0;
7530  const char *zName = 0;
7531
7532  /* Search the recovered schema for an object with root page iRoot. */
7533  shellPreparePrintf(pState->db, pRc, &pStmt,
7534      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7535  );
7536  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7537    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7538    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7539      bNoop = 1;
7540      break;
7541    }
7542    if( sqlite3_stricmp(zType, "table")==0 ){
7543      zName = (const char*)sqlite3_column_text(pStmt, 1);
7544      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7545      if( zName!=0 && zSql!=0 ){
7546        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7547        break;
7548      }
7549    }
7550  }
7551
7552  shellFinalize(pRc, pStmt);
7553  *pbNoop = bNoop;
7554  return pRet;
7555}
7556
7557/*
7558** Return a RecoverTable object representing the orphans table.
7559*/
7560static RecoverTable *recoverOrphanTable(
7561  ShellState *pState,             /* Shell state object */
7562  int *pRc,                       /* IN/OUT: Error code */
7563  const char *zLostAndFound,      /* Base name for orphans table */
7564  int nCol                        /* Number of user data columns */
7565){
7566  RecoverTable *pTab = 0;
7567  if( nCol>=0 && *pRc==SQLITE_OK ){
7568    int i;
7569
7570    /* This block determines the name of the orphan table. The prefered
7571    ** name is zLostAndFound. But if that clashes with another name
7572    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7573    ** and so on until a non-clashing name is found.  */
7574    int iTab = 0;
7575    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7576    sqlite3_stmt *pTest = 0;
7577    shellPrepare(pState->db, pRc,
7578        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7579    );
7580    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7581    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7582      shellReset(pRc, pTest);
7583      sqlite3_free(zTab);
7584      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7585      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7586    }
7587    shellFinalize(pRc, pTest);
7588
7589    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7590    if( pTab ){
7591      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7592      pTab->nCol = nCol;
7593      pTab->iPk = -2;
7594      if( nCol>0 ){
7595        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7596        if( pTab->azlCol ){
7597          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7598          for(i=nCol-1; i>=0; i--){
7599            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7600          }
7601        }
7602      }
7603
7604      if( *pRc!=SQLITE_OK ){
7605        recoverFreeTable(pTab);
7606        pTab = 0;
7607      }else{
7608        raw_printf(pState->out,
7609            "CREATE TABLE %s(rootpgno INTEGER, "
7610            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7611        );
7612        for(i=0; i<nCol; i++){
7613          raw_printf(pState->out, ", c%d", i);
7614        }
7615        raw_printf(pState->out, ");\n");
7616      }
7617    }
7618    sqlite3_free(zTab);
7619  }
7620  return pTab;
7621}
7622
7623/*
7624** This function is called to recover data from the database. A script
7625** to construct a new database containing all recovered data is output
7626** on stream pState->out.
7627*/
7628static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7629  int rc = SQLITE_OK;
7630  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7631  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7632  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7633  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7634  const char *zLostAndFound = "lost_and_found";
7635  int i;
7636  int nOrphan = -1;
7637  RecoverTable *pOrphan = 0;
7638
7639  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7640  int bRowids = 1;                /* 0 if --no-rowids */
7641  for(i=1; i<nArg; i++){
7642    char *z = azArg[i];
7643    int n;
7644    if( z[0]=='-' && z[1]=='-' ) z++;
7645    n = strlen30(z);
7646    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7647      bFreelist = 0;
7648    }else
7649    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7650      i++;
7651      zRecoveryDb = azArg[i];
7652    }else
7653    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7654      i++;
7655      zLostAndFound = azArg[i];
7656    }else
7657    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7658      bRowids = 0;
7659    }
7660    else{
7661      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7662      showHelp(pState->out, azArg[0]);
7663      return 1;
7664    }
7665  }
7666
7667  shellExecPrintf(pState->db, &rc,
7668    /* Attach an in-memory database named 'recovery'. Create an indexed
7669    ** cache of the sqlite_dbptr virtual table. */
7670    "PRAGMA writable_schema = on;"
7671    "ATTACH %Q AS recovery;"
7672    "DROP TABLE IF EXISTS recovery.dbptr;"
7673    "DROP TABLE IF EXISTS recovery.freelist;"
7674    "DROP TABLE IF EXISTS recovery.map;"
7675    "DROP TABLE IF EXISTS recovery.schema;"
7676    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7677  );
7678
7679  if( bFreelist ){
7680    shellExec(pState->db, &rc,
7681      "WITH trunk(pgno) AS ("
7682      "  SELECT shell_int32("
7683      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7684      "      WHERE x>0"
7685      "    UNION"
7686      "  SELECT shell_int32("
7687      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7688      "      FROM trunk WHERE x>0"
7689      "),"
7690      "freelist(data, n, freepgno) AS ("
7691      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7692      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7693      "    UNION ALL"
7694      "  SELECT data, n-1, shell_int32(data, 2+n) "
7695      "      FROM freelist WHERE n>=0"
7696      ")"
7697      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7698    );
7699  }
7700
7701  /* If this is an auto-vacuum database, add all pointer-map pages to
7702  ** the freelist table. Do this regardless of whether or not
7703  ** --freelist-corrupt was specified.  */
7704  shellExec(pState->db, &rc,
7705    "WITH ptrmap(pgno) AS ("
7706    "  SELECT 2 WHERE shell_int32("
7707    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7708    "  )"
7709    "    UNION ALL "
7710    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7711    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7712    ")"
7713    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7714  );
7715
7716  shellExec(pState->db, &rc,
7717    "CREATE TABLE recovery.dbptr("
7718    "      pgno, child, PRIMARY KEY(child, pgno)"
7719    ") WITHOUT ROWID;"
7720    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7721    "    SELECT * FROM sqlite_dbptr"
7722    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7723
7724    /* Delete any pointer to page 1. This ensures that page 1 is considered
7725    ** a root page, regardless of how corrupt the db is. */
7726    "DELETE FROM recovery.dbptr WHERE child = 1;"
7727
7728    /* Delete all pointers to any pages that have more than one pointer
7729    ** to them. Such pages will be treated as root pages when recovering
7730    ** data.  */
7731    "DELETE FROM recovery.dbptr WHERE child IN ("
7732    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7733    ");"
7734
7735    /* Create the "map" table that will (eventually) contain instructions
7736    ** for dealing with each page in the db that contains one or more
7737    ** records. */
7738    "CREATE TABLE recovery.map("
7739      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7740    ");"
7741
7742    /* Populate table [map]. If there are circular loops of pages in the
7743    ** database, the following adds all pages in such a loop to the map
7744    ** as individual root pages. This could be handled better.  */
7745    "WITH pages(i, maxlen) AS ("
7746    "  SELECT page_count, ("
7747    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7748    "  ) FROM pragma_page_count WHERE page_count>0"
7749    "    UNION ALL"
7750    "  SELECT i-1, ("
7751    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7752    "  ) FROM pages WHERE i>=2"
7753    ")"
7754    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7755    "  SELECT i, maxlen, NULL, ("
7756    "    WITH p(orig, pgno, parent) AS ("
7757    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7758    "        UNION "
7759    "      SELECT i, p.parent, "
7760    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7761    "    )"
7762    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7763    ") "
7764    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7765    "UPDATE recovery.map AS o SET intkey = ("
7766    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7767    ");"
7768
7769    /* Extract data from page 1 and any linked pages into table
7770    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7771    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7772    "INSERT INTO recovery.schema SELECT "
7773    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7774    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7775    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7776    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7777    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7778    "FROM sqlite_dbdata WHERE pgno IN ("
7779    "  SELECT pgno FROM recovery.map WHERE root=1"
7780    ")"
7781    "GROUP BY pgno, cell;"
7782    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7783  );
7784
7785  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7786  ** CREATE TABLE statements that extracted from the existing schema.  */
7787  if( rc==SQLITE_OK ){
7788    sqlite3_stmt *pStmt = 0;
7789    /* ".recover" might output content in an order which causes immediate
7790    ** foreign key constraints to be violated. So disable foreign-key
7791    ** constraint enforcement to prevent problems when running the output
7792    ** script. */
7793    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7794    raw_printf(pState->out, "BEGIN;\n");
7795    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7796    shellPrepare(pState->db, &rc,
7797        "SELECT sql FROM recovery.schema "
7798        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7799    );
7800    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7801      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7802      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7803          &zCreateTable[12]
7804      );
7805    }
7806    shellFinalize(&rc, pStmt);
7807  }
7808
7809  /* Figure out if an orphan table will be required. And if so, how many
7810  ** user columns it should contain */
7811  shellPrepare(pState->db, &rc,
7812      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7813      , &pLoop
7814  );
7815  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7816    nOrphan = sqlite3_column_int(pLoop, 0);
7817  }
7818  shellFinalize(&rc, pLoop);
7819  pLoop = 0;
7820
7821  shellPrepare(pState->db, &rc,
7822      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7823  );
7824
7825  shellPrepare(pState->db, &rc,
7826      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7827      "(case when (? AND field<0) then NULL else value end)"
7828      "), ', ')"
7829      ", min(field) "
7830      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7831      "GROUP BY cell", &pCells
7832  );
7833
7834  /* Loop through each root page. */
7835  shellPrepare(pState->db, &rc,
7836      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7837      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7838      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7839      ")", &pLoop
7840  );
7841  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7842    int iRoot = sqlite3_column_int(pLoop, 0);
7843    int bIntkey = sqlite3_column_int(pLoop, 1);
7844    int nCol = sqlite3_column_int(pLoop, 2);
7845    int bNoop = 0;
7846    RecoverTable *pTab;
7847
7848    assert( bIntkey==0 || bIntkey==1 );
7849    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7850    if( bNoop || rc ) continue;
7851    if( pTab==0 ){
7852      if( pOrphan==0 ){
7853        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7854      }
7855      pTab = pOrphan;
7856      if( pTab==0 ) break;
7857    }
7858
7859    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7860      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7861    }
7862    sqlite3_bind_int(pPages, 1, iRoot);
7863    if( bRowids==0 && pTab->iPk<0 ){
7864      sqlite3_bind_int(pCells, 1, 1);
7865    }else{
7866      sqlite3_bind_int(pCells, 1, 0);
7867    }
7868    sqlite3_bind_int(pCells, 3, pTab->iPk);
7869
7870    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7871      int iPgno = sqlite3_column_int(pPages, 0);
7872      sqlite3_bind_int(pCells, 2, iPgno);
7873      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7874        int nField = sqlite3_column_int(pCells, 0);
7875        int iMin = sqlite3_column_int(pCells, 2);
7876        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7877
7878        RecoverTable *pTab2 = pTab;
7879        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7880          if( pOrphan==0 ){
7881            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7882          }
7883          pTab2 = pOrphan;
7884          if( pTab2==0 ) break;
7885        }
7886
7887        nField = nField+1;
7888        if( pTab2==pOrphan ){
7889          raw_printf(pState->out,
7890              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7891              pTab2->zQuoted, iRoot, iPgno, nField,
7892              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7893          );
7894        }else{
7895          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7896              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7897          );
7898        }
7899      }
7900      shellReset(&rc, pCells);
7901    }
7902    shellReset(&rc, pPages);
7903    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7904  }
7905  shellFinalize(&rc, pLoop);
7906  shellFinalize(&rc, pPages);
7907  shellFinalize(&rc, pCells);
7908  recoverFreeTable(pOrphan);
7909
7910  /* The rest of the schema */
7911  if( rc==SQLITE_OK ){
7912    sqlite3_stmt *pStmt = 0;
7913    shellPrepare(pState->db, &rc,
7914        "SELECT sql, name FROM recovery.schema "
7915        "WHERE sql NOT LIKE 'create table%'", &pStmt
7916    );
7917    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7918      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7919      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7920        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7921        char *zPrint = shellMPrintf(&rc,
7922          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7923          zName, zName, zSql
7924        );
7925        raw_printf(pState->out, "%s;\n", zPrint);
7926        sqlite3_free(zPrint);
7927      }else{
7928        raw_printf(pState->out, "%s;\n", zSql);
7929      }
7930    }
7931    shellFinalize(&rc, pStmt);
7932  }
7933
7934  if( rc==SQLITE_OK ){
7935    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7936    raw_printf(pState->out, "COMMIT;\n");
7937  }
7938  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7939  return rc;
7940}
7941#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7942
7943
7944/*
7945 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7946 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7947 *   close db and set it to 0, and return the columns spec, to later
7948 *   be sqlite3_free()'ed by the caller.
7949 * The return is 0 when either:
7950 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7951 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7952 * The 3rd argument, pRenamed, references an out parameter. If the
7953 * pointer is non-zero, its referent will be set to a summary of renames
7954 * done if renaming was necessary, or set to 0 if none was done. The out
7955 * string (if any) must be sqlite3_free()'ed by the caller.
7956 */
7957#ifdef SHELL_DEBUG
7958#define rc_err_oom_die(rc) \
7959  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7960  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7961    fprintf(stderr,"E:%d\n",rc), assert(0)
7962#else
7963static void rc_err_oom_die(int rc){
7964  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7965  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7966}
7967#endif
7968
7969#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7970static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7971#else  /* Otherwise, memory is faster/better for the transient DB. */
7972static const char *zCOL_DB = ":memory:";
7973#endif
7974
7975/* Define character (as C string) to separate generated column ordinal
7976 * from protected part of incoming column names. This defaults to "_"
7977 * so that incoming column identifiers that did not need not be quoted
7978 * remain usable without being quoted. It must be one character.
7979 */
7980#ifndef SHELL_AUTOCOLUMN_SEP
7981# define AUTOCOLUMN_SEP "_"
7982#else
7983# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7984#endif
7985
7986static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7987  /* Queries and D{D,M}L used here */
7988  static const char * const zTabMake = "\
7989CREATE TABLE ColNames(\
7990 cpos INTEGER PRIMARY KEY,\
7991 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7992CREATE VIEW RepeatedNames AS \
7993SELECT DISTINCT t.name FROM ColNames t \
7994WHERE t.name COLLATE NOCASE IN (\
7995 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7996);\
7997";
7998  static const char * const zTabFill = "\
7999INSERT INTO ColNames(name,nlen,chop,reps,suff)\
8000 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
8001";
8002  static const char * const zHasDupes = "\
8003SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
8004 <count(name) FROM ColNames\
8005";
8006#ifdef SHELL_COLUMN_RENAME_CLEAN
8007  static const char * const zDedoctor = "\
8008UPDATE ColNames SET chop=iif(\
8009  (substring(name,nlen,1) BETWEEN '0' AND '9')\
8010  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
8011 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
8012 0\
8013)\
8014";
8015#endif
8016  static const char * const zSetReps = "\
8017UPDATE ColNames AS t SET reps=\
8018(SELECT count(*) FROM ColNames d \
8019 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
8020 COLLATE NOCASE\
8021)\
8022";
8023#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
8024  static const char * const zColDigits = "\
8025SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
8026";
8027#else
8028  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
8029  static const char * const zColDigits = "\
8030SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
8031 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
8032 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
8033";
8034#endif
8035  static const char * const zRenameRank =
8036#ifdef SHELL_COLUMN_RENAME_CLEAN
8037    "UPDATE ColNames AS t SET suff="
8038    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
8039#else /* ...RENAME_MINIMAL_ONE_PASS */
8040"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
8041"  SELECT 0 AS nlz"
8042"  UNION"
8043"  SELECT nlz+1 AS nlz FROM Lzn"
8044"  WHERE EXISTS("
8045"   SELECT 1"
8046"   FROM ColNames t, ColNames o"
8047"   WHERE"
8048"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8049"     printf('%s"AUTOCOLUMN_SEP"%s',"
8050"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8051"     t.name"
8052"    )"
8053"    ="
8054"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8055"     printf('%s"AUTOCOLUMN_SEP"%s',"
8056"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8057"     o.name"
8058"    )"
8059"    COLLATE NOCASE"
8060"    AND o.cpos<>t.cpos"
8061"   GROUP BY t.cpos"
8062"  )"
8063") UPDATE Colnames AS t SET"
8064" chop = 0," /* No chopping, never touch incoming names. */
8065" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8066"  printf('"AUTOCOLUMN_SEP"%s', substring("
8067"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8068"  ''"
8069" )"
8070#endif
8071    ;
8072  static const char * const zCollectVar = "\
8073SELECT\
8074 '('||x'0a'\
8075 || group_concat(\
8076  cname||' TEXT',\
8077  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8078 ||')' AS ColsSpec \
8079FROM (\
8080 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8081 FROM ColNames ORDER BY cpos\
8082)";
8083  static const char * const zRenamesDone =
8084    "SELECT group_concat("
8085    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8086    " ','||x'0a')"
8087    "FROM ColNames WHERE suff<>'' OR chop!=0"
8088    ;
8089  int rc;
8090  sqlite3_stmt *pStmt = 0;
8091  assert(pDb!=0);
8092  if( zColNew ){
8093    /* Add initial or additional column. Init db if necessary. */
8094    if( *pDb==0 ){
8095      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8096#ifdef SHELL_COLFIX_DB
8097      if(*zCOL_DB!=':')
8098        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8099                     "drop view if exists RepeatedNames;",0,0,0);
8100#endif
8101      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8102      rc_err_oom_die(rc);
8103    }
8104    assert(*pDb!=0);
8105    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8106    rc_err_oom_die(rc);
8107    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8108    rc_err_oom_die(rc);
8109    rc = sqlite3_step(pStmt);
8110    rc_err_oom_die(rc);
8111    sqlite3_finalize(pStmt);
8112    return 0;
8113  }else if( *pDb==0 ){
8114    return 0;
8115  }else{
8116    /* Formulate the columns spec, close the DB, zero *pDb. */
8117    char *zColsSpec = 0;
8118    int hasDupes = db_int(*pDb, zHasDupes);
8119    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8120    if( hasDupes ){
8121#ifdef SHELL_COLUMN_RENAME_CLEAN
8122      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8123      rc_err_oom_die(rc);
8124#endif
8125      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8126      rc_err_oom_die(rc);
8127      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8128      rc_err_oom_die(rc);
8129      sqlite3_bind_int(pStmt, 1, nDigits);
8130      rc = sqlite3_step(pStmt);
8131      sqlite3_finalize(pStmt);
8132      assert(rc==SQLITE_DONE);
8133    }
8134    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8135    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8136    rc_err_oom_die(rc);
8137    rc = sqlite3_step(pStmt);
8138    if( rc==SQLITE_ROW ){
8139      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8140    }else{
8141      zColsSpec = 0;
8142    }
8143    if( pzRenamed!=0 ){
8144      if( !hasDupes ) *pzRenamed = 0;
8145      else{
8146        sqlite3_finalize(pStmt);
8147        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8148            && SQLITE_ROW==sqlite3_step(pStmt) ){
8149          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8150        }else
8151          *pzRenamed = 0;
8152      }
8153    }
8154    sqlite3_finalize(pStmt);
8155    sqlite3_close(*pDb);
8156    *pDb = 0;
8157    return zColsSpec;
8158  }
8159}
8160
8161/*
8162** If an input line begins with "." then invoke this routine to
8163** process that line.
8164**
8165** Return 1 on error, 2 to exit, and 0 otherwise.
8166*/
8167static int do_meta_command(char *zLine, ShellState *p){
8168  int h = 1;
8169  int nArg = 0;
8170  int n, c;
8171  int rc = 0;
8172  char *azArg[52];
8173
8174#ifndef SQLITE_OMIT_VIRTUALTABLE
8175  if( p->expert.pExpert ){
8176    expertFinish(p, 1, 0);
8177  }
8178#endif
8179
8180  /* Parse the input line into tokens.
8181  */
8182  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8183    while( IsSpace(zLine[h]) ){ h++; }
8184    if( zLine[h]==0 ) break;
8185    if( zLine[h]=='\'' || zLine[h]=='"' ){
8186      int delim = zLine[h++];
8187      azArg[nArg++] = &zLine[h];
8188      while( zLine[h] && zLine[h]!=delim ){
8189        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8190        h++;
8191      }
8192      if( zLine[h]==delim ){
8193        zLine[h++] = 0;
8194      }
8195      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8196    }else{
8197      azArg[nArg++] = &zLine[h];
8198      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8199      if( zLine[h] ) zLine[h++] = 0;
8200      resolve_backslashes(azArg[nArg-1]);
8201    }
8202  }
8203  azArg[nArg] = 0;
8204
8205  /* Process the input line.
8206  */
8207  if( nArg==0 ) return 0; /* no tokens, no error */
8208  n = strlen30(azArg[0]);
8209  c = azArg[0][0];
8210  clearTempFile(p);
8211
8212#ifndef SQLITE_OMIT_AUTHORIZATION
8213  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8214    if( nArg!=2 ){
8215      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8216      rc = 1;
8217      goto meta_command_exit;
8218    }
8219    open_db(p, 0);
8220    if( booleanValue(azArg[1]) ){
8221      sqlite3_set_authorizer(p->db, shellAuth, p);
8222    }else if( p->bSafeModePersist ){
8223      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8224    }else{
8225      sqlite3_set_authorizer(p->db, 0, 0);
8226    }
8227  }else
8228#endif
8229
8230#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8231  && !defined(SQLITE_SHELL_FIDDLE)
8232  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8233    open_db(p, 0);
8234    failIfSafeMode(p, "cannot run .archive in safe mode");
8235    rc = arDotCommand(p, 0, azArg, nArg);
8236  }else
8237#endif
8238
8239#ifndef SQLITE_SHELL_FIDDLE
8240  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8241   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8242  ){
8243    const char *zDestFile = 0;
8244    const char *zDb = 0;
8245    sqlite3 *pDest;
8246    sqlite3_backup *pBackup;
8247    int j;
8248    int bAsync = 0;
8249    const char *zVfs = 0;
8250    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8251    for(j=1; j<nArg; j++){
8252      const char *z = azArg[j];
8253      if( z[0]=='-' ){
8254        if( z[1]=='-' ) z++;
8255        if( strcmp(z, "-append")==0 ){
8256          zVfs = "apndvfs";
8257        }else
8258        if( strcmp(z, "-async")==0 ){
8259          bAsync = 1;
8260        }else
8261        {
8262          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8263          return 1;
8264        }
8265      }else if( zDestFile==0 ){
8266        zDestFile = azArg[j];
8267      }else if( zDb==0 ){
8268        zDb = zDestFile;
8269        zDestFile = azArg[j];
8270      }else{
8271        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8272        return 1;
8273      }
8274    }
8275    if( zDestFile==0 ){
8276      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8277      return 1;
8278    }
8279    if( zDb==0 ) zDb = "main";
8280    rc = sqlite3_open_v2(zDestFile, &pDest,
8281                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8282    if( rc!=SQLITE_OK ){
8283      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8284      close_db(pDest);
8285      return 1;
8286    }
8287    if( bAsync ){
8288      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8289                   0, 0, 0);
8290    }
8291    open_db(p, 0);
8292    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8293    if( pBackup==0 ){
8294      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8295      close_db(pDest);
8296      return 1;
8297    }
8298    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8299    sqlite3_backup_finish(pBackup);
8300    if( rc==SQLITE_DONE ){
8301      rc = 0;
8302    }else{
8303      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8304      rc = 1;
8305    }
8306    close_db(pDest);
8307  }else
8308#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8309
8310  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8311    if( nArg==2 ){
8312      bail_on_error = booleanValue(azArg[1]);
8313    }else{
8314      raw_printf(stderr, "Usage: .bail on|off\n");
8315      rc = 1;
8316    }
8317  }else
8318
8319  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8320    if( nArg==2 ){
8321      if( booleanValue(azArg[1]) ){
8322        setBinaryMode(p->out, 1);
8323      }else{
8324        setTextMode(p->out, 1);
8325      }
8326    }else{
8327      raw_printf(stderr, "Usage: .binary on|off\n");
8328      rc = 1;
8329    }
8330  }else
8331
8332  /* The undocumented ".breakpoint" command causes a call to the no-op
8333  ** routine named test_breakpoint().
8334  */
8335  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8336    test_breakpoint();
8337  }else
8338
8339#ifndef SQLITE_SHELL_FIDDLE
8340  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8341    failIfSafeMode(p, "cannot run .cd in safe mode");
8342    if( nArg==2 ){
8343#if defined(_WIN32) || defined(WIN32)
8344      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8345      rc = !SetCurrentDirectoryW(z);
8346      sqlite3_free(z);
8347#else
8348      rc = chdir(azArg[1]);
8349#endif
8350      if( rc ){
8351        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8352        rc = 1;
8353      }
8354    }else{
8355      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8356      rc = 1;
8357    }
8358  }else
8359#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8360
8361  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8362    if( nArg==2 ){
8363      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8364    }else{
8365      raw_printf(stderr, "Usage: .changes on|off\n");
8366      rc = 1;
8367    }
8368  }else
8369
8370#ifndef SQLITE_SHELL_FIDDLE
8371  /* Cancel output redirection, if it is currently set (by .testcase)
8372  ** Then read the content of the testcase-out.txt file and compare against
8373  ** azArg[1].  If there are differences, report an error and exit.
8374  */
8375  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8376    char *zRes = 0;
8377    output_reset(p);
8378    if( nArg!=2 ){
8379      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8380      rc = 2;
8381    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8382      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8383      rc = 2;
8384    }else if( testcase_glob(azArg[1],zRes)==0 ){
8385      utf8_printf(stderr,
8386                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8387                 p->zTestcase, azArg[1], zRes);
8388      rc = 1;
8389    }else{
8390      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8391      p->nCheck++;
8392    }
8393    sqlite3_free(zRes);
8394  }else
8395#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8396
8397#ifndef SQLITE_SHELL_FIDDLE
8398  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8399    failIfSafeMode(p, "cannot run .clone in safe mode");
8400    if( nArg==2 ){
8401      tryToClone(p, azArg[1]);
8402    }else{
8403      raw_printf(stderr, "Usage: .clone FILENAME\n");
8404      rc = 1;
8405    }
8406  }else
8407#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8408
8409  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8410    if( nArg==1 ){
8411      /* List available connections */
8412      int i;
8413      for(i=0; i<ArraySize(p->aAuxDb); i++){
8414        const char *zFile = p->aAuxDb[i].zDbFilename;
8415        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8416          zFile = "(not open)";
8417        }else if( zFile==0 ){
8418          zFile = "(memory)";
8419        }else if( zFile[0]==0 ){
8420          zFile = "(temporary-file)";
8421        }
8422        if( p->pAuxDb == &p->aAuxDb[i] ){
8423          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8424        }else if( p->aAuxDb[i].db!=0 ){
8425          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8426        }
8427      }
8428    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8429      int i = azArg[1][0] - '0';
8430      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8431        p->pAuxDb->db = p->db;
8432        p->pAuxDb = &p->aAuxDb[i];
8433        globalDb = p->db = p->pAuxDb->db;
8434        p->pAuxDb->db = 0;
8435      }
8436    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8437           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8438      int i = azArg[2][0] - '0';
8439      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8440        /* No-op */
8441      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8442        raw_printf(stderr, "cannot close the active database connection\n");
8443        rc = 1;
8444      }else if( p->aAuxDb[i].db ){
8445        session_close_all(p, i);
8446        close_db(p->aAuxDb[i].db);
8447        p->aAuxDb[i].db = 0;
8448      }
8449    }else{
8450      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8451      rc = 1;
8452    }
8453  }else
8454
8455  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8456    char **azName = 0;
8457    int nName = 0;
8458    sqlite3_stmt *pStmt;
8459    int i;
8460    open_db(p, 0);
8461    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8462    if( rc ){
8463      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8464      rc = 1;
8465    }else{
8466      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8467        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8468        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8469        if( zSchema==0 || zFile==0 ) continue;
8470        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8471        shell_check_oom(azName);
8472        azName[nName*2] = strdup(zSchema);
8473        azName[nName*2+1] = strdup(zFile);
8474        nName++;
8475      }
8476    }
8477    sqlite3_finalize(pStmt);
8478    for(i=0; i<nName; i++){
8479      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8480      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8481      const char *z = azName[i*2+1];
8482      utf8_printf(p->out, "%s: %s %s%s\n",
8483         azName[i*2],
8484         z && z[0] ? z : "\"\"",
8485         bRdonly ? "r/o" : "r/w",
8486         eTxn==SQLITE_TXN_NONE ? "" :
8487            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8488      free(azName[i*2]);
8489      free(azName[i*2+1]);
8490    }
8491    sqlite3_free(azName);
8492  }else
8493
8494  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8495    static const struct DbConfigChoices {
8496      const char *zName;
8497      int op;
8498    } aDbConfig[] = {
8499        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8500        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8501        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8502        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8503        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8504        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8505        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8506        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8507        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8508        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8509        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8510        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8511        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8512        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8513        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8514        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8515    };
8516    int ii, v;
8517    open_db(p, 0);
8518    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8519      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8520      if( nArg>=3 ){
8521        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8522      }
8523      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8524      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8525      if( nArg>1 ) break;
8526    }
8527    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8528      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8529      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8530    }
8531  }else
8532
8533#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8534  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8535    rc = shell_dbinfo_command(p, nArg, azArg);
8536  }else
8537
8538  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8539    open_db(p, 0);
8540    rc = recoverDatabaseCmd(p, nArg, azArg);
8541  }else
8542#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8543
8544  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8545    char *zLike = 0;
8546    char *zSql;
8547    int i;
8548    int savedShowHeader = p->showHeader;
8549    int savedShellFlags = p->shellFlgs;
8550    ShellClearFlag(p,
8551       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8552       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8553    for(i=1; i<nArg; i++){
8554      if( azArg[i][0]=='-' ){
8555        const char *z = azArg[i]+1;
8556        if( z[0]=='-' ) z++;
8557        if( strcmp(z,"preserve-rowids")==0 ){
8558#ifdef SQLITE_OMIT_VIRTUALTABLE
8559          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8560                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8561          rc = 1;
8562          sqlite3_free(zLike);
8563          goto meta_command_exit;
8564#else
8565          ShellSetFlag(p, SHFLG_PreserveRowid);
8566#endif
8567        }else
8568        if( strcmp(z,"newlines")==0 ){
8569          ShellSetFlag(p, SHFLG_Newlines);
8570        }else
8571        if( strcmp(z,"data-only")==0 ){
8572          ShellSetFlag(p, SHFLG_DumpDataOnly);
8573        }else
8574        if( strcmp(z,"nosys")==0 ){
8575          ShellSetFlag(p, SHFLG_DumpNoSys);
8576        }else
8577        {
8578          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8579          rc = 1;
8580          sqlite3_free(zLike);
8581          goto meta_command_exit;
8582        }
8583      }else{
8584        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8585        ** only dump data for tables for which either the table name matches
8586        ** the LIKE pattern, or the table appears to be a shadow table of
8587        ** a virtual table for which the name matches the LIKE pattern.
8588        */
8589        char *zExpr = sqlite3_mprintf(
8590            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8591            "  SELECT 1 FROM sqlite_schema WHERE "
8592            "    name LIKE %Q ESCAPE '\\' AND"
8593            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8594            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8595            ")", azArg[i], azArg[i]
8596        );
8597
8598        if( zLike ){
8599          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8600        }else{
8601          zLike = zExpr;
8602        }
8603      }
8604    }
8605
8606    open_db(p, 0);
8607
8608    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8609      /* When playing back a "dump", the content might appear in an order
8610      ** which causes immediate foreign key constraints to be violated.
8611      ** So disable foreign-key constraint enforcement to prevent problems. */
8612      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8613      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8614    }
8615    p->writableSchema = 0;
8616    p->showHeader = 0;
8617    /* Set writable_schema=ON since doing so forces SQLite to initialize
8618    ** as much of the schema as it can even if the sqlite_schema table is
8619    ** corrupt. */
8620    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8621    p->nErr = 0;
8622    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8623    zSql = sqlite3_mprintf(
8624      "SELECT name, type, sql FROM sqlite_schema AS o "
8625      "WHERE (%s) AND type=='table'"
8626      "  AND sql NOT NULL"
8627      " ORDER BY tbl_name='sqlite_sequence', rowid",
8628      zLike
8629    );
8630    run_schema_dump_query(p,zSql);
8631    sqlite3_free(zSql);
8632    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8633      zSql = sqlite3_mprintf(
8634        "SELECT sql FROM sqlite_schema AS o "
8635        "WHERE (%s) AND sql NOT NULL"
8636        "  AND type IN ('index','trigger','view')",
8637        zLike
8638      );
8639      run_table_dump_query(p, zSql);
8640      sqlite3_free(zSql);
8641    }
8642    sqlite3_free(zLike);
8643    if( p->writableSchema ){
8644      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8645      p->writableSchema = 0;
8646    }
8647    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8648    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8649    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8650      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8651    }
8652    p->showHeader = savedShowHeader;
8653    p->shellFlgs = savedShellFlags;
8654  }else
8655
8656  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8657    if( nArg==2 ){
8658      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8659    }else{
8660      raw_printf(stderr, "Usage: .echo on|off\n");
8661      rc = 1;
8662    }
8663  }else
8664
8665  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8666    if( nArg==2 ){
8667      p->autoEQPtest = 0;
8668      if( p->autoEQPtrace ){
8669        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8670        p->autoEQPtrace = 0;
8671      }
8672      if( strcmp(azArg[1],"full")==0 ){
8673        p->autoEQP = AUTOEQP_full;
8674      }else if( strcmp(azArg[1],"trigger")==0 ){
8675        p->autoEQP = AUTOEQP_trigger;
8676#ifdef SQLITE_DEBUG
8677      }else if( strcmp(azArg[1],"test")==0 ){
8678        p->autoEQP = AUTOEQP_on;
8679        p->autoEQPtest = 1;
8680      }else if( strcmp(azArg[1],"trace")==0 ){
8681        p->autoEQP = AUTOEQP_full;
8682        p->autoEQPtrace = 1;
8683        open_db(p, 0);
8684        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8685        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8686#endif
8687      }else{
8688        p->autoEQP = (u8)booleanValue(azArg[1]);
8689      }
8690    }else{
8691      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8692      rc = 1;
8693    }
8694  }else
8695
8696#ifndef SQLITE_SHELL_FIDDLE
8697  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8698    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8699    rc = 2;
8700  }else
8701#endif
8702
8703  /* The ".explain" command is automatic now.  It is largely pointless.  It
8704  ** retained purely for backwards compatibility */
8705  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8706    int val = 1;
8707    if( nArg>=2 ){
8708      if( strcmp(azArg[1],"auto")==0 ){
8709        val = 99;
8710      }else{
8711        val =  booleanValue(azArg[1]);
8712      }
8713    }
8714    if( val==1 && p->mode!=MODE_Explain ){
8715      p->normalMode = p->mode;
8716      p->mode = MODE_Explain;
8717      p->autoExplain = 0;
8718    }else if( val==0 ){
8719      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8720      p->autoExplain = 0;
8721    }else if( val==99 ){
8722      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8723      p->autoExplain = 1;
8724    }
8725  }else
8726
8727#ifndef SQLITE_OMIT_VIRTUALTABLE
8728  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8729    if( p->bSafeMode ){
8730      raw_printf(stderr,
8731        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8732        azArg[0]);
8733      rc = 1;
8734    }else{
8735      open_db(p, 0);
8736      expertDotCommand(p, azArg, nArg);
8737    }
8738  }else
8739#endif
8740
8741  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8742    static const struct {
8743       const char *zCtrlName;   /* Name of a test-control option */
8744       int ctrlCode;            /* Integer code for that option */
8745       const char *zUsage;      /* Usage notes */
8746    } aCtrl[] = {
8747      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8748      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8749      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8750      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8751      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8752   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8753      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8754      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8755      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8756      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8757   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8758    };
8759    int filectrl = -1;
8760    int iCtrl = -1;
8761    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8762    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8763    int n2, i;
8764    const char *zCmd = 0;
8765    const char *zSchema = 0;
8766
8767    open_db(p, 0);
8768    zCmd = nArg>=2 ? azArg[1] : "help";
8769
8770    if( zCmd[0]=='-'
8771     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8772     && nArg>=4
8773    ){
8774      zSchema = azArg[2];
8775      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8776      nArg -= 2;
8777      zCmd = azArg[1];
8778    }
8779
8780    /* The argument can optionally begin with "-" or "--" */
8781    if( zCmd[0]=='-' && zCmd[1] ){
8782      zCmd++;
8783      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8784    }
8785
8786    /* --help lists all file-controls */
8787    if( strcmp(zCmd,"help")==0 ){
8788      utf8_printf(p->out, "Available file-controls:\n");
8789      for(i=0; i<ArraySize(aCtrl); i++){
8790        utf8_printf(p->out, "  .filectrl %s %s\n",
8791                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8792      }
8793      rc = 1;
8794      goto meta_command_exit;
8795    }
8796
8797    /* convert filectrl text option to value. allow any unique prefix
8798    ** of the option name, or a numerical value. */
8799    n2 = strlen30(zCmd);
8800    for(i=0; i<ArraySize(aCtrl); i++){
8801      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8802        if( filectrl<0 ){
8803          filectrl = aCtrl[i].ctrlCode;
8804          iCtrl = i;
8805        }else{
8806          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8807                              "Use \".filectrl --help\" for help\n", zCmd);
8808          rc = 1;
8809          goto meta_command_exit;
8810        }
8811      }
8812    }
8813    if( filectrl<0 ){
8814      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8815                         "Use \".filectrl --help\" for help\n", zCmd);
8816    }else{
8817      switch(filectrl){
8818        case SQLITE_FCNTL_SIZE_LIMIT: {
8819          if( nArg!=2 && nArg!=3 ) break;
8820          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8821          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8822          isOk = 1;
8823          break;
8824        }
8825        case SQLITE_FCNTL_LOCK_TIMEOUT:
8826        case SQLITE_FCNTL_CHUNK_SIZE: {
8827          int x;
8828          if( nArg!=3 ) break;
8829          x = (int)integerValue(azArg[2]);
8830          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8831          isOk = 2;
8832          break;
8833        }
8834        case SQLITE_FCNTL_PERSIST_WAL:
8835        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8836          int x;
8837          if( nArg!=2 && nArg!=3 ) break;
8838          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8839          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8840          iRes = x;
8841          isOk = 1;
8842          break;
8843        }
8844        case SQLITE_FCNTL_DATA_VERSION:
8845        case SQLITE_FCNTL_HAS_MOVED: {
8846          int x;
8847          if( nArg!=2 ) break;
8848          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8849          iRes = x;
8850          isOk = 1;
8851          break;
8852        }
8853        case SQLITE_FCNTL_TEMPFILENAME: {
8854          char *z = 0;
8855          if( nArg!=2 ) break;
8856          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8857          if( z ){
8858            utf8_printf(p->out, "%s\n", z);
8859            sqlite3_free(z);
8860          }
8861          isOk = 2;
8862          break;
8863        }
8864        case SQLITE_FCNTL_RESERVE_BYTES: {
8865          int x;
8866          if( nArg>=3 ){
8867            x = atoi(azArg[2]);
8868            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8869          }
8870          x = -1;
8871          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8872          utf8_printf(p->out,"%d\n", x);
8873          isOk = 2;
8874          break;
8875        }
8876      }
8877    }
8878    if( isOk==0 && iCtrl>=0 ){
8879      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8880      rc = 1;
8881    }else if( isOk==1 ){
8882      char zBuf[100];
8883      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8884      raw_printf(p->out, "%s\n", zBuf);
8885    }
8886  }else
8887
8888  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8889    ShellState data;
8890    int doStats = 0;
8891    memcpy(&data, p, sizeof(data));
8892    data.showHeader = 0;
8893    data.cMode = data.mode = MODE_Semi;
8894    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8895      data.cMode = data.mode = MODE_Pretty;
8896      nArg = 1;
8897    }
8898    if( nArg!=1 ){
8899      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8900      rc = 1;
8901      goto meta_command_exit;
8902    }
8903    open_db(p, 0);
8904    rc = sqlite3_exec(p->db,
8905       "SELECT sql FROM"
8906       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8907       "     FROM sqlite_schema UNION ALL"
8908       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8909       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8910       "ORDER BY x",
8911       callback, &data, 0
8912    );
8913    if( rc==SQLITE_OK ){
8914      sqlite3_stmt *pStmt;
8915      rc = sqlite3_prepare_v2(p->db,
8916               "SELECT rowid FROM sqlite_schema"
8917               " WHERE name GLOB 'sqlite_stat[134]'",
8918               -1, &pStmt, 0);
8919      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8920      sqlite3_finalize(pStmt);
8921    }
8922    if( doStats==0 ){
8923      raw_printf(p->out, "/* No STAT tables available */\n");
8924    }else{
8925      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8926      data.cMode = data.mode = MODE_Insert;
8927      data.zDestTable = "sqlite_stat1";
8928      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8929      data.zDestTable = "sqlite_stat4";
8930      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8931      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8932    }
8933  }else
8934
8935  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8936    if( nArg==2 ){
8937      p->showHeader = booleanValue(azArg[1]);
8938      p->shellFlgs |= SHFLG_HeaderSet;
8939    }else{
8940      raw_printf(stderr, "Usage: .headers on|off\n");
8941      rc = 1;
8942    }
8943  }else
8944
8945  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8946    if( nArg>=2 ){
8947      n = showHelp(p->out, azArg[1]);
8948      if( n==0 ){
8949        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8950      }
8951    }else{
8952      showHelp(p->out, 0);
8953    }
8954  }else
8955
8956#ifndef SQLITE_SHELL_FIDDLE
8957  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8958    char *zTable = 0;           /* Insert data into this table */
8959    char *zSchema = 0;          /* within this schema (may default to "main") */
8960    char *zFile = 0;            /* Name of file to extra content from */
8961    sqlite3_stmt *pStmt = NULL; /* A statement */
8962    int nCol;                   /* Number of columns in the table */
8963    int nByte;                  /* Number of bytes in an SQL string */
8964    int i, j;                   /* Loop counters */
8965    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8966    int nSep;                   /* Number of bytes in p->colSeparator[] */
8967    char *zSql;                 /* An SQL statement */
8968    char *zFullTabName;         /* Table name with schema if applicable */
8969    ImportCtx sCtx;             /* Reader context */
8970    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8971    int eVerbose = 0;           /* Larger for more console output */
8972    int nSkip = 0;              /* Initial lines to skip */
8973    int useOutputMode = 1;      /* Use output mode to determine separators */
8974    char *zCreate = 0;          /* CREATE TABLE statement text */
8975
8976    failIfSafeMode(p, "cannot run .import in safe mode");
8977    memset(&sCtx, 0, sizeof(sCtx));
8978    if( p->mode==MODE_Ascii ){
8979      xRead = ascii_read_one_field;
8980    }else{
8981      xRead = csv_read_one_field;
8982    }
8983    rc = 1;
8984    for(i=1; i<nArg; i++){
8985      char *z = azArg[i];
8986      if( z[0]=='-' && z[1]=='-' ) z++;
8987      if( z[0]!='-' ){
8988        if( zFile==0 ){
8989          zFile = z;
8990        }else if( zTable==0 ){
8991          zTable = z;
8992        }else{
8993          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8994          showHelp(p->out, "import");
8995          goto meta_command_exit;
8996        }
8997      }else if( strcmp(z,"-v")==0 ){
8998        eVerbose++;
8999      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
9000        zSchema = azArg[++i];
9001      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
9002        nSkip = integerValue(azArg[++i]);
9003      }else if( strcmp(z,"-ascii")==0 ){
9004        sCtx.cColSep = SEP_Unit[0];
9005        sCtx.cRowSep = SEP_Record[0];
9006        xRead = ascii_read_one_field;
9007        useOutputMode = 0;
9008      }else if( strcmp(z,"-csv")==0 ){
9009        sCtx.cColSep = ',';
9010        sCtx.cRowSep = '\n';
9011        xRead = csv_read_one_field;
9012        useOutputMode = 0;
9013      }else{
9014        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
9015        showHelp(p->out, "import");
9016        goto meta_command_exit;
9017      }
9018    }
9019    if( zTable==0 ){
9020      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
9021                  zFile==0 ? "FILE" : "TABLE");
9022      showHelp(p->out, "import");
9023      goto meta_command_exit;
9024    }
9025    seenInterrupt = 0;
9026    open_db(p, 0);
9027    if( useOutputMode ){
9028      /* If neither the --csv or --ascii options are specified, then set
9029      ** the column and row separator characters from the output mode. */
9030      nSep = strlen30(p->colSeparator);
9031      if( nSep==0 ){
9032        raw_printf(stderr,
9033                   "Error: non-null column separator required for import\n");
9034        goto meta_command_exit;
9035      }
9036      if( nSep>1 ){
9037        raw_printf(stderr,
9038              "Error: multi-character column separators not allowed"
9039              " for import\n");
9040        goto meta_command_exit;
9041      }
9042      nSep = strlen30(p->rowSeparator);
9043      if( nSep==0 ){
9044        raw_printf(stderr,
9045            "Error: non-null row separator required for import\n");
9046        goto meta_command_exit;
9047      }
9048      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9049        /* When importing CSV (only), if the row separator is set to the
9050        ** default output row separator, change it to the default input
9051        ** row separator.  This avoids having to maintain different input
9052        ** and output row separators. */
9053        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9054        nSep = strlen30(p->rowSeparator);
9055      }
9056      if( nSep>1 ){
9057        raw_printf(stderr, "Error: multi-character row separators not allowed"
9058                           " for import\n");
9059        goto meta_command_exit;
9060      }
9061      sCtx.cColSep = p->colSeparator[0];
9062      sCtx.cRowSep = p->rowSeparator[0];
9063    }
9064    sCtx.zFile = zFile;
9065    sCtx.nLine = 1;
9066    if( sCtx.zFile[0]=='|' ){
9067#ifdef SQLITE_OMIT_POPEN
9068      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9069      goto meta_command_exit;
9070#else
9071      sCtx.in = popen(sCtx.zFile+1, "r");
9072      sCtx.zFile = "<pipe>";
9073      sCtx.xCloser = pclose;
9074#endif
9075    }else{
9076      sCtx.in = fopen(sCtx.zFile, "rb");
9077      sCtx.xCloser = fclose;
9078    }
9079    if( sCtx.in==0 ){
9080      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9081      goto meta_command_exit;
9082    }
9083    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9084      char zSep[2];
9085      zSep[1] = 0;
9086      zSep[0] = sCtx.cColSep;
9087      utf8_printf(p->out, "Column separator ");
9088      output_c_string(p->out, zSep);
9089      utf8_printf(p->out, ", row separator ");
9090      zSep[0] = sCtx.cRowSep;
9091      output_c_string(p->out, zSep);
9092      utf8_printf(p->out, "\n");
9093    }
9094    sCtx.z = sqlite3_malloc64(120);
9095    if( sCtx.z==0 ){
9096      import_cleanup(&sCtx);
9097      shell_out_of_memory();
9098    }
9099    /* Below, resources must be freed before exit. */
9100    while( (nSkip--)>0 ){
9101      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9102    }
9103    if( zSchema!=0 ){
9104      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9105    }else{
9106      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9107    }
9108    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9109    if( zSql==0 || zFullTabName==0 ){
9110      import_cleanup(&sCtx);
9111      shell_out_of_memory();
9112    }
9113    nByte = strlen30(zSql);
9114    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9115    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9116    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9117      sqlite3 *dbCols = 0;
9118      char *zRenames = 0;
9119      char *zColDefs;
9120      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9121      while( xRead(&sCtx) ){
9122        zAutoColumn(sCtx.z, &dbCols, 0);
9123        if( sCtx.cTerm!=sCtx.cColSep ) break;
9124      }
9125      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9126      if( zRenames!=0 ){
9127        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9128                    "Columns renamed during .import %s due to duplicates:\n"
9129                    "%s\n", sCtx.zFile, zRenames);
9130        sqlite3_free(zRenames);
9131      }
9132      assert(dbCols==0);
9133      if( zColDefs==0 ){
9134        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9135      import_fail:
9136        sqlite3_free(zCreate);
9137        sqlite3_free(zSql);
9138        sqlite3_free(zFullTabName);
9139        import_cleanup(&sCtx);
9140        rc = 1;
9141        goto meta_command_exit;
9142      }
9143      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9144      if( eVerbose>=1 ){
9145        utf8_printf(p->out, "%s\n", zCreate);
9146      }
9147      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9148      if( rc ){
9149        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9150        goto import_fail;
9151      }
9152      sqlite3_free(zCreate);
9153      zCreate = 0;
9154      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9155    }
9156    if( rc ){
9157      if (pStmt) sqlite3_finalize(pStmt);
9158      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9159      goto import_fail;
9160    }
9161    sqlite3_free(zSql);
9162    nCol = sqlite3_column_count(pStmt);
9163    sqlite3_finalize(pStmt);
9164    pStmt = 0;
9165    if( nCol==0 ) return 0; /* no columns, no error */
9166    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9167    if( zSql==0 ){
9168      import_cleanup(&sCtx);
9169      shell_out_of_memory();
9170    }
9171    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9172    j = strlen30(zSql);
9173    for(i=1; i<nCol; i++){
9174      zSql[j++] = ',';
9175      zSql[j++] = '?';
9176    }
9177    zSql[j++] = ')';
9178    zSql[j] = 0;
9179    if( eVerbose>=2 ){
9180      utf8_printf(p->out, "Insert using: %s\n", zSql);
9181    }
9182    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9183    if( rc ){
9184      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9185      if (pStmt) sqlite3_finalize(pStmt);
9186      goto import_fail;
9187    }
9188    sqlite3_free(zSql);
9189    sqlite3_free(zFullTabName);
9190    needCommit = sqlite3_get_autocommit(p->db);
9191    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9192    do{
9193      int startLine = sCtx.nLine;
9194      for(i=0; i<nCol; i++){
9195        char *z = xRead(&sCtx);
9196        /*
9197        ** Did we reach end-of-file before finding any columns?
9198        ** If so, stop instead of NULL filling the remaining columns.
9199        */
9200        if( z==0 && i==0 ) break;
9201        /*
9202        ** Did we reach end-of-file OR end-of-line before finding any
9203        ** columns in ASCII mode?  If so, stop instead of NULL filling
9204        ** the remaining columns.
9205        */
9206        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9207        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9208        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9209          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9210                          "filling the rest with NULL\n",
9211                          sCtx.zFile, startLine, nCol, i+1);
9212          i += 2;
9213          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9214        }
9215      }
9216      if( sCtx.cTerm==sCtx.cColSep ){
9217        do{
9218          xRead(&sCtx);
9219          i++;
9220        }while( sCtx.cTerm==sCtx.cColSep );
9221        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9222                        "extras ignored\n",
9223                        sCtx.zFile, startLine, nCol, i);
9224      }
9225      if( i>=nCol ){
9226        sqlite3_step(pStmt);
9227        rc = sqlite3_reset(pStmt);
9228        if( rc!=SQLITE_OK ){
9229          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9230                      startLine, sqlite3_errmsg(p->db));
9231          sCtx.nErr++;
9232        }else{
9233          sCtx.nRow++;
9234        }
9235      }
9236    }while( sCtx.cTerm!=EOF );
9237
9238    import_cleanup(&sCtx);
9239    sqlite3_finalize(pStmt);
9240    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9241    if( eVerbose>0 ){
9242      utf8_printf(p->out,
9243          "Added %d rows with %d errors using %d lines of input\n",
9244          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9245    }
9246  }else
9247#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9248
9249#ifndef SQLITE_UNTESTABLE
9250  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9251    char *zSql;
9252    char *zCollist = 0;
9253    sqlite3_stmt *pStmt;
9254    int tnum = 0;
9255    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9256    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9257    int i;
9258    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9259      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9260                          "       .imposter off\n");
9261      /* Also allowed, but not documented:
9262      **
9263      **    .imposter TABLE IMPOSTER
9264      **
9265      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9266      ** imposter is another WITHOUT ROWID table with the columns in
9267      ** storage order. */
9268      rc = 1;
9269      goto meta_command_exit;
9270    }
9271    open_db(p, 0);
9272    if( nArg==2 ){
9273      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9274      goto meta_command_exit;
9275    }
9276    zSql = sqlite3_mprintf(
9277      "SELECT rootpage, 0 FROM sqlite_schema"
9278      " WHERE name='%q' AND type='index'"
9279      "UNION ALL "
9280      "SELECT rootpage, 1 FROM sqlite_schema"
9281      " WHERE name='%q' AND type='table'"
9282      "   AND sql LIKE '%%without%%rowid%%'",
9283      azArg[1], azArg[1]
9284    );
9285    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9286    sqlite3_free(zSql);
9287    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9288      tnum = sqlite3_column_int(pStmt, 0);
9289      isWO = sqlite3_column_int(pStmt, 1);
9290    }
9291    sqlite3_finalize(pStmt);
9292    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9293    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9294    sqlite3_free(zSql);
9295    i = 0;
9296    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9297      char zLabel[20];
9298      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9299      i++;
9300      if( zCol==0 ){
9301        if( sqlite3_column_int(pStmt,1)==-1 ){
9302          zCol = "_ROWID_";
9303        }else{
9304          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9305          zCol = zLabel;
9306        }
9307      }
9308      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9309        lenPK = (int)strlen(zCollist);
9310      }
9311      if( zCollist==0 ){
9312        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9313      }else{
9314        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9315      }
9316    }
9317    sqlite3_finalize(pStmt);
9318    if( i==0 || tnum==0 ){
9319      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9320      rc = 1;
9321      sqlite3_free(zCollist);
9322      goto meta_command_exit;
9323    }
9324    if( lenPK==0 ) lenPK = 100000;
9325    zSql = sqlite3_mprintf(
9326          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9327          azArg[2], zCollist, lenPK, zCollist);
9328    sqlite3_free(zCollist);
9329    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9330    if( rc==SQLITE_OK ){
9331      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9332      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9333      if( rc ){
9334        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9335      }else{
9336        utf8_printf(stdout, "%s;\n", zSql);
9337        raw_printf(stdout,
9338          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9339          azArg[1], isWO ? "table" : "index"
9340        );
9341      }
9342    }else{
9343      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9344      rc = 1;
9345    }
9346    sqlite3_free(zSql);
9347  }else
9348#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9349
9350#ifdef SQLITE_ENABLE_IOTRACE
9351  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9352    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9353    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9354    iotrace = 0;
9355    if( nArg<2 ){
9356      sqlite3IoTrace = 0;
9357    }else if( strcmp(azArg[1], "-")==0 ){
9358      sqlite3IoTrace = iotracePrintf;
9359      iotrace = stdout;
9360    }else{
9361      iotrace = fopen(azArg[1], "w");
9362      if( iotrace==0 ){
9363        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9364        sqlite3IoTrace = 0;
9365        rc = 1;
9366      }else{
9367        sqlite3IoTrace = iotracePrintf;
9368      }
9369    }
9370  }else
9371#endif
9372
9373  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9374    static const struct {
9375       const char *zLimitName;   /* Name of a limit */
9376       int limitCode;            /* Integer code for that limit */
9377    } aLimit[] = {
9378      { "length",                SQLITE_LIMIT_LENGTH                    },
9379      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9380      { "column",                SQLITE_LIMIT_COLUMN                    },
9381      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9382      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9383      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9384      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9385      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9386      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9387      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9388      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9389      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9390    };
9391    int i, n2;
9392    open_db(p, 0);
9393    if( nArg==1 ){
9394      for(i=0; i<ArraySize(aLimit); i++){
9395        printf("%20s %d\n", aLimit[i].zLimitName,
9396               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9397      }
9398    }else if( nArg>3 ){
9399      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9400      rc = 1;
9401      goto meta_command_exit;
9402    }else{
9403      int iLimit = -1;
9404      n2 = strlen30(azArg[1]);
9405      for(i=0; i<ArraySize(aLimit); i++){
9406        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9407          if( iLimit<0 ){
9408            iLimit = i;
9409          }else{
9410            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9411            rc = 1;
9412            goto meta_command_exit;
9413          }
9414        }
9415      }
9416      if( iLimit<0 ){
9417        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9418                        "enter \".limits\" with no arguments for a list.\n",
9419                         azArg[1]);
9420        rc = 1;
9421        goto meta_command_exit;
9422      }
9423      if( nArg==3 ){
9424        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9425                      (int)integerValue(azArg[2]));
9426      }
9427      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9428             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9429    }
9430  }else
9431
9432  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9433    open_db(p, 0);
9434    lintDotCommand(p, azArg, nArg);
9435  }else
9436
9437#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9438  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9439    const char *zFile, *zProc;
9440    char *zErrMsg = 0;
9441    failIfSafeMode(p, "cannot run .load in safe mode");
9442    if( nArg<2 ){
9443      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9444      rc = 1;
9445      goto meta_command_exit;
9446    }
9447    zFile = azArg[1];
9448    zProc = nArg>=3 ? azArg[2] : 0;
9449    open_db(p, 0);
9450    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9451    if( rc!=SQLITE_OK ){
9452      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9453      sqlite3_free(zErrMsg);
9454      rc = 1;
9455    }
9456  }else
9457#endif
9458
9459#ifndef SQLITE_SHELL_FIDDLE
9460  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9461    failIfSafeMode(p, "cannot run .log in safe mode");
9462    if( nArg!=2 ){
9463      raw_printf(stderr, "Usage: .log FILENAME\n");
9464      rc = 1;
9465    }else{
9466      const char *zFile = azArg[1];
9467      output_file_close(p->pLog);
9468      p->pLog = output_file_open(zFile, 0);
9469    }
9470  }else
9471#endif
9472
9473  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9474    const char *zMode = 0;
9475    const char *zTabname = 0;
9476    int i, n2;
9477    ColModeOpts cmOpts = ColModeOpts_default;
9478    for(i=1; i<nArg; i++){
9479      const char *z = azArg[i];
9480      if( optionMatch(z,"wrap") && i+1<nArg ){
9481        cmOpts.iWrap = integerValue(azArg[++i]);
9482      }else if( optionMatch(z,"ww") ){
9483        cmOpts.bWordWrap = 1;
9484      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9485        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9486      }else if( optionMatch(z,"quote") ){
9487        cmOpts.bQuote = 1;
9488      }else if( optionMatch(z,"noquote") ){
9489        cmOpts.bQuote = 0;
9490      }else if( zMode==0 ){
9491        zMode = z;
9492        /* Apply defaults for qbox pseudo-mods. If that
9493         * overwrites already-set values, user was informed of this.
9494         */
9495        if( strcmp(z, "qbox")==0 ){
9496          ColModeOpts cmo = ColModeOpts_default_qbox;
9497          zMode = "box";
9498          cmOpts = cmo;
9499        }
9500      }else if( zTabname==0 ){
9501        zTabname = z;
9502      }else if( z[0]=='-' ){
9503        utf8_printf(stderr, "unknown option: %s\n", z);
9504        utf8_printf(stderr, "options:\n"
9505                            "  --noquote\n"
9506                            "  --quote\n"
9507                            "  --wordwrap on/off\n"
9508                            "  --wrap N\n"
9509                            "  --ww\n");
9510        rc = 1;
9511        goto meta_command_exit;
9512      }else{
9513        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9514        rc = 1;
9515        goto meta_command_exit;
9516      }
9517    }
9518    if( zMode==0 ){
9519      if( p->mode==MODE_Column
9520       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9521      ){
9522        raw_printf
9523          (p->out,
9524           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9525           modeDescr[p->mode], p->cmOpts.iWrap,
9526           p->cmOpts.bWordWrap ? "on" : "off",
9527           p->cmOpts.bQuote ? "" : "no");
9528      }else{
9529        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9530      }
9531      zMode = modeDescr[p->mode];
9532    }
9533    n2 = strlen30(zMode);
9534    if( strncmp(zMode,"lines",n2)==0 ){
9535      p->mode = MODE_Line;
9536      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9537    }else if( strncmp(zMode,"columns",n2)==0 ){
9538      p->mode = MODE_Column;
9539      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9540        p->showHeader = 1;
9541      }
9542      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9543      p->cmOpts = cmOpts;
9544    }else if( strncmp(zMode,"list",n2)==0 ){
9545      p->mode = MODE_List;
9546      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9547      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9548    }else if( strncmp(zMode,"html",n2)==0 ){
9549      p->mode = MODE_Html;
9550    }else if( strncmp(zMode,"tcl",n2)==0 ){
9551      p->mode = MODE_Tcl;
9552      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9553      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9554    }else if( strncmp(zMode,"csv",n2)==0 ){
9555      p->mode = MODE_Csv;
9556      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9557      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9558    }else if( strncmp(zMode,"tabs",n2)==0 ){
9559      p->mode = MODE_List;
9560      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9561    }else if( strncmp(zMode,"insert",n2)==0 ){
9562      p->mode = MODE_Insert;
9563      set_table_name(p, zTabname ? zTabname : "table");
9564    }else if( strncmp(zMode,"quote",n2)==0 ){
9565      p->mode = MODE_Quote;
9566      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9567      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9568    }else if( strncmp(zMode,"ascii",n2)==0 ){
9569      p->mode = MODE_Ascii;
9570      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9571      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9572    }else if( strncmp(zMode,"markdown",n2)==0 ){
9573      p->mode = MODE_Markdown;
9574      p->cmOpts = cmOpts;
9575    }else if( strncmp(zMode,"table",n2)==0 ){
9576      p->mode = MODE_Table;
9577      p->cmOpts = cmOpts;
9578    }else if( strncmp(zMode,"box",n2)==0 ){
9579      p->mode = MODE_Box;
9580      p->cmOpts = cmOpts;
9581    }else if( strncmp(zMode,"count",n2)==0 ){
9582      p->mode = MODE_Count;
9583    }else if( strncmp(zMode,"off",n2)==0 ){
9584      p->mode = MODE_Off;
9585    }else if( strncmp(zMode,"json",n2)==0 ){
9586      p->mode = MODE_Json;
9587    }else{
9588      raw_printf(stderr, "Error: mode should be one of: "
9589         "ascii box column csv html insert json line list markdown "
9590         "qbox quote table tabs tcl\n");
9591      rc = 1;
9592    }
9593    p->cMode = p->mode;
9594  }else
9595
9596#ifndef SQLITE_SHELL_FIDDLE
9597  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9598    if( nArg!=2 ){
9599      raw_printf(stderr, "Usage: .nonce NONCE\n");
9600      rc = 1;
9601    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9602      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9603                 p->lineno, azArg[1]);
9604      exit(1);
9605    }else{
9606      p->bSafeMode = 0;
9607      return 0;  /* Return immediately to bypass the safe mode reset
9608                 ** at the end of this procedure */
9609    }
9610  }else
9611#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9612
9613  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9614    if( nArg==2 ){
9615      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9616                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9617    }else{
9618      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9619      rc = 1;
9620    }
9621  }else
9622
9623  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9624    const char *zFN = 0;     /* Pointer to constant filename */
9625    char *zNewFilename = 0;  /* Name of the database file to open */
9626    int iName = 1;           /* Index in azArg[] of the filename */
9627    int newFlag = 0;         /* True to delete file before opening */
9628    int openMode = SHELL_OPEN_UNSPEC;
9629
9630    /* Check for command-line arguments */
9631    for(iName=1; iName<nArg; iName++){
9632      const char *z = azArg[iName];
9633#ifndef SQLITE_SHELL_FIDDLE
9634      if( optionMatch(z,"new") ){
9635        newFlag = 1;
9636#ifdef SQLITE_HAVE_ZLIB
9637      }else if( optionMatch(z, "zip") ){
9638        openMode = SHELL_OPEN_ZIPFILE;
9639#endif
9640      }else if( optionMatch(z, "append") ){
9641        openMode = SHELL_OPEN_APPENDVFS;
9642      }else if( optionMatch(z, "readonly") ){
9643        openMode = SHELL_OPEN_READONLY;
9644      }else if( optionMatch(z, "nofollow") ){
9645        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9646#ifndef SQLITE_OMIT_DESERIALIZE
9647      }else if( optionMatch(z, "deserialize") ){
9648        openMode = SHELL_OPEN_DESERIALIZE;
9649      }else if( optionMatch(z, "hexdb") ){
9650        openMode = SHELL_OPEN_HEXDB;
9651      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9652        p->szMax = integerValue(azArg[++iName]);
9653#endif /* SQLITE_OMIT_DESERIALIZE */
9654      }else
9655#endif /* !SQLITE_SHELL_FIDDLE */
9656      if( z[0]=='-' ){
9657        utf8_printf(stderr, "unknown option: %s\n", z);
9658        rc = 1;
9659        goto meta_command_exit;
9660      }else if( zFN ){
9661        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9662        rc = 1;
9663        goto meta_command_exit;
9664      }else{
9665        zFN = z;
9666      }
9667    }
9668
9669    /* Close the existing database */
9670    session_close_all(p, -1);
9671    close_db(p->db);
9672    p->db = 0;
9673    p->pAuxDb->zDbFilename = 0;
9674    sqlite3_free(p->pAuxDb->zFreeOnClose);
9675    p->pAuxDb->zFreeOnClose = 0;
9676    p->openMode = openMode;
9677    p->openFlags = 0;
9678    p->szMax = 0;
9679
9680    /* If a filename is specified, try to open it first */
9681    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9682      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9683#ifndef SQLITE_SHELL_FIDDLE
9684      if( p->bSafeMode
9685       && p->openMode!=SHELL_OPEN_HEXDB
9686       && zFN
9687       && strcmp(zFN,":memory:")!=0
9688      ){
9689        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9690      }
9691#else
9692      /* WASM mode has its own sandboxed pseudo-filesystem. */
9693#endif
9694      if( zFN ){
9695        zNewFilename = sqlite3_mprintf("%s", zFN);
9696        shell_check_oom(zNewFilename);
9697      }else{
9698        zNewFilename = 0;
9699      }
9700      p->pAuxDb->zDbFilename = zNewFilename;
9701      open_db(p, OPEN_DB_KEEPALIVE);
9702      if( p->db==0 ){
9703        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9704        sqlite3_free(zNewFilename);
9705      }else{
9706        p->pAuxDb->zFreeOnClose = zNewFilename;
9707      }
9708    }
9709    if( p->db==0 ){
9710      /* As a fall-back open a TEMP database */
9711      p->pAuxDb->zDbFilename = 0;
9712      open_db(p, 0);
9713    }
9714  }else
9715
9716#ifndef SQLITE_SHELL_FIDDLE
9717  if( (c=='o'
9718        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9719   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9720  ){
9721    char *zFile = 0;
9722    int bTxtMode = 0;
9723    int i;
9724    int eMode = 0;
9725    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9726    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9727
9728    zBOM[0] = 0;
9729    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9730    if( c=='e' ){
9731      eMode = 'x';
9732      bOnce = 2;
9733    }else if( strncmp(azArg[0],"once",n)==0 ){
9734      bOnce = 1;
9735    }
9736    for(i=1; i<nArg; i++){
9737      char *z = azArg[i];
9738      if( z[0]=='-' ){
9739        if( z[1]=='-' ) z++;
9740        if( strcmp(z,"-bom")==0 ){
9741          zBOM[0] = 0xef;
9742          zBOM[1] = 0xbb;
9743          zBOM[2] = 0xbf;
9744          zBOM[3] = 0;
9745        }else if( c!='e' && strcmp(z,"-x")==0 ){
9746          eMode = 'x';  /* spreadsheet */
9747        }else if( c!='e' && strcmp(z,"-e")==0 ){
9748          eMode = 'e';  /* text editor */
9749        }else{
9750          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9751                      azArg[i]);
9752          showHelp(p->out, azArg[0]);
9753          rc = 1;
9754          goto meta_command_exit;
9755        }
9756      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9757        zFile = sqlite3_mprintf("%s", z);
9758        if( zFile && zFile[0]=='|' ){
9759          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9760          break;
9761        }
9762      }else{
9763        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9764                    azArg[i]);
9765        showHelp(p->out, azArg[0]);
9766        rc = 1;
9767        sqlite3_free(zFile);
9768        goto meta_command_exit;
9769      }
9770    }
9771    if( zFile==0 ){
9772      zFile = sqlite3_mprintf("stdout");
9773    }
9774    if( bOnce ){
9775      p->outCount = 2;
9776    }else{
9777      p->outCount = 0;
9778    }
9779    output_reset(p);
9780#ifndef SQLITE_NOHAVE_SYSTEM
9781    if( eMode=='e' || eMode=='x' ){
9782      p->doXdgOpen = 1;
9783      outputModePush(p);
9784      if( eMode=='x' ){
9785        /* spreadsheet mode.  Output as CSV. */
9786        newTempFile(p, "csv");
9787        ShellClearFlag(p, SHFLG_Echo);
9788        p->mode = MODE_Csv;
9789        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9790        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9791      }else{
9792        /* text editor mode */
9793        newTempFile(p, "txt");
9794        bTxtMode = 1;
9795      }
9796      sqlite3_free(zFile);
9797      zFile = sqlite3_mprintf("%s", p->zTempFile);
9798    }
9799#endif /* SQLITE_NOHAVE_SYSTEM */
9800    shell_check_oom(zFile);
9801    if( zFile[0]=='|' ){
9802#ifdef SQLITE_OMIT_POPEN
9803      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9804      rc = 1;
9805      p->out = stdout;
9806#else
9807      p->out = popen(zFile + 1, "w");
9808      if( p->out==0 ){
9809        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9810        p->out = stdout;
9811        rc = 1;
9812      }else{
9813        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9814        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9815      }
9816#endif
9817    }else{
9818      p->out = output_file_open(zFile, bTxtMode);
9819      if( p->out==0 ){
9820        if( strcmp(zFile,"off")!=0 ){
9821          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9822        }
9823        p->out = stdout;
9824        rc = 1;
9825      } else {
9826        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9827        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9828      }
9829    }
9830    sqlite3_free(zFile);
9831  }else
9832#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9833
9834  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9835    open_db(p,0);
9836    if( nArg<=1 ) goto parameter_syntax_error;
9837
9838    /* .parameter clear
9839    ** Clear all bind parameters by dropping the TEMP table that holds them.
9840    */
9841    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9842      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9843                   0, 0, 0);
9844    }else
9845
9846    /* .parameter list
9847    ** List all bind parameters.
9848    */
9849    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9850      sqlite3_stmt *pStmt = 0;
9851      int rx;
9852      int len = 0;
9853      rx = sqlite3_prepare_v2(p->db,
9854             "SELECT max(length(key)) "
9855             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9856      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9857        len = sqlite3_column_int(pStmt, 0);
9858        if( len>40 ) len = 40;
9859      }
9860      sqlite3_finalize(pStmt);
9861      pStmt = 0;
9862      if( len ){
9863        rx = sqlite3_prepare_v2(p->db,
9864             "SELECT key, quote(value) "
9865             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9866        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9867          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9868                      sqlite3_column_text(pStmt,1));
9869        }
9870        sqlite3_finalize(pStmt);
9871      }
9872    }else
9873
9874    /* .parameter init
9875    ** Make sure the TEMP table used to hold bind parameters exists.
9876    ** Create it if necessary.
9877    */
9878    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9879      bind_table_init(p);
9880    }else
9881
9882    /* .parameter set NAME VALUE
9883    ** Set or reset a bind parameter.  NAME should be the full parameter
9884    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9885    ** VALUE can be in either SQL literal notation, or if not it will be
9886    ** understood to be a text string.
9887    */
9888    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9889      int rx;
9890      char *zSql;
9891      sqlite3_stmt *pStmt;
9892      const char *zKey = azArg[2];
9893      const char *zValue = azArg[3];
9894      bind_table_init(p);
9895      zSql = sqlite3_mprintf(
9896                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9897                  "VALUES(%Q,%s);", zKey, zValue);
9898      shell_check_oom(zSql);
9899      pStmt = 0;
9900      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9901      sqlite3_free(zSql);
9902      if( rx!=SQLITE_OK ){
9903        sqlite3_finalize(pStmt);
9904        pStmt = 0;
9905        zSql = sqlite3_mprintf(
9906                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9907                   "VALUES(%Q,%Q);", zKey, zValue);
9908        shell_check_oom(zSql);
9909        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9910        sqlite3_free(zSql);
9911        if( rx!=SQLITE_OK ){
9912          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9913          sqlite3_finalize(pStmt);
9914          pStmt = 0;
9915          rc = 1;
9916        }
9917      }
9918      sqlite3_step(pStmt);
9919      sqlite3_finalize(pStmt);
9920    }else
9921
9922    /* .parameter unset NAME
9923    ** Remove the NAME binding from the parameter binding table, if it
9924    ** exists.
9925    */
9926    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9927      char *zSql = sqlite3_mprintf(
9928          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9929      shell_check_oom(zSql);
9930      sqlite3_exec(p->db, zSql, 0, 0, 0);
9931      sqlite3_free(zSql);
9932    }else
9933    /* If no command name matches, show a syntax error */
9934    parameter_syntax_error:
9935    showHelp(p->out, "parameter");
9936  }else
9937
9938  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9939    int i;
9940    for(i=1; i<nArg; i++){
9941      if( i>1 ) raw_printf(p->out, " ");
9942      utf8_printf(p->out, "%s", azArg[i]);
9943    }
9944    raw_printf(p->out, "\n");
9945  }else
9946
9947#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9948  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9949    int i;
9950    int nn = 0;
9951    p->flgProgress = 0;
9952    p->mxProgress = 0;
9953    p->nProgress = 0;
9954    for(i=1; i<nArg; i++){
9955      const char *z = azArg[i];
9956      if( z[0]=='-' ){
9957        z++;
9958        if( z[0]=='-' ) z++;
9959        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9960          p->flgProgress |= SHELL_PROGRESS_QUIET;
9961          continue;
9962        }
9963        if( strcmp(z,"reset")==0 ){
9964          p->flgProgress |= SHELL_PROGRESS_RESET;
9965          continue;
9966        }
9967        if( strcmp(z,"once")==0 ){
9968          p->flgProgress |= SHELL_PROGRESS_ONCE;
9969          continue;
9970        }
9971        if( strcmp(z,"limit")==0 ){
9972          if( i+1>=nArg ){
9973            utf8_printf(stderr, "Error: missing argument on --limit\n");
9974            rc = 1;
9975            goto meta_command_exit;
9976          }else{
9977            p->mxProgress = (int)integerValue(azArg[++i]);
9978          }
9979          continue;
9980        }
9981        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9982        rc = 1;
9983        goto meta_command_exit;
9984      }else{
9985        nn = (int)integerValue(z);
9986      }
9987    }
9988    open_db(p, 0);
9989    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9990  }else
9991#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9992
9993  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9994    if( nArg >= 2) {
9995      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9996    }
9997    if( nArg >= 3) {
9998      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9999    }
10000  }else
10001
10002#ifndef SQLITE_SHELL_FIDDLE
10003  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
10004    rc = 2;
10005  }else
10006#endif
10007
10008#ifndef SQLITE_SHELL_FIDDLE
10009  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
10010    FILE *inSaved = p->in;
10011    int savedLineno = p->lineno;
10012    failIfSafeMode(p, "cannot run .read in safe mode");
10013    if( nArg!=2 ){
10014      raw_printf(stderr, "Usage: .read FILE\n");
10015      rc = 1;
10016      goto meta_command_exit;
10017    }
10018    if( azArg[1][0]=='|' ){
10019#ifdef SQLITE_OMIT_POPEN
10020      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
10021      rc = 1;
10022      p->out = stdout;
10023#else
10024      p->in = popen(azArg[1]+1, "r");
10025      if( p->in==0 ){
10026        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
10027        rc = 1;
10028      }else{
10029        rc = process_input(p);
10030        pclose(p->in);
10031      }
10032#endif
10033    }else if( (p->in = openChrSource(azArg[1]))==0 ){
10034      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
10035      rc = 1;
10036    }else{
10037      rc = process_input(p);
10038      fclose(p->in);
10039    }
10040    p->in = inSaved;
10041    p->lineno = savedLineno;
10042  }else
10043#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10044
10045#ifndef SQLITE_SHELL_FIDDLE
10046  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10047    const char *zSrcFile;
10048    const char *zDb;
10049    sqlite3 *pSrc;
10050    sqlite3_backup *pBackup;
10051    int nTimeout = 0;
10052
10053    failIfSafeMode(p, "cannot run .restore in safe mode");
10054    if( nArg==2 ){
10055      zSrcFile = azArg[1];
10056      zDb = "main";
10057    }else if( nArg==3 ){
10058      zSrcFile = azArg[2];
10059      zDb = azArg[1];
10060    }else{
10061      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10062      rc = 1;
10063      goto meta_command_exit;
10064    }
10065    rc = sqlite3_open(zSrcFile, &pSrc);
10066    if( rc!=SQLITE_OK ){
10067      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10068      close_db(pSrc);
10069      return 1;
10070    }
10071    open_db(p, 0);
10072    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10073    if( pBackup==0 ){
10074      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10075      close_db(pSrc);
10076      return 1;
10077    }
10078    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10079          || rc==SQLITE_BUSY  ){
10080      if( rc==SQLITE_BUSY ){
10081        if( nTimeout++ >= 3 ) break;
10082        sqlite3_sleep(100);
10083      }
10084    }
10085    sqlite3_backup_finish(pBackup);
10086    if( rc==SQLITE_DONE ){
10087      rc = 0;
10088    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10089      raw_printf(stderr, "Error: source database is busy\n");
10090      rc = 1;
10091    }else{
10092      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10093      rc = 1;
10094    }
10095    close_db(pSrc);
10096  }else
10097#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10098
10099  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10100    if( nArg==2 ){
10101      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10102#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10103      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10104#endif
10105    }else{
10106      raw_printf(stderr, "Usage: .scanstats on|off\n");
10107      rc = 1;
10108    }
10109  }else
10110
10111  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10112    ShellText sSelect;
10113    ShellState data;
10114    char *zErrMsg = 0;
10115    const char *zDiv = "(";
10116    const char *zName = 0;
10117    int iSchema = 0;
10118    int bDebug = 0;
10119    int bNoSystemTabs = 0;
10120    int ii;
10121
10122    open_db(p, 0);
10123    memcpy(&data, p, sizeof(data));
10124    data.showHeader = 0;
10125    data.cMode = data.mode = MODE_Semi;
10126    initText(&sSelect);
10127    for(ii=1; ii<nArg; ii++){
10128      if( optionMatch(azArg[ii],"indent") ){
10129        data.cMode = data.mode = MODE_Pretty;
10130      }else if( optionMatch(azArg[ii],"debug") ){
10131        bDebug = 1;
10132      }else if( optionMatch(azArg[ii],"nosys") ){
10133        bNoSystemTabs = 1;
10134      }else if( azArg[ii][0]=='-' ){
10135        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10136        rc = 1;
10137        goto meta_command_exit;
10138      }else if( zName==0 ){
10139        zName = azArg[ii];
10140      }else{
10141        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10142        rc = 1;
10143        goto meta_command_exit;
10144      }
10145    }
10146    if( zName!=0 ){
10147      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10148                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10149                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10150                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10151      if( isSchema ){
10152        char *new_argv[2], *new_colv[2];
10153        new_argv[0] = sqlite3_mprintf(
10154                      "CREATE TABLE %s (\n"
10155                      "  type text,\n"
10156                      "  name text,\n"
10157                      "  tbl_name text,\n"
10158                      "  rootpage integer,\n"
10159                      "  sql text\n"
10160                      ")", zName);
10161        shell_check_oom(new_argv[0]);
10162        new_argv[1] = 0;
10163        new_colv[0] = "sql";
10164        new_colv[1] = 0;
10165        callback(&data, 1, new_argv, new_colv);
10166        sqlite3_free(new_argv[0]);
10167      }
10168    }
10169    if( zDiv ){
10170      sqlite3_stmt *pStmt = 0;
10171      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10172                              -1, &pStmt, 0);
10173      if( rc ){
10174        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10175        sqlite3_finalize(pStmt);
10176        rc = 1;
10177        goto meta_command_exit;
10178      }
10179      appendText(&sSelect, "SELECT sql FROM", 0);
10180      iSchema = 0;
10181      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10182        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10183        char zScNum[30];
10184        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10185        appendText(&sSelect, zDiv, 0);
10186        zDiv = " UNION ALL ";
10187        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10188        if( sqlite3_stricmp(zDb, "main")!=0 ){
10189          appendText(&sSelect, zDb, '\'');
10190        }else{
10191          appendText(&sSelect, "NULL", 0);
10192        }
10193        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10194        appendText(&sSelect, zScNum, 0);
10195        appendText(&sSelect, " AS snum, ", 0);
10196        appendText(&sSelect, zDb, '\'');
10197        appendText(&sSelect, " AS sname FROM ", 0);
10198        appendText(&sSelect, zDb, quoteChar(zDb));
10199        appendText(&sSelect, ".sqlite_schema", 0);
10200      }
10201      sqlite3_finalize(pStmt);
10202#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10203      if( zName ){
10204        appendText(&sSelect,
10205           " UNION ALL SELECT shell_module_schema(name),"
10206           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10207        0);
10208      }
10209#endif
10210      appendText(&sSelect, ") WHERE ", 0);
10211      if( zName ){
10212        char *zQarg = sqlite3_mprintf("%Q", zName);
10213        int bGlob;
10214        shell_check_oom(zQarg);
10215        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10216                strchr(zName, '[') != 0;
10217        if( strchr(zName, '.') ){
10218          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10219        }else{
10220          appendText(&sSelect, "lower(tbl_name)", 0);
10221        }
10222        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10223        appendText(&sSelect, zQarg, 0);
10224        if( !bGlob ){
10225          appendText(&sSelect, " ESCAPE '\\' ", 0);
10226        }
10227        appendText(&sSelect, " AND ", 0);
10228        sqlite3_free(zQarg);
10229      }
10230      if( bNoSystemTabs ){
10231        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10232      }
10233      appendText(&sSelect, "sql IS NOT NULL"
10234                           " ORDER BY snum, rowid", 0);
10235      if( bDebug ){
10236        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10237      }else{
10238        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10239      }
10240      freeText(&sSelect);
10241    }
10242    if( zErrMsg ){
10243      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10244      sqlite3_free(zErrMsg);
10245      rc = 1;
10246    }else if( rc != SQLITE_OK ){
10247      raw_printf(stderr,"Error: querying schema information\n");
10248      rc = 1;
10249    }else{
10250      rc = 0;
10251    }
10252  }else
10253
10254  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10255   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10256  ){
10257    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10258    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10259  }else
10260
10261#if defined(SQLITE_ENABLE_SESSION)
10262  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10263    struct AuxDb *pAuxDb = p->pAuxDb;
10264    OpenSession *pSession = &pAuxDb->aSession[0];
10265    char **azCmd = &azArg[1];
10266    int iSes = 0;
10267    int nCmd = nArg - 1;
10268    int i;
10269    if( nArg<=1 ) goto session_syntax_error;
10270    open_db(p, 0);
10271    if( nArg>=3 ){
10272      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10273        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10274      }
10275      if( iSes<pAuxDb->nSession ){
10276        pSession = &pAuxDb->aSession[iSes];
10277        azCmd++;
10278        nCmd--;
10279      }else{
10280        pSession = &pAuxDb->aSession[0];
10281        iSes = 0;
10282      }
10283    }
10284
10285    /* .session attach TABLE
10286    ** Invoke the sqlite3session_attach() interface to attach a particular
10287    ** table so that it is never filtered.
10288    */
10289    if( strcmp(azCmd[0],"attach")==0 ){
10290      if( nCmd!=2 ) goto session_syntax_error;
10291      if( pSession->p==0 ){
10292        session_not_open:
10293        raw_printf(stderr, "ERROR: No sessions are open\n");
10294      }else{
10295        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10296        if( rc ){
10297          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10298          rc = 0;
10299        }
10300      }
10301    }else
10302
10303    /* .session changeset FILE
10304    ** .session patchset FILE
10305    ** Write a changeset or patchset into a file.  The file is overwritten.
10306    */
10307    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10308      FILE *out = 0;
10309      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10310      if( nCmd!=2 ) goto session_syntax_error;
10311      if( pSession->p==0 ) goto session_not_open;
10312      out = fopen(azCmd[1], "wb");
10313      if( out==0 ){
10314        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10315                    azCmd[1]);
10316      }else{
10317        int szChng;
10318        void *pChng;
10319        if( azCmd[0][0]=='c' ){
10320          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10321        }else{
10322          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10323        }
10324        if( rc ){
10325          printf("Error: error code %d\n", rc);
10326          rc = 0;
10327        }
10328        if( pChng
10329          && fwrite(pChng, szChng, 1, out)!=1 ){
10330          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10331                  szChng);
10332        }
10333        sqlite3_free(pChng);
10334        fclose(out);
10335      }
10336    }else
10337
10338    /* .session close
10339    ** Close the identified session
10340    */
10341    if( strcmp(azCmd[0], "close")==0 ){
10342      if( nCmd!=1 ) goto session_syntax_error;
10343      if( pAuxDb->nSession ){
10344        session_close(pSession);
10345        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10346      }
10347    }else
10348
10349    /* .session enable ?BOOLEAN?
10350    ** Query or set the enable flag
10351    */
10352    if( strcmp(azCmd[0], "enable")==0 ){
10353      int ii;
10354      if( nCmd>2 ) goto session_syntax_error;
10355      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10356      if( pAuxDb->nSession ){
10357        ii = sqlite3session_enable(pSession->p, ii);
10358        utf8_printf(p->out, "session %s enable flag = %d\n",
10359                    pSession->zName, ii);
10360      }
10361    }else
10362
10363    /* .session filter GLOB ....
10364    ** Set a list of GLOB patterns of table names to be excluded.
10365    */
10366    if( strcmp(azCmd[0], "filter")==0 ){
10367      int ii, nByte;
10368      if( nCmd<2 ) goto session_syntax_error;
10369      if( pAuxDb->nSession ){
10370        for(ii=0; ii<pSession->nFilter; ii++){
10371          sqlite3_free(pSession->azFilter[ii]);
10372        }
10373        sqlite3_free(pSession->azFilter);
10374        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10375        pSession->azFilter = sqlite3_malloc( nByte );
10376        if( pSession->azFilter==0 ){
10377          raw_printf(stderr, "Error: out or memory\n");
10378          exit(1);
10379        }
10380        for(ii=1; ii<nCmd; ii++){
10381          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10382          shell_check_oom(x);
10383        }
10384        pSession->nFilter = ii-1;
10385      }
10386    }else
10387
10388    /* .session indirect ?BOOLEAN?
10389    ** Query or set the indirect flag
10390    */
10391    if( strcmp(azCmd[0], "indirect")==0 ){
10392      int ii;
10393      if( nCmd>2 ) goto session_syntax_error;
10394      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10395      if( pAuxDb->nSession ){
10396        ii = sqlite3session_indirect(pSession->p, ii);
10397        utf8_printf(p->out, "session %s indirect flag = %d\n",
10398                    pSession->zName, ii);
10399      }
10400    }else
10401
10402    /* .session isempty
10403    ** Determine if the session is empty
10404    */
10405    if( strcmp(azCmd[0], "isempty")==0 ){
10406      int ii;
10407      if( nCmd!=1 ) goto session_syntax_error;
10408      if( pAuxDb->nSession ){
10409        ii = sqlite3session_isempty(pSession->p);
10410        utf8_printf(p->out, "session %s isempty flag = %d\n",
10411                    pSession->zName, ii);
10412      }
10413    }else
10414
10415    /* .session list
10416    ** List all currently open sessions
10417    */
10418    if( strcmp(azCmd[0],"list")==0 ){
10419      for(i=0; i<pAuxDb->nSession; i++){
10420        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10421      }
10422    }else
10423
10424    /* .session open DB NAME
10425    ** Open a new session called NAME on the attached database DB.
10426    ** DB is normally "main".
10427    */
10428    if( strcmp(azCmd[0],"open")==0 ){
10429      char *zName;
10430      if( nCmd!=3 ) goto session_syntax_error;
10431      zName = azCmd[2];
10432      if( zName[0]==0 ) goto session_syntax_error;
10433      for(i=0; i<pAuxDb->nSession; i++){
10434        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10435          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10436          goto meta_command_exit;
10437        }
10438      }
10439      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10440        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10441        goto meta_command_exit;
10442      }
10443      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10444      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10445      if( rc ){
10446        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10447        rc = 0;
10448        goto meta_command_exit;
10449      }
10450      pSession->nFilter = 0;
10451      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10452      pAuxDb->nSession++;
10453      pSession->zName = sqlite3_mprintf("%s", zName);
10454      shell_check_oom(pSession->zName);
10455    }else
10456    /* If no command name matches, show a syntax error */
10457    session_syntax_error:
10458    showHelp(p->out, "session");
10459  }else
10460#endif
10461
10462#ifdef SQLITE_DEBUG
10463  /* Undocumented commands for internal testing.  Subject to change
10464  ** without notice. */
10465  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10466    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10467      int i, v;
10468      for(i=1; i<nArg; i++){
10469        v = booleanValue(azArg[i]);
10470        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10471      }
10472    }
10473    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10474      int i; sqlite3_int64 v;
10475      for(i=1; i<nArg; i++){
10476        char zBuf[200];
10477        v = integerValue(azArg[i]);
10478        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10479        utf8_printf(p->out, "%s", zBuf);
10480      }
10481    }
10482  }else
10483#endif
10484
10485  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10486    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10487    int bVerbose = 0;        /* Verbose output */
10488    int bSelftestExists;     /* True if SELFTEST already exists */
10489    int i, k;                /* Loop counters */
10490    int nTest = 0;           /* Number of tests runs */
10491    int nErr = 0;            /* Number of errors seen */
10492    ShellText str;           /* Answer for a query */
10493    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10494
10495    open_db(p,0);
10496    for(i=1; i<nArg; i++){
10497      const char *z = azArg[i];
10498      if( z[0]=='-' && z[1]=='-' ) z++;
10499      if( strcmp(z,"-init")==0 ){
10500        bIsInit = 1;
10501      }else
10502      if( strcmp(z,"-v")==0 ){
10503        bVerbose++;
10504      }else
10505      {
10506        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10507                    azArg[i], azArg[0]);
10508        raw_printf(stderr, "Should be one of: --init -v\n");
10509        rc = 1;
10510        goto meta_command_exit;
10511      }
10512    }
10513    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10514           != SQLITE_OK ){
10515      bSelftestExists = 0;
10516    }else{
10517      bSelftestExists = 1;
10518    }
10519    if( bIsInit ){
10520      createSelftestTable(p);
10521      bSelftestExists = 1;
10522    }
10523    initText(&str);
10524    appendText(&str, "x", 0);
10525    for(k=bSelftestExists; k>=0; k--){
10526      if( k==1 ){
10527        rc = sqlite3_prepare_v2(p->db,
10528            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10529            -1, &pStmt, 0);
10530      }else{
10531        rc = sqlite3_prepare_v2(p->db,
10532          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10533          "      (1,'run','PRAGMA integrity_check','ok')",
10534          -1, &pStmt, 0);
10535      }
10536      if( rc ){
10537        raw_printf(stderr, "Error querying the selftest table\n");
10538        rc = 1;
10539        sqlite3_finalize(pStmt);
10540        goto meta_command_exit;
10541      }
10542      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10543        int tno = sqlite3_column_int(pStmt, 0);
10544        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10545        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10546        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10547
10548        if( zOp==0 ) continue;
10549        if( zSql==0 ) continue;
10550        if( zAns==0 ) continue;
10551        k = 0;
10552        if( bVerbose>0 ){
10553          printf("%d: %s %s\n", tno, zOp, zSql);
10554        }
10555        if( strcmp(zOp,"memo")==0 ){
10556          utf8_printf(p->out, "%s\n", zSql);
10557        }else
10558        if( strcmp(zOp,"run")==0 ){
10559          char *zErrMsg = 0;
10560          str.n = 0;
10561          str.z[0] = 0;
10562          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10563          nTest++;
10564          if( bVerbose ){
10565            utf8_printf(p->out, "Result: %s\n", str.z);
10566          }
10567          if( rc || zErrMsg ){
10568            nErr++;
10569            rc = 1;
10570            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10571            sqlite3_free(zErrMsg);
10572          }else if( strcmp(zAns,str.z)!=0 ){
10573            nErr++;
10574            rc = 1;
10575            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10576            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10577          }
10578        }else
10579        {
10580          utf8_printf(stderr,
10581            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10582          rc = 1;
10583          break;
10584        }
10585      } /* End loop over rows of content from SELFTEST */
10586      sqlite3_finalize(pStmt);
10587    } /* End loop over k */
10588    freeText(&str);
10589    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10590  }else
10591
10592  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10593    if( nArg<2 || nArg>3 ){
10594      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10595      rc = 1;
10596    }
10597    if( nArg>=2 ){
10598      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10599                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10600    }
10601    if( nArg>=3 ){
10602      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10603                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10604    }
10605  }else
10606
10607  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10608    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10609    int i;                   /* Loop counter */
10610    int bSchema = 0;         /* Also hash the schema */
10611    int bSeparate = 0;       /* Hash each table separately */
10612    int iSize = 224;         /* Hash algorithm to use */
10613    int bDebug = 0;          /* Only show the query that would have run */
10614    sqlite3_stmt *pStmt;     /* For querying tables names */
10615    char *zSql;              /* SQL to be run */
10616    char *zSep;              /* Separator */
10617    ShellText sSql;          /* Complete SQL for the query to run the hash */
10618    ShellText sQuery;        /* Set of queries used to read all content */
10619    open_db(p, 0);
10620    for(i=1; i<nArg; i++){
10621      const char *z = azArg[i];
10622      if( z[0]=='-' ){
10623        z++;
10624        if( z[0]=='-' ) z++;
10625        if( strcmp(z,"schema")==0 ){
10626          bSchema = 1;
10627        }else
10628        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10629         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10630        ){
10631          iSize = atoi(&z[5]);
10632        }else
10633        if( strcmp(z,"debug")==0 ){
10634          bDebug = 1;
10635        }else
10636        {
10637          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10638                      azArg[i], azArg[0]);
10639          showHelp(p->out, azArg[0]);
10640          rc = 1;
10641          goto meta_command_exit;
10642        }
10643      }else if( zLike ){
10644        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10645        rc = 1;
10646        goto meta_command_exit;
10647      }else{
10648        zLike = z;
10649        bSeparate = 1;
10650        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10651      }
10652    }
10653    if( bSchema ){
10654      zSql = "SELECT lower(name) FROM sqlite_schema"
10655             " WHERE type='table' AND coalesce(rootpage,0)>1"
10656             " UNION ALL SELECT 'sqlite_schema'"
10657             " ORDER BY 1 collate nocase";
10658    }else{
10659      zSql = "SELECT lower(name) FROM sqlite_schema"
10660             " WHERE type='table' AND coalesce(rootpage,0)>1"
10661             " AND name NOT LIKE 'sqlite_%'"
10662             " ORDER BY 1 collate nocase";
10663    }
10664    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10665    initText(&sQuery);
10666    initText(&sSql);
10667    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10668    zSep = "VALUES(";
10669    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10670      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10671      if( zTab==0 ) continue;
10672      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10673      if( strncmp(zTab, "sqlite_",7)!=0 ){
10674        appendText(&sQuery,"SELECT * FROM ", 0);
10675        appendText(&sQuery,zTab,'"');
10676        appendText(&sQuery," NOT INDEXED;", 0);
10677      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10678        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10679                           " ORDER BY name;", 0);
10680      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10681        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10682                           " ORDER BY name;", 0);
10683      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10684        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10685                           " ORDER BY tbl,idx;", 0);
10686      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10687        appendText(&sQuery, "SELECT * FROM ", 0);
10688        appendText(&sQuery, zTab, 0);
10689        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10690      }
10691      appendText(&sSql, zSep, 0);
10692      appendText(&sSql, sQuery.z, '\'');
10693      sQuery.n = 0;
10694      appendText(&sSql, ",", 0);
10695      appendText(&sSql, zTab, '\'');
10696      zSep = "),(";
10697    }
10698    sqlite3_finalize(pStmt);
10699    if( bSeparate ){
10700      zSql = sqlite3_mprintf(
10701          "%s))"
10702          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10703          "   FROM [sha3sum$query]",
10704          sSql.z, iSize);
10705    }else{
10706      zSql = sqlite3_mprintf(
10707          "%s))"
10708          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10709          "   FROM [sha3sum$query]",
10710          sSql.z, iSize);
10711    }
10712    shell_check_oom(zSql);
10713    freeText(&sQuery);
10714    freeText(&sSql);
10715    if( bDebug ){
10716      utf8_printf(p->out, "%s\n", zSql);
10717    }else{
10718      shell_exec(p, zSql, 0);
10719    }
10720    sqlite3_free(zSql);
10721  }else
10722
10723#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10724  if( c=='s'
10725   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10726  ){
10727    char *zCmd;
10728    int i, x;
10729    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10730    if( nArg<2 ){
10731      raw_printf(stderr, "Usage: .system COMMAND\n");
10732      rc = 1;
10733      goto meta_command_exit;
10734    }
10735    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10736    for(i=2; i<nArg && zCmd!=0; i++){
10737      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10738                             zCmd, azArg[i]);
10739    }
10740    x = zCmd!=0 ? system(zCmd) : 1;
10741    sqlite3_free(zCmd);
10742    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10743  }else
10744#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10745
10746  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10747    static const char *azBool[] = { "off", "on", "trigger", "full"};
10748    const char *zOut;
10749    int i;
10750    if( nArg!=1 ){
10751      raw_printf(stderr, "Usage: .show\n");
10752      rc = 1;
10753      goto meta_command_exit;
10754    }
10755    utf8_printf(p->out, "%12.12s: %s\n","echo",
10756                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10757    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10758    utf8_printf(p->out, "%12.12s: %s\n","explain",
10759         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10760    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10761    if( p->mode==MODE_Column
10762     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10763    ){
10764      utf8_printf
10765        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10766         modeDescr[p->mode], p->cmOpts.iWrap,
10767         p->cmOpts.bWordWrap ? "on" : "off",
10768         p->cmOpts.bQuote ? "" : "no");
10769    }else{
10770      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10771    }
10772    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10773      output_c_string(p->out, p->nullValue);
10774      raw_printf(p->out, "\n");
10775    utf8_printf(p->out,"%12.12s: %s\n","output",
10776            strlen30(p->outfile) ? p->outfile : "stdout");
10777    utf8_printf(p->out,"%12.12s: ", "colseparator");
10778      output_c_string(p->out, p->colSeparator);
10779      raw_printf(p->out, "\n");
10780    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10781      output_c_string(p->out, p->rowSeparator);
10782      raw_printf(p->out, "\n");
10783    switch( p->statsOn ){
10784      case 0:  zOut = "off";     break;
10785      default: zOut = "on";      break;
10786      case 2:  zOut = "stmt";    break;
10787      case 3:  zOut = "vmstep";  break;
10788    }
10789    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10790    utf8_printf(p->out, "%12.12s: ", "width");
10791    for (i=0;i<p->nWidth;i++) {
10792      raw_printf(p->out, "%d ", p->colWidth[i]);
10793    }
10794    raw_printf(p->out, "\n");
10795    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10796                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10797  }else
10798
10799  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10800    if( nArg==2 ){
10801      if( strcmp(azArg[1],"stmt")==0 ){
10802        p->statsOn = 2;
10803      }else if( strcmp(azArg[1],"vmstep")==0 ){
10804        p->statsOn = 3;
10805      }else{
10806        p->statsOn = (u8)booleanValue(azArg[1]);
10807      }
10808    }else if( nArg==1 ){
10809      display_stats(p->db, p, 0);
10810    }else{
10811      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10812      rc = 1;
10813    }
10814  }else
10815
10816  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10817   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10818                 || strncmp(azArg[0], "indexes", n)==0) )
10819  ){
10820    sqlite3_stmt *pStmt;
10821    char **azResult;
10822    int nRow, nAlloc;
10823    int ii;
10824    ShellText s;
10825    initText(&s);
10826    open_db(p, 0);
10827    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10828    if( rc ){
10829      sqlite3_finalize(pStmt);
10830      return shellDatabaseError(p->db);
10831    }
10832
10833    if( nArg>2 && c=='i' ){
10834      /* It is an historical accident that the .indexes command shows an error
10835      ** when called with the wrong number of arguments whereas the .tables
10836      ** command does not. */
10837      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10838      rc = 1;
10839      sqlite3_finalize(pStmt);
10840      goto meta_command_exit;
10841    }
10842    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10843      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10844      if( zDbName==0 ) continue;
10845      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10846      if( sqlite3_stricmp(zDbName, "main")==0 ){
10847        appendText(&s, "SELECT name FROM ", 0);
10848      }else{
10849        appendText(&s, "SELECT ", 0);
10850        appendText(&s, zDbName, '\'');
10851        appendText(&s, "||'.'||name FROM ", 0);
10852      }
10853      appendText(&s, zDbName, '"');
10854      appendText(&s, ".sqlite_schema ", 0);
10855      if( c=='t' ){
10856        appendText(&s," WHERE type IN ('table','view')"
10857                      "   AND name NOT LIKE 'sqlite_%'"
10858                      "   AND name LIKE ?1", 0);
10859      }else{
10860        appendText(&s," WHERE type='index'"
10861                      "   AND tbl_name LIKE ?1", 0);
10862      }
10863    }
10864    rc = sqlite3_finalize(pStmt);
10865    if( rc==SQLITE_OK ){
10866      appendText(&s, " ORDER BY 1", 0);
10867      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10868    }
10869    freeText(&s);
10870    if( rc ) return shellDatabaseError(p->db);
10871
10872    /* Run the SQL statement prepared by the above block. Store the results
10873    ** as an array of nul-terminated strings in azResult[].  */
10874    nRow = nAlloc = 0;
10875    azResult = 0;
10876    if( nArg>1 ){
10877      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10878    }else{
10879      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10880    }
10881    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10882      if( nRow>=nAlloc ){
10883        char **azNew;
10884        int n2 = nAlloc*2 + 10;
10885        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10886        shell_check_oom(azNew);
10887        nAlloc = n2;
10888        azResult = azNew;
10889      }
10890      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10891      shell_check_oom(azResult[nRow]);
10892      nRow++;
10893    }
10894    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10895      rc = shellDatabaseError(p->db);
10896    }
10897
10898    /* Pretty-print the contents of array azResult[] to the output */
10899    if( rc==0 && nRow>0 ){
10900      int len, maxlen = 0;
10901      int i, j;
10902      int nPrintCol, nPrintRow;
10903      for(i=0; i<nRow; i++){
10904        len = strlen30(azResult[i]);
10905        if( len>maxlen ) maxlen = len;
10906      }
10907      nPrintCol = 80/(maxlen+2);
10908      if( nPrintCol<1 ) nPrintCol = 1;
10909      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10910      for(i=0; i<nPrintRow; i++){
10911        for(j=i; j<nRow; j+=nPrintRow){
10912          char *zSp = j<nPrintRow ? "" : "  ";
10913          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10914                      azResult[j] ? azResult[j]:"");
10915        }
10916        raw_printf(p->out, "\n");
10917      }
10918    }
10919
10920    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10921    sqlite3_free(azResult);
10922  }else
10923
10924#ifndef SQLITE_SHELL_FIDDLE
10925  /* Begin redirecting output to the file "testcase-out.txt" */
10926  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10927    output_reset(p);
10928    p->out = output_file_open("testcase-out.txt", 0);
10929    if( p->out==0 ){
10930      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10931    }
10932    if( nArg>=2 ){
10933      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10934    }else{
10935      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10936    }
10937  }else
10938#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10939
10940#ifndef SQLITE_UNTESTABLE
10941  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10942    static const struct {
10943       const char *zCtrlName;   /* Name of a test-control option */
10944       int ctrlCode;            /* Integer code for that option */
10945       int unSafe;              /* Not valid for --safe mode */
10946       const char *zUsage;      /* Usage notes */
10947    } aCtrl[] = {
10948      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10949      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10950    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10951    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10952      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10953      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10954    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10955      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10956      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10957      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10958      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10959      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10960#ifdef YYCOVERAGE
10961      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10962#endif
10963      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10964      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10965      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10966      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10967      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10968      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10969      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10970    };
10971    int testctrl = -1;
10972    int iCtrl = -1;
10973    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10974    int isOk = 0;
10975    int i, n2;
10976    const char *zCmd = 0;
10977
10978    open_db(p, 0);
10979    zCmd = nArg>=2 ? azArg[1] : "help";
10980
10981    /* The argument can optionally begin with "-" or "--" */
10982    if( zCmd[0]=='-' && zCmd[1] ){
10983      zCmd++;
10984      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10985    }
10986
10987    /* --help lists all test-controls */
10988    if( strcmp(zCmd,"help")==0 ){
10989      utf8_printf(p->out, "Available test-controls:\n");
10990      for(i=0; i<ArraySize(aCtrl); i++){
10991        utf8_printf(p->out, "  .testctrl %s %s\n",
10992                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10993      }
10994      rc = 1;
10995      goto meta_command_exit;
10996    }
10997
10998    /* convert testctrl text option to value. allow any unique prefix
10999    ** of the option name, or a numerical value. */
11000    n2 = strlen30(zCmd);
11001    for(i=0; i<ArraySize(aCtrl); i++){
11002      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
11003        if( testctrl<0 ){
11004          testctrl = aCtrl[i].ctrlCode;
11005          iCtrl = i;
11006        }else{
11007          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
11008                              "Use \".testctrl --help\" for help\n", zCmd);
11009          rc = 1;
11010          goto meta_command_exit;
11011        }
11012      }
11013    }
11014    if( testctrl<0 ){
11015      utf8_printf(stderr,"Error: unknown test-control: %s\n"
11016                         "Use \".testctrl --help\" for help\n", zCmd);
11017    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
11018      utf8_printf(stderr,
11019         "line %d: \".testctrl %s\" may not be used in safe mode\n",
11020         p->lineno, aCtrl[iCtrl].zCtrlName);
11021      exit(1);
11022    }else{
11023      switch(testctrl){
11024
11025        /* sqlite3_test_control(int, db, int) */
11026        case SQLITE_TESTCTRL_OPTIMIZATIONS:
11027          if( nArg==3 ){
11028            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
11029            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11030            isOk = 3;
11031          }
11032          break;
11033
11034        /* sqlite3_test_control(int) */
11035        case SQLITE_TESTCTRL_PRNG_SAVE:
11036        case SQLITE_TESTCTRL_PRNG_RESTORE:
11037        case SQLITE_TESTCTRL_BYTEORDER:
11038          if( nArg==2 ){
11039            rc2 = sqlite3_test_control(testctrl);
11040            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
11041          }
11042          break;
11043
11044        /* sqlite3_test_control(int, uint) */
11045        case SQLITE_TESTCTRL_PENDING_BYTE:
11046          if( nArg==3 ){
11047            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11048            rc2 = sqlite3_test_control(testctrl, opt);
11049            isOk = 3;
11050          }
11051          break;
11052
11053        /* sqlite3_test_control(int, int, sqlite3*) */
11054        case SQLITE_TESTCTRL_PRNG_SEED:
11055          if( nArg==3 || nArg==4 ){
11056            int ii = (int)integerValue(azArg[2]);
11057            sqlite3 *db;
11058            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11059              sqlite3_randomness(sizeof(ii),&ii);
11060              printf("-- random seed: %d\n", ii);
11061            }
11062            if( nArg==3 ){
11063              db = 0;
11064            }else{
11065              db = p->db;
11066              /* Make sure the schema has been loaded */
11067              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11068            }
11069            rc2 = sqlite3_test_control(testctrl, ii, db);
11070            isOk = 3;
11071          }
11072          break;
11073
11074        /* sqlite3_test_control(int, int) */
11075        case SQLITE_TESTCTRL_ASSERT:
11076        case SQLITE_TESTCTRL_ALWAYS:
11077          if( nArg==3 ){
11078            int opt = booleanValue(azArg[2]);
11079            rc2 = sqlite3_test_control(testctrl, opt);
11080            isOk = 1;
11081          }
11082          break;
11083
11084        /* sqlite3_test_control(int, int) */
11085        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11086        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11087          if( nArg==3 ){
11088            int opt = booleanValue(azArg[2]);
11089            rc2 = sqlite3_test_control(testctrl, opt);
11090            isOk = 3;
11091          }
11092          break;
11093
11094        /* sqlite3_test_control(sqlite3*) */
11095        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11096          rc2 = sqlite3_test_control(testctrl, p->db);
11097          isOk = 3;
11098          break;
11099
11100        case SQLITE_TESTCTRL_IMPOSTER:
11101          if( nArg==5 ){
11102            rc2 = sqlite3_test_control(testctrl, p->db,
11103                          azArg[2],
11104                          integerValue(azArg[3]),
11105                          integerValue(azArg[4]));
11106            isOk = 3;
11107          }
11108          break;
11109
11110        case SQLITE_TESTCTRL_SEEK_COUNT: {
11111          u64 x = 0;
11112          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11113          utf8_printf(p->out, "%llu\n", x);
11114          isOk = 3;
11115          break;
11116        }
11117
11118#ifdef YYCOVERAGE
11119        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11120          if( nArg==2 ){
11121            sqlite3_test_control(testctrl, p->out);
11122            isOk = 3;
11123          }
11124          break;
11125        }
11126#endif
11127#ifdef SQLITE_DEBUG
11128        case SQLITE_TESTCTRL_TUNE: {
11129          if( nArg==4 ){
11130            int id = (int)integerValue(azArg[2]);
11131            int val = (int)integerValue(azArg[3]);
11132            sqlite3_test_control(testctrl, id, &val);
11133            isOk = 3;
11134          }else if( nArg==3 ){
11135            int id = (int)integerValue(azArg[2]);
11136            sqlite3_test_control(testctrl, -id, &rc2);
11137            isOk = 1;
11138          }else if( nArg==2 ){
11139            int id = 1;
11140            while(1){
11141              int val = 0;
11142              rc2 = sqlite3_test_control(testctrl, -id, &val);
11143              if( rc2!=SQLITE_OK ) break;
11144              if( id>1 ) utf8_printf(p->out, "  ");
11145              utf8_printf(p->out, "%d: %d", id, val);
11146              id++;
11147            }
11148            if( id>1 ) utf8_printf(p->out, "\n");
11149            isOk = 3;
11150          }
11151          break;
11152        }
11153#endif
11154        case SQLITE_TESTCTRL_SORTER_MMAP:
11155          if( nArg==3 ){
11156            int opt = (unsigned int)integerValue(azArg[2]);
11157            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11158            isOk = 3;
11159          }
11160          break;
11161      }
11162    }
11163    if( isOk==0 && iCtrl>=0 ){
11164      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11165      rc = 1;
11166    }else if( isOk==1 ){
11167      raw_printf(p->out, "%d\n", rc2);
11168    }else if( isOk==2 ){
11169      raw_printf(p->out, "0x%08x\n", rc2);
11170    }
11171  }else
11172#endif /* !defined(SQLITE_UNTESTABLE) */
11173
11174  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11175    open_db(p, 0);
11176    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11177  }else
11178
11179  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11180    if( nArg==2 ){
11181      enableTimer = booleanValue(azArg[1]);
11182      if( enableTimer && !HAS_TIMER ){
11183        raw_printf(stderr, "Error: timer not available on this system.\n");
11184        enableTimer = 0;
11185      }
11186    }else{
11187      raw_printf(stderr, "Usage: .timer on|off\n");
11188      rc = 1;
11189    }
11190  }else
11191
11192#ifndef SQLITE_OMIT_TRACE
11193  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11194    int mType = 0;
11195    int jj;
11196    open_db(p, 0);
11197    for(jj=1; jj<nArg; jj++){
11198      const char *z = azArg[jj];
11199      if( z[0]=='-' ){
11200        if( optionMatch(z, "expanded") ){
11201          p->eTraceType = SHELL_TRACE_EXPANDED;
11202        }
11203#ifdef SQLITE_ENABLE_NORMALIZE
11204        else if( optionMatch(z, "normalized") ){
11205          p->eTraceType = SHELL_TRACE_NORMALIZED;
11206        }
11207#endif
11208        else if( optionMatch(z, "plain") ){
11209          p->eTraceType = SHELL_TRACE_PLAIN;
11210        }
11211        else if( optionMatch(z, "profile") ){
11212          mType |= SQLITE_TRACE_PROFILE;
11213        }
11214        else if( optionMatch(z, "row") ){
11215          mType |= SQLITE_TRACE_ROW;
11216        }
11217        else if( optionMatch(z, "stmt") ){
11218          mType |= SQLITE_TRACE_STMT;
11219        }
11220        else if( optionMatch(z, "close") ){
11221          mType |= SQLITE_TRACE_CLOSE;
11222        }
11223        else {
11224          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11225          rc = 1;
11226          goto meta_command_exit;
11227        }
11228      }else{
11229        output_file_close(p->traceOut);
11230        p->traceOut = output_file_open(azArg[1], 0);
11231      }
11232    }
11233    if( p->traceOut==0 ){
11234      sqlite3_trace_v2(p->db, 0, 0, 0);
11235    }else{
11236      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11237      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11238    }
11239  }else
11240#endif /* !defined(SQLITE_OMIT_TRACE) */
11241
11242#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11243  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11244    int ii;
11245    int lenOpt;
11246    char *zOpt;
11247    if( nArg<2 ){
11248      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11249      rc = 1;
11250      goto meta_command_exit;
11251    }
11252    open_db(p, 0);
11253    zOpt = azArg[1];
11254    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11255    lenOpt = (int)strlen(zOpt);
11256    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11257      assert( azArg[nArg]==0 );
11258      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11259    }else{
11260      for(ii=1; ii<nArg; ii++){
11261        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11262      }
11263    }
11264  }else
11265#endif
11266
11267#if SQLITE_USER_AUTHENTICATION
11268  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11269    if( nArg<2 ){
11270      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11271      rc = 1;
11272      goto meta_command_exit;
11273    }
11274    open_db(p, 0);
11275    if( strcmp(azArg[1],"login")==0 ){
11276      if( nArg!=4 ){
11277        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11278        rc = 1;
11279        goto meta_command_exit;
11280      }
11281      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11282                                     strlen30(azArg[3]));
11283      if( rc ){
11284        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11285        rc = 1;
11286      }
11287    }else if( strcmp(azArg[1],"add")==0 ){
11288      if( nArg!=5 ){
11289        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11290        rc = 1;
11291        goto meta_command_exit;
11292      }
11293      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11294                            booleanValue(azArg[4]));
11295      if( rc ){
11296        raw_printf(stderr, "User-Add failed: %d\n", rc);
11297        rc = 1;
11298      }
11299    }else if( strcmp(azArg[1],"edit")==0 ){
11300      if( nArg!=5 ){
11301        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11302        rc = 1;
11303        goto meta_command_exit;
11304      }
11305      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11306                              booleanValue(azArg[4]));
11307      if( rc ){
11308        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11309        rc = 1;
11310      }
11311    }else if( strcmp(azArg[1],"delete")==0 ){
11312      if( nArg!=3 ){
11313        raw_printf(stderr, "Usage: .user delete USER\n");
11314        rc = 1;
11315        goto meta_command_exit;
11316      }
11317      rc = sqlite3_user_delete(p->db, azArg[2]);
11318      if( rc ){
11319        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11320        rc = 1;
11321      }
11322    }else{
11323      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11324      rc = 1;
11325      goto meta_command_exit;
11326    }
11327  }else
11328#endif /* SQLITE_USER_AUTHENTICATION */
11329
11330  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11331    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11332        sqlite3_libversion(), sqlite3_sourceid());
11333#if SQLITE_HAVE_ZLIB
11334    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11335#endif
11336#define CTIMEOPT_VAL_(opt) #opt
11337#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11338#if defined(__clang__) && defined(__clang_major__)
11339    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11340                    CTIMEOPT_VAL(__clang_minor__) "."
11341                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11342#elif defined(_MSC_VER)
11343    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11344#elif defined(__GNUC__) && defined(__VERSION__)
11345    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11346#endif
11347  }else
11348
11349  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11350    const char *zDbName = nArg==2 ? azArg[1] : "main";
11351    sqlite3_vfs *pVfs = 0;
11352    if( p->db ){
11353      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11354      if( pVfs ){
11355        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11356        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11357        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11358        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11359      }
11360    }
11361  }else
11362
11363  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11364    sqlite3_vfs *pVfs;
11365    sqlite3_vfs *pCurrent = 0;
11366    if( p->db ){
11367      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11368    }
11369    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11370      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11371           pVfs==pCurrent ? "  <--- CURRENT" : "");
11372      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11373      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11374      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11375      if( pVfs->pNext ){
11376        raw_printf(p->out, "-----------------------------------\n");
11377      }
11378    }
11379  }else
11380
11381  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11382    const char *zDbName = nArg==2 ? azArg[1] : "main";
11383    char *zVfsName = 0;
11384    if( p->db ){
11385      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11386      if( zVfsName ){
11387        utf8_printf(p->out, "%s\n", zVfsName);
11388        sqlite3_free(zVfsName);
11389      }
11390    }
11391  }else
11392
11393  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11394    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11395    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11396  }else
11397
11398  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11399    int j;
11400    assert( nArg<=ArraySize(azArg) );
11401    p->nWidth = nArg-1;
11402    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11403    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11404    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11405    for(j=1; j<nArg; j++){
11406      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11407    }
11408  }else
11409
11410  {
11411    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11412      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11413    rc = 1;
11414  }
11415
11416meta_command_exit:
11417  if( p->outCount ){
11418    p->outCount--;
11419    if( p->outCount==0 ) output_reset(p);
11420  }
11421  p->bSafeMode = p->bSafeModePersist;
11422  return rc;
11423}
11424
11425/* Line scan result and intermediate states (supporting scan resumption)
11426*/
11427#ifndef CHAR_BIT
11428# define CHAR_BIT 8
11429#endif
11430typedef enum {
11431  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11432  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11433  QSS_Start = 0
11434} QuickScanState;
11435#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11436#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11437#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11438#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11439#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11440
11441/*
11442** Scan line for classification to guide shell's handling.
11443** The scan is resumable for subsequent lines when prior
11444** return values are passed as the 2nd argument.
11445*/
11446static QuickScanState quickscan(char *zLine, QuickScanState qss){
11447  char cin;
11448  char cWait = (char)qss; /* intentional narrowing loss */
11449  if( cWait==0 ){
11450  PlainScan:
11451    assert( cWait==0 );
11452    while( (cin = *zLine++)!=0 ){
11453      if( IsSpace(cin) )
11454        continue;
11455      switch (cin){
11456      case '-':
11457        if( *zLine!='-' )
11458          break;
11459        while((cin = *++zLine)!=0 )
11460          if( cin=='\n')
11461            goto PlainScan;
11462        return qss;
11463      case ';':
11464        qss |= QSS_EndingSemi;
11465        continue;
11466      case '/':
11467        if( *zLine=='*' ){
11468          ++zLine;
11469          cWait = '*';
11470          qss = QSS_SETV(qss, cWait);
11471          goto TermScan;
11472        }
11473        break;
11474      case '[':
11475        cin = ']';
11476        /* fall thru */
11477      case '`': case '\'': case '"':
11478        cWait = cin;
11479        qss = QSS_HasDark | cWait;
11480        goto TermScan;
11481      default:
11482        break;
11483      }
11484      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11485    }
11486  }else{
11487  TermScan:
11488    while( (cin = *zLine++)!=0 ){
11489      if( cin==cWait ){
11490        switch( cWait ){
11491        case '*':
11492          if( *zLine != '/' )
11493            continue;
11494          ++zLine;
11495          cWait = 0;
11496          qss = QSS_SETV(qss, 0);
11497          goto PlainScan;
11498        case '`': case '\'': case '"':
11499          if(*zLine==cWait){
11500            ++zLine;
11501            continue;
11502          }
11503          /* fall thru */
11504        case ']':
11505          cWait = 0;
11506          qss = QSS_SETV(qss, 0);
11507          goto PlainScan;
11508        default: assert(0);
11509        }
11510      }
11511    }
11512  }
11513  return qss;
11514}
11515
11516/*
11517** Return TRUE if the line typed in is an SQL command terminator other
11518** than a semi-colon.  The SQL Server style "go" command is understood
11519** as is the Oracle "/".
11520*/
11521static int line_is_command_terminator(char *zLine){
11522  while( IsSpace(zLine[0]) ){ zLine++; };
11523  if( zLine[0]=='/' )
11524    zLine += 1; /* Oracle */
11525  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11526    zLine += 2; /* SQL Server */
11527  else
11528    return 0;
11529  return quickscan(zLine, QSS_Start)==QSS_Start;
11530}
11531
11532/*
11533** We need a default sqlite3_complete() implementation to use in case
11534** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11535** any arbitrary text is a complete SQL statement.  This is not very
11536** user-friendly, but it does seem to work.
11537*/
11538#ifdef SQLITE_OMIT_COMPLETE
11539#define sqlite3_complete(x) 1
11540#endif
11541
11542/*
11543** Return true if zSql is a complete SQL statement.  Return false if it
11544** ends in the middle of a string literal or C-style comment.
11545*/
11546static int line_is_complete(char *zSql, int nSql){
11547  int rc;
11548  if( zSql==0 ) return 1;
11549  zSql[nSql] = ';';
11550  zSql[nSql+1] = 0;
11551  rc = sqlite3_complete(zSql);
11552  zSql[nSql] = 0;
11553  return rc;
11554}
11555
11556/*
11557** Run a single line of SQL.  Return the number of errors.
11558*/
11559static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11560  int rc;
11561  char *zErrMsg = 0;
11562
11563  open_db(p, 0);
11564  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11565  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11566  BEGIN_TIMER;
11567  rc = shell_exec(p, zSql, &zErrMsg);
11568  END_TIMER;
11569  if( rc || zErrMsg ){
11570    char zPrefix[100];
11571    const char *zErrorTail;
11572    const char *zErrorType;
11573    if( zErrMsg==0 ){
11574      zErrorType = "Error";
11575      zErrorTail = sqlite3_errmsg(p->db);
11576    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11577      zErrorType = "Parse error";
11578      zErrorTail = &zErrMsg[12];
11579    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11580      zErrorType = "Runtime error";
11581      zErrorTail = &zErrMsg[10];
11582    }else{
11583      zErrorType = "Error";
11584      zErrorTail = zErrMsg;
11585    }
11586    if( in!=0 || !stdin_is_interactive ){
11587      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11588                       "%s near line %d:", zErrorType, startline);
11589    }else{
11590      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11591    }
11592    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11593    sqlite3_free(zErrMsg);
11594    zErrMsg = 0;
11595    return 1;
11596  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11597    char zLineBuf[2000];
11598    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11599            "changes: %lld   total_changes: %lld",
11600            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11601    raw_printf(p->out, "%s\n", zLineBuf);
11602  }
11603  return 0;
11604}
11605
11606static void echo_group_input(ShellState *p, const char *zDo){
11607  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11608}
11609
11610#ifdef SQLITE_SHELL_FIDDLE
11611/*
11612** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11613** because we need the global shellState and cannot access it from that function
11614** without moving lots of code around (creating a larger/messier diff).
11615*/
11616static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11617  /* Parse the next line from shellState.wasm.zInput. */
11618  const char *zBegin = shellState.wasm.zPos;
11619  const char *z = zBegin;
11620  char *zLine = 0;
11621  int nZ = 0;
11622
11623  UNUSED_PARAMETER(in);
11624  UNUSED_PARAMETER(isContinuation);
11625  if(!z || !*z){
11626    return 0;
11627  }
11628  while(*z && isspace(*z)) ++z;
11629  zBegin = z;
11630  for(; *z && '\n'!=*z; ++nZ, ++z){}
11631  if(nZ>0 && '\r'==zBegin[nZ-1]){
11632    --nZ;
11633  }
11634  shellState.wasm.zPos = z;
11635  zLine = realloc(zPrior, nZ+1);
11636  shell_check_oom(zLine);
11637  memcpy(zLine, zBegin, (size_t)nZ);
11638  zLine[nZ] = 0;
11639  return zLine;
11640}
11641#endif /* SQLITE_SHELL_FIDDLE */
11642
11643/*
11644** Read input from *in and process it.  If *in==0 then input
11645** is interactive - the user is typing it it.  Otherwise, input
11646** is coming from a file or device.  A prompt is issued and history
11647** is saved only if input is interactive.  An interrupt signal will
11648** cause this routine to exit immediately, unless input is interactive.
11649**
11650** Return the number of errors.
11651*/
11652static int process_input(ShellState *p){
11653  char *zLine = 0;          /* A single input line */
11654  char *zSql = 0;           /* Accumulated SQL text */
11655  int nLine;                /* Length of current line */
11656  int nSql = 0;             /* Bytes of zSql[] used */
11657  int nAlloc = 0;           /* Allocated zSql[] space */
11658  int rc;                   /* Error code */
11659  int errCnt = 0;           /* Number of errors seen */
11660  int startline = 0;        /* Line number for start of current input */
11661  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11662
11663  if( p->inputNesting==MAX_INPUT_NESTING ){
11664    /* This will be more informative in a later version. */
11665    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11666                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11667    return 1;
11668  }
11669  ++p->inputNesting;
11670  p->lineno = 0;
11671  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11672    fflush(p->out);
11673    zLine = one_input_line(p->in, zLine, nSql>0);
11674    if( zLine==0 ){
11675      /* End of input */
11676      if( p->in==0 && stdin_is_interactive ) printf("\n");
11677      break;
11678    }
11679    if( seenInterrupt ){
11680      if( p->in!=0 ) break;
11681      seenInterrupt = 0;
11682    }
11683    p->lineno++;
11684    if( QSS_INPLAIN(qss)
11685        && line_is_command_terminator(zLine)
11686        && line_is_complete(zSql, nSql) ){
11687      memcpy(zLine,";",2);
11688    }
11689    qss = quickscan(zLine, qss);
11690    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11691      /* Just swallow single-line whitespace */
11692      echo_group_input(p, zLine);
11693      qss = QSS_Start;
11694      continue;
11695    }
11696    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11697      echo_group_input(p, zLine);
11698      if( zLine[0]=='.' ){
11699        rc = do_meta_command(zLine, p);
11700        if( rc==2 ){ /* exit requested */
11701          break;
11702        }else if( rc ){
11703          errCnt++;
11704        }
11705      }
11706      qss = QSS_Start;
11707      continue;
11708    }
11709    /* No single-line dispositions remain; accumulate line(s). */
11710    nLine = strlen30(zLine);
11711    if( nSql+nLine+2>=nAlloc ){
11712      /* Grow buffer by half-again increments when big. */
11713      nAlloc = nSql+(nSql>>1)+nLine+100;
11714      zSql = realloc(zSql, nAlloc);
11715      shell_check_oom(zSql);
11716    }
11717    if( nSql==0 ){
11718      int i;
11719      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11720      assert( nAlloc>0 && zSql!=0 );
11721      memcpy(zSql, zLine+i, nLine+1-i);
11722      startline = p->lineno;
11723      nSql = nLine-i;
11724    }else{
11725      zSql[nSql++] = '\n';
11726      memcpy(zSql+nSql, zLine, nLine+1);
11727      nSql += nLine;
11728    }
11729    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11730      echo_group_input(p, zSql);
11731      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11732      nSql = 0;
11733      if( p->outCount ){
11734        output_reset(p);
11735        p->outCount = 0;
11736      }else{
11737        clearTempFile(p);
11738      }
11739      p->bSafeMode = p->bSafeModePersist;
11740      qss = QSS_Start;
11741    }else if( nSql && QSS_PLAINWHITE(qss) ){
11742      echo_group_input(p, zSql);
11743      nSql = 0;
11744      qss = QSS_Start;
11745    }
11746  }
11747  if( nSql ){
11748    /* This may be incomplete. Let the SQL parser deal with that. */
11749    echo_group_input(p, zSql);
11750    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11751  }
11752  free(zSql);
11753  free(zLine);
11754  --p->inputNesting;
11755  return errCnt>0;
11756}
11757
11758/*
11759** Return a pathname which is the user's home directory.  A
11760** 0 return indicates an error of some kind.
11761*/
11762static char *find_home_dir(int clearFlag){
11763  static char *home_dir = NULL;
11764  if( clearFlag ){
11765    free(home_dir);
11766    home_dir = 0;
11767    return 0;
11768  }
11769  if( home_dir ) return home_dir;
11770
11771#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11772     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11773  {
11774    struct passwd *pwent;
11775    uid_t uid = getuid();
11776    if( (pwent=getpwuid(uid)) != NULL) {
11777      home_dir = pwent->pw_dir;
11778    }
11779  }
11780#endif
11781
11782#if defined(_WIN32_WCE)
11783  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11784   */
11785  home_dir = "/";
11786#else
11787
11788#if defined(_WIN32) || defined(WIN32)
11789  if (!home_dir) {
11790    home_dir = getenv("USERPROFILE");
11791  }
11792#endif
11793
11794  if (!home_dir) {
11795    home_dir = getenv("HOME");
11796  }
11797
11798#if defined(_WIN32) || defined(WIN32)
11799  if (!home_dir) {
11800    char *zDrive, *zPath;
11801    int n;
11802    zDrive = getenv("HOMEDRIVE");
11803    zPath = getenv("HOMEPATH");
11804    if( zDrive && zPath ){
11805      n = strlen30(zDrive) + strlen30(zPath) + 1;
11806      home_dir = malloc( n );
11807      if( home_dir==0 ) return 0;
11808      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11809      return home_dir;
11810    }
11811    home_dir = "c:\\";
11812  }
11813#endif
11814
11815#endif /* !_WIN32_WCE */
11816
11817  if( home_dir ){
11818    int n = strlen30(home_dir) + 1;
11819    char *z = malloc( n );
11820    if( z ) memcpy(z, home_dir, n);
11821    home_dir = z;
11822  }
11823
11824  return home_dir;
11825}
11826
11827/*
11828** Read input from the file given by sqliterc_override.  Or if that
11829** parameter is NULL, take input from ~/.sqliterc
11830**
11831** Returns the number of errors.
11832*/
11833static void process_sqliterc(
11834  ShellState *p,                  /* Configuration data */
11835  const char *sqliterc_override   /* Name of config file. NULL to use default */
11836){
11837  char *home_dir = NULL;
11838  const char *sqliterc = sqliterc_override;
11839  char *zBuf = 0;
11840  FILE *inSaved = p->in;
11841  int savedLineno = p->lineno;
11842
11843  if (sqliterc == NULL) {
11844    home_dir = find_home_dir(0);
11845    if( home_dir==0 ){
11846      raw_printf(stderr, "-- warning: cannot find home directory;"
11847                      " cannot read ~/.sqliterc\n");
11848      return;
11849    }
11850    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11851    shell_check_oom(zBuf);
11852    sqliterc = zBuf;
11853  }
11854  p->in = fopen(sqliterc,"rb");
11855  if( p->in ){
11856    if( stdin_is_interactive ){
11857      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11858    }
11859    if( process_input(p) && bail_on_error ) exit(1);
11860    fclose(p->in);
11861  }else if( sqliterc_override!=0 ){
11862    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11863    if( bail_on_error ) exit(1);
11864  }
11865  p->in = inSaved;
11866  p->lineno = savedLineno;
11867  sqlite3_free(zBuf);
11868}
11869
11870/*
11871** Show available command line options
11872*/
11873static const char zOptions[] =
11874#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11875  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11876#endif
11877  "   -append              append the database to the end of the file\n"
11878  "   -ascii               set output mode to 'ascii'\n"
11879  "   -bail                stop after hitting an error\n"
11880  "   -batch               force batch I/O\n"
11881  "   -box                 set output mode to 'box'\n"
11882  "   -column              set output mode to 'column'\n"
11883  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11884  "   -csv                 set output mode to 'csv'\n"
11885#if !defined(SQLITE_OMIT_DESERIALIZE)
11886  "   -deserialize         open the database using sqlite3_deserialize()\n"
11887#endif
11888  "   -echo                print inputs before execution\n"
11889  "   -init FILENAME       read/process named file\n"
11890  "   -[no]header          turn headers on or off\n"
11891#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11892  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11893#endif
11894  "   -help                show this message\n"
11895  "   -html                set output mode to HTML\n"
11896  "   -interactive         force interactive I/O\n"
11897  "   -json                set output mode to 'json'\n"
11898  "   -line                set output mode to 'line'\n"
11899  "   -list                set output mode to 'list'\n"
11900  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11901  "   -markdown            set output mode to 'markdown'\n"
11902#if !defined(SQLITE_OMIT_DESERIALIZE)
11903  "   -maxsize N           maximum size for a --deserialize database\n"
11904#endif
11905  "   -memtrace            trace all memory allocations and deallocations\n"
11906  "   -mmap N              default mmap size set to N\n"
11907#ifdef SQLITE_ENABLE_MULTIPLEX
11908  "   -multiplex           enable the multiplexor VFS\n"
11909#endif
11910  "   -newline SEP         set output row separator. Default: '\\n'\n"
11911  "   -nofollow            refuse to open symbolic links to database files\n"
11912  "   -nonce STRING        set the safe-mode escape nonce\n"
11913  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11914  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11915  "   -quote               set output mode to 'quote'\n"
11916  "   -readonly            open the database read-only\n"
11917  "   -safe                enable safe-mode\n"
11918  "   -separator SEP       set output column separator. Default: '|'\n"
11919#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11920  "   -sorterref SIZE      sorter references threshold size\n"
11921#endif
11922  "   -stats               print memory stats before each finalize\n"
11923  "   -table               set output mode to 'table'\n"
11924  "   -tabs                set output mode to 'tabs'\n"
11925  "   -version             show SQLite version\n"
11926  "   -vfs NAME            use NAME as the default VFS\n"
11927#ifdef SQLITE_ENABLE_VFSTRACE
11928  "   -vfstrace            enable tracing of all VFS calls\n"
11929#endif
11930#ifdef SQLITE_HAVE_ZLIB
11931  "   -zip                 open the file as a ZIP Archive\n"
11932#endif
11933;
11934static void usage(int showDetail){
11935  utf8_printf(stderr,
11936      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11937      "FILENAME is the name of an SQLite database. A new database is created\n"
11938      "if the file does not previously exist.\n", Argv0);
11939  if( showDetail ){
11940    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11941  }else{
11942    raw_printf(stderr, "Use the -help option for additional information\n");
11943  }
11944  exit(1);
11945}
11946
11947/*
11948** Internal check:  Verify that the SQLite is uninitialized.  Print a
11949** error message if it is initialized.
11950*/
11951static void verify_uninitialized(void){
11952  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11953    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11954                        " initialization.\n");
11955  }
11956}
11957
11958/*
11959** Initialize the state information in data
11960*/
11961static void main_init(ShellState *data) {
11962  memset(data, 0, sizeof(*data));
11963  data->normalMode = data->cMode = data->mode = MODE_List;
11964  data->autoExplain = 1;
11965  data->pAuxDb = &data->aAuxDb[0];
11966  memcpy(data->colSeparator,SEP_Column, 2);
11967  memcpy(data->rowSeparator,SEP_Row, 2);
11968  data->showHeader = 0;
11969  data->shellFlgs = SHFLG_Lookaside;
11970  verify_uninitialized();
11971  sqlite3_config(SQLITE_CONFIG_URI, 1);
11972  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11973  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11974  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11975  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11976}
11977
11978/*
11979** Output text to the console in a font that attracts extra attention.
11980*/
11981#ifdef _WIN32
11982static void printBold(const char *zText){
11983#if !SQLITE_OS_WINRT
11984  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11985  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11986  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11987  SetConsoleTextAttribute(out,
11988         FOREGROUND_RED|FOREGROUND_INTENSITY
11989  );
11990#endif
11991  printf("%s", zText);
11992#if !SQLITE_OS_WINRT
11993  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11994#endif
11995}
11996#else
11997static void printBold(const char *zText){
11998  printf("\033[1m%s\033[0m", zText);
11999}
12000#endif
12001
12002/*
12003** Get the argument to an --option.  Throw an error and die if no argument
12004** is available.
12005*/
12006static char *cmdline_option_value(int argc, char **argv, int i){
12007  if( i==argc ){
12008    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
12009            argv[0], argv[argc-1]);
12010    exit(1);
12011  }
12012  return argv[i];
12013}
12014
12015#ifndef SQLITE_SHELL_IS_UTF8
12016#  if (defined(_WIN32) || defined(WIN32)) \
12017   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
12018#    define SQLITE_SHELL_IS_UTF8          (0)
12019#  else
12020#    define SQLITE_SHELL_IS_UTF8          (1)
12021#  endif
12022#endif
12023
12024#ifdef SQLITE_SHELL_FIDDLE
12025#  define main fiddle_main
12026#endif
12027
12028#if SQLITE_SHELL_IS_UTF8
12029int SQLITE_CDECL main(int argc, char **argv){
12030#else
12031int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
12032  char **argv;
12033#endif
12034#ifdef SQLITE_DEBUG
12035  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
12036#endif
12037  char *zErrMsg = 0;
12038#ifdef SQLITE_SHELL_FIDDLE
12039#  define data shellState
12040#else
12041  ShellState data;
12042#endif
12043  const char *zInitFile = 0;
12044  int i;
12045  int rc = 0;
12046  int warnInmemoryDb = 0;
12047  int readStdin = 1;
12048  int nCmd = 0;
12049  char **azCmd = 0;
12050  const char *zVfs = 0;           /* Value of -vfs command-line option */
12051#if !SQLITE_SHELL_IS_UTF8
12052  char **argvToFree = 0;
12053  int argcToFree = 0;
12054#endif
12055
12056  setBinaryMode(stdin, 0);
12057  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12058#ifdef SQLITE_SHELL_FIDDLE
12059  stdin_is_interactive = 0;
12060  stdout_is_console = 1;
12061  data.wasm.zDefaultDbName = "/fiddle.sqlite3";
12062#else
12063  stdin_is_interactive = isatty(0);
12064  stdout_is_console = isatty(1);
12065#endif
12066
12067#if !defined(_WIN32_WCE)
12068  if( getenv("SQLITE_DEBUG_BREAK") ){
12069    if( isatty(0) && isatty(2) ){
12070      fprintf(stderr,
12071          "attach debugger to process %d and press any key to continue.\n",
12072          GETPID());
12073      fgetc(stdin);
12074    }else{
12075#if defined(_WIN32) || defined(WIN32)
12076#if SQLITE_OS_WINRT
12077      __debugbreak();
12078#else
12079      DebugBreak();
12080#endif
12081#elif defined(SIGTRAP)
12082      raise(SIGTRAP);
12083#endif
12084    }
12085  }
12086#endif
12087
12088#if USE_SYSTEM_SQLITE+0!=1
12089  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12090    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12091            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12092    exit(1);
12093  }
12094#endif
12095  main_init(&data);
12096
12097  /* On Windows, we must translate command-line arguments into UTF-8.
12098  ** The SQLite memory allocator subsystem has to be enabled in order to
12099  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12100  ** subsequent sqlite3_config() calls will work.  So copy all results into
12101  ** memory that does not come from the SQLite memory allocator.
12102  */
12103#if !SQLITE_SHELL_IS_UTF8
12104  sqlite3_initialize();
12105  argvToFree = malloc(sizeof(argv[0])*argc*2);
12106  shell_check_oom(argvToFree);
12107  argcToFree = argc;
12108  argv = argvToFree + argc;
12109  for(i=0; i<argc; i++){
12110    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12111    int n;
12112    shell_check_oom(z);
12113    n = (int)strlen(z);
12114    argv[i] = malloc( n+1 );
12115    shell_check_oom(argv[i]);
12116    memcpy(argv[i], z, n+1);
12117    argvToFree[i] = argv[i];
12118    sqlite3_free(z);
12119  }
12120  sqlite3_shutdown();
12121#endif
12122
12123  assert( argc>=1 && argv && argv[0] );
12124  Argv0 = argv[0];
12125
12126  /* Make sure we have a valid signal handler early, before anything
12127  ** else is done.
12128  */
12129#ifdef SIGINT
12130  signal(SIGINT, interrupt_handler);
12131#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12132  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12133#endif
12134
12135#ifdef SQLITE_SHELL_DBNAME_PROC
12136  {
12137    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12138    ** of a C-function that will provide the name of the database file.  Use
12139    ** this compile-time option to embed this shell program in larger
12140    ** applications. */
12141    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12142    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12143    warnInmemoryDb = 0;
12144  }
12145#endif
12146
12147  /* Do an initial pass through the command-line argument to locate
12148  ** the name of the database file, the name of the initialization file,
12149  ** the size of the alternative malloc heap,
12150  ** and the first command to execute.
12151  */
12152  verify_uninitialized();
12153  for(i=1; i<argc; i++){
12154    char *z;
12155    z = argv[i];
12156    if( z[0]!='-' ){
12157      if( data.aAuxDb->zDbFilename==0 ){
12158        data.aAuxDb->zDbFilename = z;
12159      }else{
12160        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12161        ** mean that nothing is read from stdin */
12162        readStdin = 0;
12163        nCmd++;
12164        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12165        shell_check_oom(azCmd);
12166        azCmd[nCmd-1] = z;
12167      }
12168    }
12169    if( z[1]=='-' ) z++;
12170    if( strcmp(z,"-separator")==0
12171     || strcmp(z,"-nullvalue")==0
12172     || strcmp(z,"-newline")==0
12173     || strcmp(z,"-cmd")==0
12174    ){
12175      (void)cmdline_option_value(argc, argv, ++i);
12176    }else if( strcmp(z,"-init")==0 ){
12177      zInitFile = cmdline_option_value(argc, argv, ++i);
12178    }else if( strcmp(z,"-batch")==0 ){
12179      /* Need to check for batch mode here to so we can avoid printing
12180      ** informational messages (like from process_sqliterc) before
12181      ** we do the actual processing of arguments later in a second pass.
12182      */
12183      stdin_is_interactive = 0;
12184    }else if( strcmp(z,"-heap")==0 ){
12185#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12186      const char *zSize;
12187      sqlite3_int64 szHeap;
12188
12189      zSize = cmdline_option_value(argc, argv, ++i);
12190      szHeap = integerValue(zSize);
12191      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12192      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12193#else
12194      (void)cmdline_option_value(argc, argv, ++i);
12195#endif
12196    }else if( strcmp(z,"-pagecache")==0 ){
12197      sqlite3_int64 n, sz;
12198      sz = integerValue(cmdline_option_value(argc,argv,++i));
12199      if( sz>70000 ) sz = 70000;
12200      if( sz<0 ) sz = 0;
12201      n = integerValue(cmdline_option_value(argc,argv,++i));
12202      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12203        n = 0xffffffffffffLL/sz;
12204      }
12205      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12206                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12207      data.shellFlgs |= SHFLG_Pagecache;
12208    }else if( strcmp(z,"-lookaside")==0 ){
12209      int n, sz;
12210      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12211      if( sz<0 ) sz = 0;
12212      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12213      if( n<0 ) n = 0;
12214      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12215      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12216    }else if( strcmp(z,"-threadsafe")==0 ){
12217      int n;
12218      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12219      switch( n ){
12220         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12221         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12222         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12223      }
12224#ifdef SQLITE_ENABLE_VFSTRACE
12225    }else if( strcmp(z,"-vfstrace")==0 ){
12226      extern int vfstrace_register(
12227         const char *zTraceName,
12228         const char *zOldVfsName,
12229         int (*xOut)(const char*,void*),
12230         void *pOutArg,
12231         int makeDefault
12232      );
12233      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12234#endif
12235#ifdef SQLITE_ENABLE_MULTIPLEX
12236    }else if( strcmp(z,"-multiplex")==0 ){
12237      extern int sqlite3_multiple_initialize(const char*,int);
12238      sqlite3_multiplex_initialize(0, 1);
12239#endif
12240    }else if( strcmp(z,"-mmap")==0 ){
12241      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12242      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12243#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12244    }else if( strcmp(z,"-sorterref")==0 ){
12245      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12246      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12247#endif
12248    }else if( strcmp(z,"-vfs")==0 ){
12249      zVfs = cmdline_option_value(argc, argv, ++i);
12250#ifdef SQLITE_HAVE_ZLIB
12251    }else if( strcmp(z,"-zip")==0 ){
12252      data.openMode = SHELL_OPEN_ZIPFILE;
12253#endif
12254    }else if( strcmp(z,"-append")==0 ){
12255      data.openMode = SHELL_OPEN_APPENDVFS;
12256#ifndef SQLITE_OMIT_DESERIALIZE
12257    }else if( strcmp(z,"-deserialize")==0 ){
12258      data.openMode = SHELL_OPEN_DESERIALIZE;
12259    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12260      data.szMax = integerValue(argv[++i]);
12261#endif
12262    }else if( strcmp(z,"-readonly")==0 ){
12263      data.openMode = SHELL_OPEN_READONLY;
12264    }else if( strcmp(z,"-nofollow")==0 ){
12265      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12266#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12267    }else if( strncmp(z, "-A",2)==0 ){
12268      /* All remaining command-line arguments are passed to the ".archive"
12269      ** command, so ignore them */
12270      break;
12271#endif
12272    }else if( strcmp(z, "-memtrace")==0 ){
12273      sqlite3MemTraceActivate(stderr);
12274    }else if( strcmp(z,"-bail")==0 ){
12275      bail_on_error = 1;
12276    }else if( strcmp(z,"-nonce")==0 ){
12277      free(data.zNonce);
12278      data.zNonce = strdup(argv[++i]);
12279    }else if( strcmp(z,"-safe")==0 ){
12280      /* no-op - catch this on the second pass */
12281    }
12282  }
12283  verify_uninitialized();
12284
12285
12286#ifdef SQLITE_SHELL_INIT_PROC
12287  {
12288    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12289    ** of a C-function that will perform initialization actions on SQLite that
12290    ** occur just before or after sqlite3_initialize(). Use this compile-time
12291    ** option to embed this shell program in larger applications. */
12292    extern void SQLITE_SHELL_INIT_PROC(void);
12293    SQLITE_SHELL_INIT_PROC();
12294  }
12295#else
12296  /* All the sqlite3_config() calls have now been made. So it is safe
12297  ** to call sqlite3_initialize() and process any command line -vfs option. */
12298  sqlite3_initialize();
12299#endif
12300
12301  if( zVfs ){
12302    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12303    if( pVfs ){
12304      sqlite3_vfs_register(pVfs, 1);
12305    }else{
12306      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12307      exit(1);
12308    }
12309  }
12310
12311  if( data.pAuxDb->zDbFilename==0 ){
12312#ifndef SQLITE_OMIT_MEMORYDB
12313    data.pAuxDb->zDbFilename = ":memory:";
12314    warnInmemoryDb = argc==1;
12315#else
12316    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12317    return 1;
12318#endif
12319  }
12320  data.out = stdout;
12321#ifndef SQLITE_SHELL_FIDDLE
12322  sqlite3_appendvfs_init(0,0,0);
12323#endif
12324
12325  /* Go ahead and open the database file if it already exists.  If the
12326  ** file does not exist, delay opening it.  This prevents empty database
12327  ** files from being created if a user mistypes the database name argument
12328  ** to the sqlite command-line tool.
12329  */
12330  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12331    open_db(&data, 0);
12332  }
12333
12334  /* Process the initialization file if there is one.  If no -init option
12335  ** is given on the command line, look for a file named ~/.sqliterc and
12336  ** try to process it.
12337  */
12338  process_sqliterc(&data,zInitFile);
12339
12340  /* Make a second pass through the command-line argument and set
12341  ** options.  This second pass is delayed until after the initialization
12342  ** file is processed so that the command-line arguments will override
12343  ** settings in the initialization file.
12344  */
12345  for(i=1; i<argc; i++){
12346    char *z = argv[i];
12347    if( z[0]!='-' ) continue;
12348    if( z[1]=='-' ){ z++; }
12349    if( strcmp(z,"-init")==0 ){
12350      i++;
12351    }else if( strcmp(z,"-html")==0 ){
12352      data.mode = MODE_Html;
12353    }else if( strcmp(z,"-list")==0 ){
12354      data.mode = MODE_List;
12355    }else if( strcmp(z,"-quote")==0 ){
12356      data.mode = MODE_Quote;
12357      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12358      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12359    }else if( strcmp(z,"-line")==0 ){
12360      data.mode = MODE_Line;
12361    }else if( strcmp(z,"-column")==0 ){
12362      data.mode = MODE_Column;
12363    }else if( strcmp(z,"-json")==0 ){
12364      data.mode = MODE_Json;
12365    }else if( strcmp(z,"-markdown")==0 ){
12366      data.mode = MODE_Markdown;
12367    }else if( strcmp(z,"-table")==0 ){
12368      data.mode = MODE_Table;
12369    }else if( strcmp(z,"-box")==0 ){
12370      data.mode = MODE_Box;
12371    }else if( strcmp(z,"-csv")==0 ){
12372      data.mode = MODE_Csv;
12373      memcpy(data.colSeparator,",",2);
12374#ifdef SQLITE_HAVE_ZLIB
12375    }else if( strcmp(z,"-zip")==0 ){
12376      data.openMode = SHELL_OPEN_ZIPFILE;
12377#endif
12378    }else if( strcmp(z,"-append")==0 ){
12379      data.openMode = SHELL_OPEN_APPENDVFS;
12380#ifndef SQLITE_OMIT_DESERIALIZE
12381    }else if( strcmp(z,"-deserialize")==0 ){
12382      data.openMode = SHELL_OPEN_DESERIALIZE;
12383    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12384      data.szMax = integerValue(argv[++i]);
12385#endif
12386    }else if( strcmp(z,"-readonly")==0 ){
12387      data.openMode = SHELL_OPEN_READONLY;
12388    }else if( strcmp(z,"-nofollow")==0 ){
12389      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12390    }else if( strcmp(z,"-ascii")==0 ){
12391      data.mode = MODE_Ascii;
12392      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12393      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12394    }else if( strcmp(z,"-tabs")==0 ){
12395      data.mode = MODE_List;
12396      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12397      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12398    }else if( strcmp(z,"-separator")==0 ){
12399      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12400                       "%s",cmdline_option_value(argc,argv,++i));
12401    }else if( strcmp(z,"-newline")==0 ){
12402      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12403                       "%s",cmdline_option_value(argc,argv,++i));
12404    }else if( strcmp(z,"-nullvalue")==0 ){
12405      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12406                       "%s",cmdline_option_value(argc,argv,++i));
12407    }else if( strcmp(z,"-header")==0 ){
12408      data.showHeader = 1;
12409      ShellSetFlag(&data, SHFLG_HeaderSet);
12410     }else if( strcmp(z,"-noheader")==0 ){
12411      data.showHeader = 0;
12412      ShellSetFlag(&data, SHFLG_HeaderSet);
12413    }else if( strcmp(z,"-echo")==0 ){
12414      ShellSetFlag(&data, SHFLG_Echo);
12415    }else if( strcmp(z,"-eqp")==0 ){
12416      data.autoEQP = AUTOEQP_on;
12417    }else if( strcmp(z,"-eqpfull")==0 ){
12418      data.autoEQP = AUTOEQP_full;
12419    }else if( strcmp(z,"-stats")==0 ){
12420      data.statsOn = 1;
12421    }else if( strcmp(z,"-scanstats")==0 ){
12422      data.scanstatsOn = 1;
12423    }else if( strcmp(z,"-backslash")==0 ){
12424      /* Undocumented command-line option: -backslash
12425      ** Causes C-style backslash escapes to be evaluated in SQL statements
12426      ** prior to sending the SQL into SQLite.  Useful for injecting
12427      ** crazy bytes in the middle of SQL statements for testing and debugging.
12428      */
12429      ShellSetFlag(&data, SHFLG_Backslash);
12430    }else if( strcmp(z,"-bail")==0 ){
12431      /* No-op.  The bail_on_error flag should already be set. */
12432    }else if( strcmp(z,"-version")==0 ){
12433      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12434      return 0;
12435    }else if( strcmp(z,"-interactive")==0 ){
12436      stdin_is_interactive = 1;
12437    }else if( strcmp(z,"-batch")==0 ){
12438      stdin_is_interactive = 0;
12439    }else if( strcmp(z,"-heap")==0 ){
12440      i++;
12441    }else if( strcmp(z,"-pagecache")==0 ){
12442      i+=2;
12443    }else if( strcmp(z,"-lookaside")==0 ){
12444      i+=2;
12445    }else if( strcmp(z,"-threadsafe")==0 ){
12446      i+=2;
12447    }else if( strcmp(z,"-nonce")==0 ){
12448      i += 2;
12449    }else if( strcmp(z,"-mmap")==0 ){
12450      i++;
12451    }else if( strcmp(z,"-memtrace")==0 ){
12452      i++;
12453#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12454    }else if( strcmp(z,"-sorterref")==0 ){
12455      i++;
12456#endif
12457    }else if( strcmp(z,"-vfs")==0 ){
12458      i++;
12459#ifdef SQLITE_ENABLE_VFSTRACE
12460    }else if( strcmp(z,"-vfstrace")==0 ){
12461      i++;
12462#endif
12463#ifdef SQLITE_ENABLE_MULTIPLEX
12464    }else if( strcmp(z,"-multiplex")==0 ){
12465      i++;
12466#endif
12467    }else if( strcmp(z,"-help")==0 ){
12468      usage(1);
12469    }else if( strcmp(z,"-cmd")==0 ){
12470      /* Run commands that follow -cmd first and separately from commands
12471      ** that simply appear on the command-line.  This seems goofy.  It would
12472      ** be better if all commands ran in the order that they appear.  But
12473      ** we retain the goofy behavior for historical compatibility. */
12474      if( i==argc-1 ) break;
12475      z = cmdline_option_value(argc,argv,++i);
12476      if( z[0]=='.' ){
12477        rc = do_meta_command(z, &data);
12478        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12479      }else{
12480        open_db(&data, 0);
12481        rc = shell_exec(&data, z, &zErrMsg);
12482        if( zErrMsg!=0 ){
12483          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12484          if( bail_on_error ) return rc!=0 ? rc : 1;
12485        }else if( rc!=0 ){
12486          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12487          if( bail_on_error ) return rc;
12488        }
12489      }
12490#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12491    }else if( strncmp(z, "-A", 2)==0 ){
12492      if( nCmd>0 ){
12493        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12494                            " with \"%s\"\n", z);
12495        return 1;
12496      }
12497      open_db(&data, OPEN_DB_ZIPFILE);
12498      if( z[2] ){
12499        argv[i] = &z[2];
12500        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12501      }else{
12502        arDotCommand(&data, 1, argv+i, argc-i);
12503      }
12504      readStdin = 0;
12505      break;
12506#endif
12507    }else if( strcmp(z,"-safe")==0 ){
12508      data.bSafeMode = data.bSafeModePersist = 1;
12509    }else{
12510      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12511      raw_printf(stderr,"Use -help for a list of options.\n");
12512      return 1;
12513    }
12514    data.cMode = data.mode;
12515  }
12516
12517  if( !readStdin ){
12518    /* Run all arguments that do not begin with '-' as if they were separate
12519    ** command-line inputs, except for the argToSkip argument which contains
12520    ** the database filename.
12521    */
12522    for(i=0; i<nCmd; i++){
12523      if( azCmd[i][0]=='.' ){
12524        rc = do_meta_command(azCmd[i], &data);
12525        if( rc ){
12526          free(azCmd);
12527          return rc==2 ? 0 : rc;
12528        }
12529      }else{
12530        open_db(&data, 0);
12531        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12532        if( zErrMsg || rc ){
12533          if( zErrMsg!=0 ){
12534            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12535          }else{
12536            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12537          }
12538          sqlite3_free(zErrMsg);
12539          free(azCmd);
12540          return rc!=0 ? rc : 1;
12541        }
12542      }
12543    }
12544  }else{
12545    /* Run commands received from standard input
12546    */
12547    if( stdin_is_interactive ){
12548      char *zHome;
12549      char *zHistory;
12550      int nHistory;
12551      printf(
12552        "SQLite version %s %.19s\n" /*extra-version-info*/
12553        "Enter \".help\" for usage hints.\n",
12554        sqlite3_libversion(), sqlite3_sourceid()
12555      );
12556      if( warnInmemoryDb ){
12557        printf("Connected to a ");
12558        printBold("transient in-memory database");
12559        printf(".\nUse \".open FILENAME\" to reopen on a "
12560               "persistent database.\n");
12561      }
12562      zHistory = getenv("SQLITE_HISTORY");
12563      if( zHistory ){
12564        zHistory = strdup(zHistory);
12565      }else if( (zHome = find_home_dir(0))!=0 ){
12566        nHistory = strlen30(zHome) + 20;
12567        if( (zHistory = malloc(nHistory))!=0 ){
12568          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12569        }
12570      }
12571      if( zHistory ){ shell_read_history(zHistory); }
12572#if HAVE_READLINE || HAVE_EDITLINE
12573      rl_attempted_completion_function = readline_completion;
12574#elif HAVE_LINENOISE
12575      linenoiseSetCompletionCallback(linenoise_completion);
12576#endif
12577      data.in = 0;
12578      rc = process_input(&data);
12579      if( zHistory ){
12580        shell_stifle_history(2000);
12581        shell_write_history(zHistory);
12582        free(zHistory);
12583      }
12584    }else{
12585      data.in = stdin;
12586      rc = process_input(&data);
12587    }
12588  }
12589#ifndef SQLITE_SHELL_FIDDLE
12590  /* In WASM mode we have to leave the db state in place so that
12591  ** client code can "push" SQL into it after this call returns. */
12592  free(azCmd);
12593  set_table_name(&data, 0);
12594  if( data.db ){
12595    session_close_all(&data, -1);
12596    close_db(data.db);
12597  }
12598  for(i=0; i<ArraySize(data.aAuxDb); i++){
12599    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12600    if( data.aAuxDb[i].db ){
12601      session_close_all(&data, i);
12602      close_db(data.aAuxDb[i].db);
12603    }
12604  }
12605  find_home_dir(1);
12606  output_reset(&data);
12607  data.doXdgOpen = 0;
12608  clearTempFile(&data);
12609#if !SQLITE_SHELL_IS_UTF8
12610  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12611  free(argvToFree);
12612#endif
12613  free(data.colWidth);
12614  free(data.zNonce);
12615  /* Clear the global data structure so that valgrind will detect memory
12616  ** leaks */
12617  memset(&data, 0, sizeof(data));
12618#ifdef SQLITE_DEBUG
12619  if( sqlite3_memory_used()>mem_main_enter ){
12620    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12621                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12622  }
12623#endif
12624#endif /* !SQLITE_SHELL_FIDDLE */
12625  return rc;
12626}
12627
12628
12629#ifdef SQLITE_SHELL_FIDDLE
12630/* Only for emcc experimentation purposes. */
12631int fiddle_experiment(int a,int b){
12632  return a + b;
12633}
12634
12635/*
12636** Returns a pointer to the current DB handle.
12637*/
12638sqlite3 * fiddle_db_handle(){
12639  return globalDb;
12640}
12641
12642/*
12643** Returns a pointer to the given DB name's VFS. If zDbName is 0 then
12644** "main" is assumed. Returns 0 if no db with the given name is
12645** open.
12646*/
12647sqlite3_vfs * fiddle_db_vfs(const char *zDbName){
12648  sqlite3_vfs * pVfs = 0;
12649  if(globalDb){
12650    sqlite3_file_control(globalDb, zDbName ? zDbName : "main",
12651                         SQLITE_FCNTL_VFS_POINTER, &pVfs);
12652  }
12653  return pVfs;
12654}
12655
12656/* Only for emcc experimentation purposes. */
12657sqlite3 * fiddle_db_arg(sqlite3 *arg){
12658    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12659    return arg;
12660}
12661
12662/*
12663** Intended to be called via a SharedWorker() while a separate
12664** SharedWorker() (which manages the wasm module) is performing work
12665** which should be interrupted. Unfortunately, SharedWorker is not
12666** portable enough to make real use of.
12667*/
12668void fiddle_interrupt(void){
12669  if( globalDb ) sqlite3_interrupt(globalDb);
12670}
12671
12672/*
12673** Returns the filename of the given db name, assuming "main" if
12674** zDbName is NULL. Returns NULL if globalDb is not opened.
12675*/
12676const char * fiddle_db_filename(const char * zDbName){
12677    return globalDb
12678      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12679      : NULL;
12680}
12681
12682/*
12683** Completely wipes out the contents of the currently-opened database
12684** but leaves its storage intact for reuse.
12685*/
12686void fiddle_reset_db(void){
12687  if( globalDb ){
12688    int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
12689    if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0);
12690    sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
12691  }
12692}
12693
12694/*
12695** Uses the current database's VFS xRead to stream the db file's
12696** contents out to the given callback. The callback gets a single
12697** chunk of size n (its 2nd argument) on each call and must return 0
12698** on success, non-0 on error. This function returns 0 on success,
12699** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
12700** code from the callback. Note that this is not thread-friendly: it
12701** expects that it will be the only thread reading the db file and
12702** takes no measures to ensure that is the case.
12703*/
12704int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){
12705  sqlite3_int64 nSize = 0;
12706  sqlite3_int64 nPos = 0;
12707  sqlite3_file * pFile = 0;
12708  unsigned char buf[1024 * 8];
12709  int nBuf = (int)sizeof(buf);
12710  int rc = shellState.db
12711    ? sqlite3_file_control(shellState.db, "main",
12712                           SQLITE_FCNTL_FILE_POINTER, &pFile)
12713    : SQLITE_NOTFOUND;
12714  if( rc ) return rc;
12715  rc = pFile->pMethods->xFileSize(pFile, &nSize);
12716  if( rc ) return rc;
12717  if(nSize % nBuf){
12718    /* DB size is not an even multiple of the buffer size. Reduce
12719    ** buffer size so that we do not unduly inflate the db size when
12720    ** exporting. */
12721    if(0 == nSize % 4096) nBuf = 4096;
12722    else if(0 == nSize % 2048) nBuf = 2048;
12723    else if(0 == nSize % 1024) nBuf = 1024;
12724    else nBuf = 512;
12725  }
12726  for( ; 0==rc && nPos<nSize; nPos += nBuf ){
12727    rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
12728    if(SQLITE_IOERR_SHORT_READ == rc){
12729      rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
12730    }
12731    if( 0==rc ) rc = xCallback(buf, nBuf);
12732  }
12733  return rc;
12734}
12735
12736/*
12737** Trivial exportable function for emscripten. It processes zSql as if
12738** it were input to the sqlite3 shell and redirects all output to the
12739** wasm binding. If fiddle_main() has not been called by the time this
12740** is called, this function calls it with a conservative set of
12741** flags.
12742*/
12743void fiddle_exec(const char * zSql){
12744  if(zSql && *zSql){
12745    if('.'==*zSql) puts(zSql);
12746    shellState.wasm.zInput = zSql;
12747    shellState.wasm.zPos = zSql;
12748    process_input(&shellState);
12749    shellState.wasm.zInput = shellState.wasm.zPos = 0;
12750  }
12751}
12752#endif /* SQLITE_SHELL_FIDDLE */
12753