xref: /sqlite-3.40.0/src/shell.c.in (revision 3dfab260)
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** Warning pragmas copied from msvc.h in the core.
42*/
43#if defined(_MSC_VER)
44#pragma warning(disable : 4054)
45#pragma warning(disable : 4055)
46#pragma warning(disable : 4100)
47#pragma warning(disable : 4127)
48#pragma warning(disable : 4130)
49#pragma warning(disable : 4152)
50#pragma warning(disable : 4189)
51#pragma warning(disable : 4206)
52#pragma warning(disable : 4210)
53#pragma warning(disable : 4232)
54#pragma warning(disable : 4244)
55#pragma warning(disable : 4305)
56#pragma warning(disable : 4306)
57#pragma warning(disable : 4702)
58#pragma warning(disable : 4706)
59#endif /* defined(_MSC_VER) */
60
61/*
62** No support for loadable extensions in VxWorks.
63*/
64#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
65# define SQLITE_OMIT_LOAD_EXTENSION 1
66#endif
67
68/*
69** Enable large-file support for fopen() and friends on unix.
70*/
71#ifndef SQLITE_DISABLE_LFS
72# define _LARGE_FILE       1
73# ifndef _FILE_OFFSET_BITS
74#   define _FILE_OFFSET_BITS 64
75# endif
76# define _LARGEFILE_SOURCE 1
77#endif
78
79#include <stdlib.h>
80#include <string.h>
81#include <stdio.h>
82#include <assert.h>
83#include "sqlite3.h"
84typedef sqlite3_int64 i64;
85typedef sqlite3_uint64 u64;
86typedef unsigned char u8;
87#if SQLITE_USER_AUTHENTICATION
88# include "sqlite3userauth.h"
89#endif
90#include <ctype.h>
91#include <stdarg.h>
92
93#if !defined(_WIN32) && !defined(WIN32)
94# include <signal.h>
95# if !defined(__RTP__) && !defined(_WRS_KERNEL)
96#  include <pwd.h>
97# endif
98#endif
99#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100# include <unistd.h>
101# include <dirent.h>
102# define GETPID getpid
103# if defined(__MINGW32__)
104#  define DIRENT dirent
105#  ifndef S_ISLNK
106#   define S_ISLNK(mode) (0)
107#  endif
108# endif
109#else
110# define GETPID (int)GetCurrentProcessId
111#endif
112#include <sys/types.h>
113#include <sys/stat.h>
114
115#if HAVE_READLINE
116# include <readline/readline.h>
117# include <readline/history.h>
118#endif
119
120#if HAVE_EDITLINE
121# include <editline/readline.h>
122#endif
123
124#if HAVE_EDITLINE || HAVE_READLINE
125
126# define shell_add_history(X) add_history(X)
127# define shell_read_history(X) read_history(X)
128# define shell_write_history(X) write_history(X)
129# define shell_stifle_history(X) stifle_history(X)
130# define shell_readline(X) readline(X)
131
132#elif HAVE_LINENOISE
133
134# include "linenoise.h"
135# define shell_add_history(X) linenoiseHistoryAdd(X)
136# define shell_read_history(X) linenoiseHistoryLoad(X)
137# define shell_write_history(X) linenoiseHistorySave(X)
138# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
139# define shell_readline(X) linenoise(X)
140
141#else
142
143# define shell_read_history(X)
144# define shell_write_history(X)
145# define shell_stifle_history(X)
146
147# define SHELL_USE_LOCAL_GETLINE 1
148#endif
149
150
151#if defined(_WIN32) || defined(WIN32)
152# if SQLITE_OS_WINRT
153#  define SQLITE_OMIT_POPEN 1
154# else
155#  include <io.h>
156#  include <fcntl.h>
157#  define isatty(h) _isatty(h)
158#  ifndef access
159#   define access(f,m) _access((f),(m))
160#  endif
161#  ifndef unlink
162#   define unlink _unlink
163#  endif
164#  ifndef strdup
165#   define strdup _strdup
166#  endif
167#  undef popen
168#  define popen _popen
169#  undef pclose
170#  define pclose _pclose
171# endif
172#else
173 /* Make sure isatty() has a prototype. */
174 extern int isatty(int);
175
176# if !defined(__RTP__) && !defined(_WRS_KERNEL)
177  /* popen and pclose are not C89 functions and so are
178  ** sometimes omitted from the <stdio.h> header */
179   extern FILE *popen(const char*,const char*);
180   extern int pclose(FILE*);
181# else
182#  define SQLITE_OMIT_POPEN 1
183# endif
184#endif
185
186#if defined(_WIN32_WCE)
187/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
188 * thus we always assume that we have a console. That can be
189 * overridden with the -batch command line option.
190 */
191#define isatty(x) 1
192#endif
193
194/* ctype macros that work with signed characters */
195#define IsSpace(X)  isspace((unsigned char)X)
196#define IsDigit(X)  isdigit((unsigned char)X)
197#define ToLower(X)  (char)tolower((unsigned char)X)
198
199#if defined(_WIN32) || defined(WIN32)
200#if SQLITE_OS_WINRT
201#include <intrin.h>
202#endif
203#include <windows.h>
204
205/* string conversion routines only needed on Win32 */
206extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
207extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
208extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
209extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
210#endif
211
212/* On Windows, we normally run with output mode of TEXT so that \n characters
213** are automatically translated into \r\n.  However, this behavior needs
214** to be disabled in some cases (ex: when generating CSV output and when
215** rendering quoted strings that contain \n characters).  The following
216** routines take care of that.
217*/
218#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
219static void setBinaryMode(FILE *file, int isOutput){
220  if( isOutput ) fflush(file);
221  _setmode(_fileno(file), _O_BINARY);
222}
223static void setTextMode(FILE *file, int isOutput){
224  if( isOutput ) fflush(file);
225  _setmode(_fileno(file), _O_TEXT);
226}
227#else
228# define setBinaryMode(X,Y)
229# define setTextMode(X,Y)
230#endif
231
232/*
233** When compiling with emcc (a.k.a. emscripten), we're building a
234** WebAssembly (WASM) bundle and need to disable and rewire a few
235** things.
236*/
237#ifdef __EMSCRIPTEN__
238#define SQLITE_SHELL_WASM_MODE
239#else
240#undef SQLITE_SHELL_WASM_MODE
241#endif
242
243/* True if the timer is enabled */
244static int enableTimer = 0;
245
246/* Return the current wall-clock time */
247static sqlite3_int64 timeOfDay(void){
248  static sqlite3_vfs *clockVfs = 0;
249  sqlite3_int64 t;
250  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
251  if( clockVfs==0 ) return 0;  /* Never actually happens */
252  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
253    clockVfs->xCurrentTimeInt64(clockVfs, &t);
254  }else{
255    double r;
256    clockVfs->xCurrentTime(clockVfs, &r);
257    t = (sqlite3_int64)(r*86400000.0);
258  }
259  return t;
260}
261
262#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
263#include <sys/time.h>
264#include <sys/resource.h>
265
266/* VxWorks does not support getrusage() as far as we can determine */
267#if defined(_WRS_KERNEL) || defined(__RTP__)
268struct rusage {
269  struct timeval ru_utime; /* user CPU time used */
270  struct timeval ru_stime; /* system CPU time used */
271};
272#define getrusage(A,B) memset(B,0,sizeof(*B))
273#endif
274
275/* Saved resource information for the beginning of an operation */
276static struct rusage sBegin;  /* CPU time at start */
277static sqlite3_int64 iBegin;  /* Wall-clock time at start */
278
279/*
280** Begin timing an operation
281*/
282static void beginTimer(void){
283  if( enableTimer ){
284    getrusage(RUSAGE_SELF, &sBegin);
285    iBegin = timeOfDay();
286  }
287}
288
289/* Return the difference of two time_structs in seconds */
290static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
291  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
292         (double)(pEnd->tv_sec - pStart->tv_sec);
293}
294
295/*
296** Print the timing results.
297*/
298static void endTimer(void){
299  if( enableTimer ){
300    sqlite3_int64 iEnd = timeOfDay();
301    struct rusage sEnd;
302    getrusage(RUSAGE_SELF, &sEnd);
303    printf("Run Time: real %.3f user %f sys %f\n",
304       (iEnd - iBegin)*0.001,
305       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
306       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
307  }
308}
309
310#define BEGIN_TIMER beginTimer()
311#define END_TIMER endTimer()
312#define HAS_TIMER 1
313
314#elif (defined(_WIN32) || defined(WIN32))
315
316/* Saved resource information for the beginning of an operation */
317static HANDLE hProcess;
318static FILETIME ftKernelBegin;
319static FILETIME ftUserBegin;
320static sqlite3_int64 ftWallBegin;
321typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
322                                    LPFILETIME, LPFILETIME);
323static GETPROCTIMES getProcessTimesAddr = NULL;
324
325/*
326** Check to see if we have timer support.  Return 1 if necessary
327** support found (or found previously).
328*/
329static int hasTimer(void){
330  if( getProcessTimesAddr ){
331    return 1;
332  } else {
333#if !SQLITE_OS_WINRT
334    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
335    ** versions. See if the version we are running on has it, and if it
336    ** does, save off a pointer to it and the current process handle.
337    */
338    hProcess = GetCurrentProcess();
339    if( hProcess ){
340      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
341      if( NULL != hinstLib ){
342        getProcessTimesAddr =
343            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
344        if( NULL != getProcessTimesAddr ){
345          return 1;
346        }
347        FreeLibrary(hinstLib);
348      }
349    }
350#endif
351  }
352  return 0;
353}
354
355/*
356** Begin timing an operation
357*/
358static void beginTimer(void){
359  if( enableTimer && getProcessTimesAddr ){
360    FILETIME ftCreation, ftExit;
361    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
362                        &ftKernelBegin,&ftUserBegin);
363    ftWallBegin = timeOfDay();
364  }
365}
366
367/* Return the difference of two FILETIME structs in seconds */
368static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
369  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
370  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
371  return (double) ((i64End - i64Start) / 10000000.0);
372}
373
374/*
375** Print the timing results.
376*/
377static void endTimer(void){
378  if( enableTimer && getProcessTimesAddr){
379    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
380    sqlite3_int64 ftWallEnd = timeOfDay();
381    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
382    printf("Run Time: real %.3f user %f sys %f\n",
383       (ftWallEnd - ftWallBegin)*0.001,
384       timeDiff(&ftUserBegin, &ftUserEnd),
385       timeDiff(&ftKernelBegin, &ftKernelEnd));
386  }
387}
388
389#define BEGIN_TIMER beginTimer()
390#define END_TIMER endTimer()
391#define HAS_TIMER hasTimer()
392
393#else
394#define BEGIN_TIMER
395#define END_TIMER
396#define HAS_TIMER 0
397#endif
398
399/*
400** Used to prevent warnings about unused parameters
401*/
402#define UNUSED_PARAMETER(x) (void)(x)
403
404/*
405** Number of elements in an array
406*/
407#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
408
409/*
410** If the following flag is set, then command execution stops
411** at an error if we are not interactive.
412*/
413static int bail_on_error = 0;
414
415/*
416** Threat stdin as an interactive input if the following variable
417** is true.  Otherwise, assume stdin is connected to a file or pipe.
418*/
419static int stdin_is_interactive = 1;
420
421/*
422** On Windows systems we have to know if standard output is a console
423** in order to translate UTF-8 into MBCS.  The following variable is
424** true if translation is required.
425*/
426static int stdout_is_console = 1;
427
428/*
429** The following is the open SQLite database.  We make a pointer
430** to this database a static variable so that it can be accessed
431** by the SIGINT handler to interrupt database processing.
432*/
433static sqlite3 *globalDb = 0;
434
435/*
436** True if an interrupt (Control-C) has been received.
437*/
438static volatile int seenInterrupt = 0;
439
440/*
441** This is the name of our program. It is set in main(), used
442** in a number of other places, mostly for error messages.
443*/
444static char *Argv0;
445
446/*
447** Prompt strings. Initialized in main. Settable with
448**   .prompt main continue
449*/
450static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
451static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
452
453/*
454** Render output like fprintf().  Except, if the output is going to the
455** console and if this is running on a Windows machine, translate the
456** output from UTF-8 into MBCS.
457*/
458#if defined(_WIN32) || defined(WIN32)
459void utf8_printf(FILE *out, const char *zFormat, ...){
460  va_list ap;
461  va_start(ap, zFormat);
462  if( stdout_is_console && (out==stdout || out==stderr) ){
463    char *z1 = sqlite3_vmprintf(zFormat, ap);
464    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
465    sqlite3_free(z1);
466    fputs(z2, out);
467    sqlite3_free(z2);
468  }else{
469    vfprintf(out, zFormat, ap);
470  }
471  va_end(ap);
472}
473#elif !defined(utf8_printf)
474# define utf8_printf fprintf
475#endif
476
477/*
478** Render output like fprintf().  This should not be used on anything that
479** includes string formatting (e.g. "%s").
480*/
481#if !defined(raw_printf)
482# define raw_printf fprintf
483#endif
484
485/* Indicate out-of-memory and exit. */
486static void shell_out_of_memory(void){
487  raw_printf(stderr,"Error: out of memory\n");
488  exit(1);
489}
490
491/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
492** out-of-memory error.
493*/
494static void shell_check_oom(void *p){
495  if( p==0 ) shell_out_of_memory();
496}
497
498/*
499** Write I/O traces to the following stream.
500*/
501#ifdef SQLITE_ENABLE_IOTRACE
502static FILE *iotrace = 0;
503#endif
504
505/*
506** This routine works like printf in that its first argument is a
507** format string and subsequent arguments are values to be substituted
508** in place of % fields.  The result of formatting this string
509** is written to iotrace.
510*/
511#ifdef SQLITE_ENABLE_IOTRACE
512static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
513  va_list ap;
514  char *z;
515  if( iotrace==0 ) return;
516  va_start(ap, zFormat);
517  z = sqlite3_vmprintf(zFormat, ap);
518  va_end(ap);
519  utf8_printf(iotrace, "%s", z);
520  sqlite3_free(z);
521}
522#endif
523
524/*
525** Output string zUtf to stream pOut as w characters.  If w is negative,
526** then right-justify the text.  W is the width in UTF-8 characters, not
527** in bytes.  This is different from the %*.*s specification in printf
528** since with %*.*s the width is measured in bytes, not characters.
529*/
530static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
531  int i;
532  int n;
533  int aw = w<0 ? -w : w;
534  for(i=n=0; zUtf[i]; i++){
535    if( (zUtf[i]&0xc0)!=0x80 ){
536      n++;
537      if( n==aw ){
538        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
539        break;
540      }
541    }
542  }
543  if( n>=aw ){
544    utf8_printf(pOut, "%.*s", i, zUtf);
545  }else if( w<0 ){
546    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
547  }else{
548    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
549  }
550}
551
552
553/*
554** Determines if a string is a number of not.
555*/
556static int isNumber(const char *z, int *realnum){
557  if( *z=='-' || *z=='+' ) z++;
558  if( !IsDigit(*z) ){
559    return 0;
560  }
561  z++;
562  if( realnum ) *realnum = 0;
563  while( IsDigit(*z) ){ z++; }
564  if( *z=='.' ){
565    z++;
566    if( !IsDigit(*z) ) return 0;
567    while( IsDigit(*z) ){ z++; }
568    if( realnum ) *realnum = 1;
569  }
570  if( *z=='e' || *z=='E' ){
571    z++;
572    if( *z=='+' || *z=='-' ) z++;
573    if( !IsDigit(*z) ) return 0;
574    while( IsDigit(*z) ){ z++; }
575    if( realnum ) *realnum = 1;
576  }
577  return *z==0;
578}
579
580/*
581** Compute a string length that is limited to what can be stored in
582** lower 30 bits of a 32-bit signed integer.
583*/
584static int strlen30(const char *z){
585  const char *z2 = z;
586  while( *z2 ){ z2++; }
587  return 0x3fffffff & (int)(z2 - z);
588}
589
590/*
591** Return the length of a string in characters.  Multibyte UTF8 characters
592** count as a single character.
593*/
594static int strlenChar(const char *z){
595  int n = 0;
596  while( *z ){
597    if( (0xc0&*(z++))!=0x80 ) n++;
598  }
599  return n;
600}
601
602/*
603** Return open FILE * if zFile exists, can be opened for read
604** and is an ordinary file or a character stream source.
605** Otherwise return 0.
606*/
607static FILE * openChrSource(const char *zFile){
608#ifdef _WIN32
609  struct _stat x = {0};
610# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
611  /* On Windows, open first, then check the stream nature. This order
612  ** is necessary because _stat() and sibs, when checking a named pipe,
613  ** effectively break the pipe as its supplier sees it. */
614  FILE *rv = fopen(zFile, "rb");
615  if( rv==0 ) return 0;
616  if( _fstat(_fileno(rv), &x) != 0
617      || !STAT_CHR_SRC(x.st_mode)){
618    fclose(rv);
619    rv = 0;
620  }
621  return rv;
622#else
623  struct stat x = {0};
624  int rc = stat(zFile, &x);
625# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
626  if( rc!=0 ) return 0;
627  if( STAT_CHR_SRC(x.st_mode) ){
628    return fopen(zFile, "rb");
629  }else{
630    return 0;
631  }
632#endif
633#undef STAT_CHR_SRC
634}
635
636/*
637** This routine reads a line of text from FILE in, stores
638** the text in memory obtained from malloc() and returns a pointer
639** to the text.  NULL is returned at end of file, or if malloc()
640** fails.
641**
642** If zLine is not NULL then it is a malloced buffer returned from
643** a previous call to this routine that may be reused.
644*/
645static char *local_getline(char *zLine, FILE *in){
646  int nLine = zLine==0 ? 0 : 100;
647  int n = 0;
648
649  while( 1 ){
650    if( n+100>nLine ){
651      nLine = nLine*2 + 100;
652      zLine = realloc(zLine, nLine);
653      shell_check_oom(zLine);
654    }
655    if( fgets(&zLine[n], nLine - n, in)==0 ){
656      if( n==0 ){
657        free(zLine);
658        return 0;
659      }
660      zLine[n] = 0;
661      break;
662    }
663    while( zLine[n] ) n++;
664    if( n>0 && zLine[n-1]=='\n' ){
665      n--;
666      if( n>0 && zLine[n-1]=='\r' ) n--;
667      zLine[n] = 0;
668      break;
669    }
670  }
671#if defined(_WIN32) || defined(WIN32)
672  /* For interactive input on Windows systems, translate the
673  ** multi-byte characterset characters into UTF-8. */
674  if( stdin_is_interactive && in==stdin ){
675    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
676    if( zTrans ){
677      int nTrans = strlen30(zTrans)+1;
678      if( nTrans>nLine ){
679        zLine = realloc(zLine, nTrans);
680        shell_check_oom(zLine);
681      }
682      memcpy(zLine, zTrans, nTrans);
683      sqlite3_free(zTrans);
684    }
685  }
686#endif /* defined(_WIN32) || defined(WIN32) */
687  return zLine;
688}
689
690/*
691** Retrieve a single line of input text.
692**
693** If in==0 then read from standard input and prompt before each line.
694** If isContinuation is true, then a continuation prompt is appropriate.
695** If isContinuation is zero, then the main prompt should be used.
696**
697** If zPrior is not NULL then it is a buffer from a prior call to this
698** routine that can be reused.
699**
700** The result is stored in space obtained from malloc() and must either
701** be freed by the caller or else passed back into this routine via the
702** zPrior argument for reuse.
703*/
704#ifndef SQLITE_SHELL_WASM_MODE
705static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
706  char *zPrompt;
707  char *zResult;
708  if( in!=0 ){
709    zResult = local_getline(zPrior, in);
710  }else{
711    zPrompt = isContinuation ? continuePrompt : mainPrompt;
712#if SHELL_USE_LOCAL_GETLINE
713    printf("%s", zPrompt);
714    fflush(stdout);
715    zResult = local_getline(zPrior, stdin);
716#else
717    free(zPrior);
718    zResult = shell_readline(zPrompt);
719    if( zResult && *zResult ) shell_add_history(zResult);
720#endif
721  }
722  return zResult;
723}
724#endif /* !SQLITE_SHELL_WASM_MODE */
725
726/*
727** Return the value of a hexadecimal digit.  Return -1 if the input
728** is not a hex digit.
729*/
730static int hexDigitValue(char c){
731  if( c>='0' && c<='9' ) return c - '0';
732  if( c>='a' && c<='f' ) return c - 'a' + 10;
733  if( c>='A' && c<='F' ) return c - 'A' + 10;
734  return -1;
735}
736
737/*
738** Interpret zArg as an integer value, possibly with suffixes.
739*/
740static sqlite3_int64 integerValue(const char *zArg){
741  sqlite3_int64 v = 0;
742  static const struct { char *zSuffix; int iMult; } aMult[] = {
743    { "KiB", 1024 },
744    { "MiB", 1024*1024 },
745    { "GiB", 1024*1024*1024 },
746    { "KB",  1000 },
747    { "MB",  1000000 },
748    { "GB",  1000000000 },
749    { "K",   1000 },
750    { "M",   1000000 },
751    { "G",   1000000000 },
752  };
753  int i;
754  int isNeg = 0;
755  if( zArg[0]=='-' ){
756    isNeg = 1;
757    zArg++;
758  }else if( zArg[0]=='+' ){
759    zArg++;
760  }
761  if( zArg[0]=='0' && zArg[1]=='x' ){
762    int x;
763    zArg += 2;
764    while( (x = hexDigitValue(zArg[0]))>=0 ){
765      v = (v<<4) + x;
766      zArg++;
767    }
768  }else{
769    while( IsDigit(zArg[0]) ){
770      v = v*10 + zArg[0] - '0';
771      zArg++;
772    }
773  }
774  for(i=0; i<ArraySize(aMult); i++){
775    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
776      v *= aMult[i].iMult;
777      break;
778    }
779  }
780  return isNeg? -v : v;
781}
782
783/*
784** A variable length string to which one can append text.
785*/
786typedef struct ShellText ShellText;
787struct ShellText {
788  char *z;
789  int n;
790  int nAlloc;
791};
792
793/*
794** Initialize and destroy a ShellText object
795*/
796static void initText(ShellText *p){
797  memset(p, 0, sizeof(*p));
798}
799static void freeText(ShellText *p){
800  free(p->z);
801  initText(p);
802}
803
804/* zIn is either a pointer to a NULL-terminated string in memory obtained
805** from malloc(), or a NULL pointer. The string pointed to by zAppend is
806** added to zIn, and the result returned in memory obtained from malloc().
807** zIn, if it was not NULL, is freed.
808**
809** If the third argument, quote, is not '\0', then it is used as a
810** quote character for zAppend.
811*/
812static void appendText(ShellText *p, const char *zAppend, char quote){
813  int len;
814  int i;
815  int nAppend = strlen30(zAppend);
816
817  len = nAppend+p->n+1;
818  if( quote ){
819    len += 2;
820    for(i=0; i<nAppend; i++){
821      if( zAppend[i]==quote ) len++;
822    }
823  }
824
825  if( p->z==0 || p->n+len>=p->nAlloc ){
826    p->nAlloc = p->nAlloc*2 + len + 20;
827    p->z = realloc(p->z, p->nAlloc);
828    shell_check_oom(p->z);
829  }
830
831  if( quote ){
832    char *zCsr = p->z+p->n;
833    *zCsr++ = quote;
834    for(i=0; i<nAppend; i++){
835      *zCsr++ = zAppend[i];
836      if( zAppend[i]==quote ) *zCsr++ = quote;
837    }
838    *zCsr++ = quote;
839    p->n = (int)(zCsr - p->z);
840    *zCsr = '\0';
841  }else{
842    memcpy(p->z+p->n, zAppend, nAppend);
843    p->n += nAppend;
844    p->z[p->n] = '\0';
845  }
846}
847
848/*
849** Attempt to determine if identifier zName needs to be quoted, either
850** because it contains non-alphanumeric characters, or because it is an
851** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
852** that quoting is required.
853**
854** Return '"' if quoting is required.  Return 0 if no quoting is required.
855*/
856static char quoteChar(const char *zName){
857  int i;
858  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
859  for(i=0; zName[i]; i++){
860    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
861  }
862  return sqlite3_keyword_check(zName, i) ? '"' : 0;
863}
864
865/*
866** Construct a fake object name and column list to describe the structure
867** of the view, virtual table, or table valued function zSchema.zName.
868*/
869static char *shellFakeSchema(
870  sqlite3 *db,            /* The database connection containing the vtab */
871  const char *zSchema,    /* Schema of the database holding the vtab */
872  const char *zName       /* The name of the virtual table */
873){
874  sqlite3_stmt *pStmt = 0;
875  char *zSql;
876  ShellText s;
877  char cQuote;
878  char *zDiv = "(";
879  int nRow = 0;
880
881  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
882                         zSchema ? zSchema : "main", zName);
883  shell_check_oom(zSql);
884  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
885  sqlite3_free(zSql);
886  initText(&s);
887  if( zSchema ){
888    cQuote = quoteChar(zSchema);
889    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
890    appendText(&s, zSchema, cQuote);
891    appendText(&s, ".", 0);
892  }
893  cQuote = quoteChar(zName);
894  appendText(&s, zName, cQuote);
895  while( sqlite3_step(pStmt)==SQLITE_ROW ){
896    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
897    nRow++;
898    appendText(&s, zDiv, 0);
899    zDiv = ",";
900    if( zCol==0 ) zCol = "";
901    cQuote = quoteChar(zCol);
902    appendText(&s, zCol, cQuote);
903  }
904  appendText(&s, ")", 0);
905  sqlite3_finalize(pStmt);
906  if( nRow==0 ){
907    freeText(&s);
908    s.z = 0;
909  }
910  return s.z;
911}
912
913/*
914** SQL function:  shell_module_schema(X)
915**
916** Return a fake schema for the table-valued function or eponymous virtual
917** table X.
918*/
919static void shellModuleSchema(
920  sqlite3_context *pCtx,
921  int nVal,
922  sqlite3_value **apVal
923){
924  const char *zName;
925  char *zFake;
926  UNUSED_PARAMETER(nVal);
927  zName = (const char*)sqlite3_value_text(apVal[0]);
928  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
929  if( zFake ){
930    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
931                        -1, sqlite3_free);
932    free(zFake);
933  }
934}
935
936/*
937** SQL function:  shell_add_schema(S,X)
938**
939** Add the schema name X to the CREATE statement in S and return the result.
940** Examples:
941**
942**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
943**
944** Also works on
945**
946**    CREATE INDEX
947**    CREATE UNIQUE INDEX
948**    CREATE VIEW
949**    CREATE TRIGGER
950**    CREATE VIRTUAL TABLE
951**
952** This UDF is used by the .schema command to insert the schema name of
953** attached databases into the middle of the sqlite_schema.sql field.
954*/
955static void shellAddSchemaName(
956  sqlite3_context *pCtx,
957  int nVal,
958  sqlite3_value **apVal
959){
960  static const char *aPrefix[] = {
961     "TABLE",
962     "INDEX",
963     "UNIQUE INDEX",
964     "VIEW",
965     "TRIGGER",
966     "VIRTUAL TABLE"
967  };
968  int i = 0;
969  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
970  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
971  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
972  sqlite3 *db = sqlite3_context_db_handle(pCtx);
973  UNUSED_PARAMETER(nVal);
974  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
975    for(i=0; i<ArraySize(aPrefix); i++){
976      int n = strlen30(aPrefix[i]);
977      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
978        char *z = 0;
979        char *zFake = 0;
980        if( zSchema ){
981          char cQuote = quoteChar(zSchema);
982          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
983            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
984          }else{
985            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
986          }
987        }
988        if( zName
989         && aPrefix[i][0]=='V'
990         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
991        ){
992          if( z==0 ){
993            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
994          }else{
995            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
996          }
997          free(zFake);
998        }
999        if( z ){
1000          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
1001          return;
1002        }
1003      }
1004    }
1005  }
1006  sqlite3_result_value(pCtx, apVal[0]);
1007}
1008
1009/*
1010** The source code for several run-time loadable extensions is inserted
1011** below by the ../tool/mkshellc.tcl script.  Before processing that included
1012** code, we need to override some macros to make the included program code
1013** work here in the middle of this regular program.
1014*/
1015#define SQLITE_EXTENSION_INIT1
1016#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1017
1018#if defined(_WIN32) && defined(_MSC_VER)
1019INCLUDE test_windirent.h
1020INCLUDE test_windirent.c
1021#define dirent DIRENT
1022#endif
1023INCLUDE ../ext/misc/memtrace.c
1024INCLUDE ../ext/misc/shathree.c
1025INCLUDE ../ext/misc/uint.c
1026INCLUDE ../ext/misc/decimal.c
1027INCLUDE ../ext/misc/ieee754.c
1028INCLUDE ../ext/misc/series.c
1029INCLUDE ../ext/misc/regexp.c
1030#ifndef SQLITE_SHELL_WASM_MODE
1031INCLUDE ../ext/misc/fileio.c
1032INCLUDE ../ext/misc/completion.c
1033INCLUDE ../ext/misc/appendvfs.c
1034#endif
1035#ifdef SQLITE_HAVE_ZLIB
1036INCLUDE ../ext/misc/zipfile.c
1037INCLUDE ../ext/misc/sqlar.c
1038#endif
1039INCLUDE ../ext/expert/sqlite3expert.h
1040INCLUDE ../ext/expert/sqlite3expert.c
1041
1042#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1043INCLUDE ../ext/misc/dbdata.c
1044#endif
1045
1046#if defined(SQLITE_ENABLE_SESSION)
1047/*
1048** State information for a single open session
1049*/
1050typedef struct OpenSession OpenSession;
1051struct OpenSession {
1052  char *zName;             /* Symbolic name for this session */
1053  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1054  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1055  sqlite3_session *p;      /* The open session */
1056};
1057#endif
1058
1059typedef struct ExpertInfo ExpertInfo;
1060struct ExpertInfo {
1061  sqlite3expert *pExpert;
1062  int bVerbose;
1063};
1064
1065/* A single line in the EQP output */
1066typedef struct EQPGraphRow EQPGraphRow;
1067struct EQPGraphRow {
1068  int iEqpId;           /* ID for this row */
1069  int iParentId;        /* ID of the parent row */
1070  EQPGraphRow *pNext;   /* Next row in sequence */
1071  char zText[1];        /* Text to display for this row */
1072};
1073
1074/* All EQP output is collected into an instance of the following */
1075typedef struct EQPGraph EQPGraph;
1076struct EQPGraph {
1077  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1078  EQPGraphRow *pLast;   /* Last element of the pRow list */
1079  char zPrefix[100];    /* Graph prefix */
1080};
1081
1082/* Parameters affecting columnar mode result display (defaulting together) */
1083typedef struct ColModeOpts {
1084  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1085  u8 bQuote;            /* Quote results for .mode box and table */
1086  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1087} ColModeOpts;
1088#define ColModeOpts_default { 60, 0, 0 }
1089#define ColModeOpts_default_qbox { 60, 1, 0 }
1090
1091/*
1092** State information about the database connection is contained in an
1093** instance of the following structure.
1094*/
1095typedef struct ShellState ShellState;
1096struct ShellState {
1097  sqlite3 *db;           /* The database */
1098  u8 autoExplain;        /* Automatically turn on .explain mode */
1099  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1100  u8 autoEQPtest;        /* autoEQP is in test mode */
1101  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1102  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1103  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1104  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1105  u8 nEqpLevel;          /* Depth of the EQP output graph */
1106  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1107  u8 bSafeMode;          /* True to prohibit unsafe operations */
1108  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1109  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1110  unsigned statsOn;      /* True to display memory stats before each finalize */
1111  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1112  int inputNesting;      /* Track nesting level of .read and other redirects */
1113  int outCount;          /* Revert to stdout when reaching zero */
1114  int cnt;               /* Number of records displayed so far */
1115  int lineno;            /* Line number of last line read from in */
1116  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1117  FILE *in;              /* Read commands from this stream */
1118  FILE *out;             /* Write results here */
1119  FILE *traceOut;        /* Output for sqlite3_trace() */
1120  int nErr;              /* Number of errors seen */
1121  int mode;              /* An output mode setting */
1122  int modePrior;         /* Saved mode */
1123  int cMode;             /* temporary output mode for the current query */
1124  int normalMode;        /* Output mode before ".explain on" */
1125  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1126  int showHeader;        /* True to show column names in List or Column mode */
1127  int nCheck;            /* Number of ".check" commands run */
1128  unsigned nProgress;    /* Number of progress callbacks encountered */
1129  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1130  unsigned flgProgress;  /* Flags for the progress callback */
1131  unsigned shellFlgs;    /* Various flags */
1132  unsigned priorShFlgs;  /* Saved copy of flags */
1133  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1134  char *zDestTable;      /* Name of destination table when MODE_Insert */
1135  char *zTempFile;       /* Temporary file that might need deleting */
1136  char zTestcase[30];    /* Name of current test case */
1137  char colSeparator[20]; /* Column separator character for several modes */
1138  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1139  char colSepPrior[20];  /* Saved column separator */
1140  char rowSepPrior[20];  /* Saved row separator */
1141  int *colWidth;         /* Requested width of each column in columnar modes */
1142  int *actualWidth;      /* Actual width of each column */
1143  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1144  char nullValue[20];    /* The text to print when a NULL comes back from
1145                         ** the database */
1146  char outfile[FILENAME_MAX]; /* Filename for *out */
1147  sqlite3_stmt *pStmt;   /* Current statement if any. */
1148  FILE *pLog;            /* Write log output here */
1149  struct AuxDb {         /* Storage space for auxiliary database connections */
1150    sqlite3 *db;               /* Connection pointer */
1151    const char *zDbFilename;   /* Filename used to open the connection */
1152    char *zFreeOnClose;        /* Free this memory allocation on close */
1153#if defined(SQLITE_ENABLE_SESSION)
1154    int nSession;              /* Number of active sessions */
1155    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1156#endif
1157  } aAuxDb[5],           /* Array of all database connections */
1158    *pAuxDb;             /* Currently active database connection */
1159  int *aiIndent;         /* Array of indents used in MODE_Explain */
1160  int nIndent;           /* Size of array aiIndent[] */
1161  int iIndent;           /* Index of current op in aiIndent[] */
1162  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1163  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1164  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1165#ifdef SQLITE_SHELL_WASM_MODE
1166  struct {
1167    const char * zInput; /* Input string from wasm/JS proxy */
1168    const char * zPos;   /* Cursor pos into zInput */
1169  } wasm;
1170#endif
1171};
1172
1173#ifdef SQLITE_SHELL_WASM_MODE
1174static ShellState shellState;
1175#endif
1176
1177
1178/* Allowed values for ShellState.autoEQP
1179*/
1180#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1181#define AUTOEQP_on       1           /* Automatic EQP is on */
1182#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1183#define AUTOEQP_full     3           /* Show full EXPLAIN */
1184
1185/* Allowed values for ShellState.openMode
1186*/
1187#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1188#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1189#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1190#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1191#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1192#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1193#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1194
1195/* Allowed values for ShellState.eTraceType
1196*/
1197#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1198#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1199#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1200
1201/* Bits in the ShellState.flgProgress variable */
1202#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1203#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1204                                   ** callback limit is reached, and for each
1205                                   ** top-level SQL statement */
1206#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1207
1208/*
1209** These are the allowed shellFlgs values
1210*/
1211#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1212#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1213#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1214#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1215#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1216#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1217#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1218#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1219#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1220#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1221
1222/*
1223** Macros for testing and setting shellFlgs
1224*/
1225#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1226#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1227#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1228
1229/*
1230** These are the allowed modes.
1231*/
1232#define MODE_Line     0  /* One column per line.  Blank line between records */
1233#define MODE_Column   1  /* One record per line in neat columns */
1234#define MODE_List     2  /* One record per line with a separator */
1235#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1236#define MODE_Html     4  /* Generate an XHTML table */
1237#define MODE_Insert   5  /* Generate SQL "insert" statements */
1238#define MODE_Quote    6  /* Quote values as for SQL */
1239#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1240#define MODE_Csv      8  /* Quote strings, numbers are plain */
1241#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1242#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1243#define MODE_Pretty  11  /* Pretty-print schemas */
1244#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1245#define MODE_Json    13  /* Output JSON */
1246#define MODE_Markdown 14 /* Markdown formatting */
1247#define MODE_Table   15  /* MySQL-style table formatting */
1248#define MODE_Box     16  /* Unicode box-drawing characters */
1249#define MODE_Count   17  /* Output only a count of the rows of output */
1250#define MODE_Off     18  /* No query output shown */
1251
1252static const char *modeDescr[] = {
1253  "line",
1254  "column",
1255  "list",
1256  "semi",
1257  "html",
1258  "insert",
1259  "quote",
1260  "tcl",
1261  "csv",
1262  "explain",
1263  "ascii",
1264  "prettyprint",
1265  "eqp",
1266  "json",
1267  "markdown",
1268  "table",
1269  "box",
1270  "count",
1271  "off"
1272};
1273
1274/*
1275** These are the column/row/line separators used by the various
1276** import/export modes.
1277*/
1278#define SEP_Column    "|"
1279#define SEP_Row       "\n"
1280#define SEP_Tab       "\t"
1281#define SEP_Space     " "
1282#define SEP_Comma     ","
1283#define SEP_CrLf      "\r\n"
1284#define SEP_Unit      "\x1F"
1285#define SEP_Record    "\x1E"
1286
1287/*
1288** Limit input nesting via .read or any other input redirect.
1289** It's not too expensive, so a generous allowance can be made.
1290*/
1291#define MAX_INPUT_NESTING 25
1292
1293/*
1294** A callback for the sqlite3_log() interface.
1295*/
1296static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1297  ShellState *p = (ShellState*)pArg;
1298  if( p->pLog==0 ) return;
1299  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1300  fflush(p->pLog);
1301}
1302
1303/*
1304** SQL function:  shell_putsnl(X)
1305**
1306** Write the text X to the screen (or whatever output is being directed)
1307** adding a newline at the end, and then return X.
1308*/
1309static void shellPutsFunc(
1310  sqlite3_context *pCtx,
1311  int nVal,
1312  sqlite3_value **apVal
1313){
1314  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1315  (void)nVal;
1316  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1317  sqlite3_result_value(pCtx, apVal[0]);
1318}
1319
1320/*
1321** If in safe mode, print an error message described by the arguments
1322** and exit immediately.
1323*/
1324static void failIfSafeMode(
1325  ShellState *p,
1326  const char *zErrMsg,
1327  ...
1328){
1329  if( p->bSafeMode ){
1330    va_list ap;
1331    char *zMsg;
1332    va_start(ap, zErrMsg);
1333    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1334    va_end(ap);
1335    raw_printf(stderr, "line %d: ", p->lineno);
1336    utf8_printf(stderr, "%s\n", zMsg);
1337    exit(1);
1338  }
1339}
1340
1341/*
1342** SQL function:   edit(VALUE)
1343**                 edit(VALUE,EDITOR)
1344**
1345** These steps:
1346**
1347**     (1) Write VALUE into a temporary file.
1348**     (2) Run program EDITOR on that temporary file.
1349**     (3) Read the temporary file back and return its content as the result.
1350**     (4) Delete the temporary file
1351**
1352** If the EDITOR argument is omitted, use the value in the VISUAL
1353** environment variable.  If still there is no EDITOR, through an error.
1354**
1355** Also throw an error if the EDITOR program returns a non-zero exit code.
1356*/
1357#ifndef SQLITE_NOHAVE_SYSTEM
1358static void editFunc(
1359  sqlite3_context *context,
1360  int argc,
1361  sqlite3_value **argv
1362){
1363  const char *zEditor;
1364  char *zTempFile = 0;
1365  sqlite3 *db;
1366  char *zCmd = 0;
1367  int bBin;
1368  int rc;
1369  int hasCRNL = 0;
1370  FILE *f = 0;
1371  sqlite3_int64 sz;
1372  sqlite3_int64 x;
1373  unsigned char *p = 0;
1374
1375  if( argc==2 ){
1376    zEditor = (const char*)sqlite3_value_text(argv[1]);
1377  }else{
1378    zEditor = getenv("VISUAL");
1379  }
1380  if( zEditor==0 ){
1381    sqlite3_result_error(context, "no editor for edit()", -1);
1382    return;
1383  }
1384  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1385    sqlite3_result_error(context, "NULL input to edit()", -1);
1386    return;
1387  }
1388  db = sqlite3_context_db_handle(context);
1389  zTempFile = 0;
1390  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1391  if( zTempFile==0 ){
1392    sqlite3_uint64 r = 0;
1393    sqlite3_randomness(sizeof(r), &r);
1394    zTempFile = sqlite3_mprintf("temp%llx", r);
1395    if( zTempFile==0 ){
1396      sqlite3_result_error_nomem(context);
1397      return;
1398    }
1399  }
1400  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1401  /* When writing the file to be edited, do \n to \r\n conversions on systems
1402  ** that want \r\n line endings */
1403  f = fopen(zTempFile, bBin ? "wb" : "w");
1404  if( f==0 ){
1405    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1406    goto edit_func_end;
1407  }
1408  sz = sqlite3_value_bytes(argv[0]);
1409  if( bBin ){
1410    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1411  }else{
1412    const char *z = (const char*)sqlite3_value_text(argv[0]);
1413    /* Remember whether or not the value originally contained \r\n */
1414    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1415    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1416  }
1417  fclose(f);
1418  f = 0;
1419  if( x!=sz ){
1420    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1421    goto edit_func_end;
1422  }
1423  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1424  if( zCmd==0 ){
1425    sqlite3_result_error_nomem(context);
1426    goto edit_func_end;
1427  }
1428  rc = system(zCmd);
1429  sqlite3_free(zCmd);
1430  if( rc ){
1431    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1432    goto edit_func_end;
1433  }
1434  f = fopen(zTempFile, "rb");
1435  if( f==0 ){
1436    sqlite3_result_error(context,
1437      "edit() cannot reopen temp file after edit", -1);
1438    goto edit_func_end;
1439  }
1440  fseek(f, 0, SEEK_END);
1441  sz = ftell(f);
1442  rewind(f);
1443  p = sqlite3_malloc64( sz+1 );
1444  if( p==0 ){
1445    sqlite3_result_error_nomem(context);
1446    goto edit_func_end;
1447  }
1448  x = fread(p, 1, (size_t)sz, f);
1449  fclose(f);
1450  f = 0;
1451  if( x!=sz ){
1452    sqlite3_result_error(context, "could not read back the whole file", -1);
1453    goto edit_func_end;
1454  }
1455  if( bBin ){
1456    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1457  }else{
1458    sqlite3_int64 i, j;
1459    if( hasCRNL ){
1460      /* If the original contains \r\n then do no conversions back to \n */
1461    }else{
1462      /* If the file did not originally contain \r\n then convert any new
1463      ** \r\n back into \n */
1464      for(i=j=0; i<sz; i++){
1465        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1466        p[j++] = p[i];
1467      }
1468      sz = j;
1469      p[sz] = 0;
1470    }
1471    sqlite3_result_text64(context, (const char*)p, sz,
1472                          sqlite3_free, SQLITE_UTF8);
1473  }
1474  p = 0;
1475
1476edit_func_end:
1477  if( f ) fclose(f);
1478  unlink(zTempFile);
1479  sqlite3_free(zTempFile);
1480  sqlite3_free(p);
1481}
1482#endif /* SQLITE_NOHAVE_SYSTEM */
1483
1484/*
1485** Save or restore the current output mode
1486*/
1487static void outputModePush(ShellState *p){
1488  p->modePrior = p->mode;
1489  p->priorShFlgs = p->shellFlgs;
1490  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1491  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1492}
1493static void outputModePop(ShellState *p){
1494  p->mode = p->modePrior;
1495  p->shellFlgs = p->priorShFlgs;
1496  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1497  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1498}
1499
1500/*
1501** Output the given string as a hex-encoded blob (eg. X'1234' )
1502*/
1503static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1504  int i;
1505  char *zBlob = (char *)pBlob;
1506  raw_printf(out,"X'");
1507  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1508  raw_printf(out,"'");
1509}
1510
1511/*
1512** Find a string that is not found anywhere in z[].  Return a pointer
1513** to that string.
1514**
1515** Try to use zA and zB first.  If both of those are already found in z[]
1516** then make up some string and store it in the buffer zBuf.
1517*/
1518static const char *unused_string(
1519  const char *z,                    /* Result must not appear anywhere in z */
1520  const char *zA, const char *zB,   /* Try these first */
1521  char *zBuf                        /* Space to store a generated string */
1522){
1523  unsigned i = 0;
1524  if( strstr(z, zA)==0 ) return zA;
1525  if( strstr(z, zB)==0 ) return zB;
1526  do{
1527    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1528  }while( strstr(z,zBuf)!=0 );
1529  return zBuf;
1530}
1531
1532/*
1533** Output the given string as a quoted string using SQL quoting conventions.
1534**
1535** See also: output_quoted_escaped_string()
1536*/
1537static void output_quoted_string(FILE *out, const char *z){
1538  int i;
1539  char c;
1540  setBinaryMode(out, 1);
1541  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1542  if( c==0 ){
1543    utf8_printf(out,"'%s'",z);
1544  }else{
1545    raw_printf(out, "'");
1546    while( *z ){
1547      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1548      if( c=='\'' ) i++;
1549      if( i ){
1550        utf8_printf(out, "%.*s", i, z);
1551        z += i;
1552      }
1553      if( c=='\'' ){
1554        raw_printf(out, "'");
1555        continue;
1556      }
1557      if( c==0 ){
1558        break;
1559      }
1560      z++;
1561    }
1562    raw_printf(out, "'");
1563  }
1564  setTextMode(out, 1);
1565}
1566
1567/*
1568** Output the given string as a quoted string using SQL quoting conventions.
1569** Additionallly , escape the "\n" and "\r" characters so that they do not
1570** get corrupted by end-of-line translation facilities in some operating
1571** systems.
1572**
1573** This is like output_quoted_string() but with the addition of the \r\n
1574** escape mechanism.
1575*/
1576static void output_quoted_escaped_string(FILE *out, const char *z){
1577  int i;
1578  char c;
1579  setBinaryMode(out, 1);
1580  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1581  if( c==0 ){
1582    utf8_printf(out,"'%s'",z);
1583  }else{
1584    const char *zNL = 0;
1585    const char *zCR = 0;
1586    int nNL = 0;
1587    int nCR = 0;
1588    char zBuf1[20], zBuf2[20];
1589    for(i=0; z[i]; i++){
1590      if( z[i]=='\n' ) nNL++;
1591      if( z[i]=='\r' ) nCR++;
1592    }
1593    if( nNL ){
1594      raw_printf(out, "replace(");
1595      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1596    }
1597    if( nCR ){
1598      raw_printf(out, "replace(");
1599      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1600    }
1601    raw_printf(out, "'");
1602    while( *z ){
1603      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1604      if( c=='\'' ) i++;
1605      if( i ){
1606        utf8_printf(out, "%.*s", i, z);
1607        z += i;
1608      }
1609      if( c=='\'' ){
1610        raw_printf(out, "'");
1611        continue;
1612      }
1613      if( c==0 ){
1614        break;
1615      }
1616      z++;
1617      if( c=='\n' ){
1618        raw_printf(out, "%s", zNL);
1619        continue;
1620      }
1621      raw_printf(out, "%s", zCR);
1622    }
1623    raw_printf(out, "'");
1624    if( nCR ){
1625      raw_printf(out, ",'%s',char(13))", zCR);
1626    }
1627    if( nNL ){
1628      raw_printf(out, ",'%s',char(10))", zNL);
1629    }
1630  }
1631  setTextMode(out, 1);
1632}
1633
1634/*
1635** Output the given string as a quoted according to C or TCL quoting rules.
1636*/
1637static void output_c_string(FILE *out, const char *z){
1638  unsigned int c;
1639  fputc('"', out);
1640  while( (c = *(z++))!=0 ){
1641    if( c=='\\' ){
1642      fputc(c, out);
1643      fputc(c, out);
1644    }else if( c=='"' ){
1645      fputc('\\', out);
1646      fputc('"', out);
1647    }else if( c=='\t' ){
1648      fputc('\\', out);
1649      fputc('t', out);
1650    }else if( c=='\n' ){
1651      fputc('\\', out);
1652      fputc('n', out);
1653    }else if( c=='\r' ){
1654      fputc('\\', out);
1655      fputc('r', out);
1656    }else if( !isprint(c&0xff) ){
1657      raw_printf(out, "\\%03o", c&0xff);
1658    }else{
1659      fputc(c, out);
1660    }
1661  }
1662  fputc('"', out);
1663}
1664
1665/*
1666** Output the given string as a quoted according to JSON quoting rules.
1667*/
1668static void output_json_string(FILE *out, const char *z, int n){
1669  unsigned int c;
1670  if( n<0 ) n = (int)strlen(z);
1671  fputc('"', out);
1672  while( n-- ){
1673    c = *(z++);
1674    if( c=='\\' || c=='"' ){
1675      fputc('\\', out);
1676      fputc(c, out);
1677    }else if( c<=0x1f ){
1678      fputc('\\', out);
1679      if( c=='\b' ){
1680        fputc('b', out);
1681      }else if( c=='\f' ){
1682        fputc('f', out);
1683      }else if( c=='\n' ){
1684        fputc('n', out);
1685      }else if( c=='\r' ){
1686        fputc('r', out);
1687      }else if( c=='\t' ){
1688        fputc('t', out);
1689      }else{
1690         raw_printf(out, "u%04x",c);
1691      }
1692    }else{
1693      fputc(c, out);
1694    }
1695  }
1696  fputc('"', out);
1697}
1698
1699/*
1700** Output the given string with characters that are special to
1701** HTML escaped.
1702*/
1703static void output_html_string(FILE *out, const char *z){
1704  int i;
1705  if( z==0 ) z = "";
1706  while( *z ){
1707    for(i=0;   z[i]
1708            && z[i]!='<'
1709            && z[i]!='&'
1710            && z[i]!='>'
1711            && z[i]!='\"'
1712            && z[i]!='\'';
1713        i++){}
1714    if( i>0 ){
1715      utf8_printf(out,"%.*s",i,z);
1716    }
1717    if( z[i]=='<' ){
1718      raw_printf(out,"&lt;");
1719    }else if( z[i]=='&' ){
1720      raw_printf(out,"&amp;");
1721    }else if( z[i]=='>' ){
1722      raw_printf(out,"&gt;");
1723    }else if( z[i]=='\"' ){
1724      raw_printf(out,"&quot;");
1725    }else if( z[i]=='\'' ){
1726      raw_printf(out,"&#39;");
1727    }else{
1728      break;
1729    }
1730    z += i + 1;
1731  }
1732}
1733
1734/*
1735** If a field contains any character identified by a 1 in the following
1736** array, then the string must be quoted for CSV.
1737*/
1738static const char needCsvQuote[] = {
1739  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1740  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1741  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1742  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1743  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1744  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1745  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1746  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
1747  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1748  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1749  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1750  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1751  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1752  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1753  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1754  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1755};
1756
1757/*
1758** Output a single term of CSV.  Actually, p->colSeparator is used for
1759** the separator, which may or may not be a comma.  p->nullValue is
1760** the null value.  Strings are quoted if necessary.  The separator
1761** is only issued if bSep is true.
1762*/
1763static void output_csv(ShellState *p, const char *z, int bSep){
1764  FILE *out = p->out;
1765  if( z==0 ){
1766    utf8_printf(out,"%s",p->nullValue);
1767  }else{
1768    unsigned i;
1769    for(i=0; z[i]; i++){
1770      if( needCsvQuote[((unsigned char*)z)[i]] ){
1771        i = 0;
1772        break;
1773      }
1774    }
1775    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1776      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1777      shell_check_oom(zQuoted);
1778      utf8_printf(out, "%s", zQuoted);
1779      sqlite3_free(zQuoted);
1780    }else{
1781      utf8_printf(out, "%s", z);
1782    }
1783  }
1784  if( bSep ){
1785    utf8_printf(p->out, "%s", p->colSeparator);
1786  }
1787}
1788
1789/*
1790** This routine runs when the user presses Ctrl-C
1791*/
1792static void interrupt_handler(int NotUsed){
1793  UNUSED_PARAMETER(NotUsed);
1794  seenInterrupt++;
1795  if( seenInterrupt>2 ) exit(1);
1796  if( globalDb ) sqlite3_interrupt(globalDb);
1797}
1798
1799#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1800/*
1801** This routine runs for console events (e.g. Ctrl-C) on Win32
1802*/
1803static BOOL WINAPI ConsoleCtrlHandler(
1804  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1805){
1806  if( dwCtrlType==CTRL_C_EVENT ){
1807    interrupt_handler(0);
1808    return TRUE;
1809  }
1810  return FALSE;
1811}
1812#endif
1813
1814#ifndef SQLITE_OMIT_AUTHORIZATION
1815/*
1816** This authorizer runs in safe mode.
1817*/
1818static int safeModeAuth(
1819  void *pClientData,
1820  int op,
1821  const char *zA1,
1822  const char *zA2,
1823  const char *zA3,
1824  const char *zA4
1825){
1826  ShellState *p = (ShellState*)pClientData;
1827  static const char *azProhibitedFunctions[] = {
1828    "edit",
1829    "fts3_tokenizer",
1830    "load_extension",
1831    "readfile",
1832    "writefile",
1833    "zipfile",
1834    "zipfile_cds",
1835  };
1836  UNUSED_PARAMETER(zA2);
1837  UNUSED_PARAMETER(zA3);
1838  UNUSED_PARAMETER(zA4);
1839  switch( op ){
1840    case SQLITE_ATTACH: {
1841#ifndef SQLITE_SHELL_WASM_MODE
1842      /* In WASM builds the filesystem is a virtual sandbox, so
1843      ** there's no harm in using ATTACH. */
1844      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1845#endif
1846      break;
1847    }
1848    case SQLITE_FUNCTION: {
1849      int i;
1850      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1851        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1852          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1853                         azProhibitedFunctions[i]);
1854        }
1855      }
1856      break;
1857    }
1858  }
1859  return SQLITE_OK;
1860}
1861
1862/*
1863** When the ".auth ON" is set, the following authorizer callback is
1864** invoked.  It always returns SQLITE_OK.
1865*/
1866static int shellAuth(
1867  void *pClientData,
1868  int op,
1869  const char *zA1,
1870  const char *zA2,
1871  const char *zA3,
1872  const char *zA4
1873){
1874  ShellState *p = (ShellState*)pClientData;
1875  static const char *azAction[] = { 0,
1876     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1877     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1878     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1879     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1880     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1881     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1882     "PRAGMA",               "READ",                 "SELECT",
1883     "TRANSACTION",          "UPDATE",               "ATTACH",
1884     "DETACH",               "ALTER_TABLE",          "REINDEX",
1885     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1886     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1887  };
1888  int i;
1889  const char *az[4];
1890  az[0] = zA1;
1891  az[1] = zA2;
1892  az[2] = zA3;
1893  az[3] = zA4;
1894  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1895  for(i=0; i<4; i++){
1896    raw_printf(p->out, " ");
1897    if( az[i] ){
1898      output_c_string(p->out, az[i]);
1899    }else{
1900      raw_printf(p->out, "NULL");
1901    }
1902  }
1903  raw_printf(p->out, "\n");
1904  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1905  return SQLITE_OK;
1906}
1907#endif
1908
1909/*
1910** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1911**
1912** This routine converts some CREATE TABLE statements for shadow tables
1913** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1914*/
1915static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1916  if( z==0 ) return;
1917  if( zTail==0 ) return;
1918  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1919    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1920  }else{
1921    utf8_printf(out, "%s%s", z, zTail);
1922  }
1923}
1924static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1925  char c = z[n];
1926  z[n] = 0;
1927  printSchemaLine(out, z, zTail);
1928  z[n] = c;
1929}
1930
1931/*
1932** Return true if string z[] has nothing but whitespace and comments to the
1933** end of the first line.
1934*/
1935static int wsToEol(const char *z){
1936  int i;
1937  for(i=0; z[i]; i++){
1938    if( z[i]=='\n' ) return 1;
1939    if( IsSpace(z[i]) ) continue;
1940    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1941    return 0;
1942  }
1943  return 1;
1944}
1945
1946/*
1947** Add a new entry to the EXPLAIN QUERY PLAN data
1948*/
1949static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1950  EQPGraphRow *pNew;
1951  int nText = strlen30(zText);
1952  if( p->autoEQPtest ){
1953    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1954  }
1955  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1956  shell_check_oom(pNew);
1957  pNew->iEqpId = iEqpId;
1958  pNew->iParentId = p2;
1959  memcpy(pNew->zText, zText, nText+1);
1960  pNew->pNext = 0;
1961  if( p->sGraph.pLast ){
1962    p->sGraph.pLast->pNext = pNew;
1963  }else{
1964    p->sGraph.pRow = pNew;
1965  }
1966  p->sGraph.pLast = pNew;
1967}
1968
1969/*
1970** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1971** in p->sGraph.
1972*/
1973static void eqp_reset(ShellState *p){
1974  EQPGraphRow *pRow, *pNext;
1975  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1976    pNext = pRow->pNext;
1977    sqlite3_free(pRow);
1978  }
1979  memset(&p->sGraph, 0, sizeof(p->sGraph));
1980}
1981
1982/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1983** pOld, or return the first such line if pOld is NULL
1984*/
1985static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1986  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1987  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1988  return pRow;
1989}
1990
1991/* Render a single level of the graph that has iEqpId as its parent.  Called
1992** recursively to render sublevels.
1993*/
1994static void eqp_render_level(ShellState *p, int iEqpId){
1995  EQPGraphRow *pRow, *pNext;
1996  int n = strlen30(p->sGraph.zPrefix);
1997  char *z;
1998  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1999    pNext = eqp_next_row(p, iEqpId, pRow);
2000    z = pRow->zText;
2001    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2002                pNext ? "|--" : "`--", z);
2003    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2004      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2005      eqp_render_level(p, pRow->iEqpId);
2006      p->sGraph.zPrefix[n] = 0;
2007    }
2008  }
2009}
2010
2011/*
2012** Display and reset the EXPLAIN QUERY PLAN data
2013*/
2014static void eqp_render(ShellState *p){
2015  EQPGraphRow *pRow = p->sGraph.pRow;
2016  if( pRow ){
2017    if( pRow->zText[0]=='-' ){
2018      if( pRow->pNext==0 ){
2019        eqp_reset(p);
2020        return;
2021      }
2022      utf8_printf(p->out, "%s\n", pRow->zText+3);
2023      p->sGraph.pRow = pRow->pNext;
2024      sqlite3_free(pRow);
2025    }else{
2026      utf8_printf(p->out, "QUERY PLAN\n");
2027    }
2028    p->sGraph.zPrefix[0] = 0;
2029    eqp_render_level(p, 0);
2030    eqp_reset(p);
2031  }
2032}
2033
2034#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2035/*
2036** Progress handler callback.
2037*/
2038static int progress_handler(void *pClientData) {
2039  ShellState *p = (ShellState*)pClientData;
2040  p->nProgress++;
2041  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2042    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2043    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2044    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2045    return 1;
2046  }
2047  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2048    raw_printf(p->out, "Progress %u\n", p->nProgress);
2049  }
2050  return 0;
2051}
2052#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2053
2054/*
2055** Print N dashes
2056*/
2057static void print_dashes(FILE *out, int N){
2058  const char zDash[] = "--------------------------------------------------";
2059  const int nDash = sizeof(zDash) - 1;
2060  while( N>nDash ){
2061    fputs(zDash, out);
2062    N -= nDash;
2063  }
2064  raw_printf(out, "%.*s", N, zDash);
2065}
2066
2067/*
2068** Print a markdown or table-style row separator using ascii-art
2069*/
2070static void print_row_separator(
2071  ShellState *p,
2072  int nArg,
2073  const char *zSep
2074){
2075  int i;
2076  if( nArg>0 ){
2077    fputs(zSep, p->out);
2078    print_dashes(p->out, p->actualWidth[0]+2);
2079    for(i=1; i<nArg; i++){
2080      fputs(zSep, p->out);
2081      print_dashes(p->out, p->actualWidth[i]+2);
2082    }
2083    fputs(zSep, p->out);
2084  }
2085  fputs("\n", p->out);
2086}
2087
2088/*
2089** This is the callback routine that the shell
2090** invokes for each row of a query result.
2091*/
2092static int shell_callback(
2093  void *pArg,
2094  int nArg,        /* Number of result columns */
2095  char **azArg,    /* Text of each result column */
2096  char **azCol,    /* Column names */
2097  int *aiType      /* Column types.  Might be NULL */
2098){
2099  int i;
2100  ShellState *p = (ShellState*)pArg;
2101
2102  if( azArg==0 ) return 0;
2103  switch( p->cMode ){
2104    case MODE_Count:
2105    case MODE_Off: {
2106      break;
2107    }
2108    case MODE_Line: {
2109      int w = 5;
2110      if( azArg==0 ) break;
2111      for(i=0; i<nArg; i++){
2112        int len = strlen30(azCol[i] ? azCol[i] : "");
2113        if( len>w ) w = len;
2114      }
2115      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2116      for(i=0; i<nArg; i++){
2117        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2118                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2119      }
2120      break;
2121    }
2122    case MODE_Explain: {
2123      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2124      if( nArg>ArraySize(aExplainWidth) ){
2125        nArg = ArraySize(aExplainWidth);
2126      }
2127      if( p->cnt++==0 ){
2128        for(i=0; i<nArg; i++){
2129          int w = aExplainWidth[i];
2130          utf8_width_print(p->out, w, azCol[i]);
2131          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2132        }
2133        for(i=0; i<nArg; i++){
2134          int w = aExplainWidth[i];
2135          print_dashes(p->out, w);
2136          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2137        }
2138      }
2139      if( azArg==0 ) break;
2140      for(i=0; i<nArg; i++){
2141        int w = aExplainWidth[i];
2142        if( i==nArg-1 ) w = 0;
2143        if( azArg[i] && strlenChar(azArg[i])>w ){
2144          w = strlenChar(azArg[i]);
2145        }
2146        if( i==1 && p->aiIndent && p->pStmt ){
2147          if( p->iIndent<p->nIndent ){
2148            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2149          }
2150          p->iIndent++;
2151        }
2152        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2153        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2154      }
2155      break;
2156    }
2157    case MODE_Semi: {   /* .schema and .fullschema output */
2158      printSchemaLine(p->out, azArg[0], ";\n");
2159      break;
2160    }
2161    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2162      char *z;
2163      int j;
2164      int nParen = 0;
2165      char cEnd = 0;
2166      char c;
2167      int nLine = 0;
2168      assert( nArg==1 );
2169      if( azArg[0]==0 ) break;
2170      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2171       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2172      ){
2173        utf8_printf(p->out, "%s;\n", azArg[0]);
2174        break;
2175      }
2176      z = sqlite3_mprintf("%s", azArg[0]);
2177      shell_check_oom(z);
2178      j = 0;
2179      for(i=0; IsSpace(z[i]); i++){}
2180      for(; (c = z[i])!=0; i++){
2181        if( IsSpace(c) ){
2182          if( z[j-1]=='\r' ) z[j-1] = '\n';
2183          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2184        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2185          j--;
2186        }
2187        z[j++] = c;
2188      }
2189      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2190      z[j] = 0;
2191      if( strlen30(z)>=79 ){
2192        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2193          if( c==cEnd ){
2194            cEnd = 0;
2195          }else if( c=='"' || c=='\'' || c=='`' ){
2196            cEnd = c;
2197          }else if( c=='[' ){
2198            cEnd = ']';
2199          }else if( c=='-' && z[i+1]=='-' ){
2200            cEnd = '\n';
2201          }else if( c=='(' ){
2202            nParen++;
2203          }else if( c==')' ){
2204            nParen--;
2205            if( nLine>0 && nParen==0 && j>0 ){
2206              printSchemaLineN(p->out, z, j, "\n");
2207              j = 0;
2208            }
2209          }
2210          z[j++] = c;
2211          if( nParen==1 && cEnd==0
2212           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2213          ){
2214            if( c=='\n' ) j--;
2215            printSchemaLineN(p->out, z, j, "\n  ");
2216            j = 0;
2217            nLine++;
2218            while( IsSpace(z[i+1]) ){ i++; }
2219          }
2220        }
2221        z[j] = 0;
2222      }
2223      printSchemaLine(p->out, z, ";\n");
2224      sqlite3_free(z);
2225      break;
2226    }
2227    case MODE_List: {
2228      if( p->cnt++==0 && p->showHeader ){
2229        for(i=0; i<nArg; i++){
2230          utf8_printf(p->out,"%s%s",azCol[i],
2231                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2232        }
2233      }
2234      if( azArg==0 ) break;
2235      for(i=0; i<nArg; i++){
2236        char *z = azArg[i];
2237        if( z==0 ) z = p->nullValue;
2238        utf8_printf(p->out, "%s", z);
2239        if( i<nArg-1 ){
2240          utf8_printf(p->out, "%s", p->colSeparator);
2241        }else{
2242          utf8_printf(p->out, "%s", p->rowSeparator);
2243        }
2244      }
2245      break;
2246    }
2247    case MODE_Html: {
2248      if( p->cnt++==0 && p->showHeader ){
2249        raw_printf(p->out,"<TR>");
2250        for(i=0; i<nArg; i++){
2251          raw_printf(p->out,"<TH>");
2252          output_html_string(p->out, azCol[i]);
2253          raw_printf(p->out,"</TH>\n");
2254        }
2255        raw_printf(p->out,"</TR>\n");
2256      }
2257      if( azArg==0 ) break;
2258      raw_printf(p->out,"<TR>");
2259      for(i=0; i<nArg; i++){
2260        raw_printf(p->out,"<TD>");
2261        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2262        raw_printf(p->out,"</TD>\n");
2263      }
2264      raw_printf(p->out,"</TR>\n");
2265      break;
2266    }
2267    case MODE_Tcl: {
2268      if( p->cnt++==0 && p->showHeader ){
2269        for(i=0; i<nArg; i++){
2270          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2271          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2272        }
2273        utf8_printf(p->out, "%s", p->rowSeparator);
2274      }
2275      if( azArg==0 ) break;
2276      for(i=0; i<nArg; i++){
2277        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2278        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2279      }
2280      utf8_printf(p->out, "%s", p->rowSeparator);
2281      break;
2282    }
2283    case MODE_Csv: {
2284      setBinaryMode(p->out, 1);
2285      if( p->cnt++==0 && p->showHeader ){
2286        for(i=0; i<nArg; i++){
2287          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2288        }
2289        utf8_printf(p->out, "%s", p->rowSeparator);
2290      }
2291      if( nArg>0 ){
2292        for(i=0; i<nArg; i++){
2293          output_csv(p, azArg[i], i<nArg-1);
2294        }
2295        utf8_printf(p->out, "%s", p->rowSeparator);
2296      }
2297      setTextMode(p->out, 1);
2298      break;
2299    }
2300    case MODE_Insert: {
2301      if( azArg==0 ) break;
2302      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2303      if( p->showHeader ){
2304        raw_printf(p->out,"(");
2305        for(i=0; i<nArg; i++){
2306          if( i>0 ) raw_printf(p->out, ",");
2307          if( quoteChar(azCol[i]) ){
2308            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2309            shell_check_oom(z);
2310            utf8_printf(p->out, "%s", z);
2311            sqlite3_free(z);
2312          }else{
2313            raw_printf(p->out, "%s", azCol[i]);
2314          }
2315        }
2316        raw_printf(p->out,")");
2317      }
2318      p->cnt++;
2319      for(i=0; i<nArg; i++){
2320        raw_printf(p->out, i>0 ? "," : " VALUES(");
2321        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2322          utf8_printf(p->out,"NULL");
2323        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2324          if( ShellHasFlag(p, SHFLG_Newlines) ){
2325            output_quoted_string(p->out, azArg[i]);
2326          }else{
2327            output_quoted_escaped_string(p->out, azArg[i]);
2328          }
2329        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2330          utf8_printf(p->out,"%s", azArg[i]);
2331        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2332          char z[50];
2333          double r = sqlite3_column_double(p->pStmt, i);
2334          sqlite3_uint64 ur;
2335          memcpy(&ur,&r,sizeof(r));
2336          if( ur==0x7ff0000000000000LL ){
2337            raw_printf(p->out, "1e999");
2338          }else if( ur==0xfff0000000000000LL ){
2339            raw_printf(p->out, "-1e999");
2340          }else{
2341            sqlite3_int64 ir = (sqlite3_int64)r;
2342            if( r==(double)ir ){
2343              sqlite3_snprintf(50,z,"%lld.0", ir);
2344            }else{
2345              sqlite3_snprintf(50,z,"%!.20g", r);
2346            }
2347            raw_printf(p->out, "%s", z);
2348          }
2349        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2350          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2351          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2352          output_hex_blob(p->out, pBlob, nBlob);
2353        }else if( isNumber(azArg[i], 0) ){
2354          utf8_printf(p->out,"%s", azArg[i]);
2355        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2356          output_quoted_string(p->out, azArg[i]);
2357        }else{
2358          output_quoted_escaped_string(p->out, azArg[i]);
2359        }
2360      }
2361      raw_printf(p->out,");\n");
2362      break;
2363    }
2364    case MODE_Json: {
2365      if( azArg==0 ) break;
2366      if( p->cnt==0 ){
2367        fputs("[{", p->out);
2368      }else{
2369        fputs(",\n{", p->out);
2370      }
2371      p->cnt++;
2372      for(i=0; i<nArg; i++){
2373        output_json_string(p->out, azCol[i], -1);
2374        putc(':', p->out);
2375        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2376          fputs("null",p->out);
2377        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2378          char z[50];
2379          double r = sqlite3_column_double(p->pStmt, i);
2380          sqlite3_uint64 ur;
2381          memcpy(&ur,&r,sizeof(r));
2382          if( ur==0x7ff0000000000000LL ){
2383            raw_printf(p->out, "1e999");
2384          }else if( ur==0xfff0000000000000LL ){
2385            raw_printf(p->out, "-1e999");
2386          }else{
2387            sqlite3_snprintf(50,z,"%!.20g", r);
2388            raw_printf(p->out, "%s", z);
2389          }
2390        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2391          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2392          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2393          output_json_string(p->out, pBlob, nBlob);
2394        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2395          output_json_string(p->out, azArg[i], -1);
2396        }else{
2397          utf8_printf(p->out,"%s", azArg[i]);
2398        }
2399        if( i<nArg-1 ){
2400          putc(',', p->out);
2401        }
2402      }
2403      putc('}', p->out);
2404      break;
2405    }
2406    case MODE_Quote: {
2407      if( azArg==0 ) break;
2408      if( p->cnt==0 && p->showHeader ){
2409        for(i=0; i<nArg; i++){
2410          if( i>0 ) fputs(p->colSeparator, p->out);
2411          output_quoted_string(p->out, azCol[i]);
2412        }
2413        fputs(p->rowSeparator, p->out);
2414      }
2415      p->cnt++;
2416      for(i=0; i<nArg; i++){
2417        if( i>0 ) fputs(p->colSeparator, p->out);
2418        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2419          utf8_printf(p->out,"NULL");
2420        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2421          output_quoted_string(p->out, azArg[i]);
2422        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2423          utf8_printf(p->out,"%s", azArg[i]);
2424        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2425          char z[50];
2426          double r = sqlite3_column_double(p->pStmt, i);
2427          sqlite3_snprintf(50,z,"%!.20g", r);
2428          raw_printf(p->out, "%s", z);
2429        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2430          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2431          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2432          output_hex_blob(p->out, pBlob, nBlob);
2433        }else if( isNumber(azArg[i], 0) ){
2434          utf8_printf(p->out,"%s", azArg[i]);
2435        }else{
2436          output_quoted_string(p->out, azArg[i]);
2437        }
2438      }
2439      fputs(p->rowSeparator, p->out);
2440      break;
2441    }
2442    case MODE_Ascii: {
2443      if( p->cnt++==0 && p->showHeader ){
2444        for(i=0; i<nArg; i++){
2445          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2446          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2447        }
2448        utf8_printf(p->out, "%s", p->rowSeparator);
2449      }
2450      if( azArg==0 ) break;
2451      for(i=0; i<nArg; i++){
2452        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2453        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2454      }
2455      utf8_printf(p->out, "%s", p->rowSeparator);
2456      break;
2457    }
2458    case MODE_EQP: {
2459      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2460      break;
2461    }
2462  }
2463  return 0;
2464}
2465
2466/*
2467** This is the callback routine that the SQLite library
2468** invokes for each row of a query result.
2469*/
2470static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2471  /* since we don't have type info, call the shell_callback with a NULL value */
2472  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2473}
2474
2475/*
2476** This is the callback routine from sqlite3_exec() that appends all
2477** output onto the end of a ShellText object.
2478*/
2479static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2480  ShellText *p = (ShellText*)pArg;
2481  int i;
2482  UNUSED_PARAMETER(az);
2483  if( azArg==0 ) return 0;
2484  if( p->n ) appendText(p, "|", 0);
2485  for(i=0; i<nArg; i++){
2486    if( i ) appendText(p, ",", 0);
2487    if( azArg[i] ) appendText(p, azArg[i], 0);
2488  }
2489  return 0;
2490}
2491
2492/*
2493** Generate an appropriate SELFTEST table in the main database.
2494*/
2495static void createSelftestTable(ShellState *p){
2496  char *zErrMsg = 0;
2497  sqlite3_exec(p->db,
2498    "SAVEPOINT selftest_init;\n"
2499    "CREATE TABLE IF NOT EXISTS selftest(\n"
2500    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2501    "  op TEXT,\n"                   /* Operator:  memo run */
2502    "  cmd TEXT,\n"                  /* Command text */
2503    "  ans TEXT\n"                   /* Desired answer */
2504    ");"
2505    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2506    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2507    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2508    "         'memo','Tests generated by --init');\n"
2509    "INSERT INTO [_shell$self]\n"
2510    "  SELECT 'run',\n"
2511    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2512                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2513    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2514                          "FROM sqlite_schema ORDER BY 2',224));\n"
2515    "INSERT INTO [_shell$self]\n"
2516    "  SELECT 'run',"
2517    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2518    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2519    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2520    "  FROM (\n"
2521    "    SELECT name FROM sqlite_schema\n"
2522    "     WHERE type='table'\n"
2523    "       AND name<>'selftest'\n"
2524    "       AND coalesce(rootpage,0)>0\n"
2525    "  )\n"
2526    " ORDER BY name;\n"
2527    "INSERT INTO [_shell$self]\n"
2528    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2529    "INSERT INTO selftest(tno,op,cmd,ans)"
2530    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2531    "DROP TABLE [_shell$self];"
2532    ,0,0,&zErrMsg);
2533  if( zErrMsg ){
2534    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2535    sqlite3_free(zErrMsg);
2536  }
2537  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2538}
2539
2540
2541/*
2542** Set the destination table field of the ShellState structure to
2543** the name of the table given.  Escape any quote characters in the
2544** table name.
2545*/
2546static void set_table_name(ShellState *p, const char *zName){
2547  int i, n;
2548  char cQuote;
2549  char *z;
2550
2551  if( p->zDestTable ){
2552    free(p->zDestTable);
2553    p->zDestTable = 0;
2554  }
2555  if( zName==0 ) return;
2556  cQuote = quoteChar(zName);
2557  n = strlen30(zName);
2558  if( cQuote ) n += n+2;
2559  z = p->zDestTable = malloc( n+1 );
2560  shell_check_oom(z);
2561  n = 0;
2562  if( cQuote ) z[n++] = cQuote;
2563  for(i=0; zName[i]; i++){
2564    z[n++] = zName[i];
2565    if( zName[i]==cQuote ) z[n++] = cQuote;
2566  }
2567  if( cQuote ) z[n++] = cQuote;
2568  z[n] = 0;
2569}
2570
2571/*
2572** Maybe construct two lines of text that point out the position of a
2573** syntax error.  Return a pointer to the text, in memory obtained from
2574** sqlite3_malloc().  Or, if the most recent error does not involve a
2575** specific token that we can point to, return an empty string.
2576**
2577** In all cases, the memory returned is obtained from sqlite3_malloc64()
2578** and should be released by the caller invoking sqlite3_free().
2579*/
2580static char *shell_error_context(const char *zSql, sqlite3 *db){
2581  int iOffset;
2582  size_t len;
2583  char *zCode;
2584  char *zMsg;
2585  int i;
2586  if( db==0
2587   || zSql==0
2588   || (iOffset = sqlite3_error_offset(db))<0
2589  ){
2590    return sqlite3_mprintf("");
2591  }
2592  while( iOffset>50 ){
2593    iOffset--;
2594    zSql++;
2595    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2596  }
2597  len = strlen(zSql);
2598  if( len>78 ){
2599    len = 78;
2600    while( (zSql[len]&0xc0)==0x80 ) len--;
2601  }
2602  zCode = sqlite3_mprintf("%.*s", len, zSql);
2603  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2604  if( iOffset<25 ){
2605    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2606  }else{
2607    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2608  }
2609  return zMsg;
2610}
2611
2612
2613/*
2614** Execute a query statement that will generate SQL output.  Print
2615** the result columns, comma-separated, on a line and then add a
2616** semicolon terminator to the end of that line.
2617**
2618** If the number of columns is 1 and that column contains text "--"
2619** then write the semicolon on a separate line.  That way, if a
2620** "--" comment occurs at the end of the statement, the comment
2621** won't consume the semicolon terminator.
2622*/
2623static int run_table_dump_query(
2624  ShellState *p,           /* Query context */
2625  const char *zSelect      /* SELECT statement to extract content */
2626){
2627  sqlite3_stmt *pSelect;
2628  int rc;
2629  int nResult;
2630  int i;
2631  const char *z;
2632  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2633  if( rc!=SQLITE_OK || !pSelect ){
2634    char *zContext = shell_error_context(zSelect, p->db);
2635    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2636                sqlite3_errmsg(p->db), zContext);
2637    sqlite3_free(zContext);
2638    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2639    return rc;
2640  }
2641  rc = sqlite3_step(pSelect);
2642  nResult = sqlite3_column_count(pSelect);
2643  while( rc==SQLITE_ROW ){
2644    z = (const char*)sqlite3_column_text(pSelect, 0);
2645    utf8_printf(p->out, "%s", z);
2646    for(i=1; i<nResult; i++){
2647      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2648    }
2649    if( z==0 ) z = "";
2650    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2651    if( z[0] ){
2652      raw_printf(p->out, "\n;\n");
2653    }else{
2654      raw_printf(p->out, ";\n");
2655    }
2656    rc = sqlite3_step(pSelect);
2657  }
2658  rc = sqlite3_finalize(pSelect);
2659  if( rc!=SQLITE_OK ){
2660    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2661                sqlite3_errmsg(p->db));
2662    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2663  }
2664  return rc;
2665}
2666
2667/*
2668** Allocate space and save off string indicating current error.
2669*/
2670static char *save_err_msg(
2671  sqlite3 *db,           /* Database to query */
2672  const char *zPhase,    /* When the error occcurs */
2673  int rc,                /* Error code returned from API */
2674  const char *zSql       /* SQL string, or NULL */
2675){
2676  char *zErr;
2677  char *zContext;
2678  sqlite3_str *pStr = sqlite3_str_new(0);
2679  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2680  if( rc>1 ){
2681    sqlite3_str_appendf(pStr, " (%d)", rc);
2682  }
2683  zContext = shell_error_context(zSql, db);
2684  if( zContext ){
2685    sqlite3_str_appendall(pStr, zContext);
2686    sqlite3_free(zContext);
2687  }
2688  zErr = sqlite3_str_finish(pStr);
2689  shell_check_oom(zErr);
2690  return zErr;
2691}
2692
2693#ifdef __linux__
2694/*
2695** Attempt to display I/O stats on Linux using /proc/PID/io
2696*/
2697static void displayLinuxIoStats(FILE *out){
2698  FILE *in;
2699  char z[200];
2700  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2701  in = fopen(z, "rb");
2702  if( in==0 ) return;
2703  while( fgets(z, sizeof(z), in)!=0 ){
2704    static const struct {
2705      const char *zPattern;
2706      const char *zDesc;
2707    } aTrans[] = {
2708      { "rchar: ",                  "Bytes received by read():" },
2709      { "wchar: ",                  "Bytes sent to write():"    },
2710      { "syscr: ",                  "Read() system calls:"      },
2711      { "syscw: ",                  "Write() system calls:"     },
2712      { "read_bytes: ",             "Bytes read from storage:"  },
2713      { "write_bytes: ",            "Bytes written to storage:" },
2714      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2715    };
2716    int i;
2717    for(i=0; i<ArraySize(aTrans); i++){
2718      int n = strlen30(aTrans[i].zPattern);
2719      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2720        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2721        break;
2722      }
2723    }
2724  }
2725  fclose(in);
2726}
2727#endif
2728
2729/*
2730** Display a single line of status using 64-bit values.
2731*/
2732static void displayStatLine(
2733  ShellState *p,            /* The shell context */
2734  char *zLabel,             /* Label for this one line */
2735  char *zFormat,            /* Format for the result */
2736  int iStatusCtrl,          /* Which status to display */
2737  int bReset                /* True to reset the stats */
2738){
2739  sqlite3_int64 iCur = -1;
2740  sqlite3_int64 iHiwtr = -1;
2741  int i, nPercent;
2742  char zLine[200];
2743  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2744  for(i=0, nPercent=0; zFormat[i]; i++){
2745    if( zFormat[i]=='%' ) nPercent++;
2746  }
2747  if( nPercent>1 ){
2748    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2749  }else{
2750    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2751  }
2752  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2753}
2754
2755/*
2756** Display memory stats.
2757*/
2758static int display_stats(
2759  sqlite3 *db,                /* Database to query */
2760  ShellState *pArg,           /* Pointer to ShellState */
2761  int bReset                  /* True to reset the stats */
2762){
2763  int iCur;
2764  int iHiwtr;
2765  FILE *out;
2766  if( pArg==0 || pArg->out==0 ) return 0;
2767  out = pArg->out;
2768
2769  if( pArg->pStmt && pArg->statsOn==2 ){
2770    int nCol, i, x;
2771    sqlite3_stmt *pStmt = pArg->pStmt;
2772    char z[100];
2773    nCol = sqlite3_column_count(pStmt);
2774    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2775    for(i=0; i<nCol; i++){
2776      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2777      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2778#ifndef SQLITE_OMIT_DECLTYPE
2779      sqlite3_snprintf(30, z+x, "declared type:");
2780      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2781#endif
2782#ifdef SQLITE_ENABLE_COLUMN_METADATA
2783      sqlite3_snprintf(30, z+x, "database name:");
2784      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2785      sqlite3_snprintf(30, z+x, "table name:");
2786      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2787      sqlite3_snprintf(30, z+x, "origin name:");
2788      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2789#endif
2790    }
2791  }
2792
2793  if( pArg->statsOn==3 ){
2794    if( pArg->pStmt ){
2795      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2796      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2797    }
2798    return 0;
2799  }
2800
2801  displayStatLine(pArg, "Memory Used:",
2802     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2803  displayStatLine(pArg, "Number of Outstanding Allocations:",
2804     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2805  if( pArg->shellFlgs & SHFLG_Pagecache ){
2806    displayStatLine(pArg, "Number of Pcache Pages Used:",
2807       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2808  }
2809  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2810     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2811  displayStatLine(pArg, "Largest Allocation:",
2812     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2813  displayStatLine(pArg, "Largest Pcache Allocation:",
2814     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2815#ifdef YYTRACKMAXSTACKDEPTH
2816  displayStatLine(pArg, "Deepest Parser Stack:",
2817     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2818#endif
2819
2820  if( db ){
2821    if( pArg->shellFlgs & SHFLG_Lookaside ){
2822      iHiwtr = iCur = -1;
2823      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2824                        &iCur, &iHiwtr, bReset);
2825      raw_printf(pArg->out,
2826              "Lookaside Slots Used:                %d (max %d)\n",
2827              iCur, iHiwtr);
2828      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2829                        &iCur, &iHiwtr, bReset);
2830      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2831              iHiwtr);
2832      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2833                        &iCur, &iHiwtr, bReset);
2834      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2835              iHiwtr);
2836      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2837                        &iCur, &iHiwtr, bReset);
2838      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2839              iHiwtr);
2840    }
2841    iHiwtr = iCur = -1;
2842    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2843    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2844            iCur);
2845    iHiwtr = iCur = -1;
2846    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2847    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2848    iHiwtr = iCur = -1;
2849    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2850    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2851    iHiwtr = iCur = -1;
2852    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2853    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2854    iHiwtr = iCur = -1;
2855    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2856    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2857    iHiwtr = iCur = -1;
2858    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2859    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2860            iCur);
2861    iHiwtr = iCur = -1;
2862    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2863    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2864            iCur);
2865  }
2866
2867  if( pArg->pStmt ){
2868    int iHit, iMiss;
2869    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2870                               bReset);
2871    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2872    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2873    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2874    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2875    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2876    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2877    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2878    if( iHit || iMiss ){
2879      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2880            iHit, iHit+iMiss);
2881    }
2882    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2883    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2884    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2885    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2886    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2887    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2888    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2889    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2890  }
2891
2892#ifdef __linux__
2893  displayLinuxIoStats(pArg->out);
2894#endif
2895
2896  /* Do not remove this machine readable comment: extra-stats-output-here */
2897
2898  return 0;
2899}
2900
2901/*
2902** Display scan stats.
2903*/
2904static void display_scanstats(
2905  sqlite3 *db,                    /* Database to query */
2906  ShellState *pArg                /* Pointer to ShellState */
2907){
2908#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2909  UNUSED_PARAMETER(db);
2910  UNUSED_PARAMETER(pArg);
2911#else
2912  int i, k, n, mx;
2913  raw_printf(pArg->out, "-------- scanstats --------\n");
2914  mx = 0;
2915  for(k=0; k<=mx; k++){
2916    double rEstLoop = 1.0;
2917    for(i=n=0; 1; i++){
2918      sqlite3_stmt *p = pArg->pStmt;
2919      sqlite3_int64 nLoop, nVisit;
2920      double rEst;
2921      int iSid;
2922      const char *zExplain;
2923      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2924        break;
2925      }
2926      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2927      if( iSid>mx ) mx = iSid;
2928      if( iSid!=k ) continue;
2929      if( n==0 ){
2930        rEstLoop = (double)nLoop;
2931        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2932      }
2933      n++;
2934      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2935      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2936      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2937      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2938      rEstLoop *= rEst;
2939      raw_printf(pArg->out,
2940          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2941          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2942      );
2943    }
2944  }
2945  raw_printf(pArg->out, "---------------------------\n");
2946#endif
2947}
2948
2949/*
2950** Parameter azArray points to a zero-terminated array of strings. zStr
2951** points to a single nul-terminated string. Return non-zero if zStr
2952** is equal, according to strcmp(), to any of the strings in the array.
2953** Otherwise, return zero.
2954*/
2955static int str_in_array(const char *zStr, const char **azArray){
2956  int i;
2957  for(i=0; azArray[i]; i++){
2958    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2959  }
2960  return 0;
2961}
2962
2963/*
2964** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2965** and populate the ShellState.aiIndent[] array with the number of
2966** spaces each opcode should be indented before it is output.
2967**
2968** The indenting rules are:
2969**
2970**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2971**       all opcodes that occur between the p2 jump destination and the opcode
2972**       itself by 2 spaces.
2973**
2974**     * Do the previous for "Return" instructions for when P2 is positive.
2975**       See tag-20220407a in wherecode.c and vdbe.c.
2976**
2977**     * For each "Goto", if the jump destination is earlier in the program
2978**       and ends on one of:
2979**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2980**       or if the P1 parameter is one instead of zero,
2981**       then indent all opcodes between the earlier instruction
2982**       and "Goto" by 2 spaces.
2983*/
2984static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2985  const char *zSql;               /* The text of the SQL statement */
2986  const char *z;                  /* Used to check if this is an EXPLAIN */
2987  int *abYield = 0;               /* True if op is an OP_Yield */
2988  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2989  int iOp;                        /* Index of operation in p->aiIndent[] */
2990
2991  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2992                           "Return", 0 };
2993  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2994                            "Rewind", 0 };
2995  const char *azGoto[] = { "Goto", 0 };
2996
2997  /* Try to figure out if this is really an EXPLAIN statement. If this
2998  ** cannot be verified, return early.  */
2999  if( sqlite3_column_count(pSql)!=8 ){
3000    p->cMode = p->mode;
3001    return;
3002  }
3003  zSql = sqlite3_sql(pSql);
3004  if( zSql==0 ) return;
3005  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3006  if( sqlite3_strnicmp(z, "explain", 7) ){
3007    p->cMode = p->mode;
3008    return;
3009  }
3010
3011  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3012    int i;
3013    int iAddr = sqlite3_column_int(pSql, 0);
3014    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3015
3016    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3017    ** p2 is an instruction address, set variable p2op to the index of that
3018    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3019    ** the current instruction is part of a sub-program generated by an
3020    ** SQL trigger or foreign key.  */
3021    int p2 = sqlite3_column_int(pSql, 3);
3022    int p2op = (p2 + (iOp-iAddr));
3023
3024    /* Grow the p->aiIndent array as required */
3025    if( iOp>=nAlloc ){
3026      if( iOp==0 ){
3027        /* Do further verfication that this is explain output.  Abort if
3028        ** it is not */
3029        static const char *explainCols[] = {
3030           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3031        int jj;
3032        for(jj=0; jj<ArraySize(explainCols); jj++){
3033          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3034            p->cMode = p->mode;
3035            sqlite3_reset(pSql);
3036            return;
3037          }
3038        }
3039      }
3040      nAlloc += 100;
3041      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3042      shell_check_oom(p->aiIndent);
3043      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3044      shell_check_oom(abYield);
3045    }
3046    abYield[iOp] = str_in_array(zOp, azYield);
3047    p->aiIndent[iOp] = 0;
3048    p->nIndent = iOp+1;
3049
3050    if( str_in_array(zOp, azNext) && p2op>0 ){
3051      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3052    }
3053    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3054     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3055    ){
3056      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3057    }
3058  }
3059
3060  p->iIndent = 0;
3061  sqlite3_free(abYield);
3062  sqlite3_reset(pSql);
3063}
3064
3065/*
3066** Free the array allocated by explain_data_prepare().
3067*/
3068static void explain_data_delete(ShellState *p){
3069  sqlite3_free(p->aiIndent);
3070  p->aiIndent = 0;
3071  p->nIndent = 0;
3072  p->iIndent = 0;
3073}
3074
3075/*
3076** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3077*/
3078static unsigned int savedSelectTrace;
3079static unsigned int savedWhereTrace;
3080static void disable_debug_trace_modes(void){
3081  unsigned int zero = 0;
3082  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3083  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3084  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3085  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3086}
3087static void restore_debug_trace_modes(void){
3088  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3089  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3090}
3091
3092/* Create the TEMP table used to store parameter bindings */
3093static void bind_table_init(ShellState *p){
3094  int wrSchema = 0;
3095  int defensiveMode = 0;
3096  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3097  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3098  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3099  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3100  sqlite3_exec(p->db,
3101    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3102    "  key TEXT PRIMARY KEY,\n"
3103    "  value\n"
3104    ") WITHOUT ROWID;",
3105    0, 0, 0);
3106  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3107  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3108}
3109
3110/*
3111** Bind parameters on a prepared statement.
3112**
3113** Parameter bindings are taken from a TEMP table of the form:
3114**
3115**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3116**    WITHOUT ROWID;
3117**
3118** No bindings occur if this table does not exist.  The name of the table
3119** begins with "sqlite_" so that it will not collide with ordinary application
3120** tables.  The table must be in the TEMP schema.
3121*/
3122static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3123  int nVar;
3124  int i;
3125  int rc;
3126  sqlite3_stmt *pQ = 0;
3127
3128  nVar = sqlite3_bind_parameter_count(pStmt);
3129  if( nVar==0 ) return;  /* Nothing to do */
3130  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3131                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3132    return; /* Parameter table does not exist */
3133  }
3134  rc = sqlite3_prepare_v2(pArg->db,
3135          "SELECT value FROM temp.sqlite_parameters"
3136          " WHERE key=?1", -1, &pQ, 0);
3137  if( rc || pQ==0 ) return;
3138  for(i=1; i<=nVar; i++){
3139    char zNum[30];
3140    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3141    if( zVar==0 ){
3142      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3143      zVar = zNum;
3144    }
3145    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3146    if( sqlite3_step(pQ)==SQLITE_ROW ){
3147      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3148    }else{
3149      sqlite3_bind_null(pStmt, i);
3150    }
3151    sqlite3_reset(pQ);
3152  }
3153  sqlite3_finalize(pQ);
3154}
3155
3156/*
3157** UTF8 box-drawing characters.  Imagine box lines like this:
3158**
3159**           1
3160**           |
3161**       4 --+-- 2
3162**           |
3163**           3
3164**
3165** Each box characters has between 2 and 4 of the lines leading from
3166** the center.  The characters are here identified by the numbers of
3167** their corresponding lines.
3168*/
3169#define BOX_24   "\342\224\200"  /* U+2500 --- */
3170#define BOX_13   "\342\224\202"  /* U+2502  |  */
3171#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3172#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3173#define BOX_12   "\342\224\224"  /* U+2514  '- */
3174#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3175#define BOX_123  "\342\224\234"  /* U+251c  |- */
3176#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3177#define BOX_234  "\342\224\254"  /* U+252c -,- */
3178#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3179#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3180
3181/* Draw horizontal line N characters long using unicode box
3182** characters
3183*/
3184static void print_box_line(FILE *out, int N){
3185  const char zDash[] =
3186      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3187      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3188  const int nDash = sizeof(zDash) - 1;
3189  N *= 3;
3190  while( N>nDash ){
3191    utf8_printf(out, zDash);
3192    N -= nDash;
3193  }
3194  utf8_printf(out, "%.*s", N, zDash);
3195}
3196
3197/*
3198** Draw a horizontal separator for a MODE_Box table.
3199*/
3200static void print_box_row_separator(
3201  ShellState *p,
3202  int nArg,
3203  const char *zSep1,
3204  const char *zSep2,
3205  const char *zSep3
3206){
3207  int i;
3208  if( nArg>0 ){
3209    utf8_printf(p->out, "%s", zSep1);
3210    print_box_line(p->out, p->actualWidth[0]+2);
3211    for(i=1; i<nArg; i++){
3212      utf8_printf(p->out, "%s", zSep2);
3213      print_box_line(p->out, p->actualWidth[i]+2);
3214    }
3215    utf8_printf(p->out, "%s", zSep3);
3216  }
3217  fputs("\n", p->out);
3218}
3219
3220/*
3221** z[] is a line of text that is to be displayed the .mode box or table or
3222** similar tabular formats.  z[] might contain control characters such
3223** as \n, \t, \f, or \r.
3224**
3225** Compute characters to display on the first line of z[].  Stop at the
3226** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3227** from malloc()) of that first line, which caller should free sometime.
3228** Write anything to display on the next line into *pzTail.  If this is
3229** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3230*/
3231static char *translateForDisplayAndDup(
3232  const unsigned char *z,            /* Input text to be transformed */
3233  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3234  int mxWidth,                       /* Max width.  0 means no limit */
3235  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3236){
3237  int i;                 /* Input bytes consumed */
3238  int j;                 /* Output bytes generated */
3239  int k;                 /* Input bytes to be displayed */
3240  int n;                 /* Output column number */
3241  unsigned char *zOut;   /* Output text */
3242
3243  if( z==0 ){
3244    *pzTail = 0;
3245    return 0;
3246  }
3247  if( mxWidth<0 ) mxWidth = -mxWidth;
3248  if( mxWidth==0 ) mxWidth = 1000000;
3249  i = j = n = 0;
3250  while( n<mxWidth ){
3251    if( z[i]>=' ' ){
3252      n++;
3253      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3254      continue;
3255    }
3256    if( z[i]=='\t' ){
3257      do{
3258        n++;
3259        j++;
3260      }while( (n&7)!=0 && n<mxWidth );
3261      i++;
3262      continue;
3263    }
3264    break;
3265  }
3266  if( n>=mxWidth && bWordWrap  ){
3267    /* Perhaps try to back up to a better place to break the line */
3268    for(k=i; k>i/2; k--){
3269      if( isspace(z[k-1]) ) break;
3270    }
3271    if( k<=i/2 ){
3272      for(k=i; k>i/2; k--){
3273        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3274      }
3275    }
3276    if( k<=i/2 ){
3277      k = i;
3278    }else{
3279      i = k;
3280      while( z[i]==' ' ) i++;
3281    }
3282  }else{
3283    k = i;
3284  }
3285  if( n>=mxWidth && z[i]>=' ' ){
3286   *pzTail = &z[i];
3287  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3288    *pzTail = z[i+2] ? &z[i+2] : 0;
3289  }else if( z[i]==0 || z[i+1]==0 ){
3290    *pzTail = 0;
3291  }else{
3292    *pzTail = &z[i+1];
3293  }
3294  zOut = malloc( j+1 );
3295  shell_check_oom(zOut);
3296  i = j = n = 0;
3297  while( i<k ){
3298    if( z[i]>=' ' ){
3299      n++;
3300      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3301      continue;
3302    }
3303    if( z[i]=='\t' ){
3304      do{
3305        n++;
3306        zOut[j++] = ' ';
3307      }while( (n&7)!=0 && n<mxWidth );
3308      i++;
3309      continue;
3310    }
3311    break;
3312  }
3313  zOut[j] = 0;
3314  return (char*)zOut;
3315}
3316
3317/* Extract the value of the i-th current column for pStmt as an SQL literal
3318** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3319** the caller.
3320*/
3321static char *quoted_column(sqlite3_stmt *pStmt, int i){
3322  switch( sqlite3_column_type(pStmt, i) ){
3323    case SQLITE_NULL: {
3324      return sqlite3_mprintf("NULL");
3325    }
3326    case SQLITE_INTEGER:
3327    case SQLITE_FLOAT: {
3328      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3329    }
3330    case SQLITE_TEXT: {
3331      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3332    }
3333    case SQLITE_BLOB: {
3334      int j;
3335      sqlite3_str *pStr = sqlite3_str_new(0);
3336      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3337      int n = sqlite3_column_bytes(pStmt,i);
3338      sqlite3_str_append(pStr, "x'", 2);
3339      for(j=0; j<n; j++){
3340        sqlite3_str_appendf(pStr, "%02x", a[j]);
3341      }
3342      sqlite3_str_append(pStr, "'", 1);
3343      return sqlite3_str_finish(pStr);
3344    }
3345  }
3346  return 0; /* Not reached */
3347}
3348
3349/*
3350** Run a prepared statement and output the result in one of the
3351** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3352** or MODE_Box.
3353**
3354** This is different from ordinary exec_prepared_stmt() in that
3355** it has to run the entire query and gather the results into memory
3356** first, in order to determine column widths, before providing
3357** any output.
3358*/
3359static void exec_prepared_stmt_columnar(
3360  ShellState *p,                        /* Pointer to ShellState */
3361  sqlite3_stmt *pStmt                   /* Statment to run */
3362){
3363  sqlite3_int64 nRow = 0;
3364  int nColumn = 0;
3365  char **azData = 0;
3366  sqlite3_int64 nAlloc = 0;
3367  char *abRowDiv = 0;
3368  const unsigned char *uz;
3369  const char *z;
3370  char **azQuoted = 0;
3371  int rc;
3372  sqlite3_int64 i, nData;
3373  int j, nTotal, w, n;
3374  const char *colSep = 0;
3375  const char *rowSep = 0;
3376  const unsigned char **azNextLine = 0;
3377  int bNextLine = 0;
3378  int bMultiLineRowExists = 0;
3379  int bw = p->cmOpts.bWordWrap;
3380  const char *zEmpty = "";
3381  const char *zShowNull = p->nullValue;
3382
3383  rc = sqlite3_step(pStmt);
3384  if( rc!=SQLITE_ROW ) return;
3385  nColumn = sqlite3_column_count(pStmt);
3386  nAlloc = nColumn*4;
3387  if( nAlloc<=0 ) nAlloc = 1;
3388  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3389  shell_check_oom(azData);
3390  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3391  shell_check_oom((void*)azNextLine);
3392  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3393  if( p->cmOpts.bQuote ){
3394    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3395    shell_check_oom(azQuoted);
3396    memset(azQuoted, 0, nColumn*sizeof(char*) );
3397  }
3398  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3399  shell_check_oom(abRowDiv);
3400  if( nColumn>p->nWidth ){
3401    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3402    shell_check_oom(p->colWidth);
3403    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3404    p->nWidth = nColumn;
3405    p->actualWidth = &p->colWidth[nColumn];
3406  }
3407  memset(p->actualWidth, 0, nColumn*sizeof(int));
3408  for(i=0; i<nColumn; i++){
3409    w = p->colWidth[i];
3410    if( w<0 ) w = -w;
3411    p->actualWidth[i] = w;
3412  }
3413  for(i=0; i<nColumn; i++){
3414    const unsigned char *zNotUsed;
3415    int wx = p->colWidth[i];
3416    if( wx==0 ){
3417      wx = p->cmOpts.iWrap;
3418    }
3419    if( wx<0 ) wx = -wx;
3420    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3421    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3422  }
3423  do{
3424    int useNextLine = bNextLine;
3425    bNextLine = 0;
3426    if( (nRow+2)*nColumn >= nAlloc ){
3427      nAlloc *= 2;
3428      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3429      shell_check_oom(azData);
3430      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3431      shell_check_oom(abRowDiv);
3432    }
3433    abRowDiv[nRow] = 1;
3434    nRow++;
3435    for(i=0; i<nColumn; i++){
3436      int wx = p->colWidth[i];
3437      if( wx==0 ){
3438        wx = p->cmOpts.iWrap;
3439      }
3440      if( wx<0 ) wx = -wx;
3441      if( useNextLine ){
3442        uz = azNextLine[i];
3443        if( uz==0 ) uz = (u8*)zEmpty;
3444      }else if( p->cmOpts.bQuote ){
3445        sqlite3_free(azQuoted[i]);
3446        azQuoted[i] = quoted_column(pStmt,i);
3447        uz = (const unsigned char*)azQuoted[i];
3448      }else{
3449        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3450        if( uz==0 ) uz = (u8*)zShowNull;
3451      }
3452      azData[nRow*nColumn + i]
3453        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3454      if( azNextLine[i] ){
3455        bNextLine = 1;
3456        abRowDiv[nRow-1] = 0;
3457        bMultiLineRowExists = 1;
3458      }
3459    }
3460  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3461  nTotal = nColumn*(nRow+1);
3462  for(i=0; i<nTotal; i++){
3463    z = azData[i];
3464    if( z==0 ) z = (char*)zEmpty;
3465    n = strlenChar(z);
3466    j = i%nColumn;
3467    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3468  }
3469  if( seenInterrupt ) goto columnar_end;
3470  if( nColumn==0 ) goto columnar_end;
3471  switch( p->cMode ){
3472    case MODE_Column: {
3473      colSep = "  ";
3474      rowSep = "\n";
3475      if( p->showHeader ){
3476        for(i=0; i<nColumn; i++){
3477          w = p->actualWidth[i];
3478          if( p->colWidth[i]<0 ) w = -w;
3479          utf8_width_print(p->out, w, azData[i]);
3480          fputs(i==nColumn-1?"\n":"  ", p->out);
3481        }
3482        for(i=0; i<nColumn; i++){
3483          print_dashes(p->out, p->actualWidth[i]);
3484          fputs(i==nColumn-1?"\n":"  ", p->out);
3485        }
3486      }
3487      break;
3488    }
3489    case MODE_Table: {
3490      colSep = " | ";
3491      rowSep = " |\n";
3492      print_row_separator(p, nColumn, "+");
3493      fputs("| ", p->out);
3494      for(i=0; i<nColumn; i++){
3495        w = p->actualWidth[i];
3496        n = strlenChar(azData[i]);
3497        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3498        fputs(i==nColumn-1?" |\n":" | ", p->out);
3499      }
3500      print_row_separator(p, nColumn, "+");
3501      break;
3502    }
3503    case MODE_Markdown: {
3504      colSep = " | ";
3505      rowSep = " |\n";
3506      fputs("| ", p->out);
3507      for(i=0; i<nColumn; i++){
3508        w = p->actualWidth[i];
3509        n = strlenChar(azData[i]);
3510        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3511        fputs(i==nColumn-1?" |\n":" | ", p->out);
3512      }
3513      print_row_separator(p, nColumn, "|");
3514      break;
3515    }
3516    case MODE_Box: {
3517      colSep = " " BOX_13 " ";
3518      rowSep = " " BOX_13 "\n";
3519      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3520      utf8_printf(p->out, BOX_13 " ");
3521      for(i=0; i<nColumn; i++){
3522        w = p->actualWidth[i];
3523        n = strlenChar(azData[i]);
3524        utf8_printf(p->out, "%*s%s%*s%s",
3525            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3526            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3527      }
3528      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3529      break;
3530    }
3531  }
3532  for(i=nColumn, j=0; i<nTotal; i++, j++){
3533    if( j==0 && p->cMode!=MODE_Column ){
3534      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3535    }
3536    z = azData[i];
3537    if( z==0 ) z = p->nullValue;
3538    w = p->actualWidth[j];
3539    if( p->colWidth[j]<0 ) w = -w;
3540    utf8_width_print(p->out, w, z);
3541    if( j==nColumn-1 ){
3542      utf8_printf(p->out, "%s", rowSep);
3543      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3544        if( p->cMode==MODE_Table ){
3545          print_row_separator(p, nColumn, "+");
3546        }else if( p->cMode==MODE_Box ){
3547          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3548        }else if( p->cMode==MODE_Column ){
3549          raw_printf(p->out, "\n");
3550        }
3551      }
3552      j = -1;
3553      if( seenInterrupt ) goto columnar_end;
3554    }else{
3555      utf8_printf(p->out, "%s", colSep);
3556    }
3557  }
3558  if( p->cMode==MODE_Table ){
3559    print_row_separator(p, nColumn, "+");
3560  }else if( p->cMode==MODE_Box ){
3561    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3562  }
3563columnar_end:
3564  if( seenInterrupt ){
3565    utf8_printf(p->out, "Interrupt\n");
3566  }
3567  nData = (nRow+1)*nColumn;
3568  for(i=0; i<nData; i++){
3569    z = azData[i];
3570    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3571  }
3572  sqlite3_free(azData);
3573  sqlite3_free((void*)azNextLine);
3574  sqlite3_free(abRowDiv);
3575  if( azQuoted ){
3576    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3577    sqlite3_free(azQuoted);
3578  }
3579}
3580
3581/*
3582** Run a prepared statement
3583*/
3584static void exec_prepared_stmt(
3585  ShellState *pArg,                                /* Pointer to ShellState */
3586  sqlite3_stmt *pStmt                              /* Statment to run */
3587){
3588  int rc;
3589  sqlite3_uint64 nRow = 0;
3590
3591  if( pArg->cMode==MODE_Column
3592   || pArg->cMode==MODE_Table
3593   || pArg->cMode==MODE_Box
3594   || pArg->cMode==MODE_Markdown
3595  ){
3596    exec_prepared_stmt_columnar(pArg, pStmt);
3597    return;
3598  }
3599
3600  /* perform the first step.  this will tell us if we
3601  ** have a result set or not and how wide it is.
3602  */
3603  rc = sqlite3_step(pStmt);
3604  /* if we have a result set... */
3605  if( SQLITE_ROW == rc ){
3606    /* allocate space for col name ptr, value ptr, and type */
3607    int nCol = sqlite3_column_count(pStmt);
3608    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3609    if( !pData ){
3610      shell_out_of_memory();
3611    }else{
3612      char **azCols = (char **)pData;      /* Names of result columns */
3613      char **azVals = &azCols[nCol];       /* Results */
3614      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3615      int i, x;
3616      assert(sizeof(int) <= sizeof(char *));
3617      /* save off ptrs to column names */
3618      for(i=0; i<nCol; i++){
3619        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3620      }
3621      do{
3622        nRow++;
3623        /* extract the data and data types */
3624        for(i=0; i<nCol; i++){
3625          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3626          if( x==SQLITE_BLOB
3627           && pArg
3628           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3629          ){
3630            azVals[i] = "";
3631          }else{
3632            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3633          }
3634          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3635            rc = SQLITE_NOMEM;
3636            break; /* from for */
3637          }
3638        } /* end for */
3639
3640        /* if data and types extracted successfully... */
3641        if( SQLITE_ROW == rc ){
3642          /* call the supplied callback with the result row data */
3643          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3644            rc = SQLITE_ABORT;
3645          }else{
3646            rc = sqlite3_step(pStmt);
3647          }
3648        }
3649      } while( SQLITE_ROW == rc );
3650      sqlite3_free(pData);
3651      if( pArg->cMode==MODE_Json ){
3652        fputs("]\n", pArg->out);
3653      }else if( pArg->cMode==MODE_Count ){
3654        char zBuf[200];
3655        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3656                         nRow, nRow!=1 ? "s" : "");
3657        printf("%s", zBuf);
3658      }
3659    }
3660  }
3661}
3662
3663#ifndef SQLITE_OMIT_VIRTUALTABLE
3664/*
3665** This function is called to process SQL if the previous shell command
3666** was ".expert". It passes the SQL in the second argument directly to
3667** the sqlite3expert object.
3668**
3669** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3670** code. In this case, (*pzErr) may be set to point to a buffer containing
3671** an English language error message. It is the responsibility of the
3672** caller to eventually free this buffer using sqlite3_free().
3673*/
3674static int expertHandleSQL(
3675  ShellState *pState,
3676  const char *zSql,
3677  char **pzErr
3678){
3679  assert( pState->expert.pExpert );
3680  assert( pzErr==0 || *pzErr==0 );
3681  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3682}
3683
3684/*
3685** This function is called either to silently clean up the object
3686** created by the ".expert" command (if bCancel==1), or to generate a
3687** report from it and then clean it up (if bCancel==0).
3688**
3689** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3690** code. In this case, (*pzErr) may be set to point to a buffer containing
3691** an English language error message. It is the responsibility of the
3692** caller to eventually free this buffer using sqlite3_free().
3693*/
3694static int expertFinish(
3695  ShellState *pState,
3696  int bCancel,
3697  char **pzErr
3698){
3699  int rc = SQLITE_OK;
3700  sqlite3expert *p = pState->expert.pExpert;
3701  assert( p );
3702  assert( bCancel || pzErr==0 || *pzErr==0 );
3703  if( bCancel==0 ){
3704    FILE *out = pState->out;
3705    int bVerbose = pState->expert.bVerbose;
3706
3707    rc = sqlite3_expert_analyze(p, pzErr);
3708    if( rc==SQLITE_OK ){
3709      int nQuery = sqlite3_expert_count(p);
3710      int i;
3711
3712      if( bVerbose ){
3713        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3714        raw_printf(out, "-- Candidates -----------------------------\n");
3715        raw_printf(out, "%s\n", zCand);
3716      }
3717      for(i=0; i<nQuery; i++){
3718        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3719        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3720        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3721        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3722        if( bVerbose ){
3723          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3724          raw_printf(out, "%s\n\n", zSql);
3725        }
3726        raw_printf(out, "%s\n", zIdx);
3727        raw_printf(out, "%s\n", zEQP);
3728      }
3729    }
3730  }
3731  sqlite3_expert_destroy(p);
3732  pState->expert.pExpert = 0;
3733  return rc;
3734}
3735
3736/*
3737** Implementation of ".expert" dot command.
3738*/
3739static int expertDotCommand(
3740  ShellState *pState,             /* Current shell tool state */
3741  char **azArg,                   /* Array of arguments passed to dot command */
3742  int nArg                        /* Number of entries in azArg[] */
3743){
3744  int rc = SQLITE_OK;
3745  char *zErr = 0;
3746  int i;
3747  int iSample = 0;
3748
3749  assert( pState->expert.pExpert==0 );
3750  memset(&pState->expert, 0, sizeof(ExpertInfo));
3751
3752  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3753    char *z = azArg[i];
3754    int n;
3755    if( z[0]=='-' && z[1]=='-' ) z++;
3756    n = strlen30(z);
3757    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3758      pState->expert.bVerbose = 1;
3759    }
3760    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3761      if( i==(nArg-1) ){
3762        raw_printf(stderr, "option requires an argument: %s\n", z);
3763        rc = SQLITE_ERROR;
3764      }else{
3765        iSample = (int)integerValue(azArg[++i]);
3766        if( iSample<0 || iSample>100 ){
3767          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3768          rc = SQLITE_ERROR;
3769        }
3770      }
3771    }
3772    else{
3773      raw_printf(stderr, "unknown option: %s\n", z);
3774      rc = SQLITE_ERROR;
3775    }
3776  }
3777
3778  if( rc==SQLITE_OK ){
3779    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3780    if( pState->expert.pExpert==0 ){
3781      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3782      rc = SQLITE_ERROR;
3783    }else{
3784      sqlite3_expert_config(
3785          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3786      );
3787    }
3788  }
3789  sqlite3_free(zErr);
3790
3791  return rc;
3792}
3793#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3794
3795/*
3796** Execute a statement or set of statements.  Print
3797** any result rows/columns depending on the current mode
3798** set via the supplied callback.
3799**
3800** This is very similar to SQLite's built-in sqlite3_exec()
3801** function except it takes a slightly different callback
3802** and callback data argument.
3803*/
3804static int shell_exec(
3805  ShellState *pArg,                         /* Pointer to ShellState */
3806  const char *zSql,                         /* SQL to be evaluated */
3807  char **pzErrMsg                           /* Error msg written here */
3808){
3809  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3810  int rc = SQLITE_OK;             /* Return Code */
3811  int rc2;
3812  const char *zLeftover;          /* Tail of unprocessed SQL */
3813  sqlite3 *db = pArg->db;
3814
3815  if( pzErrMsg ){
3816    *pzErrMsg = NULL;
3817  }
3818
3819#ifndef SQLITE_OMIT_VIRTUALTABLE
3820  if( pArg->expert.pExpert ){
3821    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3822    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3823  }
3824#endif
3825
3826  while( zSql[0] && (SQLITE_OK == rc) ){
3827    static const char *zStmtSql;
3828    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3829    if( SQLITE_OK != rc ){
3830      if( pzErrMsg ){
3831        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3832      }
3833    }else{
3834      if( !pStmt ){
3835        /* this happens for a comment or white-space */
3836        zSql = zLeftover;
3837        while( IsSpace(zSql[0]) ) zSql++;
3838        continue;
3839      }
3840      zStmtSql = sqlite3_sql(pStmt);
3841      if( zStmtSql==0 ) zStmtSql = "";
3842      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3843
3844      /* save off the prepared statment handle and reset row count */
3845      if( pArg ){
3846        pArg->pStmt = pStmt;
3847        pArg->cnt = 0;
3848      }
3849
3850      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3851      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3852        sqlite3_stmt *pExplain;
3853        char *zEQP;
3854        int triggerEQP = 0;
3855        disable_debug_trace_modes();
3856        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3857        if( pArg->autoEQP>=AUTOEQP_trigger ){
3858          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3859        }
3860        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3861        shell_check_oom(zEQP);
3862        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3863        if( rc==SQLITE_OK ){
3864          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3865            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3866            int iEqpId = sqlite3_column_int(pExplain, 0);
3867            int iParentId = sqlite3_column_int(pExplain, 1);
3868            if( zEQPLine==0 ) zEQPLine = "";
3869            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3870            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3871          }
3872          eqp_render(pArg);
3873        }
3874        sqlite3_finalize(pExplain);
3875        sqlite3_free(zEQP);
3876        if( pArg->autoEQP>=AUTOEQP_full ){
3877          /* Also do an EXPLAIN for ".eqp full" mode */
3878          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3879          shell_check_oom(zEQP);
3880          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3881          if( rc==SQLITE_OK ){
3882            pArg->cMode = MODE_Explain;
3883            explain_data_prepare(pArg, pExplain);
3884            exec_prepared_stmt(pArg, pExplain);
3885            explain_data_delete(pArg);
3886          }
3887          sqlite3_finalize(pExplain);
3888          sqlite3_free(zEQP);
3889        }
3890        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3891          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3892          /* Reprepare pStmt before reactiving trace modes */
3893          sqlite3_finalize(pStmt);
3894          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3895          if( pArg ) pArg->pStmt = pStmt;
3896        }
3897        restore_debug_trace_modes();
3898      }
3899
3900      if( pArg ){
3901        pArg->cMode = pArg->mode;
3902        if( pArg->autoExplain ){
3903          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3904            pArg->cMode = MODE_Explain;
3905          }
3906          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3907            pArg->cMode = MODE_EQP;
3908          }
3909        }
3910
3911        /* If the shell is currently in ".explain" mode, gather the extra
3912        ** data required to add indents to the output.*/
3913        if( pArg->cMode==MODE_Explain ){
3914          explain_data_prepare(pArg, pStmt);
3915        }
3916      }
3917
3918      bind_prepared_stmt(pArg, pStmt);
3919      exec_prepared_stmt(pArg, pStmt);
3920      explain_data_delete(pArg);
3921      eqp_render(pArg);
3922
3923      /* print usage stats if stats on */
3924      if( pArg && pArg->statsOn ){
3925        display_stats(db, pArg, 0);
3926      }
3927
3928      /* print loop-counters if required */
3929      if( pArg && pArg->scanstatsOn ){
3930        display_scanstats(db, pArg);
3931      }
3932
3933      /* Finalize the statement just executed. If this fails, save a
3934      ** copy of the error message. Otherwise, set zSql to point to the
3935      ** next statement to execute. */
3936      rc2 = sqlite3_finalize(pStmt);
3937      if( rc!=SQLITE_NOMEM ) rc = rc2;
3938      if( rc==SQLITE_OK ){
3939        zSql = zLeftover;
3940        while( IsSpace(zSql[0]) ) zSql++;
3941      }else if( pzErrMsg ){
3942        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3943      }
3944
3945      /* clear saved stmt handle */
3946      if( pArg ){
3947        pArg->pStmt = NULL;
3948      }
3949    }
3950  } /* end while */
3951
3952  return rc;
3953}
3954
3955/*
3956** Release memory previously allocated by tableColumnList().
3957*/
3958static void freeColumnList(char **azCol){
3959  int i;
3960  for(i=1; azCol[i]; i++){
3961    sqlite3_free(azCol[i]);
3962  }
3963  /* azCol[0] is a static string */
3964  sqlite3_free(azCol);
3965}
3966
3967/*
3968** Return a list of pointers to strings which are the names of all
3969** columns in table zTab.   The memory to hold the names is dynamically
3970** allocated and must be released by the caller using a subsequent call
3971** to freeColumnList().
3972**
3973** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3974** value that needs to be preserved, then azCol[0] is filled in with the
3975** name of the rowid column.
3976**
3977** The first regular column in the table is azCol[1].  The list is terminated
3978** by an entry with azCol[i]==0.
3979*/
3980static char **tableColumnList(ShellState *p, const char *zTab){
3981  char **azCol = 0;
3982  sqlite3_stmt *pStmt;
3983  char *zSql;
3984  int nCol = 0;
3985  int nAlloc = 0;
3986  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3987  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3988  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3989  int rc;
3990
3991  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3992  shell_check_oom(zSql);
3993  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3994  sqlite3_free(zSql);
3995  if( rc ) return 0;
3996  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3997    if( nCol>=nAlloc-2 ){
3998      nAlloc = nAlloc*2 + nCol + 10;
3999      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
4000      shell_check_oom(azCol);
4001    }
4002    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4003    shell_check_oom(azCol[nCol]);
4004    if( sqlite3_column_int(pStmt, 5) ){
4005      nPK++;
4006      if( nPK==1
4007       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4008                          "INTEGER")==0
4009      ){
4010        isIPK = 1;
4011      }else{
4012        isIPK = 0;
4013      }
4014    }
4015  }
4016  sqlite3_finalize(pStmt);
4017  if( azCol==0 ) return 0;
4018  azCol[0] = 0;
4019  azCol[nCol+1] = 0;
4020
4021  /* The decision of whether or not a rowid really needs to be preserved
4022  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4023  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4024  ** rowids on tables where the rowid is inaccessible because there are other
4025  ** columns in the table named "rowid", "_rowid_", and "oid".
4026  */
4027  if( preserveRowid && isIPK ){
4028    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4029    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4030    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4031    ** ROWID aliases.  To distinguish these cases, check to see if
4032    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4033    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4034    */
4035    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4036                           " WHERE origin='pk'", zTab);
4037    shell_check_oom(zSql);
4038    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4039    sqlite3_free(zSql);
4040    if( rc ){
4041      freeColumnList(azCol);
4042      return 0;
4043    }
4044    rc = sqlite3_step(pStmt);
4045    sqlite3_finalize(pStmt);
4046    preserveRowid = rc==SQLITE_ROW;
4047  }
4048  if( preserveRowid ){
4049    /* Only preserve the rowid if we can find a name to use for the
4050    ** rowid */
4051    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4052    int i, j;
4053    for(j=0; j<3; j++){
4054      for(i=1; i<=nCol; i++){
4055        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4056      }
4057      if( i>nCol ){
4058        /* At this point, we know that azRowid[j] is not the name of any
4059        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4060        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4061        ** tables will fail this last check */
4062        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4063        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4064        break;
4065      }
4066    }
4067  }
4068  return azCol;
4069}
4070
4071/*
4072** Toggle the reverse_unordered_selects setting.
4073*/
4074static void toggleSelectOrder(sqlite3 *db){
4075  sqlite3_stmt *pStmt = 0;
4076  int iSetting = 0;
4077  char zStmt[100];
4078  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4079  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4080    iSetting = sqlite3_column_int(pStmt, 0);
4081  }
4082  sqlite3_finalize(pStmt);
4083  sqlite3_snprintf(sizeof(zStmt), zStmt,
4084       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4085  sqlite3_exec(db, zStmt, 0, 0, 0);
4086}
4087
4088/*
4089** This is a different callback routine used for dumping the database.
4090** Each row received by this callback consists of a table name,
4091** the table type ("index" or "table") and SQL to create the table.
4092** This routine should print text sufficient to recreate the table.
4093*/
4094static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4095  int rc;
4096  const char *zTable;
4097  const char *zType;
4098  const char *zSql;
4099  ShellState *p = (ShellState *)pArg;
4100  int dataOnly;
4101  int noSys;
4102
4103  UNUSED_PARAMETER(azNotUsed);
4104  if( nArg!=3 || azArg==0 ) return 0;
4105  zTable = azArg[0];
4106  zType = azArg[1];
4107  zSql = azArg[2];
4108  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4109  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4110
4111  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4112    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4113  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4114    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4115  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4116    return 0;
4117  }else if( dataOnly ){
4118    /* no-op */
4119  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4120    char *zIns;
4121    if( !p->writableSchema ){
4122      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4123      p->writableSchema = 1;
4124    }
4125    zIns = sqlite3_mprintf(
4126       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4127       "VALUES('table','%q','%q',0,'%q');",
4128       zTable, zTable, zSql);
4129    shell_check_oom(zIns);
4130    utf8_printf(p->out, "%s\n", zIns);
4131    sqlite3_free(zIns);
4132    return 0;
4133  }else{
4134    printSchemaLine(p->out, zSql, ";\n");
4135  }
4136
4137  if( strcmp(zType, "table")==0 ){
4138    ShellText sSelect;
4139    ShellText sTable;
4140    char **azCol;
4141    int i;
4142    char *savedDestTable;
4143    int savedMode;
4144
4145    azCol = tableColumnList(p, zTable);
4146    if( azCol==0 ){
4147      p->nErr++;
4148      return 0;
4149    }
4150
4151    /* Always quote the table name, even if it appears to be pure ascii,
4152    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4153    initText(&sTable);
4154    appendText(&sTable, zTable, quoteChar(zTable));
4155    /* If preserving the rowid, add a column list after the table name.
4156    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4157    ** instead of the usual "INSERT INTO tab VALUES(...)".
4158    */
4159    if( azCol[0] ){
4160      appendText(&sTable, "(", 0);
4161      appendText(&sTable, azCol[0], 0);
4162      for(i=1; azCol[i]; i++){
4163        appendText(&sTable, ",", 0);
4164        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4165      }
4166      appendText(&sTable, ")", 0);
4167    }
4168
4169    /* Build an appropriate SELECT statement */
4170    initText(&sSelect);
4171    appendText(&sSelect, "SELECT ", 0);
4172    if( azCol[0] ){
4173      appendText(&sSelect, azCol[0], 0);
4174      appendText(&sSelect, ",", 0);
4175    }
4176    for(i=1; azCol[i]; i++){
4177      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4178      if( azCol[i+1] ){
4179        appendText(&sSelect, ",", 0);
4180      }
4181    }
4182    freeColumnList(azCol);
4183    appendText(&sSelect, " FROM ", 0);
4184    appendText(&sSelect, zTable, quoteChar(zTable));
4185
4186    savedDestTable = p->zDestTable;
4187    savedMode = p->mode;
4188    p->zDestTable = sTable.z;
4189    p->mode = p->cMode = MODE_Insert;
4190    rc = shell_exec(p, sSelect.z, 0);
4191    if( (rc&0xff)==SQLITE_CORRUPT ){
4192      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4193      toggleSelectOrder(p->db);
4194      shell_exec(p, sSelect.z, 0);
4195      toggleSelectOrder(p->db);
4196    }
4197    p->zDestTable = savedDestTable;
4198    p->mode = savedMode;
4199    freeText(&sTable);
4200    freeText(&sSelect);
4201    if( rc ) p->nErr++;
4202  }
4203  return 0;
4204}
4205
4206/*
4207** Run zQuery.  Use dump_callback() as the callback routine so that
4208** the contents of the query are output as SQL statements.
4209**
4210** If we get a SQLITE_CORRUPT error, rerun the query after appending
4211** "ORDER BY rowid DESC" to the end.
4212*/
4213static int run_schema_dump_query(
4214  ShellState *p,
4215  const char *zQuery
4216){
4217  int rc;
4218  char *zErr = 0;
4219  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4220  if( rc==SQLITE_CORRUPT ){
4221    char *zQ2;
4222    int len = strlen30(zQuery);
4223    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4224    if( zErr ){
4225      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4226      sqlite3_free(zErr);
4227      zErr = 0;
4228    }
4229    zQ2 = malloc( len+100 );
4230    if( zQ2==0 ) return rc;
4231    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4232    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4233    if( rc ){
4234      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4235    }else{
4236      rc = SQLITE_CORRUPT;
4237    }
4238    sqlite3_free(zErr);
4239    free(zQ2);
4240  }
4241  return rc;
4242}
4243
4244/*
4245** Text of help messages.
4246**
4247** The help text for each individual command begins with a line that starts
4248** with ".".  Subsequent lines are supplemental information.
4249**
4250** There must be two or more spaces between the end of the command and the
4251** start of the description of what that command does.
4252*/
4253static const char *(azHelp[]) = {
4254#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4255  && !defined(SQLITE_SHELL_WASM_MODE)
4256  ".archive ...             Manage SQL archives",
4257  "   Each command must have exactly one of the following options:",
4258  "     -c, --create               Create a new archive",
4259  "     -u, --update               Add or update files with changed mtime",
4260  "     -i, --insert               Like -u but always add even if unchanged",
4261  "     -r, --remove               Remove files from archive",
4262  "     -t, --list                 List contents of archive",
4263  "     -x, --extract              Extract files from archive",
4264  "   Optional arguments:",
4265  "     -v, --verbose              Print each filename as it is processed",
4266  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4267  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4268  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4269  "     -g, --glob                 Use glob matching for names in archive",
4270  "     -n, --dryrun               Show the SQL that would have occurred",
4271  "   Examples:",
4272  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4273  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4274  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4275  "   See also:",
4276  "      http://sqlite.org/cli.html#sqlite_archive_support",
4277#endif
4278#ifndef SQLITE_OMIT_AUTHORIZATION
4279  ".auth ON|OFF             Show authorizer callbacks",
4280#endif
4281#ifndef SQLITE_SHELL_WASM_MODE
4282  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4283  "   Options:",
4284  "       --append            Use the appendvfs",
4285  "       --async             Write to FILE without journal and fsync()",
4286#endif
4287  ".bail on|off             Stop after hitting an error.  Default OFF",
4288  ".binary on|off           Turn binary output on or off.  Default OFF",
4289#ifndef SQLITE_SHELL_WASM_MODE
4290  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4291#endif
4292  ".changes on|off          Show number of rows changed by SQL",
4293#ifndef SQLITE_SHELL_WASM_MODE
4294  ".check GLOB              Fail if output since .testcase does not match",
4295  ".clone NEWDB             Clone data into NEWDB from the existing database",
4296#endif
4297  ".connection [close] [#]  Open or close an auxiliary database connection",
4298  ".databases               List names and files of attached databases",
4299  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4300#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4301  ".dbinfo ?DB?             Show status information about the database",
4302#endif
4303  ".dump ?OBJECTS?          Render database content as SQL",
4304  "   Options:",
4305  "     --data-only            Output only INSERT statements",
4306  "     --newlines             Allow unescaped newline characters in output",
4307  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4308  "     --preserve-rowids      Include ROWID values in the output",
4309  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4310  "   Additional LIKE patterns can be given in subsequent arguments",
4311  ".echo on|off             Turn command echo on or off",
4312  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4313  "   Other Modes:",
4314#ifdef SQLITE_DEBUG
4315  "      test                  Show raw EXPLAIN QUERY PLAN output",
4316  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4317#endif
4318  "      trigger               Like \"full\" but also show trigger bytecode",
4319#ifndef SQLITE_SHELL_WASM_MODE
4320  ".excel                   Display the output of next command in spreadsheet",
4321  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4322#endif
4323#ifndef SQLITE_SHELL_WASM_MODE
4324  ".exit ?CODE?             Exit this program with return-code CODE",
4325#endif
4326  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4327  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4328  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4329  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4330  "   --help                  Show CMD details",
4331  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4332  ".headers on|off          Turn display of headers on or off",
4333  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4334#ifndef SQLITE_SHELL_WASM_MODE
4335  ".import FILE TABLE       Import data from FILE into TABLE",
4336  "   Options:",
4337  "     --ascii               Use \\037 and \\036 as column and row separators",
4338  "     --csv                 Use , and \\n as column and row separators",
4339  "     --skip N              Skip the first N rows of input",
4340  "     --schema S            Target table to be S.TABLE",
4341  "     -v                    \"Verbose\" - increase auxiliary output",
4342  "   Notes:",
4343  "     *  If TABLE does not exist, it is created.  The first row of input",
4344  "        determines the column names.",
4345  "     *  If neither --csv or --ascii are used, the input mode is derived",
4346  "        from the \".mode\" output mode",
4347  "     *  If FILE begins with \"|\" then it is a command that generates the",
4348  "        input text.",
4349#endif
4350#ifndef SQLITE_OMIT_TEST_CONTROL
4351  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4352#endif
4353  ".indexes ?TABLE?         Show names of indexes",
4354  "                           If TABLE is specified, only show indexes for",
4355  "                           tables matching TABLE using the LIKE operator.",
4356#ifdef SQLITE_ENABLE_IOTRACE
4357  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4358#endif
4359  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4360  ".lint OPTIONS            Report potential schema issues.",
4361  "     Options:",
4362  "        fkey-indexes     Find missing foreign key indexes",
4363#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
4364  ".load FILE ?ENTRY?       Load an extension library",
4365#endif
4366#ifndef SQLITE_SHELL_WASM_MODE
4367  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4368#endif
4369  ".mode MODE ?OPTIONS?     Set output mode",
4370  "   MODE is one of:",
4371  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4372  "     box         Tables using unicode box-drawing characters",
4373  "     csv         Comma-separated values",
4374  "     column      Output in columns.  (See .width)",
4375  "     html        HTML <table> code",
4376  "     insert      SQL insert statements for TABLE",
4377  "     json        Results in a JSON array",
4378  "     line        One value per line",
4379  "     list        Values delimited by \"|\"",
4380  "     markdown    Markdown table format",
4381  "     qbox        Shorthand for \"box --width 60 --quote\"",
4382  "     quote       Escape answers as for SQL",
4383  "     table       ASCII-art table",
4384  "     tabs        Tab-separated values",
4385  "     tcl         TCL list elements",
4386  "   OPTIONS: (for columnar modes or insert mode):",
4387  "     --wrap N       Wrap output lines to no longer than N characters",
4388  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4389  "     --ww           Shorthand for \"--wordwrap 1\"",
4390  "     --quote        Quote output text as SQL literals",
4391  "     --noquote      Do not quote output text",
4392  "     TABLE          The name of SQL table used for \"insert\" mode",
4393#ifndef SQLITE_SHELL_WASM_MODE
4394  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4395#endif
4396  ".nullvalue STRING        Use STRING in place of NULL values",
4397#ifndef SQLITE_SHELL_WASM_MODE
4398  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4399  "     If FILE begins with '|' then open as a pipe",
4400  "       --bom  Put a UTF8 byte-order mark at the beginning",
4401  "       -e     Send output to the system text editor",
4402  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4403  /* Note that .open is (partially) available in WASM builds but is
4404  ** currently only intended to be used by the fiddle tool, not
4405  ** end users, so is "undocumented." */
4406  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4407  "     Options:",
4408  "        --append        Use appendvfs to append database to the end of FILE",
4409#endif
4410#ifndef SQLITE_OMIT_DESERIALIZE
4411  "        --deserialize   Load into memory using sqlite3_deserialize()",
4412  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4413  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4414#endif
4415  "        --new           Initialize FILE to an empty database",
4416  "        --nofollow      Do not follow symbolic links",
4417  "        --readonly      Open FILE readonly",
4418  "        --zip           FILE is a ZIP archive",
4419#ifndef SQLITE_SHELL_WASM_MODE
4420  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4421  "   If FILE begins with '|' then open it as a pipe.",
4422  "   Options:",
4423  "     --bom                 Prefix output with a UTF8 byte-order mark",
4424  "     -e                    Send output to the system text editor",
4425  "     -x                    Send output as CSV to a spreadsheet",
4426#endif
4427  ".parameter CMD ...       Manage SQL parameter bindings",
4428  "   clear                   Erase all bindings",
4429  "   init                    Initialize the TEMP table that holds bindings",
4430  "   list                    List the current parameter bindings",
4431  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4432  "                           PARAMETER should start with one of: $ : @ ?",
4433  "   unset PARAMETER         Remove PARAMETER from the binding table",
4434  ".print STRING...         Print literal STRING",
4435#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4436  ".progress N              Invoke progress handler after every N opcodes",
4437  "   --limit N                 Interrupt after N progress callbacks",
4438  "   --once                    Do no more than one progress interrupt",
4439  "   --quiet|-q                No output except at interrupts",
4440  "   --reset                   Reset the count for each input and interrupt",
4441#endif
4442  ".prompt MAIN CONTINUE    Replace the standard prompts",
4443#ifndef SQLITE_SHELL_WASM_MODE
4444  ".quit                    Exit this program",
4445  ".read FILE               Read input from FILE or command output",
4446  "    If FILE begins with \"|\", it is a command that generates the input.",
4447#endif
4448#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4449  ".recover                 Recover as much data as possible from corrupt db.",
4450  "   --freelist-corrupt       Assume the freelist is corrupt",
4451  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4452  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4453  "   --no-rowids              Do not attempt to recover rowid values",
4454  "                            that are not also INTEGER PRIMARY KEYs",
4455#endif
4456#ifndef SQLITE_SHELL_WASM_MODE
4457  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4458  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4459#endif
4460  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4461  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4462  "   Options:",
4463  "      --indent             Try to pretty-print the schema",
4464  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4465  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4466  "    Options:",
4467  "       --init               Create a new SELFTEST table",
4468  "       -v                   Verbose output",
4469  ".separator COL ?ROW?     Change the column and row separators",
4470#if defined(SQLITE_ENABLE_SESSION)
4471  ".session ?NAME? CMD ...  Create or control sessions",
4472  "   Subcommands:",
4473  "     attach TABLE             Attach TABLE",
4474  "     changeset FILE           Write a changeset into FILE",
4475  "     close                    Close one session",
4476  "     enable ?BOOLEAN?         Set or query the enable bit",
4477  "     filter GLOB...           Reject tables matching GLOBs",
4478  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4479  "     isempty                  Query whether the session is empty",
4480  "     list                     List currently open session names",
4481  "     open DB NAME             Open a new session on DB",
4482  "     patchset FILE            Write a patchset into FILE",
4483  "   If ?NAME? is omitted, the first defined session is used.",
4484#endif
4485  ".sha3sum ...             Compute a SHA3 hash of database content",
4486  "    Options:",
4487  "      --schema              Also hash the sqlite_schema table",
4488  "      --sha3-224            Use the sha3-224 algorithm",
4489  "      --sha3-256            Use the sha3-256 algorithm (default)",
4490  "      --sha3-384            Use the sha3-384 algorithm",
4491  "      --sha3-512            Use the sha3-512 algorithm",
4492  "    Any other argument is a LIKE pattern for tables to hash",
4493#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4494  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4495#endif
4496  ".show                    Show the current values for various settings",
4497  ".stats ?ARG?             Show stats or turn stats on or off",
4498  "   off                      Turn off automatic stat display",
4499  "   on                       Turn on automatic stat display",
4500  "   stmt                     Show statement stats",
4501  "   vmstep                   Show the virtual machine step count only",
4502#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
4503  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4504#endif
4505  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4506#ifndef SQLITE_SHELL_WASM_MODE
4507  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4508#endif
4509  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4510  "                           Run \".testctrl\" with no arguments for details",
4511  ".timeout MS              Try opening locked tables for MS milliseconds",
4512  ".timer on|off            Turn SQL timer on or off",
4513#ifndef SQLITE_OMIT_TRACE
4514  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4515  "    FILE                    Send output to FILE",
4516  "    stdout                  Send output to stdout",
4517  "    stderr                  Send output to stderr",
4518  "    off                     Disable tracing",
4519  "    --expanded              Expand query parameters",
4520#ifdef SQLITE_ENABLE_NORMALIZE
4521  "    --normalized            Normal the SQL statements",
4522#endif
4523  "    --plain                 Show SQL as it is input",
4524  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4525  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4526  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4527  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4528#endif /* SQLITE_OMIT_TRACE */
4529#ifdef SQLITE_DEBUG
4530  ".unmodule NAME ...       Unregister virtual table modules",
4531  "    --allexcept             Unregister everything except those named",
4532#endif
4533  ".vfsinfo ?AUX?           Information about the top-level VFS",
4534  ".vfslist                 List all available VFSes",
4535  ".vfsname ?AUX?           Print the name of the VFS stack",
4536  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4537  "     Negative values right-justify",
4538};
4539
4540/*
4541** Output help text.
4542**
4543** zPattern describes the set of commands for which help text is provided.
4544** If zPattern is NULL, then show all commands, but only give a one-line
4545** description of each.
4546**
4547** Return the number of matches.
4548*/
4549static int showHelp(FILE *out, const char *zPattern){
4550  int i = 0;
4551  int j = 0;
4552  int n = 0;
4553  char *zPat;
4554  if( zPattern==0
4555   || zPattern[0]=='0'
4556   || strcmp(zPattern,"-a")==0
4557   || strcmp(zPattern,"-all")==0
4558   || strcmp(zPattern,"--all")==0
4559  ){
4560    /* Show all commands, but only one line per command */
4561    if( zPattern==0 ) zPattern = "";
4562    for(i=0; i<ArraySize(azHelp); i++){
4563      if( azHelp[i][0]=='.' || zPattern[0] ){
4564        utf8_printf(out, "%s\n", azHelp[i]);
4565        n++;
4566      }
4567    }
4568  }else{
4569    /* Look for commands that for which zPattern is an exact prefix */
4570    zPat = sqlite3_mprintf(".%s*", zPattern);
4571    shell_check_oom(zPat);
4572    for(i=0; i<ArraySize(azHelp); i++){
4573      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4574        utf8_printf(out, "%s\n", azHelp[i]);
4575        j = i+1;
4576        n++;
4577      }
4578    }
4579    sqlite3_free(zPat);
4580    if( n ){
4581      if( n==1 ){
4582        /* when zPattern is a prefix of exactly one command, then include the
4583        ** details of that command, which should begin at offset j */
4584        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4585          utf8_printf(out, "%s\n", azHelp[j]);
4586          j++;
4587        }
4588      }
4589      return n;
4590    }
4591    /* Look for commands that contain zPattern anywhere.  Show the complete
4592    ** text of all commands that match. */
4593    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4594    shell_check_oom(zPat);
4595    for(i=0; i<ArraySize(azHelp); i++){
4596      if( azHelp[i][0]=='.' ) j = i;
4597      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4598        utf8_printf(out, "%s\n", azHelp[j]);
4599        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4600          j++;
4601          utf8_printf(out, "%s\n", azHelp[j]);
4602        }
4603        i = j;
4604        n++;
4605      }
4606    }
4607    sqlite3_free(zPat);
4608  }
4609  return n;
4610}
4611
4612/* Forward reference */
4613static int process_input(ShellState *p);
4614
4615/*
4616** Read the content of file zName into memory obtained from sqlite3_malloc64()
4617** and return a pointer to the buffer. The caller is responsible for freeing
4618** the memory.
4619**
4620** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4621** read.
4622**
4623** For convenience, a nul-terminator byte is always appended to the data read
4624** from the file before the buffer is returned. This byte is not included in
4625** the final value of (*pnByte), if applicable.
4626**
4627** NULL is returned if any error is encountered. The final value of *pnByte
4628** is undefined in this case.
4629*/
4630static char *readFile(const char *zName, int *pnByte){
4631  FILE *in = fopen(zName, "rb");
4632  long nIn;
4633  size_t nRead;
4634  char *pBuf;
4635  if( in==0 ) return 0;
4636  fseek(in, 0, SEEK_END);
4637  nIn = ftell(in);
4638  rewind(in);
4639  pBuf = sqlite3_malloc64( nIn+1 );
4640  if( pBuf==0 ){ fclose(in); return 0; }
4641  nRead = fread(pBuf, nIn, 1, in);
4642  fclose(in);
4643  if( nRead!=1 ){
4644    sqlite3_free(pBuf);
4645    return 0;
4646  }
4647  pBuf[nIn] = 0;
4648  if( pnByte ) *pnByte = nIn;
4649  return pBuf;
4650}
4651
4652#if defined(SQLITE_ENABLE_SESSION)
4653/*
4654** Close a single OpenSession object and release all of its associated
4655** resources.
4656*/
4657static void session_close(OpenSession *pSession){
4658  int i;
4659  sqlite3session_delete(pSession->p);
4660  sqlite3_free(pSession->zName);
4661  for(i=0; i<pSession->nFilter; i++){
4662    sqlite3_free(pSession->azFilter[i]);
4663  }
4664  sqlite3_free(pSession->azFilter);
4665  memset(pSession, 0, sizeof(OpenSession));
4666}
4667#endif
4668
4669/*
4670** Close all OpenSession objects and release all associated resources.
4671*/
4672#if defined(SQLITE_ENABLE_SESSION)
4673static void session_close_all(ShellState *p, int i){
4674  int j;
4675  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4676  for(j=0; j<pAuxDb->nSession; j++){
4677    session_close(&pAuxDb->aSession[j]);
4678  }
4679  pAuxDb->nSession = 0;
4680}
4681#else
4682# define session_close_all(X,Y)
4683#endif
4684
4685/*
4686** Implementation of the xFilter function for an open session.  Omit
4687** any tables named by ".session filter" but let all other table through.
4688*/
4689#if defined(SQLITE_ENABLE_SESSION)
4690static int session_filter(void *pCtx, const char *zTab){
4691  OpenSession *pSession = (OpenSession*)pCtx;
4692  int i;
4693  for(i=0; i<pSession->nFilter; i++){
4694    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4695  }
4696  return 1;
4697}
4698#endif
4699
4700/*
4701** Try to deduce the type of file for zName based on its content.  Return
4702** one of the SHELL_OPEN_* constants.
4703**
4704** If the file does not exist or is empty but its name looks like a ZIP
4705** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4706** Otherwise, assume an ordinary database regardless of the filename if
4707** the type cannot be determined from content.
4708*/
4709int deduceDatabaseType(const char *zName, int dfltZip){
4710  FILE *f = fopen(zName, "rb");
4711  size_t n;
4712  int rc = SHELL_OPEN_UNSPEC;
4713  char zBuf[100];
4714  if( f==0 ){
4715    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4716       return SHELL_OPEN_ZIPFILE;
4717    }else{
4718       return SHELL_OPEN_NORMAL;
4719    }
4720  }
4721  n = fread(zBuf, 16, 1, f);
4722  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4723    fclose(f);
4724    return SHELL_OPEN_NORMAL;
4725  }
4726  fseek(f, -25, SEEK_END);
4727  n = fread(zBuf, 25, 1, f);
4728  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4729    rc = SHELL_OPEN_APPENDVFS;
4730  }else{
4731    fseek(f, -22, SEEK_END);
4732    n = fread(zBuf, 22, 1, f);
4733    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4734       && zBuf[3]==0x06 ){
4735      rc = SHELL_OPEN_ZIPFILE;
4736    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4737      rc = SHELL_OPEN_ZIPFILE;
4738    }
4739  }
4740  fclose(f);
4741  return rc;
4742}
4743
4744#ifndef SQLITE_OMIT_DESERIALIZE
4745/*
4746** Reconstruct an in-memory database using the output from the "dbtotxt"
4747** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4748** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4749*/
4750static unsigned char *readHexDb(ShellState *p, int *pnData){
4751  unsigned char *a = 0;
4752  int nLine;
4753  int n = 0;
4754  int pgsz = 0;
4755  int iOffset = 0;
4756  int j, k;
4757  int rc;
4758  FILE *in;
4759  const char *zDbFilename = p->pAuxDb->zDbFilename;
4760  unsigned int x[16];
4761  char zLine[1000];
4762  if( zDbFilename ){
4763    in = fopen(zDbFilename, "r");
4764    if( in==0 ){
4765      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4766      return 0;
4767    }
4768    nLine = 0;
4769  }else{
4770    in = p->in;
4771    nLine = p->lineno;
4772    if( in==0 ) in = stdin;
4773  }
4774  *pnData = 0;
4775  nLine++;
4776  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4777  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4778  if( rc!=2 ) goto readHexDb_error;
4779  if( n<0 ) goto readHexDb_error;
4780  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4781  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4782  a = sqlite3_malloc( n ? n : 1 );
4783  shell_check_oom(a);
4784  memset(a, 0, n);
4785  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4786    utf8_printf(stderr, "invalid pagesize\n");
4787    goto readHexDb_error;
4788  }
4789  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4790    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4791    if( rc==2 ){
4792      iOffset = k;
4793      continue;
4794    }
4795    if( strncmp(zLine, "| end ", 6)==0 ){
4796      break;
4797    }
4798    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4799                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4800                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4801    if( rc==17 ){
4802      k = iOffset+j;
4803      if( k+16<=n && k>=0 ){
4804        int ii;
4805        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4806      }
4807    }
4808  }
4809  *pnData = n;
4810  if( in!=p->in ){
4811    fclose(in);
4812  }else{
4813    p->lineno = nLine;
4814  }
4815  return a;
4816
4817readHexDb_error:
4818  if( in!=p->in ){
4819    fclose(in);
4820  }else{
4821    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4822      nLine++;
4823      if(strncmp(zLine, "| end ", 6)==0 ) break;
4824    }
4825    p->lineno = nLine;
4826  }
4827  sqlite3_free(a);
4828  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4829  return 0;
4830}
4831#endif /* SQLITE_OMIT_DESERIALIZE */
4832
4833/*
4834** Scalar function "shell_int32". The first argument to this function
4835** must be a blob. The second a non-negative integer. This function
4836** reads and returns a 32-bit big-endian integer from byte
4837** offset (4*<arg2>) of the blob.
4838*/
4839static void shellInt32(
4840  sqlite3_context *context,
4841  int argc,
4842  sqlite3_value **argv
4843){
4844  const unsigned char *pBlob;
4845  int nBlob;
4846  int iInt;
4847
4848  UNUSED_PARAMETER(argc);
4849  nBlob = sqlite3_value_bytes(argv[0]);
4850  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4851  iInt = sqlite3_value_int(argv[1]);
4852
4853  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4854    const unsigned char *a = &pBlob[iInt*4];
4855    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4856                       + ((sqlite3_int64)a[1]<<16)
4857                       + ((sqlite3_int64)a[2]<< 8)
4858                       + ((sqlite3_int64)a[3]<< 0);
4859    sqlite3_result_int64(context, iVal);
4860  }
4861}
4862
4863/*
4864** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4865** using "..." with internal double-quote characters doubled.
4866*/
4867static void shellIdQuote(
4868  sqlite3_context *context,
4869  int argc,
4870  sqlite3_value **argv
4871){
4872  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4873  UNUSED_PARAMETER(argc);
4874  if( zName ){
4875    char *z = sqlite3_mprintf("\"%w\"", zName);
4876    sqlite3_result_text(context, z, -1, sqlite3_free);
4877  }
4878}
4879
4880/*
4881** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4882*/
4883static void shellUSleepFunc(
4884  sqlite3_context *context,
4885  int argcUnused,
4886  sqlite3_value **argv
4887){
4888  int sleep = sqlite3_value_int(argv[0]);
4889  (void)argcUnused;
4890  sqlite3_sleep(sleep/1000);
4891  sqlite3_result_int(context, sleep);
4892}
4893
4894/*
4895** Scalar function "shell_escape_crnl" used by the .recover command.
4896** The argument passed to this function is the output of built-in
4897** function quote(). If the first character of the input is "'",
4898** indicating that the value passed to quote() was a text value,
4899** then this function searches the input for "\n" and "\r" characters
4900** and adds a wrapper similar to the following:
4901**
4902**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4903**
4904** Or, if the first character of the input is not "'", then a copy
4905** of the input is returned.
4906*/
4907static void shellEscapeCrnl(
4908  sqlite3_context *context,
4909  int argc,
4910  sqlite3_value **argv
4911){
4912  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4913  UNUSED_PARAMETER(argc);
4914  if( zText && zText[0]=='\'' ){
4915    int nText = sqlite3_value_bytes(argv[0]);
4916    int i;
4917    char zBuf1[20];
4918    char zBuf2[20];
4919    const char *zNL = 0;
4920    const char *zCR = 0;
4921    int nCR = 0;
4922    int nNL = 0;
4923
4924    for(i=0; zText[i]; i++){
4925      if( zNL==0 && zText[i]=='\n' ){
4926        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4927        nNL = (int)strlen(zNL);
4928      }
4929      if( zCR==0 && zText[i]=='\r' ){
4930        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4931        nCR = (int)strlen(zCR);
4932      }
4933    }
4934
4935    if( zNL || zCR ){
4936      int iOut = 0;
4937      i64 nMax = (nNL > nCR) ? nNL : nCR;
4938      i64 nAlloc = nMax * nText + (nMax+64)*2;
4939      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4940      if( zOut==0 ){
4941        sqlite3_result_error_nomem(context);
4942        return;
4943      }
4944
4945      if( zNL && zCR ){
4946        memcpy(&zOut[iOut], "replace(replace(", 16);
4947        iOut += 16;
4948      }else{
4949        memcpy(&zOut[iOut], "replace(", 8);
4950        iOut += 8;
4951      }
4952      for(i=0; zText[i]; i++){
4953        if( zText[i]=='\n' ){
4954          memcpy(&zOut[iOut], zNL, nNL);
4955          iOut += nNL;
4956        }else if( zText[i]=='\r' ){
4957          memcpy(&zOut[iOut], zCR, nCR);
4958          iOut += nCR;
4959        }else{
4960          zOut[iOut] = zText[i];
4961          iOut++;
4962        }
4963      }
4964
4965      if( zNL ){
4966        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4967        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4968        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4969      }
4970      if( zCR ){
4971        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4972        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4973        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4974      }
4975
4976      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4977      sqlite3_free(zOut);
4978      return;
4979    }
4980  }
4981
4982  sqlite3_result_value(context, argv[0]);
4983}
4984
4985/* Flags for open_db().
4986**
4987** The default behavior of open_db() is to exit(1) if the database fails to
4988** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4989** but still returns without calling exit.
4990**
4991** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4992** ZIP archive if the file does not exist or is empty and its name matches
4993** the *.zip pattern.
4994*/
4995#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4996#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4997
4998/*
4999** Make sure the database is open.  If it is not, then open it.  If
5000** the database fails to open, print an error message and exit.
5001*/
5002static void open_db(ShellState *p, int openFlags){
5003  if( p->db==0 ){
5004    const char *zDbFilename = p->pAuxDb->zDbFilename;
5005    if( p->openMode==SHELL_OPEN_UNSPEC ){
5006      if( zDbFilename==0 || zDbFilename[0]==0 ){
5007        p->openMode = SHELL_OPEN_NORMAL;
5008      }else{
5009        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5010                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5011      }
5012    }
5013    switch( p->openMode ){
5014      case SHELL_OPEN_APPENDVFS: {
5015        sqlite3_open_v2(zDbFilename, &p->db,
5016           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5017        break;
5018      }
5019      case SHELL_OPEN_HEXDB:
5020      case SHELL_OPEN_DESERIALIZE: {
5021        sqlite3_open(0, &p->db);
5022        break;
5023      }
5024      case SHELL_OPEN_ZIPFILE: {
5025        sqlite3_open(":memory:", &p->db);
5026        break;
5027      }
5028      case SHELL_OPEN_READONLY: {
5029        sqlite3_open_v2(zDbFilename, &p->db,
5030            SQLITE_OPEN_READONLY|p->openFlags, 0);
5031        break;
5032      }
5033      case SHELL_OPEN_UNSPEC:
5034      case SHELL_OPEN_NORMAL: {
5035        sqlite3_open_v2(zDbFilename, &p->db,
5036           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5037        break;
5038      }
5039    }
5040    globalDb = p->db;
5041    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5042      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5043          zDbFilename, sqlite3_errmsg(p->db));
5044      if( openFlags & OPEN_DB_KEEPALIVE ){
5045        sqlite3_open(":memory:", &p->db);
5046        return;
5047      }
5048      exit(1);
5049    }
5050#ifndef SQLITE_OMIT_LOAD_EXTENSION
5051    sqlite3_enable_load_extension(p->db, 1);
5052#endif
5053    sqlite3_shathree_init(p->db, 0, 0);
5054    sqlite3_uint_init(p->db, 0, 0);
5055    sqlite3_decimal_init(p->db, 0, 0);
5056    sqlite3_regexp_init(p->db, 0, 0);
5057    sqlite3_ieee_init(p->db, 0, 0);
5058    sqlite3_series_init(p->db, 0, 0);
5059#ifndef SQLITE_SHELL_WASM_MODE
5060    sqlite3_fileio_init(p->db, 0, 0);
5061    sqlite3_completion_init(p->db, 0, 0);
5062#endif
5063#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5064    sqlite3_dbdata_init(p->db, 0, 0);
5065#endif
5066#ifdef SQLITE_HAVE_ZLIB
5067    if( !p->bSafeModePersist ){
5068      sqlite3_zipfile_init(p->db, 0, 0);
5069      sqlite3_sqlar_init(p->db, 0, 0);
5070    }
5071#endif
5072    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5073                            shellAddSchemaName, 0, 0);
5074    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5075                            shellModuleSchema, 0, 0);
5076    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5077                            shellPutsFunc, 0, 0);
5078    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5079                            shellEscapeCrnl, 0, 0);
5080    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5081                            shellInt32, 0, 0);
5082    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5083                            shellIdQuote, 0, 0);
5084    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5085                            shellUSleepFunc, 0, 0);
5086#ifndef SQLITE_NOHAVE_SYSTEM
5087    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5088                            editFunc, 0, 0);
5089    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5090                            editFunc, 0, 0);
5091#endif
5092    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5093      char *zSql = sqlite3_mprintf(
5094         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5095      shell_check_oom(zSql);
5096      sqlite3_exec(p->db, zSql, 0, 0, 0);
5097      sqlite3_free(zSql);
5098    }
5099#ifndef SQLITE_OMIT_DESERIALIZE
5100    else
5101    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5102      int rc;
5103      int nData = 0;
5104      unsigned char *aData;
5105      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5106        aData = (unsigned char*)readFile(zDbFilename, &nData);
5107      }else{
5108        aData = readHexDb(p, &nData);
5109        if( aData==0 ){
5110          return;
5111        }
5112      }
5113      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5114                   SQLITE_DESERIALIZE_RESIZEABLE |
5115                   SQLITE_DESERIALIZE_FREEONCLOSE);
5116      if( rc ){
5117        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5118      }
5119      if( p->szMax>0 ){
5120        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5121      }
5122    }
5123#endif
5124  }
5125  if( p->bSafeModePersist && p->db!=0 ){
5126    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5127  }
5128}
5129
5130/*
5131** Attempt to close the databaes connection.  Report errors.
5132*/
5133void close_db(sqlite3 *db){
5134  int rc = sqlite3_close(db);
5135  if( rc ){
5136    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5137        rc, sqlite3_errmsg(db));
5138  }
5139}
5140
5141#if HAVE_READLINE || HAVE_EDITLINE
5142/*
5143** Readline completion callbacks
5144*/
5145static char *readline_completion_generator(const char *text, int state){
5146  static sqlite3_stmt *pStmt = 0;
5147  char *zRet;
5148  if( state==0 ){
5149    char *zSql;
5150    sqlite3_finalize(pStmt);
5151    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5152                           "  FROM completion(%Q) ORDER BY 1", text);
5153    shell_check_oom(zSql);
5154    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5155    sqlite3_free(zSql);
5156  }
5157  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5158    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5159    zRet = z ? strdup(z) : 0;
5160  }else{
5161    sqlite3_finalize(pStmt);
5162    pStmt = 0;
5163    zRet = 0;
5164  }
5165  return zRet;
5166}
5167static char **readline_completion(const char *zText, int iStart, int iEnd){
5168  rl_attempted_completion_over = 1;
5169  return rl_completion_matches(zText, readline_completion_generator);
5170}
5171
5172#elif HAVE_LINENOISE
5173/*
5174** Linenoise completion callback
5175*/
5176static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5177  int nLine = strlen30(zLine);
5178  int i, iStart;
5179  sqlite3_stmt *pStmt = 0;
5180  char *zSql;
5181  char zBuf[1000];
5182
5183  if( nLine>sizeof(zBuf)-30 ) return;
5184  if( zLine[0]=='.' || zLine[0]=='#') return;
5185  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5186  if( i==nLine-1 ) return;
5187  iStart = i+1;
5188  memcpy(zBuf, zLine, iStart);
5189  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5190                         "  FROM completion(%Q,%Q) ORDER BY 1",
5191                         &zLine[iStart], zLine);
5192  shell_check_oom(zSql);
5193  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5194  sqlite3_free(zSql);
5195  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5196  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5197    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5198    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5199    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5200      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5201      linenoiseAddCompletion(lc, zBuf);
5202    }
5203  }
5204  sqlite3_finalize(pStmt);
5205}
5206#endif
5207
5208/*
5209** Do C-language style dequoting.
5210**
5211**    \a    -> alarm
5212**    \b    -> backspace
5213**    \t    -> tab
5214**    \n    -> newline
5215**    \v    -> vertical tab
5216**    \f    -> form feed
5217**    \r    -> carriage return
5218**    \s    -> space
5219**    \"    -> "
5220**    \'    -> '
5221**    \\    -> backslash
5222**    \NNN  -> ascii character NNN in octal
5223*/
5224static void resolve_backslashes(char *z){
5225  int i, j;
5226  char c;
5227  while( *z && *z!='\\' ) z++;
5228  for(i=j=0; (c = z[i])!=0; i++, j++){
5229    if( c=='\\' && z[i+1]!=0 ){
5230      c = z[++i];
5231      if( c=='a' ){
5232        c = '\a';
5233      }else if( c=='b' ){
5234        c = '\b';
5235      }else if( c=='t' ){
5236        c = '\t';
5237      }else if( c=='n' ){
5238        c = '\n';
5239      }else if( c=='v' ){
5240        c = '\v';
5241      }else if( c=='f' ){
5242        c = '\f';
5243      }else if( c=='r' ){
5244        c = '\r';
5245      }else if( c=='"' ){
5246        c = '"';
5247      }else if( c=='\'' ){
5248        c = '\'';
5249      }else if( c=='\\' ){
5250        c = '\\';
5251      }else if( c>='0' && c<='7' ){
5252        c -= '0';
5253        if( z[i+1]>='0' && z[i+1]<='7' ){
5254          i++;
5255          c = (c<<3) + z[i] - '0';
5256          if( z[i+1]>='0' && z[i+1]<='7' ){
5257            i++;
5258            c = (c<<3) + z[i] - '0';
5259          }
5260        }
5261      }
5262    }
5263    z[j] = c;
5264  }
5265  if( j<i ) z[j] = 0;
5266}
5267
5268/*
5269** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5270** for TRUE and FALSE.  Return the integer value if appropriate.
5271*/
5272static int booleanValue(const char *zArg){
5273  int i;
5274  if( zArg[0]=='0' && zArg[1]=='x' ){
5275    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5276  }else{
5277    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5278  }
5279  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5280  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5281    return 1;
5282  }
5283  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5284    return 0;
5285  }
5286  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5287          zArg);
5288  return 0;
5289}
5290
5291/*
5292** Set or clear a shell flag according to a boolean value.
5293*/
5294static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5295  if( booleanValue(zArg) ){
5296    ShellSetFlag(p, mFlag);
5297  }else{
5298    ShellClearFlag(p, mFlag);
5299  }
5300}
5301
5302/*
5303** Close an output file, assuming it is not stderr or stdout
5304*/
5305static void output_file_close(FILE *f){
5306  if( f && f!=stdout && f!=stderr ) fclose(f);
5307}
5308
5309/*
5310** Try to open an output file.   The names "stdout" and "stderr" are
5311** recognized and do the right thing.  NULL is returned if the output
5312** filename is "off".
5313*/
5314static FILE *output_file_open(const char *zFile, int bTextMode){
5315  FILE *f;
5316  if( strcmp(zFile,"stdout")==0 ){
5317    f = stdout;
5318  }else if( strcmp(zFile, "stderr")==0 ){
5319    f = stderr;
5320  }else if( strcmp(zFile, "off")==0 ){
5321    f = 0;
5322  }else{
5323    f = fopen(zFile, bTextMode ? "w" : "wb");
5324    if( f==0 ){
5325      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5326    }
5327  }
5328  return f;
5329}
5330
5331#ifndef SQLITE_OMIT_TRACE
5332/*
5333** A routine for handling output from sqlite3_trace().
5334*/
5335static int sql_trace_callback(
5336  unsigned mType,         /* The trace type */
5337  void *pArg,             /* The ShellState pointer */
5338  void *pP,               /* Usually a pointer to sqlite_stmt */
5339  void *pX                /* Auxiliary output */
5340){
5341  ShellState *p = (ShellState*)pArg;
5342  sqlite3_stmt *pStmt;
5343  const char *zSql;
5344  int nSql;
5345  if( p->traceOut==0 ) return 0;
5346  if( mType==SQLITE_TRACE_CLOSE ){
5347    utf8_printf(p->traceOut, "-- closing database connection\n");
5348    return 0;
5349  }
5350  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5351    zSql = (const char*)pX;
5352  }else{
5353    pStmt = (sqlite3_stmt*)pP;
5354    switch( p->eTraceType ){
5355      case SHELL_TRACE_EXPANDED: {
5356        zSql = sqlite3_expanded_sql(pStmt);
5357        break;
5358      }
5359#ifdef SQLITE_ENABLE_NORMALIZE
5360      case SHELL_TRACE_NORMALIZED: {
5361        zSql = sqlite3_normalized_sql(pStmt);
5362        break;
5363      }
5364#endif
5365      default: {
5366        zSql = sqlite3_sql(pStmt);
5367        break;
5368      }
5369    }
5370  }
5371  if( zSql==0 ) return 0;
5372  nSql = strlen30(zSql);
5373  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5374  switch( mType ){
5375    case SQLITE_TRACE_ROW:
5376    case SQLITE_TRACE_STMT: {
5377      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5378      break;
5379    }
5380    case SQLITE_TRACE_PROFILE: {
5381      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5382      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5383      break;
5384    }
5385  }
5386  return 0;
5387}
5388#endif
5389
5390/*
5391** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5392** a useful spot to set a debugger breakpoint.
5393*/
5394static void test_breakpoint(void){
5395  static int nCall = 0;
5396  nCall++;
5397}
5398
5399/*
5400** An object used to read a CSV and other files for import.
5401*/
5402typedef struct ImportCtx ImportCtx;
5403struct ImportCtx {
5404  const char *zFile;  /* Name of the input file */
5405  FILE *in;           /* Read the CSV text from this input stream */
5406  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5407  char *z;            /* Accumulated text for a field */
5408  int n;              /* Number of bytes in z */
5409  int nAlloc;         /* Space allocated for z[] */
5410  int nLine;          /* Current line number */
5411  int nRow;           /* Number of rows imported */
5412  int nErr;           /* Number of errors encountered */
5413  int bNotFirst;      /* True if one or more bytes already read */
5414  int cTerm;          /* Character that terminated the most recent field */
5415  int cColSep;        /* The column separator character.  (Usually ",") */
5416  int cRowSep;        /* The row separator character.  (Usually "\n") */
5417};
5418
5419/* Clean up resourced used by an ImportCtx */
5420static void import_cleanup(ImportCtx *p){
5421  if( p->in!=0 && p->xCloser!=0 ){
5422    p->xCloser(p->in);
5423    p->in = 0;
5424  }
5425  sqlite3_free(p->z);
5426  p->z = 0;
5427}
5428
5429/* Append a single byte to z[] */
5430static void import_append_char(ImportCtx *p, int c){
5431  if( p->n+1>=p->nAlloc ){
5432    p->nAlloc += p->nAlloc + 100;
5433    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5434    shell_check_oom(p->z);
5435  }
5436  p->z[p->n++] = (char)c;
5437}
5438
5439/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5440** with the option of having a separator other than ",".
5441**
5442**   +  Input comes from p->in.
5443**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5444**      from sqlite3_malloc64().
5445**   +  Use p->cSep as the column separator.  The default is ",".
5446**   +  Use p->rSep as the row separator.  The default is "\n".
5447**   +  Keep track of the line number in p->nLine.
5448**   +  Store the character that terminates the field in p->cTerm.  Store
5449**      EOF on end-of-file.
5450**   +  Report syntax errors on stderr
5451*/
5452static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5453  int c;
5454  int cSep = p->cColSep;
5455  int rSep = p->cRowSep;
5456  p->n = 0;
5457  c = fgetc(p->in);
5458  if( c==EOF || seenInterrupt ){
5459    p->cTerm = EOF;
5460    return 0;
5461  }
5462  if( c=='"' ){
5463    int pc, ppc;
5464    int startLine = p->nLine;
5465    int cQuote = c;
5466    pc = ppc = 0;
5467    while( 1 ){
5468      c = fgetc(p->in);
5469      if( c==rSep ) p->nLine++;
5470      if( c==cQuote ){
5471        if( pc==cQuote ){
5472          pc = 0;
5473          continue;
5474        }
5475      }
5476      if( (c==cSep && pc==cQuote)
5477       || (c==rSep && pc==cQuote)
5478       || (c==rSep && pc=='\r' && ppc==cQuote)
5479       || (c==EOF && pc==cQuote)
5480      ){
5481        do{ p->n--; }while( p->z[p->n]!=cQuote );
5482        p->cTerm = c;
5483        break;
5484      }
5485      if( pc==cQuote && c!='\r' ){
5486        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5487                p->zFile, p->nLine, cQuote);
5488      }
5489      if( c==EOF ){
5490        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5491                p->zFile, startLine, cQuote);
5492        p->cTerm = c;
5493        break;
5494      }
5495      import_append_char(p, c);
5496      ppc = pc;
5497      pc = c;
5498    }
5499  }else{
5500    /* If this is the first field being parsed and it begins with the
5501    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5502    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5503      import_append_char(p, c);
5504      c = fgetc(p->in);
5505      if( (c&0xff)==0xbb ){
5506        import_append_char(p, c);
5507        c = fgetc(p->in);
5508        if( (c&0xff)==0xbf ){
5509          p->bNotFirst = 1;
5510          p->n = 0;
5511          return csv_read_one_field(p);
5512        }
5513      }
5514    }
5515    while( c!=EOF && c!=cSep && c!=rSep ){
5516      import_append_char(p, c);
5517      c = fgetc(p->in);
5518    }
5519    if( c==rSep ){
5520      p->nLine++;
5521      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5522    }
5523    p->cTerm = c;
5524  }
5525  if( p->z ) p->z[p->n] = 0;
5526  p->bNotFirst = 1;
5527  return p->z;
5528}
5529
5530/* Read a single field of ASCII delimited text.
5531**
5532**   +  Input comes from p->in.
5533**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5534**      from sqlite3_malloc64().
5535**   +  Use p->cSep as the column separator.  The default is "\x1F".
5536**   +  Use p->rSep as the row separator.  The default is "\x1E".
5537**   +  Keep track of the row number in p->nLine.
5538**   +  Store the character that terminates the field in p->cTerm.  Store
5539**      EOF on end-of-file.
5540**   +  Report syntax errors on stderr
5541*/
5542static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5543  int c;
5544  int cSep = p->cColSep;
5545  int rSep = p->cRowSep;
5546  p->n = 0;
5547  c = fgetc(p->in);
5548  if( c==EOF || seenInterrupt ){
5549    p->cTerm = EOF;
5550    return 0;
5551  }
5552  while( c!=EOF && c!=cSep && c!=rSep ){
5553    import_append_char(p, c);
5554    c = fgetc(p->in);
5555  }
5556  if( c==rSep ){
5557    p->nLine++;
5558  }
5559  p->cTerm = c;
5560  if( p->z ) p->z[p->n] = 0;
5561  return p->z;
5562}
5563
5564/*
5565** Try to transfer data for table zTable.  If an error is seen while
5566** moving forward, try to go backwards.  The backwards movement won't
5567** work for WITHOUT ROWID tables.
5568*/
5569static void tryToCloneData(
5570  ShellState *p,
5571  sqlite3 *newDb,
5572  const char *zTable
5573){
5574  sqlite3_stmt *pQuery = 0;
5575  sqlite3_stmt *pInsert = 0;
5576  char *zQuery = 0;
5577  char *zInsert = 0;
5578  int rc;
5579  int i, j, n;
5580  int nTable = strlen30(zTable);
5581  int k = 0;
5582  int cnt = 0;
5583  const int spinRate = 10000;
5584
5585  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5586  shell_check_oom(zQuery);
5587  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5588  if( rc ){
5589    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5590            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5591            zQuery);
5592    goto end_data_xfer;
5593  }
5594  n = sqlite3_column_count(pQuery);
5595  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5596  shell_check_oom(zInsert);
5597  sqlite3_snprintf(200+nTable,zInsert,
5598                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5599  i = strlen30(zInsert);
5600  for(j=1; j<n; j++){
5601    memcpy(zInsert+i, ",?", 2);
5602    i += 2;
5603  }
5604  memcpy(zInsert+i, ");", 3);
5605  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5606  if( rc ){
5607    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5608            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5609            zQuery);
5610    goto end_data_xfer;
5611  }
5612  for(k=0; k<2; k++){
5613    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5614      for(i=0; i<n; i++){
5615        switch( sqlite3_column_type(pQuery, i) ){
5616          case SQLITE_NULL: {
5617            sqlite3_bind_null(pInsert, i+1);
5618            break;
5619          }
5620          case SQLITE_INTEGER: {
5621            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5622            break;
5623          }
5624          case SQLITE_FLOAT: {
5625            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5626            break;
5627          }
5628          case SQLITE_TEXT: {
5629            sqlite3_bind_text(pInsert, i+1,
5630                             (const char*)sqlite3_column_text(pQuery,i),
5631                             -1, SQLITE_STATIC);
5632            break;
5633          }
5634          case SQLITE_BLOB: {
5635            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5636                                            sqlite3_column_bytes(pQuery,i),
5637                                            SQLITE_STATIC);
5638            break;
5639          }
5640        }
5641      } /* End for */
5642      rc = sqlite3_step(pInsert);
5643      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5644        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5645                        sqlite3_errmsg(newDb));
5646      }
5647      sqlite3_reset(pInsert);
5648      cnt++;
5649      if( (cnt%spinRate)==0 ){
5650        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5651        fflush(stdout);
5652      }
5653    } /* End while */
5654    if( rc==SQLITE_DONE ) break;
5655    sqlite3_finalize(pQuery);
5656    sqlite3_free(zQuery);
5657    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5658                             zTable);
5659    shell_check_oom(zQuery);
5660    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5661    if( rc ){
5662      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5663      break;
5664    }
5665  } /* End for(k=0...) */
5666
5667end_data_xfer:
5668  sqlite3_finalize(pQuery);
5669  sqlite3_finalize(pInsert);
5670  sqlite3_free(zQuery);
5671  sqlite3_free(zInsert);
5672}
5673
5674
5675/*
5676** Try to transfer all rows of the schema that match zWhere.  For
5677** each row, invoke xForEach() on the object defined by that row.
5678** If an error is encountered while moving forward through the
5679** sqlite_schema table, try again moving backwards.
5680*/
5681static void tryToCloneSchema(
5682  ShellState *p,
5683  sqlite3 *newDb,
5684  const char *zWhere,
5685  void (*xForEach)(ShellState*,sqlite3*,const char*)
5686){
5687  sqlite3_stmt *pQuery = 0;
5688  char *zQuery = 0;
5689  int rc;
5690  const unsigned char *zName;
5691  const unsigned char *zSql;
5692  char *zErrMsg = 0;
5693
5694  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5695                           " WHERE %s", zWhere);
5696  shell_check_oom(zQuery);
5697  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5698  if( rc ){
5699    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5700                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5701                    zQuery);
5702    goto end_schema_xfer;
5703  }
5704  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5705    zName = sqlite3_column_text(pQuery, 0);
5706    zSql = sqlite3_column_text(pQuery, 1);
5707    if( zName==0 || zSql==0 ) continue;
5708    printf("%s... ", zName); fflush(stdout);
5709    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5710    if( zErrMsg ){
5711      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5712      sqlite3_free(zErrMsg);
5713      zErrMsg = 0;
5714    }
5715    if( xForEach ){
5716      xForEach(p, newDb, (const char*)zName);
5717    }
5718    printf("done\n");
5719  }
5720  if( rc!=SQLITE_DONE ){
5721    sqlite3_finalize(pQuery);
5722    sqlite3_free(zQuery);
5723    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5724                             " WHERE %s ORDER BY rowid DESC", zWhere);
5725    shell_check_oom(zQuery);
5726    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5727    if( rc ){
5728      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5729                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5730                      zQuery);
5731      goto end_schema_xfer;
5732    }
5733    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5734      zName = sqlite3_column_text(pQuery, 0);
5735      zSql = sqlite3_column_text(pQuery, 1);
5736      if( zName==0 || zSql==0 ) continue;
5737      printf("%s... ", zName); fflush(stdout);
5738      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5739      if( zErrMsg ){
5740        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5741        sqlite3_free(zErrMsg);
5742        zErrMsg = 0;
5743      }
5744      if( xForEach ){
5745        xForEach(p, newDb, (const char*)zName);
5746      }
5747      printf("done\n");
5748    }
5749  }
5750end_schema_xfer:
5751  sqlite3_finalize(pQuery);
5752  sqlite3_free(zQuery);
5753}
5754
5755/*
5756** Open a new database file named "zNewDb".  Try to recover as much information
5757** as possible out of the main database (which might be corrupt) and write it
5758** into zNewDb.
5759*/
5760static void tryToClone(ShellState *p, const char *zNewDb){
5761  int rc;
5762  sqlite3 *newDb = 0;
5763  if( access(zNewDb,0)==0 ){
5764    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5765    return;
5766  }
5767  rc = sqlite3_open(zNewDb, &newDb);
5768  if( rc ){
5769    utf8_printf(stderr, "Cannot create output database: %s\n",
5770            sqlite3_errmsg(newDb));
5771  }else{
5772    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5773    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5774    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5775    tryToCloneSchema(p, newDb, "type!='table'", 0);
5776    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5777    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5778  }
5779  close_db(newDb);
5780}
5781
5782/*
5783** Change the output file back to stdout.
5784**
5785** If the p->doXdgOpen flag is set, that means the output was being
5786** redirected to a temporary file named by p->zTempFile.  In that case,
5787** launch start/open/xdg-open on that temporary file.
5788*/
5789static void output_reset(ShellState *p){
5790  if( p->outfile[0]=='|' ){
5791#ifndef SQLITE_OMIT_POPEN
5792    pclose(p->out);
5793#endif
5794  }else{
5795    output_file_close(p->out);
5796#ifndef SQLITE_NOHAVE_SYSTEM
5797    if( p->doXdgOpen ){
5798      const char *zXdgOpenCmd =
5799#if defined(_WIN32)
5800      "start";
5801#elif defined(__APPLE__)
5802      "open";
5803#else
5804      "xdg-open";
5805#endif
5806      char *zCmd;
5807      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5808      if( system(zCmd) ){
5809        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5810      }else{
5811        /* Give the start/open/xdg-open command some time to get
5812        ** going before we continue, and potential delete the
5813        ** p->zTempFile data file out from under it */
5814        sqlite3_sleep(2000);
5815      }
5816      sqlite3_free(zCmd);
5817      outputModePop(p);
5818      p->doXdgOpen = 0;
5819    }
5820#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5821  }
5822  p->outfile[0] = 0;
5823  p->out = stdout;
5824}
5825
5826/*
5827** Run an SQL command and return the single integer result.
5828*/
5829static int db_int(sqlite3 *db, const char *zSql){
5830  sqlite3_stmt *pStmt;
5831  int res = 0;
5832  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5833  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5834    res = sqlite3_column_int(pStmt,0);
5835  }
5836  sqlite3_finalize(pStmt);
5837  return res;
5838}
5839
5840#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5841/*
5842** Convert a 2-byte or 4-byte big-endian integer into a native integer
5843*/
5844static unsigned int get2byteInt(unsigned char *a){
5845  return (a[0]<<8) + a[1];
5846}
5847static unsigned int get4byteInt(unsigned char *a){
5848  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5849}
5850
5851/*
5852** Implementation of the ".dbinfo" command.
5853**
5854** Return 1 on error, 2 to exit, and 0 otherwise.
5855*/
5856static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5857  static const struct { const char *zName; int ofst; } aField[] = {
5858     { "file change counter:",  24  },
5859     { "database page count:",  28  },
5860     { "freelist page count:",  36  },
5861     { "schema cookie:",        40  },
5862     { "schema format:",        44  },
5863     { "default cache size:",   48  },
5864     { "autovacuum top root:",  52  },
5865     { "incremental vacuum:",   64  },
5866     { "text encoding:",        56  },
5867     { "user version:",         60  },
5868     { "application id:",       68  },
5869     { "software version:",     96  },
5870  };
5871  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5872     { "number of tables:",
5873       "SELECT count(*) FROM %s WHERE type='table'" },
5874     { "number of indexes:",
5875       "SELECT count(*) FROM %s WHERE type='index'" },
5876     { "number of triggers:",
5877       "SELECT count(*) FROM %s WHERE type='trigger'" },
5878     { "number of views:",
5879       "SELECT count(*) FROM %s WHERE type='view'" },
5880     { "schema size:",
5881       "SELECT total(length(sql)) FROM %s" },
5882  };
5883  int i, rc;
5884  unsigned iDataVersion;
5885  char *zSchemaTab;
5886  char *zDb = nArg>=2 ? azArg[1] : "main";
5887  sqlite3_stmt *pStmt = 0;
5888  unsigned char aHdr[100];
5889  open_db(p, 0);
5890  if( p->db==0 ) return 1;
5891  rc = sqlite3_prepare_v2(p->db,
5892             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5893             -1, &pStmt, 0);
5894  if( rc ){
5895    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5896    sqlite3_finalize(pStmt);
5897    return 1;
5898  }
5899  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5900  if( sqlite3_step(pStmt)==SQLITE_ROW
5901   && sqlite3_column_bytes(pStmt,0)>100
5902  ){
5903    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5904    sqlite3_finalize(pStmt);
5905  }else{
5906    raw_printf(stderr, "unable to read database header\n");
5907    sqlite3_finalize(pStmt);
5908    return 1;
5909  }
5910  i = get2byteInt(aHdr+16);
5911  if( i==1 ) i = 65536;
5912  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5913  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5914  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5915  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5916  for(i=0; i<ArraySize(aField); i++){
5917    int ofst = aField[i].ofst;
5918    unsigned int val = get4byteInt(aHdr + ofst);
5919    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5920    switch( ofst ){
5921      case 56: {
5922        if( val==1 ) raw_printf(p->out, " (utf8)");
5923        if( val==2 ) raw_printf(p->out, " (utf16le)");
5924        if( val==3 ) raw_printf(p->out, " (utf16be)");
5925      }
5926    }
5927    raw_printf(p->out, "\n");
5928  }
5929  if( zDb==0 ){
5930    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5931  }else if( strcmp(zDb,"temp")==0 ){
5932    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5933  }else{
5934    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5935  }
5936  for(i=0; i<ArraySize(aQuery); i++){
5937    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5938    int val = db_int(p->db, zSql);
5939    sqlite3_free(zSql);
5940    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5941  }
5942  sqlite3_free(zSchemaTab);
5943  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5944  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5945  return 0;
5946}
5947#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5948          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5949
5950/*
5951** Print the current sqlite3_errmsg() value to stderr and return 1.
5952*/
5953static int shellDatabaseError(sqlite3 *db){
5954  const char *zErr = sqlite3_errmsg(db);
5955  utf8_printf(stderr, "Error: %s\n", zErr);
5956  return 1;
5957}
5958
5959/*
5960** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5961** if they match and FALSE (0) if they do not match.
5962**
5963** Globbing rules:
5964**
5965**      '*'       Matches any sequence of zero or more characters.
5966**
5967**      '?'       Matches exactly one character.
5968**
5969**     [...]      Matches one character from the enclosed list of
5970**                characters.
5971**
5972**     [^...]     Matches one character not in the enclosed list.
5973**
5974**      '#'       Matches any sequence of one or more digits with an
5975**                optional + or - sign in front
5976**
5977**      ' '       Any span of whitespace matches any other span of
5978**                whitespace.
5979**
5980** Extra whitespace at the end of z[] is ignored.
5981*/
5982static int testcase_glob(const char *zGlob, const char *z){
5983  int c, c2;
5984  int invert;
5985  int seen;
5986
5987  while( (c = (*(zGlob++)))!=0 ){
5988    if( IsSpace(c) ){
5989      if( !IsSpace(*z) ) return 0;
5990      while( IsSpace(*zGlob) ) zGlob++;
5991      while( IsSpace(*z) ) z++;
5992    }else if( c=='*' ){
5993      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5994        if( c=='?' && (*(z++))==0 ) return 0;
5995      }
5996      if( c==0 ){
5997        return 1;
5998      }else if( c=='[' ){
5999        while( *z && testcase_glob(zGlob-1,z)==0 ){
6000          z++;
6001        }
6002        return (*z)!=0;
6003      }
6004      while( (c2 = (*(z++)))!=0 ){
6005        while( c2!=c ){
6006          c2 = *(z++);
6007          if( c2==0 ) return 0;
6008        }
6009        if( testcase_glob(zGlob,z) ) return 1;
6010      }
6011      return 0;
6012    }else if( c=='?' ){
6013      if( (*(z++))==0 ) return 0;
6014    }else if( c=='[' ){
6015      int prior_c = 0;
6016      seen = 0;
6017      invert = 0;
6018      c = *(z++);
6019      if( c==0 ) return 0;
6020      c2 = *(zGlob++);
6021      if( c2=='^' ){
6022        invert = 1;
6023        c2 = *(zGlob++);
6024      }
6025      if( c2==']' ){
6026        if( c==']' ) seen = 1;
6027        c2 = *(zGlob++);
6028      }
6029      while( c2 && c2!=']' ){
6030        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6031          c2 = *(zGlob++);
6032          if( c>=prior_c && c<=c2 ) seen = 1;
6033          prior_c = 0;
6034        }else{
6035          if( c==c2 ){
6036            seen = 1;
6037          }
6038          prior_c = c2;
6039        }
6040        c2 = *(zGlob++);
6041      }
6042      if( c2==0 || (seen ^ invert)==0 ) return 0;
6043    }else if( c=='#' ){
6044      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6045      if( !IsDigit(z[0]) ) return 0;
6046      z++;
6047      while( IsDigit(z[0]) ){ z++; }
6048    }else{
6049      if( c!=(*(z++)) ) return 0;
6050    }
6051  }
6052  while( IsSpace(*z) ){ z++; }
6053  return *z==0;
6054}
6055
6056
6057/*
6058** Compare the string as a command-line option with either one or two
6059** initial "-" characters.
6060*/
6061static int optionMatch(const char *zStr, const char *zOpt){
6062  if( zStr[0]!='-' ) return 0;
6063  zStr++;
6064  if( zStr[0]=='-' ) zStr++;
6065  return strcmp(zStr, zOpt)==0;
6066}
6067
6068/*
6069** Delete a file.
6070*/
6071int shellDeleteFile(const char *zFilename){
6072  int rc;
6073#ifdef _WIN32
6074  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6075  rc = _wunlink(z);
6076  sqlite3_free(z);
6077#else
6078  rc = unlink(zFilename);
6079#endif
6080  return rc;
6081}
6082
6083/*
6084** Try to delete the temporary file (if there is one) and free the
6085** memory used to hold the name of the temp file.
6086*/
6087static void clearTempFile(ShellState *p){
6088  if( p->zTempFile==0 ) return;
6089  if( p->doXdgOpen ) return;
6090  if( shellDeleteFile(p->zTempFile) ) return;
6091  sqlite3_free(p->zTempFile);
6092  p->zTempFile = 0;
6093}
6094
6095/*
6096** Create a new temp file name with the given suffix.
6097*/
6098static void newTempFile(ShellState *p, const char *zSuffix){
6099  clearTempFile(p);
6100  sqlite3_free(p->zTempFile);
6101  p->zTempFile = 0;
6102  if( p->db ){
6103    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6104  }
6105  if( p->zTempFile==0 ){
6106    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6107    ** will not work and we will need to fallback to guessing */
6108    char *zTemp;
6109    sqlite3_uint64 r;
6110    sqlite3_randomness(sizeof(r), &r);
6111    zTemp = getenv("TEMP");
6112    if( zTemp==0 ) zTemp = getenv("TMP");
6113    if( zTemp==0 ){
6114#ifdef _WIN32
6115      zTemp = "\\tmp";
6116#else
6117      zTemp = "/tmp";
6118#endif
6119    }
6120    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6121  }else{
6122    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6123  }
6124  shell_check_oom(p->zTempFile);
6125}
6126
6127
6128/*
6129** The implementation of SQL scalar function fkey_collate_clause(), used
6130** by the ".lint fkey-indexes" command. This scalar function is always
6131** called with four arguments - the parent table name, the parent column name,
6132** the child table name and the child column name.
6133**
6134**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6135**
6136** If either of the named tables or columns do not exist, this function
6137** returns an empty string. An empty string is also returned if both tables
6138** and columns exist but have the same default collation sequence. Or,
6139** if both exist but the default collation sequences are different, this
6140** function returns the string " COLLATE <parent-collation>", where
6141** <parent-collation> is the default collation sequence of the parent column.
6142*/
6143static void shellFkeyCollateClause(
6144  sqlite3_context *pCtx,
6145  int nVal,
6146  sqlite3_value **apVal
6147){
6148  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6149  const char *zParent;
6150  const char *zParentCol;
6151  const char *zParentSeq;
6152  const char *zChild;
6153  const char *zChildCol;
6154  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6155  int rc;
6156
6157  assert( nVal==4 );
6158  zParent = (const char*)sqlite3_value_text(apVal[0]);
6159  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6160  zChild = (const char*)sqlite3_value_text(apVal[2]);
6161  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6162
6163  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6164  rc = sqlite3_table_column_metadata(
6165      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6166  );
6167  if( rc==SQLITE_OK ){
6168    rc = sqlite3_table_column_metadata(
6169        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6170    );
6171  }
6172
6173  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6174    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6175    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6176    sqlite3_free(z);
6177  }
6178}
6179
6180
6181/*
6182** The implementation of dot-command ".lint fkey-indexes".
6183*/
6184static int lintFkeyIndexes(
6185  ShellState *pState,             /* Current shell tool state */
6186  char **azArg,                   /* Array of arguments passed to dot command */
6187  int nArg                        /* Number of entries in azArg[] */
6188){
6189  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6190  FILE *out = pState->out;        /* Stream to write non-error output to */
6191  int bVerbose = 0;               /* If -verbose is present */
6192  int bGroupByParent = 0;         /* If -groupbyparent is present */
6193  int i;                          /* To iterate through azArg[] */
6194  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6195  int rc;                         /* Return code */
6196  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6197
6198  /*
6199  ** This SELECT statement returns one row for each foreign key constraint
6200  ** in the schema of the main database. The column values are:
6201  **
6202  ** 0. The text of an SQL statement similar to:
6203  **
6204  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6205  **
6206  **    This SELECT is similar to the one that the foreign keys implementation
6207  **    needs to run internally on child tables. If there is an index that can
6208  **    be used to optimize this query, then it can also be used by the FK
6209  **    implementation to optimize DELETE or UPDATE statements on the parent
6210  **    table.
6211  **
6212  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6213  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6214  **    contains an index that can be used to optimize the query.
6215  **
6216  ** 2. Human readable text that describes the child table and columns. e.g.
6217  **
6218  **       "child_table(child_key1, child_key2)"
6219  **
6220  ** 3. Human readable text that describes the parent table and columns. e.g.
6221  **
6222  **       "parent_table(parent_key1, parent_key2)"
6223  **
6224  ** 4. A full CREATE INDEX statement for an index that could be used to
6225  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6226  **
6227  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6228  **
6229  ** 5. The name of the parent table.
6230  **
6231  ** These six values are used by the C logic below to generate the report.
6232  */
6233  const char *zSql =
6234  "SELECT "
6235    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6236    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6237    "  || fkey_collate_clause("
6238    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6239    ", "
6240    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6241    "  || group_concat('*=?', ' AND ') || ')'"
6242    ", "
6243    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6244    ", "
6245    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6246    ", "
6247    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6248    "  || ' ON ' || quote(s.name) || '('"
6249    "  || group_concat(quote(f.[from]) ||"
6250    "        fkey_collate_clause("
6251    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6252    "  || ');'"
6253    ", "
6254    "     f.[table] "
6255    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6256    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6257    "GROUP BY s.name, f.id "
6258    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6259  ;
6260  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6261
6262  for(i=2; i<nArg; i++){
6263    int n = strlen30(azArg[i]);
6264    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6265      bVerbose = 1;
6266    }
6267    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6268      bGroupByParent = 1;
6269      zIndent = "    ";
6270    }
6271    else{
6272      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6273          azArg[0], azArg[1]
6274      );
6275      return SQLITE_ERROR;
6276    }
6277  }
6278
6279  /* Register the fkey_collate_clause() SQL function */
6280  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6281      0, shellFkeyCollateClause, 0, 0
6282  );
6283
6284
6285  if( rc==SQLITE_OK ){
6286    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6287  }
6288  if( rc==SQLITE_OK ){
6289    sqlite3_bind_int(pSql, 1, bGroupByParent);
6290  }
6291
6292  if( rc==SQLITE_OK ){
6293    int rc2;
6294    char *zPrev = 0;
6295    while( SQLITE_ROW==sqlite3_step(pSql) ){
6296      int res = -1;
6297      sqlite3_stmt *pExplain = 0;
6298      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6299      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6300      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6301      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6302      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6303      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6304
6305      if( zEQP==0 ) continue;
6306      if( zGlob==0 ) continue;
6307      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6308      if( rc!=SQLITE_OK ) break;
6309      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6310        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6311        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6312                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6313      }
6314      rc = sqlite3_finalize(pExplain);
6315      if( rc!=SQLITE_OK ) break;
6316
6317      if( res<0 ){
6318        raw_printf(stderr, "Error: internal error");
6319        break;
6320      }else{
6321        if( bGroupByParent
6322        && (bVerbose || res==0)
6323        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6324        ){
6325          raw_printf(out, "-- Parent table %s\n", zParent);
6326          sqlite3_free(zPrev);
6327          zPrev = sqlite3_mprintf("%s", zParent);
6328        }
6329
6330        if( res==0 ){
6331          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6332        }else if( bVerbose ){
6333          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6334              zIndent, zFrom, zTarget
6335          );
6336        }
6337      }
6338    }
6339    sqlite3_free(zPrev);
6340
6341    if( rc!=SQLITE_OK ){
6342      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6343    }
6344
6345    rc2 = sqlite3_finalize(pSql);
6346    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6347      rc = rc2;
6348      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6349    }
6350  }else{
6351    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6352  }
6353
6354  return rc;
6355}
6356
6357/*
6358** Implementation of ".lint" dot command.
6359*/
6360static int lintDotCommand(
6361  ShellState *pState,             /* Current shell tool state */
6362  char **azArg,                   /* Array of arguments passed to dot command */
6363  int nArg                        /* Number of entries in azArg[] */
6364){
6365  int n;
6366  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6367  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6368  return lintFkeyIndexes(pState, azArg, nArg);
6369
6370 usage:
6371  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6372  raw_printf(stderr, "Where sub-commands are:\n");
6373  raw_printf(stderr, "    fkey-indexes\n");
6374  return SQLITE_ERROR;
6375}
6376
6377#if !defined SQLITE_OMIT_VIRTUALTABLE
6378static void shellPrepare(
6379  sqlite3 *db,
6380  int *pRc,
6381  const char *zSql,
6382  sqlite3_stmt **ppStmt
6383){
6384  *ppStmt = 0;
6385  if( *pRc==SQLITE_OK ){
6386    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6387    if( rc!=SQLITE_OK ){
6388      raw_printf(stderr, "sql error: %s (%d)\n",
6389          sqlite3_errmsg(db), sqlite3_errcode(db)
6390      );
6391      *pRc = rc;
6392    }
6393  }
6394}
6395
6396/*
6397** Create a prepared statement using printf-style arguments for the SQL.
6398**
6399** This routine is could be marked "static".  But it is not always used,
6400** depending on compile-time options.  By omitting the "static", we avoid
6401** nuisance compiler warnings about "defined but not used".
6402*/
6403void shellPreparePrintf(
6404  sqlite3 *db,
6405  int *pRc,
6406  sqlite3_stmt **ppStmt,
6407  const char *zFmt,
6408  ...
6409){
6410  *ppStmt = 0;
6411  if( *pRc==SQLITE_OK ){
6412    va_list ap;
6413    char *z;
6414    va_start(ap, zFmt);
6415    z = sqlite3_vmprintf(zFmt, ap);
6416    va_end(ap);
6417    if( z==0 ){
6418      *pRc = SQLITE_NOMEM;
6419    }else{
6420      shellPrepare(db, pRc, z, ppStmt);
6421      sqlite3_free(z);
6422    }
6423  }
6424}
6425
6426/* Finalize the prepared statement created using shellPreparePrintf().
6427**
6428** This routine is could be marked "static".  But it is not always used,
6429** depending on compile-time options.  By omitting the "static", we avoid
6430** nuisance compiler warnings about "defined but not used".
6431*/
6432void shellFinalize(
6433  int *pRc,
6434  sqlite3_stmt *pStmt
6435){
6436  if( pStmt ){
6437    sqlite3 *db = sqlite3_db_handle(pStmt);
6438    int rc = sqlite3_finalize(pStmt);
6439    if( *pRc==SQLITE_OK ){
6440      if( rc!=SQLITE_OK ){
6441        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6442      }
6443      *pRc = rc;
6444    }
6445  }
6446}
6447
6448/* Reset the prepared statement created using shellPreparePrintf().
6449**
6450** This routine is could be marked "static".  But it is not always used,
6451** depending on compile-time options.  By omitting the "static", we avoid
6452** nuisance compiler warnings about "defined but not used".
6453*/
6454void shellReset(
6455  int *pRc,
6456  sqlite3_stmt *pStmt
6457){
6458  int rc = sqlite3_reset(pStmt);
6459  if( *pRc==SQLITE_OK ){
6460    if( rc!=SQLITE_OK ){
6461      sqlite3 *db = sqlite3_db_handle(pStmt);
6462      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6463    }
6464    *pRc = rc;
6465  }
6466}
6467#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6468
6469#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6470/******************************************************************************
6471** The ".archive" or ".ar" command.
6472*/
6473/*
6474** Structure representing a single ".ar" command.
6475*/
6476typedef struct ArCommand ArCommand;
6477struct ArCommand {
6478  u8 eCmd;                        /* An AR_CMD_* value */
6479  u8 bVerbose;                    /* True if --verbose */
6480  u8 bZip;                        /* True if the archive is a ZIP */
6481  u8 bDryRun;                     /* True if --dry-run */
6482  u8 bAppend;                     /* True if --append */
6483  u8 bGlob;                       /* True if --glob */
6484  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6485  int nArg;                       /* Number of command arguments */
6486  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6487  const char *zFile;              /* --file argument, or NULL */
6488  const char *zDir;               /* --directory argument, or NULL */
6489  char **azArg;                   /* Array of command arguments */
6490  ShellState *p;                  /* Shell state */
6491  sqlite3 *db;                    /* Database containing the archive */
6492};
6493
6494/*
6495** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6496*/
6497static int arUsage(FILE *f){
6498  showHelp(f,"archive");
6499  return SQLITE_ERROR;
6500}
6501
6502/*
6503** Print an error message for the .ar command to stderr and return
6504** SQLITE_ERROR.
6505*/
6506static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6507  va_list ap;
6508  char *z;
6509  va_start(ap, zFmt);
6510  z = sqlite3_vmprintf(zFmt, ap);
6511  va_end(ap);
6512  utf8_printf(stderr, "Error: %s\n", z);
6513  if( pAr->fromCmdLine ){
6514    utf8_printf(stderr, "Use \"-A\" for more help\n");
6515  }else{
6516    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6517  }
6518  sqlite3_free(z);
6519  return SQLITE_ERROR;
6520}
6521
6522/*
6523** Values for ArCommand.eCmd.
6524*/
6525#define AR_CMD_CREATE       1
6526#define AR_CMD_UPDATE       2
6527#define AR_CMD_INSERT       3
6528#define AR_CMD_EXTRACT      4
6529#define AR_CMD_LIST         5
6530#define AR_CMD_HELP         6
6531#define AR_CMD_REMOVE       7
6532
6533/*
6534** Other (non-command) switches.
6535*/
6536#define AR_SWITCH_VERBOSE     8
6537#define AR_SWITCH_FILE        9
6538#define AR_SWITCH_DIRECTORY  10
6539#define AR_SWITCH_APPEND     11
6540#define AR_SWITCH_DRYRUN     12
6541#define AR_SWITCH_GLOB       13
6542
6543static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6544  switch( eSwitch ){
6545    case AR_CMD_CREATE:
6546    case AR_CMD_EXTRACT:
6547    case AR_CMD_LIST:
6548    case AR_CMD_REMOVE:
6549    case AR_CMD_UPDATE:
6550    case AR_CMD_INSERT:
6551    case AR_CMD_HELP:
6552      if( pAr->eCmd ){
6553        return arErrorMsg(pAr, "multiple command options");
6554      }
6555      pAr->eCmd = eSwitch;
6556      break;
6557
6558    case AR_SWITCH_DRYRUN:
6559      pAr->bDryRun = 1;
6560      break;
6561    case AR_SWITCH_GLOB:
6562      pAr->bGlob = 1;
6563      break;
6564    case AR_SWITCH_VERBOSE:
6565      pAr->bVerbose = 1;
6566      break;
6567    case AR_SWITCH_APPEND:
6568      pAr->bAppend = 1;
6569      /* Fall thru into --file */
6570    case AR_SWITCH_FILE:
6571      pAr->zFile = zArg;
6572      break;
6573    case AR_SWITCH_DIRECTORY:
6574      pAr->zDir = zArg;
6575      break;
6576  }
6577
6578  return SQLITE_OK;
6579}
6580
6581/*
6582** Parse the command line for an ".ar" command. The results are written into
6583** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6584** successfully, otherwise an error message is written to stderr and
6585** SQLITE_ERROR returned.
6586*/
6587static int arParseCommand(
6588  char **azArg,                   /* Array of arguments passed to dot command */
6589  int nArg,                       /* Number of entries in azArg[] */
6590  ArCommand *pAr                  /* Populate this object */
6591){
6592  struct ArSwitch {
6593    const char *zLong;
6594    char cShort;
6595    u8 eSwitch;
6596    u8 bArg;
6597  } aSwitch[] = {
6598    { "create",    'c', AR_CMD_CREATE,       0 },
6599    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6600    { "insert",    'i', AR_CMD_INSERT,       0 },
6601    { "list",      't', AR_CMD_LIST,         0 },
6602    { "remove",    'r', AR_CMD_REMOVE,       0 },
6603    { "update",    'u', AR_CMD_UPDATE,       0 },
6604    { "help",      'h', AR_CMD_HELP,         0 },
6605    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6606    { "file",      'f', AR_SWITCH_FILE,      1 },
6607    { "append",    'a', AR_SWITCH_APPEND,    1 },
6608    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6609    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6610    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6611  };
6612  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6613  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6614
6615  if( nArg<=1 ){
6616    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6617    return arUsage(stderr);
6618  }else{
6619    char *z = azArg[1];
6620    if( z[0]!='-' ){
6621      /* Traditional style [tar] invocation */
6622      int i;
6623      int iArg = 2;
6624      for(i=0; z[i]; i++){
6625        const char *zArg = 0;
6626        struct ArSwitch *pOpt;
6627        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6628          if( z[i]==pOpt->cShort ) break;
6629        }
6630        if( pOpt==pEnd ){
6631          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6632        }
6633        if( pOpt->bArg ){
6634          if( iArg>=nArg ){
6635            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6636          }
6637          zArg = azArg[iArg++];
6638        }
6639        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6640      }
6641      pAr->nArg = nArg-iArg;
6642      if( pAr->nArg>0 ){
6643        pAr->azArg = &azArg[iArg];
6644      }
6645    }else{
6646      /* Non-traditional invocation */
6647      int iArg;
6648      for(iArg=1; iArg<nArg; iArg++){
6649        int n;
6650        z = azArg[iArg];
6651        if( z[0]!='-' ){
6652          /* All remaining command line words are command arguments. */
6653          pAr->azArg = &azArg[iArg];
6654          pAr->nArg = nArg-iArg;
6655          break;
6656        }
6657        n = strlen30(z);
6658
6659        if( z[1]!='-' ){
6660          int i;
6661          /* One or more short options */
6662          for(i=1; i<n; i++){
6663            const char *zArg = 0;
6664            struct ArSwitch *pOpt;
6665            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6666              if( z[i]==pOpt->cShort ) break;
6667            }
6668            if( pOpt==pEnd ){
6669              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6670            }
6671            if( pOpt->bArg ){
6672              if( i<(n-1) ){
6673                zArg = &z[i+1];
6674                i = n;
6675              }else{
6676                if( iArg>=(nArg-1) ){
6677                  return arErrorMsg(pAr, "option requires an argument: %c",
6678                                    z[i]);
6679                }
6680                zArg = azArg[++iArg];
6681              }
6682            }
6683            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6684          }
6685        }else if( z[2]=='\0' ){
6686          /* A -- option, indicating that all remaining command line words
6687          ** are command arguments.  */
6688          pAr->azArg = &azArg[iArg+1];
6689          pAr->nArg = nArg-iArg-1;
6690          break;
6691        }else{
6692          /* A long option */
6693          const char *zArg = 0;             /* Argument for option, if any */
6694          struct ArSwitch *pMatch = 0;      /* Matching option */
6695          struct ArSwitch *pOpt;            /* Iterator */
6696          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6697            const char *zLong = pOpt->zLong;
6698            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6699              if( pMatch ){
6700                return arErrorMsg(pAr, "ambiguous option: %s",z);
6701              }else{
6702                pMatch = pOpt;
6703              }
6704            }
6705          }
6706
6707          if( pMatch==0 ){
6708            return arErrorMsg(pAr, "unrecognized option: %s", z);
6709          }
6710          if( pMatch->bArg ){
6711            if( iArg>=(nArg-1) ){
6712              return arErrorMsg(pAr, "option requires an argument: %s", z);
6713            }
6714            zArg = azArg[++iArg];
6715          }
6716          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6717        }
6718      }
6719    }
6720  }
6721
6722  return SQLITE_OK;
6723}
6724
6725/*
6726** This function assumes that all arguments within the ArCommand.azArg[]
6727** array refer to archive members, as for the --extract, --list or --remove
6728** commands. It checks that each of them are "present". If any specified
6729** file is not present in the archive, an error is printed to stderr and an
6730** error code returned. Otherwise, if all specified arguments are present
6731** in the archive, SQLITE_OK is returned. Here, "present" means either an
6732** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6733** when pAr->bGlob is true.
6734**
6735** This function strips any trailing '/' characters from each argument.
6736** This is consistent with the way the [tar] command seems to work on
6737** Linux.
6738*/
6739static int arCheckEntries(ArCommand *pAr){
6740  int rc = SQLITE_OK;
6741  if( pAr->nArg ){
6742    int i, j;
6743    sqlite3_stmt *pTest = 0;
6744    const char *zSel = (pAr->bGlob)
6745      ? "SELECT name FROM %s WHERE glob($name,name)"
6746      : "SELECT name FROM %s WHERE name=$name";
6747
6748    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6749    j = sqlite3_bind_parameter_index(pTest, "$name");
6750    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6751      char *z = pAr->azArg[i];
6752      int n = strlen30(z);
6753      int bOk = 0;
6754      while( n>0 && z[n-1]=='/' ) n--;
6755      z[n] = '\0';
6756      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6757      if( SQLITE_ROW==sqlite3_step(pTest) ){
6758        bOk = 1;
6759      }
6760      shellReset(&rc, pTest);
6761      if( rc==SQLITE_OK && bOk==0 ){
6762        utf8_printf(stderr, "not found in archive: %s\n", z);
6763        rc = SQLITE_ERROR;
6764      }
6765    }
6766    shellFinalize(&rc, pTest);
6767  }
6768  return rc;
6769}
6770
6771/*
6772** Format a WHERE clause that can be used against the "sqlar" table to
6773** identify all archive members that match the command arguments held
6774** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6775** The caller is responsible for eventually calling sqlite3_free() on
6776** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6777** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6778*/
6779static void arWhereClause(
6780  int *pRc,
6781  ArCommand *pAr,
6782  char **pzWhere                  /* OUT: New WHERE clause */
6783){
6784  char *zWhere = 0;
6785  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6786  if( *pRc==SQLITE_OK ){
6787    if( pAr->nArg==0 ){
6788      zWhere = sqlite3_mprintf("1");
6789    }else{
6790      int i;
6791      const char *zSep = "";
6792      for(i=0; i<pAr->nArg; i++){
6793        const char *z = pAr->azArg[i];
6794        zWhere = sqlite3_mprintf(
6795          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6796          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6797        );
6798        if( zWhere==0 ){
6799          *pRc = SQLITE_NOMEM;
6800          break;
6801        }
6802        zSep = " OR ";
6803      }
6804    }
6805  }
6806  *pzWhere = zWhere;
6807}
6808
6809/*
6810** Implementation of .ar "lisT" command.
6811*/
6812static int arListCommand(ArCommand *pAr){
6813  const char *zSql = "SELECT %s FROM %s WHERE %s";
6814  const char *azCols[] = {
6815    "name",
6816    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6817  };
6818
6819  char *zWhere = 0;
6820  sqlite3_stmt *pSql = 0;
6821  int rc;
6822
6823  rc = arCheckEntries(pAr);
6824  arWhereClause(&rc, pAr, &zWhere);
6825
6826  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6827                     pAr->zSrcTable, zWhere);
6828  if( pAr->bDryRun ){
6829    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6830  }else{
6831    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6832      if( pAr->bVerbose ){
6833        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6834            sqlite3_column_text(pSql, 0),
6835            sqlite3_column_int(pSql, 1),
6836            sqlite3_column_text(pSql, 2),
6837            sqlite3_column_text(pSql, 3)
6838        );
6839      }else{
6840        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6841      }
6842    }
6843  }
6844  shellFinalize(&rc, pSql);
6845  sqlite3_free(zWhere);
6846  return rc;
6847}
6848
6849
6850/*
6851** Implementation of .ar "Remove" command.
6852*/
6853static int arRemoveCommand(ArCommand *pAr){
6854  int rc = 0;
6855  char *zSql = 0;
6856  char *zWhere = 0;
6857
6858  if( pAr->nArg ){
6859    /* Verify that args actually exist within the archive before proceeding.
6860    ** And formulate a WHERE clause to match them.  */
6861    rc = arCheckEntries(pAr);
6862    arWhereClause(&rc, pAr, &zWhere);
6863  }
6864  if( rc==SQLITE_OK ){
6865    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6866                           pAr->zSrcTable, zWhere);
6867    if( pAr->bDryRun ){
6868      utf8_printf(pAr->p->out, "%s\n", zSql);
6869    }else{
6870      char *zErr = 0;
6871      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6872      if( rc==SQLITE_OK ){
6873        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6874        if( rc!=SQLITE_OK ){
6875          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6876        }else{
6877          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6878        }
6879      }
6880      if( zErr ){
6881        utf8_printf(stdout, "ERROR: %s\n", zErr);
6882        sqlite3_free(zErr);
6883      }
6884    }
6885  }
6886  sqlite3_free(zWhere);
6887  sqlite3_free(zSql);
6888  return rc;
6889}
6890
6891/*
6892** Implementation of .ar "eXtract" command.
6893*/
6894static int arExtractCommand(ArCommand *pAr){
6895  const char *zSql1 =
6896    "SELECT "
6897    " ($dir || name),"
6898    " writefile(($dir || name), %s, mode, mtime) "
6899    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6900    " AND name NOT GLOB '*..[/\\]*'";
6901
6902  const char *azExtraArg[] = {
6903    "sqlar_uncompress(data, sz)",
6904    "data"
6905  };
6906
6907  sqlite3_stmt *pSql = 0;
6908  int rc = SQLITE_OK;
6909  char *zDir = 0;
6910  char *zWhere = 0;
6911  int i, j;
6912
6913  /* If arguments are specified, check that they actually exist within
6914  ** the archive before proceeding. And formulate a WHERE clause to
6915  ** match them.  */
6916  rc = arCheckEntries(pAr);
6917  arWhereClause(&rc, pAr, &zWhere);
6918
6919  if( rc==SQLITE_OK ){
6920    if( pAr->zDir ){
6921      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6922    }else{
6923      zDir = sqlite3_mprintf("");
6924    }
6925    if( zDir==0 ) rc = SQLITE_NOMEM;
6926  }
6927
6928  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6929      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6930  );
6931
6932  if( rc==SQLITE_OK ){
6933    j = sqlite3_bind_parameter_index(pSql, "$dir");
6934    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6935
6936    /* Run the SELECT statement twice. The first time, writefile() is called
6937    ** for all archive members that should be extracted. The second time,
6938    ** only for the directories. This is because the timestamps for
6939    ** extracted directories must be reset after they are populated (as
6940    ** populating them changes the timestamp).  */
6941    for(i=0; i<2; i++){
6942      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6943      sqlite3_bind_int(pSql, j, i);
6944      if( pAr->bDryRun ){
6945        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6946      }else{
6947        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6948          if( i==0 && pAr->bVerbose ){
6949            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6950          }
6951        }
6952      }
6953      shellReset(&rc, pSql);
6954    }
6955    shellFinalize(&rc, pSql);
6956  }
6957
6958  sqlite3_free(zDir);
6959  sqlite3_free(zWhere);
6960  return rc;
6961}
6962
6963/*
6964** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6965*/
6966static int arExecSql(ArCommand *pAr, const char *zSql){
6967  int rc;
6968  if( pAr->bDryRun ){
6969    utf8_printf(pAr->p->out, "%s\n", zSql);
6970    rc = SQLITE_OK;
6971  }else{
6972    char *zErr = 0;
6973    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6974    if( zErr ){
6975      utf8_printf(stdout, "ERROR: %s\n", zErr);
6976      sqlite3_free(zErr);
6977    }
6978  }
6979  return rc;
6980}
6981
6982
6983/*
6984** Implementation of .ar "create", "insert", and "update" commands.
6985**
6986**     create    ->     Create a new SQL archive
6987**     insert    ->     Insert or reinsert all files listed
6988**     update    ->     Insert files that have changed or that were not
6989**                      previously in the archive
6990**
6991** Create the "sqlar" table in the database if it does not already exist.
6992** Then add each file in the azFile[] array to the archive. Directories
6993** are added recursively. If argument bVerbose is non-zero, a message is
6994** printed on stdout for each file archived.
6995**
6996** The create command is the same as update, except that it drops
6997** any existing "sqlar" table before beginning.  The "insert" command
6998** always overwrites every file named on the command-line, where as
6999** "update" only overwrites if the size or mtime or mode has changed.
7000*/
7001static int arCreateOrUpdateCommand(
7002  ArCommand *pAr,                 /* Command arguments and options */
7003  int bUpdate,                    /* true for a --create. */
7004  int bOnlyIfChanged              /* Only update if file has changed */
7005){
7006  const char *zCreate =
7007      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7008      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7009      "  mode INT,               -- access permissions\n"
7010      "  mtime INT,              -- last modification time\n"
7011      "  sz INT,                 -- original file size\n"
7012      "  data BLOB               -- compressed content\n"
7013      ")";
7014  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7015  const char *zInsertFmt[2] = {
7016     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7017     "  SELECT\n"
7018     "    %s,\n"
7019     "    mode,\n"
7020     "    mtime,\n"
7021     "    CASE substr(lsmode(mode),1,1)\n"
7022     "      WHEN '-' THEN length(data)\n"
7023     "      WHEN 'd' THEN 0\n"
7024     "      ELSE -1 END,\n"
7025     "    sqlar_compress(data)\n"
7026     "  FROM fsdir(%Q,%Q) AS disk\n"
7027     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7028     ,
7029     "REPLACE INTO %s(name,mode,mtime,data)\n"
7030     "  SELECT\n"
7031     "    %s,\n"
7032     "    mode,\n"
7033     "    mtime,\n"
7034     "    data\n"
7035     "  FROM fsdir(%Q,%Q) AS disk\n"
7036     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7037  };
7038  int i;                          /* For iterating through azFile[] */
7039  int rc;                         /* Return code */
7040  const char *zTab = 0;           /* SQL table into which to insert */
7041  char *zSql;
7042  char zTemp[50];
7043  char *zExists = 0;
7044
7045  arExecSql(pAr, "PRAGMA page_size=512");
7046  rc = arExecSql(pAr, "SAVEPOINT ar;");
7047  if( rc!=SQLITE_OK ) return rc;
7048  zTemp[0] = 0;
7049  if( pAr->bZip ){
7050    /* Initialize the zipfile virtual table, if necessary */
7051    if( pAr->zFile ){
7052      sqlite3_uint64 r;
7053      sqlite3_randomness(sizeof(r),&r);
7054      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7055      zTab = zTemp;
7056      zSql = sqlite3_mprintf(
7057         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7058         zTab, pAr->zFile
7059      );
7060      rc = arExecSql(pAr, zSql);
7061      sqlite3_free(zSql);
7062    }else{
7063      zTab = "zip";
7064    }
7065  }else{
7066    /* Initialize the table for an SQLAR */
7067    zTab = "sqlar";
7068    if( bUpdate==0 ){
7069      rc = arExecSql(pAr, zDrop);
7070      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7071    }
7072    rc = arExecSql(pAr, zCreate);
7073  }
7074  if( bOnlyIfChanged ){
7075    zExists = sqlite3_mprintf(
7076      " AND NOT EXISTS("
7077          "SELECT 1 FROM %s AS mem"
7078          " WHERE mem.name=disk.name"
7079          " AND mem.mtime=disk.mtime"
7080          " AND mem.mode=disk.mode)", zTab);
7081  }else{
7082    zExists = sqlite3_mprintf("");
7083  }
7084  if( zExists==0 ) rc = SQLITE_NOMEM;
7085  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7086    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7087        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7088        pAr->azArg[i], pAr->zDir, zExists);
7089    rc = arExecSql(pAr, zSql2);
7090    sqlite3_free(zSql2);
7091  }
7092end_ar_transaction:
7093  if( rc!=SQLITE_OK ){
7094    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7095  }else{
7096    rc = arExecSql(pAr, "RELEASE ar;");
7097    if( pAr->bZip && pAr->zFile ){
7098      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7099      arExecSql(pAr, zSql);
7100      sqlite3_free(zSql);
7101    }
7102  }
7103  sqlite3_free(zExists);
7104  return rc;
7105}
7106
7107/*
7108** Implementation of ".ar" dot command.
7109*/
7110static int arDotCommand(
7111  ShellState *pState,          /* Current shell tool state */
7112  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7113  char **azArg,                /* Array of arguments passed to dot command */
7114  int nArg                     /* Number of entries in azArg[] */
7115){
7116  ArCommand cmd;
7117  int rc;
7118  memset(&cmd, 0, sizeof(cmd));
7119  cmd.fromCmdLine = fromCmdLine;
7120  rc = arParseCommand(azArg, nArg, &cmd);
7121  if( rc==SQLITE_OK ){
7122    int eDbType = SHELL_OPEN_UNSPEC;
7123    cmd.p = pState;
7124    cmd.db = pState->db;
7125    if( cmd.zFile ){
7126      eDbType = deduceDatabaseType(cmd.zFile, 1);
7127    }else{
7128      eDbType = pState->openMode;
7129    }
7130    if( eDbType==SHELL_OPEN_ZIPFILE ){
7131      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7132        if( cmd.zFile==0 ){
7133          cmd.zSrcTable = sqlite3_mprintf("zip");
7134        }else{
7135          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7136        }
7137      }
7138      cmd.bZip = 1;
7139    }else if( cmd.zFile ){
7140      int flags;
7141      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7142      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7143           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7144        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7145      }else{
7146        flags = SQLITE_OPEN_READONLY;
7147      }
7148      cmd.db = 0;
7149      if( cmd.bDryRun ){
7150        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7151             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7152      }
7153      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7154             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7155      if( rc!=SQLITE_OK ){
7156        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7157            cmd.zFile, sqlite3_errmsg(cmd.db)
7158        );
7159        goto end_ar_command;
7160      }
7161      sqlite3_fileio_init(cmd.db, 0, 0);
7162      sqlite3_sqlar_init(cmd.db, 0, 0);
7163      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7164                              shellPutsFunc, 0, 0);
7165
7166    }
7167    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7168      if( cmd.eCmd!=AR_CMD_CREATE
7169       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7170      ){
7171        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7172        rc = SQLITE_ERROR;
7173        goto end_ar_command;
7174      }
7175      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7176    }
7177
7178    switch( cmd.eCmd ){
7179      case AR_CMD_CREATE:
7180        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7181        break;
7182
7183      case AR_CMD_EXTRACT:
7184        rc = arExtractCommand(&cmd);
7185        break;
7186
7187      case AR_CMD_LIST:
7188        rc = arListCommand(&cmd);
7189        break;
7190
7191      case AR_CMD_HELP:
7192        arUsage(pState->out);
7193        break;
7194
7195      case AR_CMD_INSERT:
7196        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7197        break;
7198
7199      case AR_CMD_REMOVE:
7200        rc = arRemoveCommand(&cmd);
7201        break;
7202
7203      default:
7204        assert( cmd.eCmd==AR_CMD_UPDATE );
7205        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7206        break;
7207    }
7208  }
7209end_ar_command:
7210  if( cmd.db!=pState->db ){
7211    close_db(cmd.db);
7212  }
7213  sqlite3_free(cmd.zSrcTable);
7214
7215  return rc;
7216}
7217/* End of the ".archive" or ".ar" command logic
7218*******************************************************************************/
7219#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7220
7221#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7222/*
7223** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7224** Otherwise, the SQL statement or statements in zSql are executed using
7225** database connection db and the error code written to *pRc before
7226** this function returns.
7227*/
7228static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7229  int rc = *pRc;
7230  if( rc==SQLITE_OK ){
7231    char *zErr = 0;
7232    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7233    if( rc!=SQLITE_OK ){
7234      raw_printf(stderr, "SQL error: %s\n", zErr);
7235    }
7236    sqlite3_free(zErr);
7237    *pRc = rc;
7238  }
7239}
7240
7241/*
7242** Like shellExec(), except that zFmt is a printf() style format string.
7243*/
7244static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7245  char *z = 0;
7246  if( *pRc==SQLITE_OK ){
7247    va_list ap;
7248    va_start(ap, zFmt);
7249    z = sqlite3_vmprintf(zFmt, ap);
7250    va_end(ap);
7251    if( z==0 ){
7252      *pRc = SQLITE_NOMEM;
7253    }else{
7254      shellExec(db, pRc, z);
7255    }
7256    sqlite3_free(z);
7257  }
7258}
7259
7260/*
7261** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7262** Otherwise, an attempt is made to allocate, zero and return a pointer
7263** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7264** to SQLITE_NOMEM and NULL returned.
7265*/
7266static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7267  void *pRet = 0;
7268  if( *pRc==SQLITE_OK ){
7269    pRet = sqlite3_malloc64(nByte);
7270    if( pRet==0 ){
7271      *pRc = SQLITE_NOMEM;
7272    }else{
7273      memset(pRet, 0, nByte);
7274    }
7275  }
7276  return pRet;
7277}
7278
7279/*
7280** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7281** Otherwise, zFmt is treated as a printf() style string. The result of
7282** formatting it along with any trailing arguments is written into a
7283** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7284** It is the responsibility of the caller to eventually free this buffer
7285** using a call to sqlite3_free().
7286**
7287** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7288** pointer returned.
7289*/
7290static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7291  char *z = 0;
7292  if( *pRc==SQLITE_OK ){
7293    va_list ap;
7294    va_start(ap, zFmt);
7295    z = sqlite3_vmprintf(zFmt, ap);
7296    va_end(ap);
7297    if( z==0 ){
7298      *pRc = SQLITE_NOMEM;
7299    }
7300  }
7301  return z;
7302}
7303
7304
7305/*
7306** When running the ".recover" command, each output table, and the special
7307** orphaned row table if it is required, is represented by an instance
7308** of the following struct.
7309*/
7310typedef struct RecoverTable RecoverTable;
7311struct RecoverTable {
7312  char *zQuoted;                  /* Quoted version of table name */
7313  int nCol;                       /* Number of columns in table */
7314  char **azlCol;                  /* Array of column lists */
7315  int iPk;                        /* Index of IPK column */
7316};
7317
7318/*
7319** Free a RecoverTable object allocated by recoverFindTable() or
7320** recoverOrphanTable().
7321*/
7322static void recoverFreeTable(RecoverTable *pTab){
7323  if( pTab ){
7324    sqlite3_free(pTab->zQuoted);
7325    if( pTab->azlCol ){
7326      int i;
7327      for(i=0; i<=pTab->nCol; i++){
7328        sqlite3_free(pTab->azlCol[i]);
7329      }
7330      sqlite3_free(pTab->azlCol);
7331    }
7332    sqlite3_free(pTab);
7333  }
7334}
7335
7336/*
7337** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7338** Otherwise, it allocates and returns a RecoverTable object based on the
7339** final four arguments passed to this function. It is the responsibility
7340** of the caller to eventually free the returned object using
7341** recoverFreeTable().
7342*/
7343static RecoverTable *recoverNewTable(
7344  int *pRc,                       /* IN/OUT: Error code */
7345  const char *zName,              /* Name of table */
7346  const char *zSql,               /* CREATE TABLE statement */
7347  int bIntkey,
7348  int nCol
7349){
7350  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7351  int rc = *pRc;
7352  RecoverTable *pTab = 0;
7353
7354  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7355  if( rc==SQLITE_OK ){
7356    int nSqlCol = 0;
7357    int bSqlIntkey = 0;
7358    sqlite3_stmt *pStmt = 0;
7359
7360    rc = sqlite3_open("", &dbtmp);
7361    if( rc==SQLITE_OK ){
7362      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7363                              shellIdQuote, 0, 0);
7364    }
7365    if( rc==SQLITE_OK ){
7366      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7367    }
7368    if( rc==SQLITE_OK ){
7369      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7370      if( rc==SQLITE_ERROR ){
7371        rc = SQLITE_OK;
7372        goto finished;
7373      }
7374    }
7375    shellPreparePrintf(dbtmp, &rc, &pStmt,
7376        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7377    );
7378    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7379      nSqlCol = sqlite3_column_int(pStmt, 0);
7380    }
7381    shellFinalize(&rc, pStmt);
7382
7383    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7384      goto finished;
7385    }
7386
7387    shellPreparePrintf(dbtmp, &rc, &pStmt,
7388      "SELECT ("
7389      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7390      ") FROM sqlite_schema WHERE name = %Q", zName
7391    );
7392    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7393      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7394    }
7395    shellFinalize(&rc, pStmt);
7396
7397    if( bIntkey==bSqlIntkey ){
7398      int i;
7399      const char *zPk = "_rowid_";
7400      sqlite3_stmt *pPkFinder = 0;
7401
7402      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7403      ** set zPk to the name of the PK column, and pTab->iPk to the index
7404      ** of the column, where columns are 0-numbered from left to right.
7405      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7406      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7407      pTab->iPk = -2;
7408      if( bIntkey ){
7409        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7410          "SELECT cid, name FROM pragma_table_info(%Q) "
7411          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7412          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7413          , zName, zName
7414        );
7415        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7416          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7417          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7418          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7419        }
7420      }
7421
7422      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7423      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7424      pTab->nCol = nSqlCol;
7425
7426      if( bIntkey ){
7427        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7428      }else{
7429        pTab->azlCol[0] = shellMPrintf(&rc, "");
7430      }
7431      i = 1;
7432      shellPreparePrintf(dbtmp, &rc, &pStmt,
7433          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7434          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7435          "FROM pragma_table_info(%Q)",
7436          bIntkey ? ", " : "", pTab->iPk,
7437          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7438          zName
7439      );
7440      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7441        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7442        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7443        i++;
7444      }
7445      shellFinalize(&rc, pStmt);
7446
7447      shellFinalize(&rc, pPkFinder);
7448    }
7449  }
7450
7451 finished:
7452  sqlite3_close(dbtmp);
7453  *pRc = rc;
7454  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7455    recoverFreeTable(pTab);
7456    pTab = 0;
7457  }
7458  return pTab;
7459}
7460
7461/*
7462** This function is called to search the schema recovered from the
7463** sqlite_schema table of the (possibly) corrupt database as part
7464** of a ".recover" command. Specifically, for a table with root page
7465** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7466** table must be a WITHOUT ROWID table, or if non-zero, not one of
7467** those.
7468**
7469** If a table is found, a (RecoverTable*) object is returned. Or, if
7470** no such table is found, but bIntkey is false and iRoot is the
7471** root page of an index in the recovered schema, then (*pbNoop) is
7472** set to true and NULL returned. Or, if there is no such table or
7473** index, NULL is returned and (*pbNoop) set to 0, indicating that
7474** the caller should write data to the orphans table.
7475*/
7476static RecoverTable *recoverFindTable(
7477  ShellState *pState,             /* Shell state object */
7478  int *pRc,                       /* IN/OUT: Error code */
7479  int iRoot,                      /* Root page of table */
7480  int bIntkey,                    /* True for an intkey table */
7481  int nCol,                       /* Number of columns in table */
7482  int *pbNoop                     /* OUT: True if iRoot is root of index */
7483){
7484  sqlite3_stmt *pStmt = 0;
7485  RecoverTable *pRet = 0;
7486  int bNoop = 0;
7487  const char *zSql = 0;
7488  const char *zName = 0;
7489
7490  /* Search the recovered schema for an object with root page iRoot. */
7491  shellPreparePrintf(pState->db, pRc, &pStmt,
7492      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7493  );
7494  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7495    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7496    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7497      bNoop = 1;
7498      break;
7499    }
7500    if( sqlite3_stricmp(zType, "table")==0 ){
7501      zName = (const char*)sqlite3_column_text(pStmt, 1);
7502      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7503      if( zName!=0 && zSql!=0 ){
7504        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7505        break;
7506      }
7507    }
7508  }
7509
7510  shellFinalize(pRc, pStmt);
7511  *pbNoop = bNoop;
7512  return pRet;
7513}
7514
7515/*
7516** Return a RecoverTable object representing the orphans table.
7517*/
7518static RecoverTable *recoverOrphanTable(
7519  ShellState *pState,             /* Shell state object */
7520  int *pRc,                       /* IN/OUT: Error code */
7521  const char *zLostAndFound,      /* Base name for orphans table */
7522  int nCol                        /* Number of user data columns */
7523){
7524  RecoverTable *pTab = 0;
7525  if( nCol>=0 && *pRc==SQLITE_OK ){
7526    int i;
7527
7528    /* This block determines the name of the orphan table. The prefered
7529    ** name is zLostAndFound. But if that clashes with another name
7530    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7531    ** and so on until a non-clashing name is found.  */
7532    int iTab = 0;
7533    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7534    sqlite3_stmt *pTest = 0;
7535    shellPrepare(pState->db, pRc,
7536        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7537    );
7538    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7539    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7540      shellReset(pRc, pTest);
7541      sqlite3_free(zTab);
7542      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7543      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7544    }
7545    shellFinalize(pRc, pTest);
7546
7547    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7548    if( pTab ){
7549      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7550      pTab->nCol = nCol;
7551      pTab->iPk = -2;
7552      if( nCol>0 ){
7553        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7554        if( pTab->azlCol ){
7555          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7556          for(i=nCol-1; i>=0; i--){
7557            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7558          }
7559        }
7560      }
7561
7562      if( *pRc!=SQLITE_OK ){
7563        recoverFreeTable(pTab);
7564        pTab = 0;
7565      }else{
7566        raw_printf(pState->out,
7567            "CREATE TABLE %s(rootpgno INTEGER, "
7568            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7569        );
7570        for(i=0; i<nCol; i++){
7571          raw_printf(pState->out, ", c%d", i);
7572        }
7573        raw_printf(pState->out, ");\n");
7574      }
7575    }
7576    sqlite3_free(zTab);
7577  }
7578  return pTab;
7579}
7580
7581/*
7582** This function is called to recover data from the database. A script
7583** to construct a new database containing all recovered data is output
7584** on stream pState->out.
7585*/
7586static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7587  int rc = SQLITE_OK;
7588  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7589  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7590  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7591  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7592  const char *zLostAndFound = "lost_and_found";
7593  int i;
7594  int nOrphan = -1;
7595  RecoverTable *pOrphan = 0;
7596
7597  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7598  int bRowids = 1;                /* 0 if --no-rowids */
7599  for(i=1; i<nArg; i++){
7600    char *z = azArg[i];
7601    int n;
7602    if( z[0]=='-' && z[1]=='-' ) z++;
7603    n = strlen30(z);
7604    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7605      bFreelist = 0;
7606    }else
7607    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7608      i++;
7609      zRecoveryDb = azArg[i];
7610    }else
7611    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7612      i++;
7613      zLostAndFound = azArg[i];
7614    }else
7615    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7616      bRowids = 0;
7617    }
7618    else{
7619      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7620      showHelp(pState->out, azArg[0]);
7621      return 1;
7622    }
7623  }
7624
7625  shellExecPrintf(pState->db, &rc,
7626    /* Attach an in-memory database named 'recovery'. Create an indexed
7627    ** cache of the sqlite_dbptr virtual table. */
7628    "PRAGMA writable_schema = on;"
7629    "ATTACH %Q AS recovery;"
7630    "DROP TABLE IF EXISTS recovery.dbptr;"
7631    "DROP TABLE IF EXISTS recovery.freelist;"
7632    "DROP TABLE IF EXISTS recovery.map;"
7633    "DROP TABLE IF EXISTS recovery.schema;"
7634    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7635  );
7636
7637  if( bFreelist ){
7638    shellExec(pState->db, &rc,
7639      "WITH trunk(pgno) AS ("
7640      "  SELECT shell_int32("
7641      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7642      "      WHERE x>0"
7643      "    UNION"
7644      "  SELECT shell_int32("
7645      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7646      "      FROM trunk WHERE x>0"
7647      "),"
7648      "freelist(data, n, freepgno) AS ("
7649      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7650      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7651      "    UNION ALL"
7652      "  SELECT data, n-1, shell_int32(data, 2+n) "
7653      "      FROM freelist WHERE n>=0"
7654      ")"
7655      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7656    );
7657  }
7658
7659  /* If this is an auto-vacuum database, add all pointer-map pages to
7660  ** the freelist table. Do this regardless of whether or not
7661  ** --freelist-corrupt was specified.  */
7662  shellExec(pState->db, &rc,
7663    "WITH ptrmap(pgno) AS ("
7664    "  SELECT 2 WHERE shell_int32("
7665    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7666    "  )"
7667    "    UNION ALL "
7668    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7669    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7670    ")"
7671    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7672  );
7673
7674  shellExec(pState->db, &rc,
7675    "CREATE TABLE recovery.dbptr("
7676    "      pgno, child, PRIMARY KEY(child, pgno)"
7677    ") WITHOUT ROWID;"
7678    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7679    "    SELECT * FROM sqlite_dbptr"
7680    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7681
7682    /* Delete any pointer to page 1. This ensures that page 1 is considered
7683    ** a root page, regardless of how corrupt the db is. */
7684    "DELETE FROM recovery.dbptr WHERE child = 1;"
7685
7686    /* Delete all pointers to any pages that have more than one pointer
7687    ** to them. Such pages will be treated as root pages when recovering
7688    ** data.  */
7689    "DELETE FROM recovery.dbptr WHERE child IN ("
7690    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7691    ");"
7692
7693    /* Create the "map" table that will (eventually) contain instructions
7694    ** for dealing with each page in the db that contains one or more
7695    ** records. */
7696    "CREATE TABLE recovery.map("
7697      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7698    ");"
7699
7700    /* Populate table [map]. If there are circular loops of pages in the
7701    ** database, the following adds all pages in such a loop to the map
7702    ** as individual root pages. This could be handled better.  */
7703    "WITH pages(i, maxlen) AS ("
7704    "  SELECT page_count, ("
7705    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7706    "  ) FROM pragma_page_count WHERE page_count>0"
7707    "    UNION ALL"
7708    "  SELECT i-1, ("
7709    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7710    "  ) FROM pages WHERE i>=2"
7711    ")"
7712    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7713    "  SELECT i, maxlen, NULL, ("
7714    "    WITH p(orig, pgno, parent) AS ("
7715    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7716    "        UNION "
7717    "      SELECT i, p.parent, "
7718    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7719    "    )"
7720    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7721    ") "
7722    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7723    "UPDATE recovery.map AS o SET intkey = ("
7724    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7725    ");"
7726
7727    /* Extract data from page 1 and any linked pages into table
7728    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7729    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7730    "INSERT INTO recovery.schema SELECT "
7731    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7732    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7733    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7734    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7735    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7736    "FROM sqlite_dbdata WHERE pgno IN ("
7737    "  SELECT pgno FROM recovery.map WHERE root=1"
7738    ")"
7739    "GROUP BY pgno, cell;"
7740    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7741  );
7742
7743  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7744  ** CREATE TABLE statements that extracted from the existing schema.  */
7745  if( rc==SQLITE_OK ){
7746    sqlite3_stmt *pStmt = 0;
7747    /* ".recover" might output content in an order which causes immediate
7748    ** foreign key constraints to be violated. So disable foreign-key
7749    ** constraint enforcement to prevent problems when running the output
7750    ** script. */
7751    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7752    raw_printf(pState->out, "BEGIN;\n");
7753    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7754    shellPrepare(pState->db, &rc,
7755        "SELECT sql FROM recovery.schema "
7756        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7757    );
7758    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7759      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7760      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7761          &zCreateTable[12]
7762      );
7763    }
7764    shellFinalize(&rc, pStmt);
7765  }
7766
7767  /* Figure out if an orphan table will be required. And if so, how many
7768  ** user columns it should contain */
7769  shellPrepare(pState->db, &rc,
7770      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7771      , &pLoop
7772  );
7773  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7774    nOrphan = sqlite3_column_int(pLoop, 0);
7775  }
7776  shellFinalize(&rc, pLoop);
7777  pLoop = 0;
7778
7779  shellPrepare(pState->db, &rc,
7780      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7781  );
7782
7783  shellPrepare(pState->db, &rc,
7784      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7785      "(case when (? AND field<0) then NULL else value end)"
7786      "), ', ')"
7787      ", min(field) "
7788      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7789      "GROUP BY cell", &pCells
7790  );
7791
7792  /* Loop through each root page. */
7793  shellPrepare(pState->db, &rc,
7794      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7795      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7796      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7797      ")", &pLoop
7798  );
7799  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7800    int iRoot = sqlite3_column_int(pLoop, 0);
7801    int bIntkey = sqlite3_column_int(pLoop, 1);
7802    int nCol = sqlite3_column_int(pLoop, 2);
7803    int bNoop = 0;
7804    RecoverTable *pTab;
7805
7806    assert( bIntkey==0 || bIntkey==1 );
7807    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7808    if( bNoop || rc ) continue;
7809    if( pTab==0 ){
7810      if( pOrphan==0 ){
7811        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7812      }
7813      pTab = pOrphan;
7814      if( pTab==0 ) break;
7815    }
7816
7817    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7818      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7819    }
7820    sqlite3_bind_int(pPages, 1, iRoot);
7821    if( bRowids==0 && pTab->iPk<0 ){
7822      sqlite3_bind_int(pCells, 1, 1);
7823    }else{
7824      sqlite3_bind_int(pCells, 1, 0);
7825    }
7826    sqlite3_bind_int(pCells, 3, pTab->iPk);
7827
7828    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7829      int iPgno = sqlite3_column_int(pPages, 0);
7830      sqlite3_bind_int(pCells, 2, iPgno);
7831      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7832        int nField = sqlite3_column_int(pCells, 0);
7833        int iMin = sqlite3_column_int(pCells, 2);
7834        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7835
7836        RecoverTable *pTab2 = pTab;
7837        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7838          if( pOrphan==0 ){
7839            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7840          }
7841          pTab2 = pOrphan;
7842          if( pTab2==0 ) break;
7843        }
7844
7845        nField = nField+1;
7846        if( pTab2==pOrphan ){
7847          raw_printf(pState->out,
7848              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7849              pTab2->zQuoted, iRoot, iPgno, nField,
7850              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7851          );
7852        }else{
7853          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7854              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7855          );
7856        }
7857      }
7858      shellReset(&rc, pCells);
7859    }
7860    shellReset(&rc, pPages);
7861    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7862  }
7863  shellFinalize(&rc, pLoop);
7864  shellFinalize(&rc, pPages);
7865  shellFinalize(&rc, pCells);
7866  recoverFreeTable(pOrphan);
7867
7868  /* The rest of the schema */
7869  if( rc==SQLITE_OK ){
7870    sqlite3_stmt *pStmt = 0;
7871    shellPrepare(pState->db, &rc,
7872        "SELECT sql, name FROM recovery.schema "
7873        "WHERE sql NOT LIKE 'create table%'", &pStmt
7874    );
7875    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7876      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7877      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7878        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7879        char *zPrint = shellMPrintf(&rc,
7880          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7881          zName, zName, zSql
7882        );
7883        raw_printf(pState->out, "%s;\n", zPrint);
7884        sqlite3_free(zPrint);
7885      }else{
7886        raw_printf(pState->out, "%s;\n", zSql);
7887      }
7888    }
7889    shellFinalize(&rc, pStmt);
7890  }
7891
7892  if( rc==SQLITE_OK ){
7893    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7894    raw_printf(pState->out, "COMMIT;\n");
7895  }
7896  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7897  return rc;
7898}
7899#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7900
7901
7902/*
7903 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7904 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7905 *   close db and set it to 0, and return the columns spec, to later
7906 *   be sqlite3_free()'ed by the caller.
7907 * The return is 0 when either:
7908 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7909 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7910 * The 3rd argument, pRenamed, references an out parameter. If the
7911 * pointer is non-zero, its referent will be set to a summary of renames
7912 * done if renaming was necessary, or set to 0 if none was done. The out
7913 * string (if any) must be sqlite3_free()'ed by the caller.
7914 */
7915#ifdef SHELL_DEBUG
7916#define rc_err_oom_die(rc) \
7917  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7918  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7919    fprintf(stderr,"E:%d\n",rc), assert(0)
7920#else
7921static void rc_err_oom_die(int rc){
7922  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7923  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7924}
7925#endif
7926
7927#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7928static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7929#else  /* Otherwise, memory is faster/better for the transient DB. */
7930static const char *zCOL_DB = ":memory:";
7931#endif
7932
7933/* Define character (as C string) to separate generated column ordinal
7934 * from protected part of incoming column names. This defaults to "_"
7935 * so that incoming column identifiers that did not need not be quoted
7936 * remain usable without being quoted. It must be one character.
7937 */
7938#ifndef SHELL_AUTOCOLUMN_SEP
7939# define AUTOCOLUMN_SEP "_"
7940#else
7941# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7942#endif
7943
7944static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7945  /* Queries and D{D,M}L used here */
7946  static const char * const zTabMake = "\
7947CREATE TABLE ColNames(\
7948 cpos INTEGER PRIMARY KEY,\
7949 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7950CREATE VIEW RepeatedNames AS \
7951SELECT DISTINCT t.name FROM ColNames t \
7952WHERE t.name COLLATE NOCASE IN (\
7953 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7954);\
7955";
7956  static const char * const zTabFill = "\
7957INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7958 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7959";
7960  static const char * const zHasDupes = "\
7961SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7962 <count(name) FROM ColNames\
7963";
7964#ifdef SHELL_COLUMN_RENAME_CLEAN
7965  static const char * const zDedoctor = "\
7966UPDATE ColNames SET chop=iif(\
7967  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7968  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7969 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7970 0\
7971)\
7972";
7973#endif
7974  static const char * const zSetReps = "\
7975UPDATE ColNames AS t SET reps=\
7976(SELECT count(*) FROM ColNames d \
7977 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7978 COLLATE NOCASE\
7979)\
7980";
7981#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7982  static const char * const zColDigits = "\
7983SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7984";
7985#else
7986  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7987  static const char * const zColDigits = "\
7988SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7989 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7990 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7991";
7992#endif
7993  static const char * const zRenameRank =
7994#ifdef SHELL_COLUMN_RENAME_CLEAN
7995    "UPDATE ColNames AS t SET suff="
7996    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7997#else /* ...RENAME_MINIMAL_ONE_PASS */
7998"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7999"  SELECT 0 AS nlz"
8000"  UNION"
8001"  SELECT nlz+1 AS nlz FROM Lzn"
8002"  WHERE EXISTS("
8003"   SELECT 1"
8004"   FROM ColNames t, ColNames o"
8005"   WHERE"
8006"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8007"     printf('%s"AUTOCOLUMN_SEP"%s',"
8008"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8009"     t.name"
8010"    )"
8011"    ="
8012"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8013"     printf('%s"AUTOCOLUMN_SEP"%s',"
8014"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8015"     o.name"
8016"    )"
8017"    COLLATE NOCASE"
8018"    AND o.cpos<>t.cpos"
8019"   GROUP BY t.cpos"
8020"  )"
8021") UPDATE Colnames AS t SET"
8022" chop = 0," /* No chopping, never touch incoming names. */
8023" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8024"  printf('"AUTOCOLUMN_SEP"%s', substring("
8025"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8026"  ''"
8027" )"
8028#endif
8029    ;
8030  static const char * const zCollectVar = "\
8031SELECT\
8032 '('||x'0a'\
8033 || group_concat(\
8034  cname||' TEXT',\
8035  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8036 ||')' AS ColsSpec \
8037FROM (\
8038 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8039 FROM ColNames ORDER BY cpos\
8040)";
8041  static const char * const zRenamesDone =
8042    "SELECT group_concat("
8043    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8044    " ','||x'0a')"
8045    "FROM ColNames WHERE suff<>'' OR chop!=0"
8046    ;
8047  int rc;
8048  sqlite3_stmt *pStmt = 0;
8049  assert(pDb!=0);
8050  if( zColNew ){
8051    /* Add initial or additional column. Init db if necessary. */
8052    if( *pDb==0 ){
8053      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8054#ifdef SHELL_COLFIX_DB
8055      if(*zCOL_DB!=':')
8056        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8057                     "drop view if exists RepeatedNames;",0,0,0);
8058#endif
8059      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8060      rc_err_oom_die(rc);
8061    }
8062    assert(*pDb!=0);
8063    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8064    rc_err_oom_die(rc);
8065    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8066    rc_err_oom_die(rc);
8067    rc = sqlite3_step(pStmt);
8068    rc_err_oom_die(rc);
8069    sqlite3_finalize(pStmt);
8070    return 0;
8071  }else if( *pDb==0 ){
8072    return 0;
8073  }else{
8074    /* Formulate the columns spec, close the DB, zero *pDb. */
8075    char *zColsSpec = 0;
8076    int hasDupes = db_int(*pDb, zHasDupes);
8077    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8078    if( hasDupes ){
8079#ifdef SHELL_COLUMN_RENAME_CLEAN
8080      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8081      rc_err_oom_die(rc);
8082#endif
8083      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8084      rc_err_oom_die(rc);
8085      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8086      rc_err_oom_die(rc);
8087      sqlite3_bind_int(pStmt, 1, nDigits);
8088      rc = sqlite3_step(pStmt);
8089      sqlite3_finalize(pStmt);
8090      assert(rc==SQLITE_DONE);
8091    }
8092    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8093    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8094    rc_err_oom_die(rc);
8095    rc = sqlite3_step(pStmt);
8096    if( rc==SQLITE_ROW ){
8097      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8098    }else{
8099      zColsSpec = 0;
8100    }
8101    if( pzRenamed!=0 ){
8102      if( !hasDupes ) *pzRenamed = 0;
8103      else{
8104        sqlite3_finalize(pStmt);
8105        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8106            && SQLITE_ROW==sqlite3_step(pStmt) ){
8107          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8108        }else
8109          *pzRenamed = 0;
8110      }
8111    }
8112    sqlite3_finalize(pStmt);
8113    sqlite3_close(*pDb);
8114    *pDb = 0;
8115    return zColsSpec;
8116  }
8117}
8118
8119/*
8120** If an input line begins with "." then invoke this routine to
8121** process that line.
8122**
8123** Return 1 on error, 2 to exit, and 0 otherwise.
8124*/
8125static int do_meta_command(char *zLine, ShellState *p){
8126  int h = 1;
8127  int nArg = 0;
8128  int n, c;
8129  int rc = 0;
8130  char *azArg[52];
8131
8132#ifndef SQLITE_OMIT_VIRTUALTABLE
8133  if( p->expert.pExpert ){
8134    expertFinish(p, 1, 0);
8135  }
8136#endif
8137
8138  /* Parse the input line into tokens.
8139  */
8140  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8141    while( IsSpace(zLine[h]) ){ h++; }
8142    if( zLine[h]==0 ) break;
8143    if( zLine[h]=='\'' || zLine[h]=='"' ){
8144      int delim = zLine[h++];
8145      azArg[nArg++] = &zLine[h];
8146      while( zLine[h] && zLine[h]!=delim ){
8147        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8148        h++;
8149      }
8150      if( zLine[h]==delim ){
8151        zLine[h++] = 0;
8152      }
8153      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8154    }else{
8155      azArg[nArg++] = &zLine[h];
8156      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8157      if( zLine[h] ) zLine[h++] = 0;
8158      resolve_backslashes(azArg[nArg-1]);
8159    }
8160  }
8161  azArg[nArg] = 0;
8162
8163  /* Process the input line.
8164  */
8165  if( nArg==0 ) return 0; /* no tokens, no error */
8166  n = strlen30(azArg[0]);
8167  c = azArg[0][0];
8168  clearTempFile(p);
8169
8170#ifndef SQLITE_OMIT_AUTHORIZATION
8171  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8172    if( nArg!=2 ){
8173      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8174      rc = 1;
8175      goto meta_command_exit;
8176    }
8177    open_db(p, 0);
8178    if( booleanValue(azArg[1]) ){
8179      sqlite3_set_authorizer(p->db, shellAuth, p);
8180    }else if( p->bSafeModePersist ){
8181      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8182    }else{
8183      sqlite3_set_authorizer(p->db, 0, 0);
8184    }
8185  }else
8186#endif
8187
8188#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8189  && !defined(SQLITE_SHELL_WASM_MODE)
8190  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8191    open_db(p, 0);
8192    failIfSafeMode(p, "cannot run .archive in safe mode");
8193    rc = arDotCommand(p, 0, azArg, nArg);
8194  }else
8195#endif
8196
8197#ifndef SQLITE_SHELL_WASM_MODE
8198  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8199   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8200  ){
8201    const char *zDestFile = 0;
8202    const char *zDb = 0;
8203    sqlite3 *pDest;
8204    sqlite3_backup *pBackup;
8205    int j;
8206    int bAsync = 0;
8207    const char *zVfs = 0;
8208    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8209    for(j=1; j<nArg; j++){
8210      const char *z = azArg[j];
8211      if( z[0]=='-' ){
8212        if( z[1]=='-' ) z++;
8213        if( strcmp(z, "-append")==0 ){
8214          zVfs = "apndvfs";
8215        }else
8216        if( strcmp(z, "-async")==0 ){
8217          bAsync = 1;
8218        }else
8219        {
8220          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8221          return 1;
8222        }
8223      }else if( zDestFile==0 ){
8224        zDestFile = azArg[j];
8225      }else if( zDb==0 ){
8226        zDb = zDestFile;
8227        zDestFile = azArg[j];
8228      }else{
8229        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8230        return 1;
8231      }
8232    }
8233    if( zDestFile==0 ){
8234      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8235      return 1;
8236    }
8237    if( zDb==0 ) zDb = "main";
8238    rc = sqlite3_open_v2(zDestFile, &pDest,
8239                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8240    if( rc!=SQLITE_OK ){
8241      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8242      close_db(pDest);
8243      return 1;
8244    }
8245    if( bAsync ){
8246      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8247                   0, 0, 0);
8248    }
8249    open_db(p, 0);
8250    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8251    if( pBackup==0 ){
8252      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8253      close_db(pDest);
8254      return 1;
8255    }
8256    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8257    sqlite3_backup_finish(pBackup);
8258    if( rc==SQLITE_DONE ){
8259      rc = 0;
8260    }else{
8261      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8262      rc = 1;
8263    }
8264    close_db(pDest);
8265  }else
8266#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8267
8268  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8269    if( nArg==2 ){
8270      bail_on_error = booleanValue(azArg[1]);
8271    }else{
8272      raw_printf(stderr, "Usage: .bail on|off\n");
8273      rc = 1;
8274    }
8275  }else
8276
8277  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8278    if( nArg==2 ){
8279      if( booleanValue(azArg[1]) ){
8280        setBinaryMode(p->out, 1);
8281      }else{
8282        setTextMode(p->out, 1);
8283      }
8284    }else{
8285      raw_printf(stderr, "Usage: .binary on|off\n");
8286      rc = 1;
8287    }
8288  }else
8289
8290  /* The undocumented ".breakpoint" command causes a call to the no-op
8291  ** routine named test_breakpoint().
8292  */
8293  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8294    test_breakpoint();
8295  }else
8296
8297#ifndef SQLITE_SHELL_WASM_MODE
8298  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8299    failIfSafeMode(p, "cannot run .cd in safe mode");
8300    if( nArg==2 ){
8301#if defined(_WIN32) || defined(WIN32)
8302      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8303      rc = !SetCurrentDirectoryW(z);
8304      sqlite3_free(z);
8305#else
8306      rc = chdir(azArg[1]);
8307#endif
8308      if( rc ){
8309        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8310        rc = 1;
8311      }
8312    }else{
8313      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8314      rc = 1;
8315    }
8316  }else
8317#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8318
8319  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8320    if( nArg==2 ){
8321      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8322    }else{
8323      raw_printf(stderr, "Usage: .changes on|off\n");
8324      rc = 1;
8325    }
8326  }else
8327
8328#ifndef SQLITE_SHELL_WASM_MODE
8329  /* Cancel output redirection, if it is currently set (by .testcase)
8330  ** Then read the content of the testcase-out.txt file and compare against
8331  ** azArg[1].  If there are differences, report an error and exit.
8332  */
8333  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8334    char *zRes = 0;
8335    output_reset(p);
8336    if( nArg!=2 ){
8337      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8338      rc = 2;
8339    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8340      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8341      rc = 2;
8342    }else if( testcase_glob(azArg[1],zRes)==0 ){
8343      utf8_printf(stderr,
8344                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8345                 p->zTestcase, azArg[1], zRes);
8346      rc = 1;
8347    }else{
8348      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8349      p->nCheck++;
8350    }
8351    sqlite3_free(zRes);
8352  }else
8353#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8354
8355#ifndef SQLITE_SHELL_WASM_MODE
8356  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8357    failIfSafeMode(p, "cannot run .clone in safe mode");
8358    if( nArg==2 ){
8359      tryToClone(p, azArg[1]);
8360    }else{
8361      raw_printf(stderr, "Usage: .clone FILENAME\n");
8362      rc = 1;
8363    }
8364  }else
8365#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
8366
8367  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8368    if( nArg==1 ){
8369      /* List available connections */
8370      int i;
8371      for(i=0; i<ArraySize(p->aAuxDb); i++){
8372        const char *zFile = p->aAuxDb[i].zDbFilename;
8373        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8374          zFile = "(not open)";
8375        }else if( zFile==0 ){
8376          zFile = "(memory)";
8377        }else if( zFile[0]==0 ){
8378          zFile = "(temporary-file)";
8379        }
8380        if( p->pAuxDb == &p->aAuxDb[i] ){
8381          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8382        }else if( p->aAuxDb[i].db!=0 ){
8383          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8384        }
8385      }
8386    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8387      int i = azArg[1][0] - '0';
8388      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8389        p->pAuxDb->db = p->db;
8390        p->pAuxDb = &p->aAuxDb[i];
8391        globalDb = p->db = p->pAuxDb->db;
8392        p->pAuxDb->db = 0;
8393      }
8394    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8395           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8396      int i = azArg[2][0] - '0';
8397      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8398        /* No-op */
8399      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8400        raw_printf(stderr, "cannot close the active database connection\n");
8401        rc = 1;
8402      }else if( p->aAuxDb[i].db ){
8403        session_close_all(p, i);
8404        close_db(p->aAuxDb[i].db);
8405        p->aAuxDb[i].db = 0;
8406      }
8407    }else{
8408      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8409      rc = 1;
8410    }
8411  }else
8412
8413  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8414    char **azName = 0;
8415    int nName = 0;
8416    sqlite3_stmt *pStmt;
8417    int i;
8418    open_db(p, 0);
8419    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8420    if( rc ){
8421      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8422      rc = 1;
8423    }else{
8424      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8425        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8426        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8427        if( zSchema==0 || zFile==0 ) continue;
8428        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8429        shell_check_oom(azName);
8430        azName[nName*2] = strdup(zSchema);
8431        azName[nName*2+1] = strdup(zFile);
8432        nName++;
8433      }
8434    }
8435    sqlite3_finalize(pStmt);
8436    for(i=0; i<nName; i++){
8437      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8438      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8439      const char *z = azName[i*2+1];
8440      utf8_printf(p->out, "%s: %s %s%s\n",
8441         azName[i*2],
8442         z && z[0] ? z : "\"\"",
8443         bRdonly ? "r/o" : "r/w",
8444         eTxn==SQLITE_TXN_NONE ? "" :
8445            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8446      free(azName[i*2]);
8447      free(azName[i*2+1]);
8448    }
8449    sqlite3_free(azName);
8450  }else
8451
8452  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8453    static const struct DbConfigChoices {
8454      const char *zName;
8455      int op;
8456    } aDbConfig[] = {
8457        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8458        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8459        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8460        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8461        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8462        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8463        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8464        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8465        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8466        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8467        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8468        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8469        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8470        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8471        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8472        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8473    };
8474    int ii, v;
8475    open_db(p, 0);
8476    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8477      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8478      if( nArg>=3 ){
8479        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8480      }
8481      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8482      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8483      if( nArg>1 ) break;
8484    }
8485    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8486      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8487      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8488    }
8489  }else
8490
8491#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8492  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8493    rc = shell_dbinfo_command(p, nArg, azArg);
8494  }else
8495
8496  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8497    open_db(p, 0);
8498    rc = recoverDatabaseCmd(p, nArg, azArg);
8499  }else
8500#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8501
8502  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8503    char *zLike = 0;
8504    char *zSql;
8505    int i;
8506    int savedShowHeader = p->showHeader;
8507    int savedShellFlags = p->shellFlgs;
8508    ShellClearFlag(p,
8509       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8510       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8511    for(i=1; i<nArg; i++){
8512      if( azArg[i][0]=='-' ){
8513        const char *z = azArg[i]+1;
8514        if( z[0]=='-' ) z++;
8515        if( strcmp(z,"preserve-rowids")==0 ){
8516#ifdef SQLITE_OMIT_VIRTUALTABLE
8517          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8518                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8519          rc = 1;
8520          sqlite3_free(zLike);
8521          goto meta_command_exit;
8522#else
8523          ShellSetFlag(p, SHFLG_PreserveRowid);
8524#endif
8525        }else
8526        if( strcmp(z,"newlines")==0 ){
8527          ShellSetFlag(p, SHFLG_Newlines);
8528        }else
8529        if( strcmp(z,"data-only")==0 ){
8530          ShellSetFlag(p, SHFLG_DumpDataOnly);
8531        }else
8532        if( strcmp(z,"nosys")==0 ){
8533          ShellSetFlag(p, SHFLG_DumpNoSys);
8534        }else
8535        {
8536          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8537          rc = 1;
8538          sqlite3_free(zLike);
8539          goto meta_command_exit;
8540        }
8541      }else{
8542        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8543        ** only dump data for tables for which either the table name matches
8544        ** the LIKE pattern, or the table appears to be a shadow table of
8545        ** a virtual table for which the name matches the LIKE pattern.
8546        */
8547        char *zExpr = sqlite3_mprintf(
8548            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8549            "  SELECT 1 FROM sqlite_schema WHERE "
8550            "    name LIKE %Q ESCAPE '\\' AND"
8551            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8552            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8553            ")", azArg[i], azArg[i]
8554        );
8555
8556        if( zLike ){
8557          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8558        }else{
8559          zLike = zExpr;
8560        }
8561      }
8562    }
8563
8564    open_db(p, 0);
8565
8566    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8567      /* When playing back a "dump", the content might appear in an order
8568      ** which causes immediate foreign key constraints to be violated.
8569      ** So disable foreign-key constraint enforcement to prevent problems. */
8570      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8571      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8572    }
8573    p->writableSchema = 0;
8574    p->showHeader = 0;
8575    /* Set writable_schema=ON since doing so forces SQLite to initialize
8576    ** as much of the schema as it can even if the sqlite_schema table is
8577    ** corrupt. */
8578    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8579    p->nErr = 0;
8580    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8581    zSql = sqlite3_mprintf(
8582      "SELECT name, type, sql FROM sqlite_schema AS o "
8583      "WHERE (%s) AND type=='table'"
8584      "  AND sql NOT NULL"
8585      " ORDER BY tbl_name='sqlite_sequence', rowid",
8586      zLike
8587    );
8588    run_schema_dump_query(p,zSql);
8589    sqlite3_free(zSql);
8590    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8591      zSql = sqlite3_mprintf(
8592        "SELECT sql FROM sqlite_schema AS o "
8593        "WHERE (%s) AND sql NOT NULL"
8594        "  AND type IN ('index','trigger','view')",
8595        zLike
8596      );
8597      run_table_dump_query(p, zSql);
8598      sqlite3_free(zSql);
8599    }
8600    sqlite3_free(zLike);
8601    if( p->writableSchema ){
8602      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8603      p->writableSchema = 0;
8604    }
8605    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8606    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8607    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8608      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8609    }
8610    p->showHeader = savedShowHeader;
8611    p->shellFlgs = savedShellFlags;
8612  }else
8613
8614  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8615    if( nArg==2 ){
8616      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8617    }else{
8618      raw_printf(stderr, "Usage: .echo on|off\n");
8619      rc = 1;
8620    }
8621  }else
8622
8623  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8624    if( nArg==2 ){
8625      p->autoEQPtest = 0;
8626      if( p->autoEQPtrace ){
8627        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8628        p->autoEQPtrace = 0;
8629      }
8630      if( strcmp(azArg[1],"full")==0 ){
8631        p->autoEQP = AUTOEQP_full;
8632      }else if( strcmp(azArg[1],"trigger")==0 ){
8633        p->autoEQP = AUTOEQP_trigger;
8634#ifdef SQLITE_DEBUG
8635      }else if( strcmp(azArg[1],"test")==0 ){
8636        p->autoEQP = AUTOEQP_on;
8637        p->autoEQPtest = 1;
8638      }else if( strcmp(azArg[1],"trace")==0 ){
8639        p->autoEQP = AUTOEQP_full;
8640        p->autoEQPtrace = 1;
8641        open_db(p, 0);
8642        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8643        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8644#endif
8645      }else{
8646        p->autoEQP = (u8)booleanValue(azArg[1]);
8647      }
8648    }else{
8649      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8650      rc = 1;
8651    }
8652  }else
8653
8654#ifndef SQLITE_SHELL_WASM_MODE
8655  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8656    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8657    rc = 2;
8658  }else
8659#endif
8660
8661  /* The ".explain" command is automatic now.  It is largely pointless.  It
8662  ** retained purely for backwards compatibility */
8663  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8664    int val = 1;
8665    if( nArg>=2 ){
8666      if( strcmp(azArg[1],"auto")==0 ){
8667        val = 99;
8668      }else{
8669        val =  booleanValue(azArg[1]);
8670      }
8671    }
8672    if( val==1 && p->mode!=MODE_Explain ){
8673      p->normalMode = p->mode;
8674      p->mode = MODE_Explain;
8675      p->autoExplain = 0;
8676    }else if( val==0 ){
8677      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8678      p->autoExplain = 0;
8679    }else if( val==99 ){
8680      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8681      p->autoExplain = 1;
8682    }
8683  }else
8684
8685#ifndef SQLITE_OMIT_VIRTUALTABLE
8686  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8687    if( p->bSafeMode ){
8688      raw_printf(stderr,
8689        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8690        azArg[0]);
8691      rc = 1;
8692    }else{
8693      open_db(p, 0);
8694      expertDotCommand(p, azArg, nArg);
8695    }
8696  }else
8697#endif
8698
8699  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8700    static const struct {
8701       const char *zCtrlName;   /* Name of a test-control option */
8702       int ctrlCode;            /* Integer code for that option */
8703       const char *zUsage;      /* Usage notes */
8704    } aCtrl[] = {
8705      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8706      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8707      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8708      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8709      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8710   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8711      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8712      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8713      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8714      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8715   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8716    };
8717    int filectrl = -1;
8718    int iCtrl = -1;
8719    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8720    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8721    int n2, i;
8722    const char *zCmd = 0;
8723    const char *zSchema = 0;
8724
8725    open_db(p, 0);
8726    zCmd = nArg>=2 ? azArg[1] : "help";
8727
8728    if( zCmd[0]=='-'
8729     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8730     && nArg>=4
8731    ){
8732      zSchema = azArg[2];
8733      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8734      nArg -= 2;
8735      zCmd = azArg[1];
8736    }
8737
8738    /* The argument can optionally begin with "-" or "--" */
8739    if( zCmd[0]=='-' && zCmd[1] ){
8740      zCmd++;
8741      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8742    }
8743
8744    /* --help lists all file-controls */
8745    if( strcmp(zCmd,"help")==0 ){
8746      utf8_printf(p->out, "Available file-controls:\n");
8747      for(i=0; i<ArraySize(aCtrl); i++){
8748        utf8_printf(p->out, "  .filectrl %s %s\n",
8749                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8750      }
8751      rc = 1;
8752      goto meta_command_exit;
8753    }
8754
8755    /* convert filectrl text option to value. allow any unique prefix
8756    ** of the option name, or a numerical value. */
8757    n2 = strlen30(zCmd);
8758    for(i=0; i<ArraySize(aCtrl); i++){
8759      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8760        if( filectrl<0 ){
8761          filectrl = aCtrl[i].ctrlCode;
8762          iCtrl = i;
8763        }else{
8764          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8765                              "Use \".filectrl --help\" for help\n", zCmd);
8766          rc = 1;
8767          goto meta_command_exit;
8768        }
8769      }
8770    }
8771    if( filectrl<0 ){
8772      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8773                         "Use \".filectrl --help\" for help\n", zCmd);
8774    }else{
8775      switch(filectrl){
8776        case SQLITE_FCNTL_SIZE_LIMIT: {
8777          if( nArg!=2 && nArg!=3 ) break;
8778          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8779          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8780          isOk = 1;
8781          break;
8782        }
8783        case SQLITE_FCNTL_LOCK_TIMEOUT:
8784        case SQLITE_FCNTL_CHUNK_SIZE: {
8785          int x;
8786          if( nArg!=3 ) break;
8787          x = (int)integerValue(azArg[2]);
8788          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8789          isOk = 2;
8790          break;
8791        }
8792        case SQLITE_FCNTL_PERSIST_WAL:
8793        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8794          int x;
8795          if( nArg!=2 && nArg!=3 ) break;
8796          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8797          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8798          iRes = x;
8799          isOk = 1;
8800          break;
8801        }
8802        case SQLITE_FCNTL_DATA_VERSION:
8803        case SQLITE_FCNTL_HAS_MOVED: {
8804          int x;
8805          if( nArg!=2 ) break;
8806          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8807          iRes = x;
8808          isOk = 1;
8809          break;
8810        }
8811        case SQLITE_FCNTL_TEMPFILENAME: {
8812          char *z = 0;
8813          if( nArg!=2 ) break;
8814          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8815          if( z ){
8816            utf8_printf(p->out, "%s\n", z);
8817            sqlite3_free(z);
8818          }
8819          isOk = 2;
8820          break;
8821        }
8822        case SQLITE_FCNTL_RESERVE_BYTES: {
8823          int x;
8824          if( nArg>=3 ){
8825            x = atoi(azArg[2]);
8826            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8827          }
8828          x = -1;
8829          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8830          utf8_printf(p->out,"%d\n", x);
8831          isOk = 2;
8832          break;
8833        }
8834      }
8835    }
8836    if( isOk==0 && iCtrl>=0 ){
8837      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8838      rc = 1;
8839    }else if( isOk==1 ){
8840      char zBuf[100];
8841      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8842      raw_printf(p->out, "%s\n", zBuf);
8843    }
8844  }else
8845
8846  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8847    ShellState data;
8848    int doStats = 0;
8849    memcpy(&data, p, sizeof(data));
8850    data.showHeader = 0;
8851    data.cMode = data.mode = MODE_Semi;
8852    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8853      data.cMode = data.mode = MODE_Pretty;
8854      nArg = 1;
8855    }
8856    if( nArg!=1 ){
8857      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8858      rc = 1;
8859      goto meta_command_exit;
8860    }
8861    open_db(p, 0);
8862    rc = sqlite3_exec(p->db,
8863       "SELECT sql FROM"
8864       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8865       "     FROM sqlite_schema UNION ALL"
8866       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8867       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8868       "ORDER BY x",
8869       callback, &data, 0
8870    );
8871    if( rc==SQLITE_OK ){
8872      sqlite3_stmt *pStmt;
8873      rc = sqlite3_prepare_v2(p->db,
8874               "SELECT rowid FROM sqlite_schema"
8875               " WHERE name GLOB 'sqlite_stat[134]'",
8876               -1, &pStmt, 0);
8877      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8878      sqlite3_finalize(pStmt);
8879    }
8880    if( doStats==0 ){
8881      raw_printf(p->out, "/* No STAT tables available */\n");
8882    }else{
8883      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8884      data.cMode = data.mode = MODE_Insert;
8885      data.zDestTable = "sqlite_stat1";
8886      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8887      data.zDestTable = "sqlite_stat4";
8888      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8889      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8890    }
8891  }else
8892
8893  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8894    if( nArg==2 ){
8895      p->showHeader = booleanValue(azArg[1]);
8896      p->shellFlgs |= SHFLG_HeaderSet;
8897    }else{
8898      raw_printf(stderr, "Usage: .headers on|off\n");
8899      rc = 1;
8900    }
8901  }else
8902
8903  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8904    if( nArg>=2 ){
8905      n = showHelp(p->out, azArg[1]);
8906      if( n==0 ){
8907        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8908      }
8909    }else{
8910      showHelp(p->out, 0);
8911    }
8912  }else
8913
8914#ifndef SQLITE_SHELL_WASM_MODE
8915  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8916    char *zTable = 0;           /* Insert data into this table */
8917    char *zSchema = 0;          /* within this schema (may default to "main") */
8918    char *zFile = 0;            /* Name of file to extra content from */
8919    sqlite3_stmt *pStmt = NULL; /* A statement */
8920    int nCol;                   /* Number of columns in the table */
8921    int nByte;                  /* Number of bytes in an SQL string */
8922    int i, j;                   /* Loop counters */
8923    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8924    int nSep;                   /* Number of bytes in p->colSeparator[] */
8925    char *zSql;                 /* An SQL statement */
8926    char *zFullTabName;         /* Table name with schema if applicable */
8927    ImportCtx sCtx;             /* Reader context */
8928    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8929    int eVerbose = 0;           /* Larger for more console output */
8930    int nSkip = 0;              /* Initial lines to skip */
8931    int useOutputMode = 1;      /* Use output mode to determine separators */
8932    char *zCreate = 0;          /* CREATE TABLE statement text */
8933
8934    failIfSafeMode(p, "cannot run .import in safe mode");
8935    memset(&sCtx, 0, sizeof(sCtx));
8936    if( p->mode==MODE_Ascii ){
8937      xRead = ascii_read_one_field;
8938    }else{
8939      xRead = csv_read_one_field;
8940    }
8941    rc = 1;
8942    for(i=1; i<nArg; i++){
8943      char *z = azArg[i];
8944      if( z[0]=='-' && z[1]=='-' ) z++;
8945      if( z[0]!='-' ){
8946        if( zFile==0 ){
8947          zFile = z;
8948        }else if( zTable==0 ){
8949          zTable = z;
8950        }else{
8951          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8952          showHelp(p->out, "import");
8953          goto meta_command_exit;
8954        }
8955      }else if( strcmp(z,"-v")==0 ){
8956        eVerbose++;
8957      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8958        zSchema = azArg[++i];
8959      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8960        nSkip = integerValue(azArg[++i]);
8961      }else if( strcmp(z,"-ascii")==0 ){
8962        sCtx.cColSep = SEP_Unit[0];
8963        sCtx.cRowSep = SEP_Record[0];
8964        xRead = ascii_read_one_field;
8965        useOutputMode = 0;
8966      }else if( strcmp(z,"-csv")==0 ){
8967        sCtx.cColSep = ',';
8968        sCtx.cRowSep = '\n';
8969        xRead = csv_read_one_field;
8970        useOutputMode = 0;
8971      }else{
8972        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8973        showHelp(p->out, "import");
8974        goto meta_command_exit;
8975      }
8976    }
8977    if( zTable==0 ){
8978      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8979                  zFile==0 ? "FILE" : "TABLE");
8980      showHelp(p->out, "import");
8981      goto meta_command_exit;
8982    }
8983    seenInterrupt = 0;
8984    open_db(p, 0);
8985    if( useOutputMode ){
8986      /* If neither the --csv or --ascii options are specified, then set
8987      ** the column and row separator characters from the output mode. */
8988      nSep = strlen30(p->colSeparator);
8989      if( nSep==0 ){
8990        raw_printf(stderr,
8991                   "Error: non-null column separator required for import\n");
8992        goto meta_command_exit;
8993      }
8994      if( nSep>1 ){
8995        raw_printf(stderr,
8996              "Error: multi-character column separators not allowed"
8997              " for import\n");
8998        goto meta_command_exit;
8999      }
9000      nSep = strlen30(p->rowSeparator);
9001      if( nSep==0 ){
9002        raw_printf(stderr,
9003            "Error: non-null row separator required for import\n");
9004        goto meta_command_exit;
9005      }
9006      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9007        /* When importing CSV (only), if the row separator is set to the
9008        ** default output row separator, change it to the default input
9009        ** row separator.  This avoids having to maintain different input
9010        ** and output row separators. */
9011        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9012        nSep = strlen30(p->rowSeparator);
9013      }
9014      if( nSep>1 ){
9015        raw_printf(stderr, "Error: multi-character row separators not allowed"
9016                           " for import\n");
9017        goto meta_command_exit;
9018      }
9019      sCtx.cColSep = p->colSeparator[0];
9020      sCtx.cRowSep = p->rowSeparator[0];
9021    }
9022    sCtx.zFile = zFile;
9023    sCtx.nLine = 1;
9024    if( sCtx.zFile[0]=='|' ){
9025#ifdef SQLITE_OMIT_POPEN
9026      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9027      goto meta_command_exit;
9028#else
9029      sCtx.in = popen(sCtx.zFile+1, "r");
9030      sCtx.zFile = "<pipe>";
9031      sCtx.xCloser = pclose;
9032#endif
9033    }else{
9034      sCtx.in = fopen(sCtx.zFile, "rb");
9035      sCtx.xCloser = fclose;
9036    }
9037    if( sCtx.in==0 ){
9038      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9039      goto meta_command_exit;
9040    }
9041    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9042      char zSep[2];
9043      zSep[1] = 0;
9044      zSep[0] = sCtx.cColSep;
9045      utf8_printf(p->out, "Column separator ");
9046      output_c_string(p->out, zSep);
9047      utf8_printf(p->out, ", row separator ");
9048      zSep[0] = sCtx.cRowSep;
9049      output_c_string(p->out, zSep);
9050      utf8_printf(p->out, "\n");
9051    }
9052    sCtx.z = sqlite3_malloc64(120);
9053    if( sCtx.z==0 ){
9054      import_cleanup(&sCtx);
9055      shell_out_of_memory();
9056    }
9057    /* Below, resources must be freed before exit. */
9058    while( (nSkip--)>0 ){
9059      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9060    }
9061    if( zSchema!=0 ){
9062      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9063    }else{
9064      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9065    }
9066    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9067    if( zSql==0 || zFullTabName==0 ){
9068      import_cleanup(&sCtx);
9069      shell_out_of_memory();
9070    }
9071    nByte = strlen30(zSql);
9072    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9073    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9074    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9075      sqlite3 *dbCols = 0;
9076      char *zRenames = 0;
9077      char *zColDefs;
9078      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9079      while( xRead(&sCtx) ){
9080        zAutoColumn(sCtx.z, &dbCols, 0);
9081        if( sCtx.cTerm!=sCtx.cColSep ) break;
9082      }
9083      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9084      if( zRenames!=0 ){
9085        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9086                    "Columns renamed during .import %s due to duplicates:\n"
9087                    "%s\n", sCtx.zFile, zRenames);
9088        sqlite3_free(zRenames);
9089      }
9090      assert(dbCols==0);
9091      if( zColDefs==0 ){
9092        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9093      import_fail:
9094        sqlite3_free(zCreate);
9095        sqlite3_free(zSql);
9096        sqlite3_free(zFullTabName);
9097        import_cleanup(&sCtx);
9098        rc = 1;
9099        goto meta_command_exit;
9100      }
9101      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9102      if( eVerbose>=1 ){
9103        utf8_printf(p->out, "%s\n", zCreate);
9104      }
9105      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9106      if( rc ){
9107        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9108        goto import_fail;
9109      }
9110      sqlite3_free(zCreate);
9111      zCreate = 0;
9112      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9113    }
9114    if( rc ){
9115      if (pStmt) sqlite3_finalize(pStmt);
9116      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9117      goto import_fail;
9118    }
9119    sqlite3_free(zSql);
9120    nCol = sqlite3_column_count(pStmt);
9121    sqlite3_finalize(pStmt);
9122    pStmt = 0;
9123    if( nCol==0 ) return 0; /* no columns, no error */
9124    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9125    if( zSql==0 ){
9126      import_cleanup(&sCtx);
9127      shell_out_of_memory();
9128    }
9129    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9130    j = strlen30(zSql);
9131    for(i=1; i<nCol; i++){
9132      zSql[j++] = ',';
9133      zSql[j++] = '?';
9134    }
9135    zSql[j++] = ')';
9136    zSql[j] = 0;
9137    if( eVerbose>=2 ){
9138      utf8_printf(p->out, "Insert using: %s\n", zSql);
9139    }
9140    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9141    if( rc ){
9142      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9143      if (pStmt) sqlite3_finalize(pStmt);
9144      goto import_fail;
9145    }
9146    sqlite3_free(zSql);
9147    sqlite3_free(zFullTabName);
9148    needCommit = sqlite3_get_autocommit(p->db);
9149    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9150    do{
9151      int startLine = sCtx.nLine;
9152      for(i=0; i<nCol; i++){
9153        char *z = xRead(&sCtx);
9154        /*
9155        ** Did we reach end-of-file before finding any columns?
9156        ** If so, stop instead of NULL filling the remaining columns.
9157        */
9158        if( z==0 && i==0 ) break;
9159        /*
9160        ** Did we reach end-of-file OR end-of-line before finding any
9161        ** columns in ASCII mode?  If so, stop instead of NULL filling
9162        ** the remaining columns.
9163        */
9164        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9165        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9166        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9167          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9168                          "filling the rest with NULL\n",
9169                          sCtx.zFile, startLine, nCol, i+1);
9170          i += 2;
9171          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9172        }
9173      }
9174      if( sCtx.cTerm==sCtx.cColSep ){
9175        do{
9176          xRead(&sCtx);
9177          i++;
9178        }while( sCtx.cTerm==sCtx.cColSep );
9179        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9180                        "extras ignored\n",
9181                        sCtx.zFile, startLine, nCol, i);
9182      }
9183      if( i>=nCol ){
9184        sqlite3_step(pStmt);
9185        rc = sqlite3_reset(pStmt);
9186        if( rc!=SQLITE_OK ){
9187          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9188                      startLine, sqlite3_errmsg(p->db));
9189          sCtx.nErr++;
9190        }else{
9191          sCtx.nRow++;
9192        }
9193      }
9194    }while( sCtx.cTerm!=EOF );
9195
9196    import_cleanup(&sCtx);
9197    sqlite3_finalize(pStmt);
9198    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9199    if( eVerbose>0 ){
9200      utf8_printf(p->out,
9201          "Added %d rows with %d errors using %d lines of input\n",
9202          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9203    }
9204  }else
9205#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9206
9207#ifndef SQLITE_UNTESTABLE
9208  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9209    char *zSql;
9210    char *zCollist = 0;
9211    sqlite3_stmt *pStmt;
9212    int tnum = 0;
9213    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9214    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9215    int i;
9216    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9217      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9218                          "       .imposter off\n");
9219      /* Also allowed, but not documented:
9220      **
9221      **    .imposter TABLE IMPOSTER
9222      **
9223      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9224      ** imposter is another WITHOUT ROWID table with the columns in
9225      ** storage order. */
9226      rc = 1;
9227      goto meta_command_exit;
9228    }
9229    open_db(p, 0);
9230    if( nArg==2 ){
9231      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9232      goto meta_command_exit;
9233    }
9234    zSql = sqlite3_mprintf(
9235      "SELECT rootpage, 0 FROM sqlite_schema"
9236      " WHERE name='%q' AND type='index'"
9237      "UNION ALL "
9238      "SELECT rootpage, 1 FROM sqlite_schema"
9239      " WHERE name='%q' AND type='table'"
9240      "   AND sql LIKE '%%without%%rowid%%'",
9241      azArg[1], azArg[1]
9242    );
9243    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9244    sqlite3_free(zSql);
9245    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9246      tnum = sqlite3_column_int(pStmt, 0);
9247      isWO = sqlite3_column_int(pStmt, 1);
9248    }
9249    sqlite3_finalize(pStmt);
9250    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9251    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9252    sqlite3_free(zSql);
9253    i = 0;
9254    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9255      char zLabel[20];
9256      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9257      i++;
9258      if( zCol==0 ){
9259        if( sqlite3_column_int(pStmt,1)==-1 ){
9260          zCol = "_ROWID_";
9261        }else{
9262          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9263          zCol = zLabel;
9264        }
9265      }
9266      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9267        lenPK = (int)strlen(zCollist);
9268      }
9269      if( zCollist==0 ){
9270        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9271      }else{
9272        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9273      }
9274    }
9275    sqlite3_finalize(pStmt);
9276    if( i==0 || tnum==0 ){
9277      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9278      rc = 1;
9279      sqlite3_free(zCollist);
9280      goto meta_command_exit;
9281    }
9282    if( lenPK==0 ) lenPK = 100000;
9283    zSql = sqlite3_mprintf(
9284          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9285          azArg[2], zCollist, lenPK, zCollist);
9286    sqlite3_free(zCollist);
9287    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9288    if( rc==SQLITE_OK ){
9289      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9290      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9291      if( rc ){
9292        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9293      }else{
9294        utf8_printf(stdout, "%s;\n", zSql);
9295        raw_printf(stdout,
9296          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9297          azArg[1], isWO ? "table" : "index"
9298        );
9299      }
9300    }else{
9301      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9302      rc = 1;
9303    }
9304    sqlite3_free(zSql);
9305  }else
9306#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9307
9308#ifdef SQLITE_ENABLE_IOTRACE
9309  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9310    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9311    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9312    iotrace = 0;
9313    if( nArg<2 ){
9314      sqlite3IoTrace = 0;
9315    }else if( strcmp(azArg[1], "-")==0 ){
9316      sqlite3IoTrace = iotracePrintf;
9317      iotrace = stdout;
9318    }else{
9319      iotrace = fopen(azArg[1], "w");
9320      if( iotrace==0 ){
9321        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9322        sqlite3IoTrace = 0;
9323        rc = 1;
9324      }else{
9325        sqlite3IoTrace = iotracePrintf;
9326      }
9327    }
9328  }else
9329#endif
9330
9331  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9332    static const struct {
9333       const char *zLimitName;   /* Name of a limit */
9334       int limitCode;            /* Integer code for that limit */
9335    } aLimit[] = {
9336      { "length",                SQLITE_LIMIT_LENGTH                    },
9337      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9338      { "column",                SQLITE_LIMIT_COLUMN                    },
9339      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9340      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9341      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9342      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9343      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9344      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9345      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9346      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9347      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9348    };
9349    int i, n2;
9350    open_db(p, 0);
9351    if( nArg==1 ){
9352      for(i=0; i<ArraySize(aLimit); i++){
9353        printf("%20s %d\n", aLimit[i].zLimitName,
9354               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9355      }
9356    }else if( nArg>3 ){
9357      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9358      rc = 1;
9359      goto meta_command_exit;
9360    }else{
9361      int iLimit = -1;
9362      n2 = strlen30(azArg[1]);
9363      for(i=0; i<ArraySize(aLimit); i++){
9364        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9365          if( iLimit<0 ){
9366            iLimit = i;
9367          }else{
9368            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9369            rc = 1;
9370            goto meta_command_exit;
9371          }
9372        }
9373      }
9374      if( iLimit<0 ){
9375        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9376                        "enter \".limits\" with no arguments for a list.\n",
9377                         azArg[1]);
9378        rc = 1;
9379        goto meta_command_exit;
9380      }
9381      if( nArg==3 ){
9382        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9383                      (int)integerValue(azArg[2]));
9384      }
9385      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9386             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9387    }
9388  }else
9389
9390  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9391    open_db(p, 0);
9392    lintDotCommand(p, azArg, nArg);
9393  }else
9394
9395#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_WASM_MODE)
9396  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9397    const char *zFile, *zProc;
9398    char *zErrMsg = 0;
9399    failIfSafeMode(p, "cannot run .load in safe mode");
9400    if( nArg<2 ){
9401      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9402      rc = 1;
9403      goto meta_command_exit;
9404    }
9405    zFile = azArg[1];
9406    zProc = nArg>=3 ? azArg[2] : 0;
9407    open_db(p, 0);
9408    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9409    if( rc!=SQLITE_OK ){
9410      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9411      sqlite3_free(zErrMsg);
9412      rc = 1;
9413    }
9414  }else
9415#endif
9416
9417#ifndef SQLITE_SHELL_WASM_MODE
9418  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9419    failIfSafeMode(p, "cannot run .log in safe mode");
9420    if( nArg!=2 ){
9421      raw_printf(stderr, "Usage: .log FILENAME\n");
9422      rc = 1;
9423    }else{
9424      const char *zFile = azArg[1];
9425      output_file_close(p->pLog);
9426      p->pLog = output_file_open(zFile, 0);
9427    }
9428  }else
9429#endif
9430
9431  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9432    const char *zMode = 0;
9433    const char *zTabname = 0;
9434    int i, n2;
9435    ColModeOpts cmOpts = ColModeOpts_default;
9436    for(i=1; i<nArg; i++){
9437      const char *z = azArg[i];
9438      if( optionMatch(z,"wrap") && i+1<nArg ){
9439        cmOpts.iWrap = integerValue(azArg[++i]);
9440      }else if( optionMatch(z,"ww") ){
9441        cmOpts.bWordWrap = 1;
9442      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9443        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9444      }else if( optionMatch(z,"quote") ){
9445        cmOpts.bQuote = 1;
9446      }else if( optionMatch(z,"noquote") ){
9447        cmOpts.bQuote = 0;
9448      }else if( zMode==0 ){
9449        zMode = z;
9450        /* Apply defaults for qbox pseudo-mods. If that
9451         * overwrites already-set values, user was informed of this.
9452         */
9453        if( strcmp(z, "qbox")==0 ){
9454          ColModeOpts cmo = ColModeOpts_default_qbox;
9455          zMode = "box";
9456          cmOpts = cmo;
9457        }
9458      }else if( zTabname==0 ){
9459        zTabname = z;
9460      }else if( z[0]=='-' ){
9461        utf8_printf(stderr, "unknown option: %s\n", z);
9462        utf8_printf(stderr, "options:\n"
9463                            "  --noquote\n"
9464                            "  --quote\n"
9465                            "  --wordwrap on/off\n"
9466                            "  --wrap N\n"
9467                            "  --ww\n");
9468        rc = 1;
9469        goto meta_command_exit;
9470      }else{
9471        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9472        rc = 1;
9473        goto meta_command_exit;
9474      }
9475    }
9476    if( zMode==0 ){
9477      if( p->mode==MODE_Column
9478       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9479      ){
9480        raw_printf
9481          (p->out,
9482           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9483           modeDescr[p->mode], p->cmOpts.iWrap,
9484           p->cmOpts.bWordWrap ? "on" : "off",
9485           p->cmOpts.bQuote ? "" : "no");
9486      }else{
9487        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9488      }
9489      zMode = modeDescr[p->mode];
9490    }
9491    n2 = strlen30(zMode);
9492    if( strncmp(zMode,"lines",n2)==0 ){
9493      p->mode = MODE_Line;
9494      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9495    }else if( strncmp(zMode,"columns",n2)==0 ){
9496      p->mode = MODE_Column;
9497      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9498        p->showHeader = 1;
9499      }
9500      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9501      p->cmOpts = cmOpts;
9502    }else if( strncmp(zMode,"list",n2)==0 ){
9503      p->mode = MODE_List;
9504      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9505      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9506    }else if( strncmp(zMode,"html",n2)==0 ){
9507      p->mode = MODE_Html;
9508    }else if( strncmp(zMode,"tcl",n2)==0 ){
9509      p->mode = MODE_Tcl;
9510      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9511      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9512    }else if( strncmp(zMode,"csv",n2)==0 ){
9513      p->mode = MODE_Csv;
9514      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9515      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9516    }else if( strncmp(zMode,"tabs",n2)==0 ){
9517      p->mode = MODE_List;
9518      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9519    }else if( strncmp(zMode,"insert",n2)==0 ){
9520      p->mode = MODE_Insert;
9521      set_table_name(p, zTabname ? zTabname : "table");
9522    }else if( strncmp(zMode,"quote",n2)==0 ){
9523      p->mode = MODE_Quote;
9524      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9525      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9526    }else if( strncmp(zMode,"ascii",n2)==0 ){
9527      p->mode = MODE_Ascii;
9528      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9529      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9530    }else if( strncmp(zMode,"markdown",n2)==0 ){
9531      p->mode = MODE_Markdown;
9532      p->cmOpts = cmOpts;
9533    }else if( strncmp(zMode,"table",n2)==0 ){
9534      p->mode = MODE_Table;
9535      p->cmOpts = cmOpts;
9536    }else if( strncmp(zMode,"box",n2)==0 ){
9537      p->mode = MODE_Box;
9538      p->cmOpts = cmOpts;
9539    }else if( strncmp(zMode,"count",n2)==0 ){
9540      p->mode = MODE_Count;
9541    }else if( strncmp(zMode,"off",n2)==0 ){
9542      p->mode = MODE_Off;
9543    }else if( strncmp(zMode,"json",n2)==0 ){
9544      p->mode = MODE_Json;
9545    }else{
9546      raw_printf(stderr, "Error: mode should be one of: "
9547         "ascii box column csv html insert json line list markdown "
9548         "qbox quote table tabs tcl\n");
9549      rc = 1;
9550    }
9551    p->cMode = p->mode;
9552  }else
9553
9554#ifndef SQLITE_SHELL_WASM_MODE
9555  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9556    if( nArg!=2 ){
9557      raw_printf(stderr, "Usage: .nonce NONCE\n");
9558      rc = 1;
9559    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9560      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9561                 p->lineno, azArg[1]);
9562      exit(1);
9563    }else{
9564      p->bSafeMode = 0;
9565      return 0;  /* Return immediately to bypass the safe mode reset
9566                 ** at the end of this procedure */
9567    }
9568  }else
9569#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9570
9571  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9572    if( nArg==2 ){
9573      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9574                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9575    }else{
9576      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9577      rc = 1;
9578    }
9579  }else
9580
9581  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9582    const char *zFN = 0;     /* Pointer to constant filename */
9583    char *zNewFilename = 0;  /* Name of the database file to open */
9584    int iName = 1;           /* Index in azArg[] of the filename */
9585    int newFlag = 0;         /* True to delete file before opening */
9586    int openMode = SHELL_OPEN_UNSPEC;
9587
9588    /* Check for command-line arguments */
9589    for(iName=1; iName<nArg; iName++){
9590      const char *z = azArg[iName];
9591#ifndef SQLITE_SHELL_WASM_MODE
9592      if( optionMatch(z,"new") ){
9593        newFlag = 1;
9594#ifdef SQLITE_HAVE_ZLIB
9595      }else if( optionMatch(z, "zip") ){
9596        openMode = SHELL_OPEN_ZIPFILE;
9597#endif
9598      }else if( optionMatch(z, "append") ){
9599        openMode = SHELL_OPEN_APPENDVFS;
9600      }else if( optionMatch(z, "readonly") ){
9601        openMode = SHELL_OPEN_READONLY;
9602      }else if( optionMatch(z, "nofollow") ){
9603        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9604#ifndef SQLITE_OMIT_DESERIALIZE
9605      }else if( optionMatch(z, "deserialize") ){
9606        openMode = SHELL_OPEN_DESERIALIZE;
9607      }else if( optionMatch(z, "hexdb") ){
9608        openMode = SHELL_OPEN_HEXDB;
9609      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9610        p->szMax = integerValue(azArg[++iName]);
9611#endif /* SQLITE_OMIT_DESERIALIZE */
9612      }else
9613#endif /* !SQLITE_SHELL_WASM_MODE */
9614      if( z[0]=='-' ){
9615        utf8_printf(stderr, "unknown option: %s\n", z);
9616        rc = 1;
9617        goto meta_command_exit;
9618      }else if( zFN ){
9619        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9620        rc = 1;
9621        goto meta_command_exit;
9622      }else{
9623        zFN = z;
9624      }
9625    }
9626
9627    /* Close the existing database */
9628    session_close_all(p, -1);
9629    close_db(p->db);
9630    p->db = 0;
9631    p->pAuxDb->zDbFilename = 0;
9632    sqlite3_free(p->pAuxDb->zFreeOnClose);
9633    p->pAuxDb->zFreeOnClose = 0;
9634    p->openMode = openMode;
9635    p->openFlags = 0;
9636    p->szMax = 0;
9637
9638    /* If a filename is specified, try to open it first */
9639    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9640      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9641#ifndef SQLITE_SHELL_WASM_MODE
9642      if( p->bSafeMode
9643       && p->openMode!=SHELL_OPEN_HEXDB
9644       && zFN
9645       && strcmp(zFN,":memory:")!=0
9646      ){
9647        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9648      }
9649#else
9650      /* WASM mode has its own sandboxed pseudo-filesystem. */
9651#endif
9652      if( zFN ){
9653        zNewFilename = sqlite3_mprintf("%s", zFN);
9654        shell_check_oom(zNewFilename);
9655      }else{
9656        zNewFilename = 0;
9657      }
9658      p->pAuxDb->zDbFilename = zNewFilename;
9659      open_db(p, OPEN_DB_KEEPALIVE);
9660      if( p->db==0 ){
9661        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9662        sqlite3_free(zNewFilename);
9663      }else{
9664        p->pAuxDb->zFreeOnClose = zNewFilename;
9665      }
9666    }
9667    if( p->db==0 ){
9668      /* As a fall-back open a TEMP database */
9669      p->pAuxDb->zDbFilename = 0;
9670      open_db(p, 0);
9671    }
9672  }else
9673
9674#ifndef SQLITE_SHELL_WASM_MODE
9675  if( (c=='o'
9676        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9677   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9678  ){
9679    char *zFile = 0;
9680    int bTxtMode = 0;
9681    int i;
9682    int eMode = 0;
9683    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9684    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9685
9686    zBOM[0] = 0;
9687    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9688    if( c=='e' ){
9689      eMode = 'x';
9690      bOnce = 2;
9691    }else if( strncmp(azArg[0],"once",n)==0 ){
9692      bOnce = 1;
9693    }
9694    for(i=1; i<nArg; i++){
9695      char *z = azArg[i];
9696      if( z[0]=='-' ){
9697        if( z[1]=='-' ) z++;
9698        if( strcmp(z,"-bom")==0 ){
9699          zBOM[0] = 0xef;
9700          zBOM[1] = 0xbb;
9701          zBOM[2] = 0xbf;
9702          zBOM[3] = 0;
9703        }else if( c!='e' && strcmp(z,"-x")==0 ){
9704          eMode = 'x';  /* spreadsheet */
9705        }else if( c!='e' && strcmp(z,"-e")==0 ){
9706          eMode = 'e';  /* text editor */
9707        }else{
9708          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9709                      azArg[i]);
9710          showHelp(p->out, azArg[0]);
9711          rc = 1;
9712          goto meta_command_exit;
9713        }
9714      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9715        zFile = sqlite3_mprintf("%s", z);
9716        if( zFile && zFile[0]=='|' ){
9717          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9718          break;
9719        }
9720      }else{
9721        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9722                    azArg[i]);
9723        showHelp(p->out, azArg[0]);
9724        rc = 1;
9725        sqlite3_free(zFile);
9726        goto meta_command_exit;
9727      }
9728    }
9729    if( zFile==0 ){
9730      zFile = sqlite3_mprintf("stdout");
9731    }
9732    if( bOnce ){
9733      p->outCount = 2;
9734    }else{
9735      p->outCount = 0;
9736    }
9737    output_reset(p);
9738#ifndef SQLITE_NOHAVE_SYSTEM
9739    if( eMode=='e' || eMode=='x' ){
9740      p->doXdgOpen = 1;
9741      outputModePush(p);
9742      if( eMode=='x' ){
9743        /* spreadsheet mode.  Output as CSV. */
9744        newTempFile(p, "csv");
9745        ShellClearFlag(p, SHFLG_Echo);
9746        p->mode = MODE_Csv;
9747        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9748        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9749      }else{
9750        /* text editor mode */
9751        newTempFile(p, "txt");
9752        bTxtMode = 1;
9753      }
9754      sqlite3_free(zFile);
9755      zFile = sqlite3_mprintf("%s", p->zTempFile);
9756    }
9757#endif /* SQLITE_NOHAVE_SYSTEM */
9758    shell_check_oom(zFile);
9759    if( zFile[0]=='|' ){
9760#ifdef SQLITE_OMIT_POPEN
9761      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9762      rc = 1;
9763      p->out = stdout;
9764#else
9765      p->out = popen(zFile + 1, "w");
9766      if( p->out==0 ){
9767        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9768        p->out = stdout;
9769        rc = 1;
9770      }else{
9771        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9772        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9773      }
9774#endif
9775    }else{
9776      p->out = output_file_open(zFile, bTxtMode);
9777      if( p->out==0 ){
9778        if( strcmp(zFile,"off")!=0 ){
9779          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9780        }
9781        p->out = stdout;
9782        rc = 1;
9783      } else {
9784        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9785        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9786      }
9787    }
9788    sqlite3_free(zFile);
9789  }else
9790#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
9791
9792  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9793    open_db(p,0);
9794    if( nArg<=1 ) goto parameter_syntax_error;
9795
9796    /* .parameter clear
9797    ** Clear all bind parameters by dropping the TEMP table that holds them.
9798    */
9799    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9800      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9801                   0, 0, 0);
9802    }else
9803
9804    /* .parameter list
9805    ** List all bind parameters.
9806    */
9807    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9808      sqlite3_stmt *pStmt = 0;
9809      int rx;
9810      int len = 0;
9811      rx = sqlite3_prepare_v2(p->db,
9812             "SELECT max(length(key)) "
9813             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9814      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9815        len = sqlite3_column_int(pStmt, 0);
9816        if( len>40 ) len = 40;
9817      }
9818      sqlite3_finalize(pStmt);
9819      pStmt = 0;
9820      if( len ){
9821        rx = sqlite3_prepare_v2(p->db,
9822             "SELECT key, quote(value) "
9823             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9824        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9825          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9826                      sqlite3_column_text(pStmt,1));
9827        }
9828        sqlite3_finalize(pStmt);
9829      }
9830    }else
9831
9832    /* .parameter init
9833    ** Make sure the TEMP table used to hold bind parameters exists.
9834    ** Create it if necessary.
9835    */
9836    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9837      bind_table_init(p);
9838    }else
9839
9840    /* .parameter set NAME VALUE
9841    ** Set or reset a bind parameter.  NAME should be the full parameter
9842    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9843    ** VALUE can be in either SQL literal notation, or if not it will be
9844    ** understood to be a text string.
9845    */
9846    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9847      int rx;
9848      char *zSql;
9849      sqlite3_stmt *pStmt;
9850      const char *zKey = azArg[2];
9851      const char *zValue = azArg[3];
9852      bind_table_init(p);
9853      zSql = sqlite3_mprintf(
9854                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9855                  "VALUES(%Q,%s);", zKey, zValue);
9856      shell_check_oom(zSql);
9857      pStmt = 0;
9858      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9859      sqlite3_free(zSql);
9860      if( rx!=SQLITE_OK ){
9861        sqlite3_finalize(pStmt);
9862        pStmt = 0;
9863        zSql = sqlite3_mprintf(
9864                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9865                   "VALUES(%Q,%Q);", zKey, zValue);
9866        shell_check_oom(zSql);
9867        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9868        sqlite3_free(zSql);
9869        if( rx!=SQLITE_OK ){
9870          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9871          sqlite3_finalize(pStmt);
9872          pStmt = 0;
9873          rc = 1;
9874        }
9875      }
9876      sqlite3_step(pStmt);
9877      sqlite3_finalize(pStmt);
9878    }else
9879
9880    /* .parameter unset NAME
9881    ** Remove the NAME binding from the parameter binding table, if it
9882    ** exists.
9883    */
9884    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9885      char *zSql = sqlite3_mprintf(
9886          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9887      shell_check_oom(zSql);
9888      sqlite3_exec(p->db, zSql, 0, 0, 0);
9889      sqlite3_free(zSql);
9890    }else
9891    /* If no command name matches, show a syntax error */
9892    parameter_syntax_error:
9893    showHelp(p->out, "parameter");
9894  }else
9895
9896  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9897    int i;
9898    for(i=1; i<nArg; i++){
9899      if( i>1 ) raw_printf(p->out, " ");
9900      utf8_printf(p->out, "%s", azArg[i]);
9901    }
9902    raw_printf(p->out, "\n");
9903  }else
9904
9905#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9906  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9907    int i;
9908    int nn = 0;
9909    p->flgProgress = 0;
9910    p->mxProgress = 0;
9911    p->nProgress = 0;
9912    for(i=1; i<nArg; i++){
9913      const char *z = azArg[i];
9914      if( z[0]=='-' ){
9915        z++;
9916        if( z[0]=='-' ) z++;
9917        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9918          p->flgProgress |= SHELL_PROGRESS_QUIET;
9919          continue;
9920        }
9921        if( strcmp(z,"reset")==0 ){
9922          p->flgProgress |= SHELL_PROGRESS_RESET;
9923          continue;
9924        }
9925        if( strcmp(z,"once")==0 ){
9926          p->flgProgress |= SHELL_PROGRESS_ONCE;
9927          continue;
9928        }
9929        if( strcmp(z,"limit")==0 ){
9930          if( i+1>=nArg ){
9931            utf8_printf(stderr, "Error: missing argument on --limit\n");
9932            rc = 1;
9933            goto meta_command_exit;
9934          }else{
9935            p->mxProgress = (int)integerValue(azArg[++i]);
9936          }
9937          continue;
9938        }
9939        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9940        rc = 1;
9941        goto meta_command_exit;
9942      }else{
9943        nn = (int)integerValue(z);
9944      }
9945    }
9946    open_db(p, 0);
9947    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9948  }else
9949#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9950
9951  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9952    if( nArg >= 2) {
9953      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9954    }
9955    if( nArg >= 3) {
9956      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9957    }
9958  }else
9959
9960#ifndef SQLITE_SHELL_WASM_MODE
9961  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9962    rc = 2;
9963  }else
9964#endif
9965
9966#ifndef SQLITE_SHELL_WASM_MODE
9967  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9968    FILE *inSaved = p->in;
9969    int savedLineno = p->lineno;
9970    failIfSafeMode(p, "cannot run .read in safe mode");
9971    if( nArg!=2 ){
9972      raw_printf(stderr, "Usage: .read FILE\n");
9973      rc = 1;
9974      goto meta_command_exit;
9975    }
9976    if( azArg[1][0]=='|' ){
9977#ifdef SQLITE_OMIT_POPEN
9978      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9979      rc = 1;
9980      p->out = stdout;
9981#else
9982      p->in = popen(azArg[1]+1, "r");
9983      if( p->in==0 ){
9984        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9985        rc = 1;
9986      }else{
9987        rc = process_input(p);
9988        pclose(p->in);
9989      }
9990#endif
9991    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9992      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9993      rc = 1;
9994    }else{
9995      rc = process_input(p);
9996      fclose(p->in);
9997    }
9998    p->in = inSaved;
9999    p->lineno = savedLineno;
10000  }else
10001#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10002
10003#ifndef SQLITE_SHELL_WASM_MODE
10004  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10005    const char *zSrcFile;
10006    const char *zDb;
10007    sqlite3 *pSrc;
10008    sqlite3_backup *pBackup;
10009    int nTimeout = 0;
10010
10011    failIfSafeMode(p, "cannot run .restore in safe mode");
10012    if( nArg==2 ){
10013      zSrcFile = azArg[1];
10014      zDb = "main";
10015    }else if( nArg==3 ){
10016      zSrcFile = azArg[2];
10017      zDb = azArg[1];
10018    }else{
10019      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10020      rc = 1;
10021      goto meta_command_exit;
10022    }
10023    rc = sqlite3_open(zSrcFile, &pSrc);
10024    if( rc!=SQLITE_OK ){
10025      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10026      close_db(pSrc);
10027      return 1;
10028    }
10029    open_db(p, 0);
10030    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10031    if( pBackup==0 ){
10032      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10033      close_db(pSrc);
10034      return 1;
10035    }
10036    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10037          || rc==SQLITE_BUSY  ){
10038      if( rc==SQLITE_BUSY ){
10039        if( nTimeout++ >= 3 ) break;
10040        sqlite3_sleep(100);
10041      }
10042    }
10043    sqlite3_backup_finish(pBackup);
10044    if( rc==SQLITE_DONE ){
10045      rc = 0;
10046    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10047      raw_printf(stderr, "Error: source database is busy\n");
10048      rc = 1;
10049    }else{
10050      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10051      rc = 1;
10052    }
10053    close_db(pSrc);
10054  }else
10055#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10056
10057  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10058    if( nArg==2 ){
10059      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10060#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10061      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10062#endif
10063    }else{
10064      raw_printf(stderr, "Usage: .scanstats on|off\n");
10065      rc = 1;
10066    }
10067  }else
10068
10069  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10070    ShellText sSelect;
10071    ShellState data;
10072    char *zErrMsg = 0;
10073    const char *zDiv = "(";
10074    const char *zName = 0;
10075    int iSchema = 0;
10076    int bDebug = 0;
10077    int bNoSystemTabs = 0;
10078    int ii;
10079
10080    open_db(p, 0);
10081    memcpy(&data, p, sizeof(data));
10082    data.showHeader = 0;
10083    data.cMode = data.mode = MODE_Semi;
10084    initText(&sSelect);
10085    for(ii=1; ii<nArg; ii++){
10086      if( optionMatch(azArg[ii],"indent") ){
10087        data.cMode = data.mode = MODE_Pretty;
10088      }else if( optionMatch(azArg[ii],"debug") ){
10089        bDebug = 1;
10090      }else if( optionMatch(azArg[ii],"nosys") ){
10091        bNoSystemTabs = 1;
10092      }else if( azArg[ii][0]=='-' ){
10093        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10094        rc = 1;
10095        goto meta_command_exit;
10096      }else if( zName==0 ){
10097        zName = azArg[ii];
10098      }else{
10099        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10100        rc = 1;
10101        goto meta_command_exit;
10102      }
10103    }
10104    if( zName!=0 ){
10105      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10106                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10107                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10108                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10109      if( isSchema ){
10110        char *new_argv[2], *new_colv[2];
10111        new_argv[0] = sqlite3_mprintf(
10112                      "CREATE TABLE %s (\n"
10113                      "  type text,\n"
10114                      "  name text,\n"
10115                      "  tbl_name text,\n"
10116                      "  rootpage integer,\n"
10117                      "  sql text\n"
10118                      ")", zName);
10119        shell_check_oom(new_argv[0]);
10120        new_argv[1] = 0;
10121        new_colv[0] = "sql";
10122        new_colv[1] = 0;
10123        callback(&data, 1, new_argv, new_colv);
10124        sqlite3_free(new_argv[0]);
10125      }
10126    }
10127    if( zDiv ){
10128      sqlite3_stmt *pStmt = 0;
10129      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10130                              -1, &pStmt, 0);
10131      if( rc ){
10132        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10133        sqlite3_finalize(pStmt);
10134        rc = 1;
10135        goto meta_command_exit;
10136      }
10137      appendText(&sSelect, "SELECT sql FROM", 0);
10138      iSchema = 0;
10139      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10140        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10141        char zScNum[30];
10142        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10143        appendText(&sSelect, zDiv, 0);
10144        zDiv = " UNION ALL ";
10145        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10146        if( sqlite3_stricmp(zDb, "main")!=0 ){
10147          appendText(&sSelect, zDb, '\'');
10148        }else{
10149          appendText(&sSelect, "NULL", 0);
10150        }
10151        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10152        appendText(&sSelect, zScNum, 0);
10153        appendText(&sSelect, " AS snum, ", 0);
10154        appendText(&sSelect, zDb, '\'');
10155        appendText(&sSelect, " AS sname FROM ", 0);
10156        appendText(&sSelect, zDb, quoteChar(zDb));
10157        appendText(&sSelect, ".sqlite_schema", 0);
10158      }
10159      sqlite3_finalize(pStmt);
10160#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10161      if( zName ){
10162        appendText(&sSelect,
10163           " UNION ALL SELECT shell_module_schema(name),"
10164           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10165        0);
10166      }
10167#endif
10168      appendText(&sSelect, ") WHERE ", 0);
10169      if( zName ){
10170        char *zQarg = sqlite3_mprintf("%Q", zName);
10171        int bGlob;
10172        shell_check_oom(zQarg);
10173        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10174                strchr(zName, '[') != 0;
10175        if( strchr(zName, '.') ){
10176          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10177        }else{
10178          appendText(&sSelect, "lower(tbl_name)", 0);
10179        }
10180        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10181        appendText(&sSelect, zQarg, 0);
10182        if( !bGlob ){
10183          appendText(&sSelect, " ESCAPE '\\' ", 0);
10184        }
10185        appendText(&sSelect, " AND ", 0);
10186        sqlite3_free(zQarg);
10187      }
10188      if( bNoSystemTabs ){
10189        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10190      }
10191      appendText(&sSelect, "sql IS NOT NULL"
10192                           " ORDER BY snum, rowid", 0);
10193      if( bDebug ){
10194        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10195      }else{
10196        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10197      }
10198      freeText(&sSelect);
10199    }
10200    if( zErrMsg ){
10201      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10202      sqlite3_free(zErrMsg);
10203      rc = 1;
10204    }else if( rc != SQLITE_OK ){
10205      raw_printf(stderr,"Error: querying schema information\n");
10206      rc = 1;
10207    }else{
10208      rc = 0;
10209    }
10210  }else
10211
10212  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10213   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10214  ){
10215    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10216    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10217  }else
10218
10219#if defined(SQLITE_ENABLE_SESSION)
10220  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10221    struct AuxDb *pAuxDb = p->pAuxDb;
10222    OpenSession *pSession = &pAuxDb->aSession[0];
10223    char **azCmd = &azArg[1];
10224    int iSes = 0;
10225    int nCmd = nArg - 1;
10226    int i;
10227    if( nArg<=1 ) goto session_syntax_error;
10228    open_db(p, 0);
10229    if( nArg>=3 ){
10230      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10231        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10232      }
10233      if( iSes<pAuxDb->nSession ){
10234        pSession = &pAuxDb->aSession[iSes];
10235        azCmd++;
10236        nCmd--;
10237      }else{
10238        pSession = &pAuxDb->aSession[0];
10239        iSes = 0;
10240      }
10241    }
10242
10243    /* .session attach TABLE
10244    ** Invoke the sqlite3session_attach() interface to attach a particular
10245    ** table so that it is never filtered.
10246    */
10247    if( strcmp(azCmd[0],"attach")==0 ){
10248      if( nCmd!=2 ) goto session_syntax_error;
10249      if( pSession->p==0 ){
10250        session_not_open:
10251        raw_printf(stderr, "ERROR: No sessions are open\n");
10252      }else{
10253        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10254        if( rc ){
10255          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10256          rc = 0;
10257        }
10258      }
10259    }else
10260
10261    /* .session changeset FILE
10262    ** .session patchset FILE
10263    ** Write a changeset or patchset into a file.  The file is overwritten.
10264    */
10265    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10266      FILE *out = 0;
10267      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10268      if( nCmd!=2 ) goto session_syntax_error;
10269      if( pSession->p==0 ) goto session_not_open;
10270      out = fopen(azCmd[1], "wb");
10271      if( out==0 ){
10272        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10273                    azCmd[1]);
10274      }else{
10275        int szChng;
10276        void *pChng;
10277        if( azCmd[0][0]=='c' ){
10278          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10279        }else{
10280          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10281        }
10282        if( rc ){
10283          printf("Error: error code %d\n", rc);
10284          rc = 0;
10285        }
10286        if( pChng
10287          && fwrite(pChng, szChng, 1, out)!=1 ){
10288          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10289                  szChng);
10290        }
10291        sqlite3_free(pChng);
10292        fclose(out);
10293      }
10294    }else
10295
10296    /* .session close
10297    ** Close the identified session
10298    */
10299    if( strcmp(azCmd[0], "close")==0 ){
10300      if( nCmd!=1 ) goto session_syntax_error;
10301      if( pAuxDb->nSession ){
10302        session_close(pSession);
10303        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10304      }
10305    }else
10306
10307    /* .session enable ?BOOLEAN?
10308    ** Query or set the enable flag
10309    */
10310    if( strcmp(azCmd[0], "enable")==0 ){
10311      int ii;
10312      if( nCmd>2 ) goto session_syntax_error;
10313      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10314      if( pAuxDb->nSession ){
10315        ii = sqlite3session_enable(pSession->p, ii);
10316        utf8_printf(p->out, "session %s enable flag = %d\n",
10317                    pSession->zName, ii);
10318      }
10319    }else
10320
10321    /* .session filter GLOB ....
10322    ** Set a list of GLOB patterns of table names to be excluded.
10323    */
10324    if( strcmp(azCmd[0], "filter")==0 ){
10325      int ii, nByte;
10326      if( nCmd<2 ) goto session_syntax_error;
10327      if( pAuxDb->nSession ){
10328        for(ii=0; ii<pSession->nFilter; ii++){
10329          sqlite3_free(pSession->azFilter[ii]);
10330        }
10331        sqlite3_free(pSession->azFilter);
10332        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10333        pSession->azFilter = sqlite3_malloc( nByte );
10334        if( pSession->azFilter==0 ){
10335          raw_printf(stderr, "Error: out or memory\n");
10336          exit(1);
10337        }
10338        for(ii=1; ii<nCmd; ii++){
10339          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10340          shell_check_oom(x);
10341        }
10342        pSession->nFilter = ii-1;
10343      }
10344    }else
10345
10346    /* .session indirect ?BOOLEAN?
10347    ** Query or set the indirect flag
10348    */
10349    if( strcmp(azCmd[0], "indirect")==0 ){
10350      int ii;
10351      if( nCmd>2 ) goto session_syntax_error;
10352      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10353      if( pAuxDb->nSession ){
10354        ii = sqlite3session_indirect(pSession->p, ii);
10355        utf8_printf(p->out, "session %s indirect flag = %d\n",
10356                    pSession->zName, ii);
10357      }
10358    }else
10359
10360    /* .session isempty
10361    ** Determine if the session is empty
10362    */
10363    if( strcmp(azCmd[0], "isempty")==0 ){
10364      int ii;
10365      if( nCmd!=1 ) goto session_syntax_error;
10366      if( pAuxDb->nSession ){
10367        ii = sqlite3session_isempty(pSession->p);
10368        utf8_printf(p->out, "session %s isempty flag = %d\n",
10369                    pSession->zName, ii);
10370      }
10371    }else
10372
10373    /* .session list
10374    ** List all currently open sessions
10375    */
10376    if( strcmp(azCmd[0],"list")==0 ){
10377      for(i=0; i<pAuxDb->nSession; i++){
10378        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10379      }
10380    }else
10381
10382    /* .session open DB NAME
10383    ** Open a new session called NAME on the attached database DB.
10384    ** DB is normally "main".
10385    */
10386    if( strcmp(azCmd[0],"open")==0 ){
10387      char *zName;
10388      if( nCmd!=3 ) goto session_syntax_error;
10389      zName = azCmd[2];
10390      if( zName[0]==0 ) goto session_syntax_error;
10391      for(i=0; i<pAuxDb->nSession; i++){
10392        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10393          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10394          goto meta_command_exit;
10395        }
10396      }
10397      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10398        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10399        goto meta_command_exit;
10400      }
10401      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10402      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10403      if( rc ){
10404        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10405        rc = 0;
10406        goto meta_command_exit;
10407      }
10408      pSession->nFilter = 0;
10409      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10410      pAuxDb->nSession++;
10411      pSession->zName = sqlite3_mprintf("%s", zName);
10412      shell_check_oom(pSession->zName);
10413    }else
10414    /* If no command name matches, show a syntax error */
10415    session_syntax_error:
10416    showHelp(p->out, "session");
10417  }else
10418#endif
10419
10420#ifdef SQLITE_DEBUG
10421  /* Undocumented commands for internal testing.  Subject to change
10422  ** without notice. */
10423  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10424    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10425      int i, v;
10426      for(i=1; i<nArg; i++){
10427        v = booleanValue(azArg[i]);
10428        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10429      }
10430    }
10431    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10432      int i; sqlite3_int64 v;
10433      for(i=1; i<nArg; i++){
10434        char zBuf[200];
10435        v = integerValue(azArg[i]);
10436        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10437        utf8_printf(p->out, "%s", zBuf);
10438      }
10439    }
10440  }else
10441#endif
10442
10443  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10444    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10445    int bVerbose = 0;        /* Verbose output */
10446    int bSelftestExists;     /* True if SELFTEST already exists */
10447    int i, k;                /* Loop counters */
10448    int nTest = 0;           /* Number of tests runs */
10449    int nErr = 0;            /* Number of errors seen */
10450    ShellText str;           /* Answer for a query */
10451    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10452
10453    open_db(p,0);
10454    for(i=1; i<nArg; i++){
10455      const char *z = azArg[i];
10456      if( z[0]=='-' && z[1]=='-' ) z++;
10457      if( strcmp(z,"-init")==0 ){
10458        bIsInit = 1;
10459      }else
10460      if( strcmp(z,"-v")==0 ){
10461        bVerbose++;
10462      }else
10463      {
10464        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10465                    azArg[i], azArg[0]);
10466        raw_printf(stderr, "Should be one of: --init -v\n");
10467        rc = 1;
10468        goto meta_command_exit;
10469      }
10470    }
10471    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10472           != SQLITE_OK ){
10473      bSelftestExists = 0;
10474    }else{
10475      bSelftestExists = 1;
10476    }
10477    if( bIsInit ){
10478      createSelftestTable(p);
10479      bSelftestExists = 1;
10480    }
10481    initText(&str);
10482    appendText(&str, "x", 0);
10483    for(k=bSelftestExists; k>=0; k--){
10484      if( k==1 ){
10485        rc = sqlite3_prepare_v2(p->db,
10486            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10487            -1, &pStmt, 0);
10488      }else{
10489        rc = sqlite3_prepare_v2(p->db,
10490          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10491          "      (1,'run','PRAGMA integrity_check','ok')",
10492          -1, &pStmt, 0);
10493      }
10494      if( rc ){
10495        raw_printf(stderr, "Error querying the selftest table\n");
10496        rc = 1;
10497        sqlite3_finalize(pStmt);
10498        goto meta_command_exit;
10499      }
10500      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10501        int tno = sqlite3_column_int(pStmt, 0);
10502        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10503        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10504        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10505
10506        if( zOp==0 ) continue;
10507        if( zSql==0 ) continue;
10508        if( zAns==0 ) continue;
10509        k = 0;
10510        if( bVerbose>0 ){
10511          printf("%d: %s %s\n", tno, zOp, zSql);
10512        }
10513        if( strcmp(zOp,"memo")==0 ){
10514          utf8_printf(p->out, "%s\n", zSql);
10515        }else
10516        if( strcmp(zOp,"run")==0 ){
10517          char *zErrMsg = 0;
10518          str.n = 0;
10519          str.z[0] = 0;
10520          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10521          nTest++;
10522          if( bVerbose ){
10523            utf8_printf(p->out, "Result: %s\n", str.z);
10524          }
10525          if( rc || zErrMsg ){
10526            nErr++;
10527            rc = 1;
10528            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10529            sqlite3_free(zErrMsg);
10530          }else if( strcmp(zAns,str.z)!=0 ){
10531            nErr++;
10532            rc = 1;
10533            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10534            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10535          }
10536        }else
10537        {
10538          utf8_printf(stderr,
10539            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10540          rc = 1;
10541          break;
10542        }
10543      } /* End loop over rows of content from SELFTEST */
10544      sqlite3_finalize(pStmt);
10545    } /* End loop over k */
10546    freeText(&str);
10547    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10548  }else
10549
10550  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10551    if( nArg<2 || nArg>3 ){
10552      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10553      rc = 1;
10554    }
10555    if( nArg>=2 ){
10556      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10557                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10558    }
10559    if( nArg>=3 ){
10560      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10561                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10562    }
10563  }else
10564
10565  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10566    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10567    int i;                   /* Loop counter */
10568    int bSchema = 0;         /* Also hash the schema */
10569    int bSeparate = 0;       /* Hash each table separately */
10570    int iSize = 224;         /* Hash algorithm to use */
10571    int bDebug = 0;          /* Only show the query that would have run */
10572    sqlite3_stmt *pStmt;     /* For querying tables names */
10573    char *zSql;              /* SQL to be run */
10574    char *zSep;              /* Separator */
10575    ShellText sSql;          /* Complete SQL for the query to run the hash */
10576    ShellText sQuery;        /* Set of queries used to read all content */
10577    open_db(p, 0);
10578    for(i=1; i<nArg; i++){
10579      const char *z = azArg[i];
10580      if( z[0]=='-' ){
10581        z++;
10582        if( z[0]=='-' ) z++;
10583        if( strcmp(z,"schema")==0 ){
10584          bSchema = 1;
10585        }else
10586        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10587         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10588        ){
10589          iSize = atoi(&z[5]);
10590        }else
10591        if( strcmp(z,"debug")==0 ){
10592          bDebug = 1;
10593        }else
10594        {
10595          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10596                      azArg[i], azArg[0]);
10597          showHelp(p->out, azArg[0]);
10598          rc = 1;
10599          goto meta_command_exit;
10600        }
10601      }else if( zLike ){
10602        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10603        rc = 1;
10604        goto meta_command_exit;
10605      }else{
10606        zLike = z;
10607        bSeparate = 1;
10608        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10609      }
10610    }
10611    if( bSchema ){
10612      zSql = "SELECT lower(name) FROM sqlite_schema"
10613             " WHERE type='table' AND coalesce(rootpage,0)>1"
10614             " UNION ALL SELECT 'sqlite_schema'"
10615             " ORDER BY 1 collate nocase";
10616    }else{
10617      zSql = "SELECT lower(name) FROM sqlite_schema"
10618             " WHERE type='table' AND coalesce(rootpage,0)>1"
10619             " AND name NOT LIKE 'sqlite_%'"
10620             " ORDER BY 1 collate nocase";
10621    }
10622    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10623    initText(&sQuery);
10624    initText(&sSql);
10625    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10626    zSep = "VALUES(";
10627    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10628      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10629      if( zTab==0 ) continue;
10630      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10631      if( strncmp(zTab, "sqlite_",7)!=0 ){
10632        appendText(&sQuery,"SELECT * FROM ", 0);
10633        appendText(&sQuery,zTab,'"');
10634        appendText(&sQuery," NOT INDEXED;", 0);
10635      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10636        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10637                           " ORDER BY name;", 0);
10638      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10639        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10640                           " ORDER BY name;", 0);
10641      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10642        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10643                           " ORDER BY tbl,idx;", 0);
10644      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10645        appendText(&sQuery, "SELECT * FROM ", 0);
10646        appendText(&sQuery, zTab, 0);
10647        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10648      }
10649      appendText(&sSql, zSep, 0);
10650      appendText(&sSql, sQuery.z, '\'');
10651      sQuery.n = 0;
10652      appendText(&sSql, ",", 0);
10653      appendText(&sSql, zTab, '\'');
10654      zSep = "),(";
10655    }
10656    sqlite3_finalize(pStmt);
10657    if( bSeparate ){
10658      zSql = sqlite3_mprintf(
10659          "%s))"
10660          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10661          "   FROM [sha3sum$query]",
10662          sSql.z, iSize);
10663    }else{
10664      zSql = sqlite3_mprintf(
10665          "%s))"
10666          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10667          "   FROM [sha3sum$query]",
10668          sSql.z, iSize);
10669    }
10670    shell_check_oom(zSql);
10671    freeText(&sQuery);
10672    freeText(&sSql);
10673    if( bDebug ){
10674      utf8_printf(p->out, "%s\n", zSql);
10675    }else{
10676      shell_exec(p, zSql, 0);
10677    }
10678    sqlite3_free(zSql);
10679  }else
10680
10681#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE)
10682  if( c=='s'
10683   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10684  ){
10685    char *zCmd;
10686    int i, x;
10687    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10688    if( nArg<2 ){
10689      raw_printf(stderr, "Usage: .system COMMAND\n");
10690      rc = 1;
10691      goto meta_command_exit;
10692    }
10693    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10694    for(i=2; i<nArg && zCmd!=0; i++){
10695      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10696                             zCmd, azArg[i]);
10697    }
10698    x = zCmd!=0 ? system(zCmd) : 1;
10699    sqlite3_free(zCmd);
10700    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10701  }else
10702#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_WASM_MODE) */
10703
10704  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10705    static const char *azBool[] = { "off", "on", "trigger", "full"};
10706    const char *zOut;
10707    int i;
10708    if( nArg!=1 ){
10709      raw_printf(stderr, "Usage: .show\n");
10710      rc = 1;
10711      goto meta_command_exit;
10712    }
10713    utf8_printf(p->out, "%12.12s: %s\n","echo",
10714                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10715    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10716    utf8_printf(p->out, "%12.12s: %s\n","explain",
10717         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10718    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10719    if( p->mode==MODE_Column
10720     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10721    ){
10722      utf8_printf
10723        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10724         modeDescr[p->mode], p->cmOpts.iWrap,
10725         p->cmOpts.bWordWrap ? "on" : "off",
10726         p->cmOpts.bQuote ? "" : "no");
10727    }else{
10728      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10729    }
10730    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10731      output_c_string(p->out, p->nullValue);
10732      raw_printf(p->out, "\n");
10733    utf8_printf(p->out,"%12.12s: %s\n","output",
10734            strlen30(p->outfile) ? p->outfile : "stdout");
10735    utf8_printf(p->out,"%12.12s: ", "colseparator");
10736      output_c_string(p->out, p->colSeparator);
10737      raw_printf(p->out, "\n");
10738    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10739      output_c_string(p->out, p->rowSeparator);
10740      raw_printf(p->out, "\n");
10741    switch( p->statsOn ){
10742      case 0:  zOut = "off";     break;
10743      default: zOut = "on";      break;
10744      case 2:  zOut = "stmt";    break;
10745      case 3:  zOut = "vmstep";  break;
10746    }
10747    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10748    utf8_printf(p->out, "%12.12s: ", "width");
10749    for (i=0;i<p->nWidth;i++) {
10750      raw_printf(p->out, "%d ", p->colWidth[i]);
10751    }
10752    raw_printf(p->out, "\n");
10753    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10754                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10755  }else
10756
10757  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10758    if( nArg==2 ){
10759      if( strcmp(azArg[1],"stmt")==0 ){
10760        p->statsOn = 2;
10761      }else if( strcmp(azArg[1],"vmstep")==0 ){
10762        p->statsOn = 3;
10763      }else{
10764        p->statsOn = (u8)booleanValue(azArg[1]);
10765      }
10766    }else if( nArg==1 ){
10767      display_stats(p->db, p, 0);
10768    }else{
10769      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10770      rc = 1;
10771    }
10772  }else
10773
10774  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10775   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10776                 || strncmp(azArg[0], "indexes", n)==0) )
10777  ){
10778    sqlite3_stmt *pStmt;
10779    char **azResult;
10780    int nRow, nAlloc;
10781    int ii;
10782    ShellText s;
10783    initText(&s);
10784    open_db(p, 0);
10785    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10786    if( rc ){
10787      sqlite3_finalize(pStmt);
10788      return shellDatabaseError(p->db);
10789    }
10790
10791    if( nArg>2 && c=='i' ){
10792      /* It is an historical accident that the .indexes command shows an error
10793      ** when called with the wrong number of arguments whereas the .tables
10794      ** command does not. */
10795      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10796      rc = 1;
10797      sqlite3_finalize(pStmt);
10798      goto meta_command_exit;
10799    }
10800    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10801      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10802      if( zDbName==0 ) continue;
10803      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10804      if( sqlite3_stricmp(zDbName, "main")==0 ){
10805        appendText(&s, "SELECT name FROM ", 0);
10806      }else{
10807        appendText(&s, "SELECT ", 0);
10808        appendText(&s, zDbName, '\'');
10809        appendText(&s, "||'.'||name FROM ", 0);
10810      }
10811      appendText(&s, zDbName, '"');
10812      appendText(&s, ".sqlite_schema ", 0);
10813      if( c=='t' ){
10814        appendText(&s," WHERE type IN ('table','view')"
10815                      "   AND name NOT LIKE 'sqlite_%'"
10816                      "   AND name LIKE ?1", 0);
10817      }else{
10818        appendText(&s," WHERE type='index'"
10819                      "   AND tbl_name LIKE ?1", 0);
10820      }
10821    }
10822    rc = sqlite3_finalize(pStmt);
10823    if( rc==SQLITE_OK ){
10824      appendText(&s, " ORDER BY 1", 0);
10825      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10826    }
10827    freeText(&s);
10828    if( rc ) return shellDatabaseError(p->db);
10829
10830    /* Run the SQL statement prepared by the above block. Store the results
10831    ** as an array of nul-terminated strings in azResult[].  */
10832    nRow = nAlloc = 0;
10833    azResult = 0;
10834    if( nArg>1 ){
10835      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10836    }else{
10837      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10838    }
10839    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10840      if( nRow>=nAlloc ){
10841        char **azNew;
10842        int n2 = nAlloc*2 + 10;
10843        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10844        shell_check_oom(azNew);
10845        nAlloc = n2;
10846        azResult = azNew;
10847      }
10848      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10849      shell_check_oom(azResult[nRow]);
10850      nRow++;
10851    }
10852    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10853      rc = shellDatabaseError(p->db);
10854    }
10855
10856    /* Pretty-print the contents of array azResult[] to the output */
10857    if( rc==0 && nRow>0 ){
10858      int len, maxlen = 0;
10859      int i, j;
10860      int nPrintCol, nPrintRow;
10861      for(i=0; i<nRow; i++){
10862        len = strlen30(azResult[i]);
10863        if( len>maxlen ) maxlen = len;
10864      }
10865      nPrintCol = 80/(maxlen+2);
10866      if( nPrintCol<1 ) nPrintCol = 1;
10867      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10868      for(i=0; i<nPrintRow; i++){
10869        for(j=i; j<nRow; j+=nPrintRow){
10870          char *zSp = j<nPrintRow ? "" : "  ";
10871          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10872                      azResult[j] ? azResult[j]:"");
10873        }
10874        raw_printf(p->out, "\n");
10875      }
10876    }
10877
10878    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10879    sqlite3_free(azResult);
10880  }else
10881
10882#ifndef SQLITE_SHELL_WASM_MODE
10883  /* Begin redirecting output to the file "testcase-out.txt" */
10884  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10885    output_reset(p);
10886    p->out = output_file_open("testcase-out.txt", 0);
10887    if( p->out==0 ){
10888      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10889    }
10890    if( nArg>=2 ){
10891      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10892    }else{
10893      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10894    }
10895  }else
10896#endif /* !defined(SQLITE_SHELL_WASM_MODE) */
10897
10898#ifndef SQLITE_UNTESTABLE
10899  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10900    static const struct {
10901       const char *zCtrlName;   /* Name of a test-control option */
10902       int ctrlCode;            /* Integer code for that option */
10903       int unSafe;              /* Not valid for --safe mode */
10904       const char *zUsage;      /* Usage notes */
10905    } aCtrl[] = {
10906      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10907      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10908    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10909    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10910      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10911      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10912    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10913      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10914      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10915      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10916      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10917      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10918#ifdef YYCOVERAGE
10919      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10920#endif
10921      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10922      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10923      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10924      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10925      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10926      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10927      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10928    };
10929    int testctrl = -1;
10930    int iCtrl = -1;
10931    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10932    int isOk = 0;
10933    int i, n2;
10934    const char *zCmd = 0;
10935
10936    open_db(p, 0);
10937    zCmd = nArg>=2 ? azArg[1] : "help";
10938
10939    /* The argument can optionally begin with "-" or "--" */
10940    if( zCmd[0]=='-' && zCmd[1] ){
10941      zCmd++;
10942      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10943    }
10944
10945    /* --help lists all test-controls */
10946    if( strcmp(zCmd,"help")==0 ){
10947      utf8_printf(p->out, "Available test-controls:\n");
10948      for(i=0; i<ArraySize(aCtrl); i++){
10949        utf8_printf(p->out, "  .testctrl %s %s\n",
10950                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10951      }
10952      rc = 1;
10953      goto meta_command_exit;
10954    }
10955
10956    /* convert testctrl text option to value. allow any unique prefix
10957    ** of the option name, or a numerical value. */
10958    n2 = strlen30(zCmd);
10959    for(i=0; i<ArraySize(aCtrl); i++){
10960      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10961        if( testctrl<0 ){
10962          testctrl = aCtrl[i].ctrlCode;
10963          iCtrl = i;
10964        }else{
10965          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10966                              "Use \".testctrl --help\" for help\n", zCmd);
10967          rc = 1;
10968          goto meta_command_exit;
10969        }
10970      }
10971    }
10972    if( testctrl<0 ){
10973      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10974                         "Use \".testctrl --help\" for help\n", zCmd);
10975    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10976      utf8_printf(stderr,
10977         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10978         p->lineno, aCtrl[iCtrl].zCtrlName);
10979      exit(1);
10980    }else{
10981      switch(testctrl){
10982
10983        /* sqlite3_test_control(int, db, int) */
10984        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10985          if( nArg==3 ){
10986            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10987            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10988            isOk = 3;
10989          }
10990          break;
10991
10992        /* sqlite3_test_control(int) */
10993        case SQLITE_TESTCTRL_PRNG_SAVE:
10994        case SQLITE_TESTCTRL_PRNG_RESTORE:
10995        case SQLITE_TESTCTRL_BYTEORDER:
10996          if( nArg==2 ){
10997            rc2 = sqlite3_test_control(testctrl);
10998            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10999          }
11000          break;
11001
11002        /* sqlite3_test_control(int, uint) */
11003        case SQLITE_TESTCTRL_PENDING_BYTE:
11004          if( nArg==3 ){
11005            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11006            rc2 = sqlite3_test_control(testctrl, opt);
11007            isOk = 3;
11008          }
11009          break;
11010
11011        /* sqlite3_test_control(int, int, sqlite3*) */
11012        case SQLITE_TESTCTRL_PRNG_SEED:
11013          if( nArg==3 || nArg==4 ){
11014            int ii = (int)integerValue(azArg[2]);
11015            sqlite3 *db;
11016            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11017              sqlite3_randomness(sizeof(ii),&ii);
11018              printf("-- random seed: %d\n", ii);
11019            }
11020            if( nArg==3 ){
11021              db = 0;
11022            }else{
11023              db = p->db;
11024              /* Make sure the schema has been loaded */
11025              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11026            }
11027            rc2 = sqlite3_test_control(testctrl, ii, db);
11028            isOk = 3;
11029          }
11030          break;
11031
11032        /* sqlite3_test_control(int, int) */
11033        case SQLITE_TESTCTRL_ASSERT:
11034        case SQLITE_TESTCTRL_ALWAYS:
11035          if( nArg==3 ){
11036            int opt = booleanValue(azArg[2]);
11037            rc2 = sqlite3_test_control(testctrl, opt);
11038            isOk = 1;
11039          }
11040          break;
11041
11042        /* sqlite3_test_control(int, int) */
11043        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11044        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11045          if( nArg==3 ){
11046            int opt = booleanValue(azArg[2]);
11047            rc2 = sqlite3_test_control(testctrl, opt);
11048            isOk = 3;
11049          }
11050          break;
11051
11052        /* sqlite3_test_control(sqlite3*) */
11053        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11054          rc2 = sqlite3_test_control(testctrl, p->db);
11055          isOk = 3;
11056          break;
11057
11058        case SQLITE_TESTCTRL_IMPOSTER:
11059          if( nArg==5 ){
11060            rc2 = sqlite3_test_control(testctrl, p->db,
11061                          azArg[2],
11062                          integerValue(azArg[3]),
11063                          integerValue(azArg[4]));
11064            isOk = 3;
11065          }
11066          break;
11067
11068        case SQLITE_TESTCTRL_SEEK_COUNT: {
11069          u64 x = 0;
11070          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11071          utf8_printf(p->out, "%llu\n", x);
11072          isOk = 3;
11073          break;
11074        }
11075
11076#ifdef YYCOVERAGE
11077        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11078          if( nArg==2 ){
11079            sqlite3_test_control(testctrl, p->out);
11080            isOk = 3;
11081          }
11082          break;
11083        }
11084#endif
11085#ifdef SQLITE_DEBUG
11086        case SQLITE_TESTCTRL_TUNE: {
11087          if( nArg==4 ){
11088            int id = (int)integerValue(azArg[2]);
11089            int val = (int)integerValue(azArg[3]);
11090            sqlite3_test_control(testctrl, id, &val);
11091            isOk = 3;
11092          }else if( nArg==3 ){
11093            int id = (int)integerValue(azArg[2]);
11094            sqlite3_test_control(testctrl, -id, &rc2);
11095            isOk = 1;
11096          }else if( nArg==2 ){
11097            int id = 1;
11098            while(1){
11099              int val = 0;
11100              rc2 = sqlite3_test_control(testctrl, -id, &val);
11101              if( rc2!=SQLITE_OK ) break;
11102              if( id>1 ) utf8_printf(p->out, "  ");
11103              utf8_printf(p->out, "%d: %d", id, val);
11104              id++;
11105            }
11106            if( id>1 ) utf8_printf(p->out, "\n");
11107            isOk = 3;
11108          }
11109          break;
11110        }
11111#endif
11112        case SQLITE_TESTCTRL_SORTER_MMAP:
11113          if( nArg==3 ){
11114            int opt = (unsigned int)integerValue(azArg[2]);
11115            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11116            isOk = 3;
11117          }
11118          break;
11119      }
11120    }
11121    if( isOk==0 && iCtrl>=0 ){
11122      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11123      rc = 1;
11124    }else if( isOk==1 ){
11125      raw_printf(p->out, "%d\n", rc2);
11126    }else if( isOk==2 ){
11127      raw_printf(p->out, "0x%08x\n", rc2);
11128    }
11129  }else
11130#endif /* !defined(SQLITE_UNTESTABLE) */
11131
11132  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11133    open_db(p, 0);
11134    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11135  }else
11136
11137  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11138    if( nArg==2 ){
11139      enableTimer = booleanValue(azArg[1]);
11140      if( enableTimer && !HAS_TIMER ){
11141        raw_printf(stderr, "Error: timer not available on this system.\n");
11142        enableTimer = 0;
11143      }
11144    }else{
11145      raw_printf(stderr, "Usage: .timer on|off\n");
11146      rc = 1;
11147    }
11148  }else
11149
11150#ifndef SQLITE_OMIT_TRACE
11151  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11152    int mType = 0;
11153    int jj;
11154    open_db(p, 0);
11155    for(jj=1; jj<nArg; jj++){
11156      const char *z = azArg[jj];
11157      if( z[0]=='-' ){
11158        if( optionMatch(z, "expanded") ){
11159          p->eTraceType = SHELL_TRACE_EXPANDED;
11160        }
11161#ifdef SQLITE_ENABLE_NORMALIZE
11162        else if( optionMatch(z, "normalized") ){
11163          p->eTraceType = SHELL_TRACE_NORMALIZED;
11164        }
11165#endif
11166        else if( optionMatch(z, "plain") ){
11167          p->eTraceType = SHELL_TRACE_PLAIN;
11168        }
11169        else if( optionMatch(z, "profile") ){
11170          mType |= SQLITE_TRACE_PROFILE;
11171        }
11172        else if( optionMatch(z, "row") ){
11173          mType |= SQLITE_TRACE_ROW;
11174        }
11175        else if( optionMatch(z, "stmt") ){
11176          mType |= SQLITE_TRACE_STMT;
11177        }
11178        else if( optionMatch(z, "close") ){
11179          mType |= SQLITE_TRACE_CLOSE;
11180        }
11181        else {
11182          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11183          rc = 1;
11184          goto meta_command_exit;
11185        }
11186      }else{
11187        output_file_close(p->traceOut);
11188        p->traceOut = output_file_open(azArg[1], 0);
11189      }
11190    }
11191    if( p->traceOut==0 ){
11192      sqlite3_trace_v2(p->db, 0, 0, 0);
11193    }else{
11194      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11195      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11196    }
11197  }else
11198#endif /* !defined(SQLITE_OMIT_TRACE) */
11199
11200#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11201  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11202    int ii;
11203    int lenOpt;
11204    char *zOpt;
11205    if( nArg<2 ){
11206      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11207      rc = 1;
11208      goto meta_command_exit;
11209    }
11210    open_db(p, 0);
11211    zOpt = azArg[1];
11212    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11213    lenOpt = (int)strlen(zOpt);
11214    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11215      assert( azArg[nArg]==0 );
11216      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11217    }else{
11218      for(ii=1; ii<nArg; ii++){
11219        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11220      }
11221    }
11222  }else
11223#endif
11224
11225#if SQLITE_USER_AUTHENTICATION
11226  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11227    if( nArg<2 ){
11228      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11229      rc = 1;
11230      goto meta_command_exit;
11231    }
11232    open_db(p, 0);
11233    if( strcmp(azArg[1],"login")==0 ){
11234      if( nArg!=4 ){
11235        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11236        rc = 1;
11237        goto meta_command_exit;
11238      }
11239      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11240                                     strlen30(azArg[3]));
11241      if( rc ){
11242        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11243        rc = 1;
11244      }
11245    }else if( strcmp(azArg[1],"add")==0 ){
11246      if( nArg!=5 ){
11247        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11248        rc = 1;
11249        goto meta_command_exit;
11250      }
11251      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11252                            booleanValue(azArg[4]));
11253      if( rc ){
11254        raw_printf(stderr, "User-Add failed: %d\n", rc);
11255        rc = 1;
11256      }
11257    }else if( strcmp(azArg[1],"edit")==0 ){
11258      if( nArg!=5 ){
11259        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11260        rc = 1;
11261        goto meta_command_exit;
11262      }
11263      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11264                              booleanValue(azArg[4]));
11265      if( rc ){
11266        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11267        rc = 1;
11268      }
11269    }else if( strcmp(azArg[1],"delete")==0 ){
11270      if( nArg!=3 ){
11271        raw_printf(stderr, "Usage: .user delete USER\n");
11272        rc = 1;
11273        goto meta_command_exit;
11274      }
11275      rc = sqlite3_user_delete(p->db, azArg[2]);
11276      if( rc ){
11277        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11278        rc = 1;
11279      }
11280    }else{
11281      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11282      rc = 1;
11283      goto meta_command_exit;
11284    }
11285  }else
11286#endif /* SQLITE_USER_AUTHENTICATION */
11287
11288  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11289    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11290        sqlite3_libversion(), sqlite3_sourceid());
11291#if SQLITE_HAVE_ZLIB
11292    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11293#endif
11294#define CTIMEOPT_VAL_(opt) #opt
11295#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11296#if defined(__clang__) && defined(__clang_major__)
11297    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11298                    CTIMEOPT_VAL(__clang_minor__) "."
11299                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11300#elif defined(_MSC_VER)
11301    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11302#elif defined(__GNUC__) && defined(__VERSION__)
11303    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11304#endif
11305  }else
11306
11307  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11308    const char *zDbName = nArg==2 ? azArg[1] : "main";
11309    sqlite3_vfs *pVfs = 0;
11310    if( p->db ){
11311      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11312      if( pVfs ){
11313        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11314        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11315        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11316        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11317      }
11318    }
11319  }else
11320
11321  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11322    sqlite3_vfs *pVfs;
11323    sqlite3_vfs *pCurrent = 0;
11324    if( p->db ){
11325      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11326    }
11327    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11328      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11329           pVfs==pCurrent ? "  <--- CURRENT" : "");
11330      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11331      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11332      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11333      if( pVfs->pNext ){
11334        raw_printf(p->out, "-----------------------------------\n");
11335      }
11336    }
11337  }else
11338
11339  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11340    const char *zDbName = nArg==2 ? azArg[1] : "main";
11341    char *zVfsName = 0;
11342    if( p->db ){
11343      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11344      if( zVfsName ){
11345        utf8_printf(p->out, "%s\n", zVfsName);
11346        sqlite3_free(zVfsName);
11347      }
11348    }
11349  }else
11350
11351  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11352    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11353    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11354  }else
11355
11356  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11357    int j;
11358    assert( nArg<=ArraySize(azArg) );
11359    p->nWidth = nArg-1;
11360    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11361    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11362    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11363    for(j=1; j<nArg; j++){
11364      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11365    }
11366  }else
11367
11368  {
11369    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11370      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11371    rc = 1;
11372  }
11373
11374meta_command_exit:
11375  if( p->outCount ){
11376    p->outCount--;
11377    if( p->outCount==0 ) output_reset(p);
11378  }
11379  p->bSafeMode = p->bSafeModePersist;
11380  return rc;
11381}
11382
11383/* Line scan result and intermediate states (supporting scan resumption)
11384*/
11385#ifndef CHAR_BIT
11386# define CHAR_BIT 8
11387#endif
11388typedef enum {
11389  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11390  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11391  QSS_Start = 0
11392} QuickScanState;
11393#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11394#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11395#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11396#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11397#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11398
11399/*
11400** Scan line for classification to guide shell's handling.
11401** The scan is resumable for subsequent lines when prior
11402** return values are passed as the 2nd argument.
11403*/
11404static QuickScanState quickscan(char *zLine, QuickScanState qss){
11405  char cin;
11406  char cWait = (char)qss; /* intentional narrowing loss */
11407  if( cWait==0 ){
11408  PlainScan:
11409    assert( cWait==0 );
11410    while( (cin = *zLine++)!=0 ){
11411      if( IsSpace(cin) )
11412        continue;
11413      switch (cin){
11414      case '-':
11415        if( *zLine!='-' )
11416          break;
11417        while((cin = *++zLine)!=0 )
11418          if( cin=='\n')
11419            goto PlainScan;
11420        return qss;
11421      case ';':
11422        qss |= QSS_EndingSemi;
11423        continue;
11424      case '/':
11425        if( *zLine=='*' ){
11426          ++zLine;
11427          cWait = '*';
11428          qss = QSS_SETV(qss, cWait);
11429          goto TermScan;
11430        }
11431        break;
11432      case '[':
11433        cin = ']';
11434        /* fall thru */
11435      case '`': case '\'': case '"':
11436        cWait = cin;
11437        qss = QSS_HasDark | cWait;
11438        goto TermScan;
11439      default:
11440        break;
11441      }
11442      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11443    }
11444  }else{
11445  TermScan:
11446    while( (cin = *zLine++)!=0 ){
11447      if( cin==cWait ){
11448        switch( cWait ){
11449        case '*':
11450          if( *zLine != '/' )
11451            continue;
11452          ++zLine;
11453          cWait = 0;
11454          qss = QSS_SETV(qss, 0);
11455          goto PlainScan;
11456        case '`': case '\'': case '"':
11457          if(*zLine==cWait){
11458            ++zLine;
11459            continue;
11460          }
11461          /* fall thru */
11462        case ']':
11463          cWait = 0;
11464          qss = QSS_SETV(qss, 0);
11465          goto PlainScan;
11466        default: assert(0);
11467        }
11468      }
11469    }
11470  }
11471  return qss;
11472}
11473
11474/*
11475** Return TRUE if the line typed in is an SQL command terminator other
11476** than a semi-colon.  The SQL Server style "go" command is understood
11477** as is the Oracle "/".
11478*/
11479static int line_is_command_terminator(char *zLine){
11480  while( IsSpace(zLine[0]) ){ zLine++; };
11481  if( zLine[0]=='/' )
11482    zLine += 1; /* Oracle */
11483  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11484    zLine += 2; /* SQL Server */
11485  else
11486    return 0;
11487  return quickscan(zLine, QSS_Start)==QSS_Start;
11488}
11489
11490/*
11491** We need a default sqlite3_complete() implementation to use in case
11492** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11493** any arbitrary text is a complete SQL statement.  This is not very
11494** user-friendly, but it does seem to work.
11495*/
11496#ifdef SQLITE_OMIT_COMPLETE
11497#define sqlite3_complete(x) 1
11498#endif
11499
11500/*
11501** Return true if zSql is a complete SQL statement.  Return false if it
11502** ends in the middle of a string literal or C-style comment.
11503*/
11504static int line_is_complete(char *zSql, int nSql){
11505  int rc;
11506  if( zSql==0 ) return 1;
11507  zSql[nSql] = ';';
11508  zSql[nSql+1] = 0;
11509  rc = sqlite3_complete(zSql);
11510  zSql[nSql] = 0;
11511  return rc;
11512}
11513
11514/*
11515** Run a single line of SQL.  Return the number of errors.
11516*/
11517static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11518  int rc;
11519  char *zErrMsg = 0;
11520
11521  open_db(p, 0);
11522  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11523  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11524  BEGIN_TIMER;
11525  rc = shell_exec(p, zSql, &zErrMsg);
11526  END_TIMER;
11527  if( rc || zErrMsg ){
11528    char zPrefix[100];
11529    const char *zErrorTail;
11530    const char *zErrorType;
11531    if( zErrMsg==0 ){
11532      zErrorType = "Error";
11533      zErrorTail = sqlite3_errmsg(p->db);
11534    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11535      zErrorType = "Parse error";
11536      zErrorTail = &zErrMsg[12];
11537    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11538      zErrorType = "Runtime error";
11539      zErrorTail = &zErrMsg[10];
11540    }else{
11541      zErrorType = "Error";
11542      zErrorTail = zErrMsg;
11543    }
11544    if( in!=0 || !stdin_is_interactive ){
11545      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11546                       "%s near line %d:", zErrorType, startline);
11547    }else{
11548      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11549    }
11550    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11551    sqlite3_free(zErrMsg);
11552    zErrMsg = 0;
11553    return 1;
11554  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11555    char zLineBuf[2000];
11556    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11557            "changes: %lld   total_changes: %lld",
11558            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11559    raw_printf(p->out, "%s\n", zLineBuf);
11560  }
11561  return 0;
11562}
11563
11564static void echo_group_input(ShellState *p, const char *zDo){
11565  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11566}
11567
11568#ifdef SQLITE_SHELL_WASM_MODE
11569/*
11570** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11571** because we need the global shellState and cannot access it from that function
11572** without moving lots of code around (creating a larger/messier diff).
11573*/
11574static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11575  /* Parse the next line from shellState.wasm.zInput. */
11576  const char *zBegin = shellState.wasm.zPos;
11577  const char *z = zBegin;
11578  char *zLine = 0;
11579  int nZ = 0;
11580
11581  UNUSED_PARAMETER(in);
11582  UNUSED_PARAMETER(isContinuation);
11583  if(!z || !*z){
11584    return 0;
11585  }
11586  while(*z && isspace(*z)) ++z;
11587  zBegin = z;
11588  for(; *z && '\n'!=*z; ++nZ, ++z){}
11589  if(nZ>0 && '\r'==zBegin[nZ-1]){
11590    --nZ;
11591  }
11592  shellState.wasm.zPos = z;
11593  zLine = realloc(zPrior, nZ+1);
11594  shell_check_oom(zLine);
11595  memcpy(zLine, zBegin, (size_t)nZ);
11596  zLine[nZ] = 0;
11597  return zLine;
11598}
11599#endif /* SQLITE_SHELL_WASM_MODE */
11600
11601/*
11602** Read input from *in and process it.  If *in==0 then input
11603** is interactive - the user is typing it it.  Otherwise, input
11604** is coming from a file or device.  A prompt is issued and history
11605** is saved only if input is interactive.  An interrupt signal will
11606** cause this routine to exit immediately, unless input is interactive.
11607**
11608** Return the number of errors.
11609*/
11610static int process_input(ShellState *p){
11611  char *zLine = 0;          /* A single input line */
11612  char *zSql = 0;           /* Accumulated SQL text */
11613  int nLine;                /* Length of current line */
11614  int nSql = 0;             /* Bytes of zSql[] used */
11615  int nAlloc = 0;           /* Allocated zSql[] space */
11616  int rc;                   /* Error code */
11617  int errCnt = 0;           /* Number of errors seen */
11618  int startline = 0;        /* Line number for start of current input */
11619  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11620
11621  if( p->inputNesting==MAX_INPUT_NESTING ){
11622    /* This will be more informative in a later version. */
11623    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11624                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11625    return 1;
11626  }
11627  ++p->inputNesting;
11628  p->lineno = 0;
11629  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11630    fflush(p->out);
11631    zLine = one_input_line(p->in, zLine, nSql>0);
11632    if( zLine==0 ){
11633      /* End of input */
11634      if( p->in==0 && stdin_is_interactive ) printf("\n");
11635      break;
11636    }
11637    if( seenInterrupt ){
11638      if( p->in!=0 ) break;
11639      seenInterrupt = 0;
11640    }
11641    p->lineno++;
11642    if( QSS_INPLAIN(qss)
11643        && line_is_command_terminator(zLine)
11644        && line_is_complete(zSql, nSql) ){
11645      memcpy(zLine,";",2);
11646    }
11647    qss = quickscan(zLine, qss);
11648    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11649      /* Just swallow single-line whitespace */
11650      echo_group_input(p, zLine);
11651      qss = QSS_Start;
11652      continue;
11653    }
11654    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11655      echo_group_input(p, zLine);
11656      if( zLine[0]=='.' ){
11657        rc = do_meta_command(zLine, p);
11658        if( rc==2 ){ /* exit requested */
11659          break;
11660        }else if( rc ){
11661          errCnt++;
11662        }
11663      }
11664      qss = QSS_Start;
11665      continue;
11666    }
11667    /* No single-line dispositions remain; accumulate line(s). */
11668    nLine = strlen30(zLine);
11669    if( nSql+nLine+2>=nAlloc ){
11670      /* Grow buffer by half-again increments when big. */
11671      nAlloc = nSql+(nSql>>1)+nLine+100;
11672      zSql = realloc(zSql, nAlloc);
11673      shell_check_oom(zSql);
11674    }
11675    if( nSql==0 ){
11676      int i;
11677      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11678      assert( nAlloc>0 && zSql!=0 );
11679      memcpy(zSql, zLine+i, nLine+1-i);
11680      startline = p->lineno;
11681      nSql = nLine-i;
11682    }else{
11683      zSql[nSql++] = '\n';
11684      memcpy(zSql+nSql, zLine, nLine+1);
11685      nSql += nLine;
11686    }
11687    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11688      echo_group_input(p, zSql);
11689      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11690      nSql = 0;
11691      if( p->outCount ){
11692        output_reset(p);
11693        p->outCount = 0;
11694      }else{
11695        clearTempFile(p);
11696      }
11697      p->bSafeMode = p->bSafeModePersist;
11698      qss = QSS_Start;
11699    }else if( nSql && QSS_PLAINWHITE(qss) ){
11700      echo_group_input(p, zSql);
11701      nSql = 0;
11702      qss = QSS_Start;
11703    }
11704  }
11705  if( nSql ){
11706    /* This may be incomplete. Let the SQL parser deal with that. */
11707    echo_group_input(p, zSql);
11708    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11709  }
11710  free(zSql);
11711  free(zLine);
11712  --p->inputNesting;
11713  return errCnt>0;
11714}
11715
11716/*
11717** Return a pathname which is the user's home directory.  A
11718** 0 return indicates an error of some kind.
11719*/
11720static char *find_home_dir(int clearFlag){
11721  static char *home_dir = NULL;
11722  if( clearFlag ){
11723    free(home_dir);
11724    home_dir = 0;
11725    return 0;
11726  }
11727  if( home_dir ) return home_dir;
11728
11729#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11730     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11731  {
11732    struct passwd *pwent;
11733    uid_t uid = getuid();
11734    if( (pwent=getpwuid(uid)) != NULL) {
11735      home_dir = pwent->pw_dir;
11736    }
11737  }
11738#endif
11739
11740#if defined(_WIN32_WCE)
11741  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11742   */
11743  home_dir = "/";
11744#else
11745
11746#if defined(_WIN32) || defined(WIN32)
11747  if (!home_dir) {
11748    home_dir = getenv("USERPROFILE");
11749  }
11750#endif
11751
11752  if (!home_dir) {
11753    home_dir = getenv("HOME");
11754  }
11755
11756#if defined(_WIN32) || defined(WIN32)
11757  if (!home_dir) {
11758    char *zDrive, *zPath;
11759    int n;
11760    zDrive = getenv("HOMEDRIVE");
11761    zPath = getenv("HOMEPATH");
11762    if( zDrive && zPath ){
11763      n = strlen30(zDrive) + strlen30(zPath) + 1;
11764      home_dir = malloc( n );
11765      if( home_dir==0 ) return 0;
11766      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11767      return home_dir;
11768    }
11769    home_dir = "c:\\";
11770  }
11771#endif
11772
11773#endif /* !_WIN32_WCE */
11774
11775  if( home_dir ){
11776    int n = strlen30(home_dir) + 1;
11777    char *z = malloc( n );
11778    if( z ) memcpy(z, home_dir, n);
11779    home_dir = z;
11780  }
11781
11782  return home_dir;
11783}
11784
11785/*
11786** Read input from the file given by sqliterc_override.  Or if that
11787** parameter is NULL, take input from ~/.sqliterc
11788**
11789** Returns the number of errors.
11790*/
11791static void process_sqliterc(
11792  ShellState *p,                  /* Configuration data */
11793  const char *sqliterc_override   /* Name of config file. NULL to use default */
11794){
11795  char *home_dir = NULL;
11796  const char *sqliterc = sqliterc_override;
11797  char *zBuf = 0;
11798  FILE *inSaved = p->in;
11799  int savedLineno = p->lineno;
11800
11801  if (sqliterc == NULL) {
11802    home_dir = find_home_dir(0);
11803    if( home_dir==0 ){
11804      raw_printf(stderr, "-- warning: cannot find home directory;"
11805                      " cannot read ~/.sqliterc\n");
11806      return;
11807    }
11808    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11809    shell_check_oom(zBuf);
11810    sqliterc = zBuf;
11811  }
11812  p->in = fopen(sqliterc,"rb");
11813  if( p->in ){
11814    if( stdin_is_interactive ){
11815      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11816    }
11817    if( process_input(p) && bail_on_error ) exit(1);
11818    fclose(p->in);
11819  }else if( sqliterc_override!=0 ){
11820    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11821    if( bail_on_error ) exit(1);
11822  }
11823  p->in = inSaved;
11824  p->lineno = savedLineno;
11825  sqlite3_free(zBuf);
11826}
11827
11828/*
11829** Show available command line options
11830*/
11831static const char zOptions[] =
11832#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11833  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11834#endif
11835  "   -append              append the database to the end of the file\n"
11836  "   -ascii               set output mode to 'ascii'\n"
11837  "   -bail                stop after hitting an error\n"
11838  "   -batch               force batch I/O\n"
11839  "   -box                 set output mode to 'box'\n"
11840  "   -column              set output mode to 'column'\n"
11841  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11842  "   -csv                 set output mode to 'csv'\n"
11843#if !defined(SQLITE_OMIT_DESERIALIZE)
11844  "   -deserialize         open the database using sqlite3_deserialize()\n"
11845#endif
11846  "   -echo                print inputs before execution\n"
11847  "   -init FILENAME       read/process named file\n"
11848  "   -[no]header          turn headers on or off\n"
11849#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11850  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11851#endif
11852  "   -help                show this message\n"
11853  "   -html                set output mode to HTML\n"
11854  "   -interactive         force interactive I/O\n"
11855  "   -json                set output mode to 'json'\n"
11856  "   -line                set output mode to 'line'\n"
11857  "   -list                set output mode to 'list'\n"
11858  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11859  "   -markdown            set output mode to 'markdown'\n"
11860#if !defined(SQLITE_OMIT_DESERIALIZE)
11861  "   -maxsize N           maximum size for a --deserialize database\n"
11862#endif
11863  "   -memtrace            trace all memory allocations and deallocations\n"
11864  "   -mmap N              default mmap size set to N\n"
11865#ifdef SQLITE_ENABLE_MULTIPLEX
11866  "   -multiplex           enable the multiplexor VFS\n"
11867#endif
11868  "   -newline SEP         set output row separator. Default: '\\n'\n"
11869  "   -nofollow            refuse to open symbolic links to database files\n"
11870  "   -nonce STRING        set the safe-mode escape nonce\n"
11871  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11872  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11873  "   -quote               set output mode to 'quote'\n"
11874  "   -readonly            open the database read-only\n"
11875  "   -safe                enable safe-mode\n"
11876  "   -separator SEP       set output column separator. Default: '|'\n"
11877#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11878  "   -sorterref SIZE      sorter references threshold size\n"
11879#endif
11880  "   -stats               print memory stats before each finalize\n"
11881  "   -table               set output mode to 'table'\n"
11882  "   -tabs                set output mode to 'tabs'\n"
11883  "   -version             show SQLite version\n"
11884  "   -vfs NAME            use NAME as the default VFS\n"
11885#ifdef SQLITE_ENABLE_VFSTRACE
11886  "   -vfstrace            enable tracing of all VFS calls\n"
11887#endif
11888#ifdef SQLITE_HAVE_ZLIB
11889  "   -zip                 open the file as a ZIP Archive\n"
11890#endif
11891;
11892static void usage(int showDetail){
11893  utf8_printf(stderr,
11894      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11895      "FILENAME is the name of an SQLite database. A new database is created\n"
11896      "if the file does not previously exist.\n", Argv0);
11897  if( showDetail ){
11898    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11899  }else{
11900    raw_printf(stderr, "Use the -help option for additional information\n");
11901  }
11902  exit(1);
11903}
11904
11905/*
11906** Internal check:  Verify that the SQLite is uninitialized.  Print a
11907** error message if it is initialized.
11908*/
11909static void verify_uninitialized(void){
11910  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11911    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11912                        " initialization.\n");
11913  }
11914}
11915
11916/*
11917** Initialize the state information in data
11918*/
11919static void main_init(ShellState *data) {
11920  memset(data, 0, sizeof(*data));
11921  data->normalMode = data->cMode = data->mode = MODE_List;
11922  data->autoExplain = 1;
11923  data->pAuxDb = &data->aAuxDb[0];
11924  memcpy(data->colSeparator,SEP_Column, 2);
11925  memcpy(data->rowSeparator,SEP_Row, 2);
11926  data->showHeader = 0;
11927  data->shellFlgs = SHFLG_Lookaside;
11928  verify_uninitialized();
11929  sqlite3_config(SQLITE_CONFIG_URI, 1);
11930  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11931  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11932  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11933  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11934}
11935
11936/*
11937** Output text to the console in a font that attracts extra attention.
11938*/
11939#ifdef _WIN32
11940static void printBold(const char *zText){
11941#if !SQLITE_OS_WINRT
11942  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11943  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11944  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11945  SetConsoleTextAttribute(out,
11946         FOREGROUND_RED|FOREGROUND_INTENSITY
11947  );
11948#endif
11949  printf("%s", zText);
11950#if !SQLITE_OS_WINRT
11951  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11952#endif
11953}
11954#else
11955static void printBold(const char *zText){
11956  printf("\033[1m%s\033[0m", zText);
11957}
11958#endif
11959
11960/*
11961** Get the argument to an --option.  Throw an error and die if no argument
11962** is available.
11963*/
11964static char *cmdline_option_value(int argc, char **argv, int i){
11965  if( i==argc ){
11966    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11967            argv[0], argv[argc-1]);
11968    exit(1);
11969  }
11970  return argv[i];
11971}
11972
11973#ifndef SQLITE_SHELL_IS_UTF8
11974#  if (defined(_WIN32) || defined(WIN32)) \
11975   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11976#    define SQLITE_SHELL_IS_UTF8          (0)
11977#  else
11978#    define SQLITE_SHELL_IS_UTF8          (1)
11979#  endif
11980#endif
11981
11982#ifdef SQLITE_SHELL_WASM_MODE
11983#  define main fiddle_main
11984#endif
11985
11986#if SQLITE_SHELL_IS_UTF8
11987int SQLITE_CDECL main(int argc, char **argv){
11988#else
11989int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11990  char **argv;
11991#endif
11992#ifdef SQLITE_DEBUG
11993  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
11994#endif
11995  char *zErrMsg = 0;
11996#ifdef SQLITE_SHELL_WASM_MODE
11997#  define data shellState
11998#else
11999  ShellState data;
12000#endif
12001  const char *zInitFile = 0;
12002  int i;
12003  int rc = 0;
12004  int warnInmemoryDb = 0;
12005  int readStdin = 1;
12006  int nCmd = 0;
12007  char **azCmd = 0;
12008  const char *zVfs = 0;           /* Value of -vfs command-line option */
12009#if !SQLITE_SHELL_IS_UTF8
12010  char **argvToFree = 0;
12011  int argcToFree = 0;
12012#endif
12013
12014  setBinaryMode(stdin, 0);
12015  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12016#ifdef SQLITE_SHELL_WASM_MODE
12017  stdin_is_interactive = 0;
12018  stdout_is_console = 1;
12019#else
12020  stdin_is_interactive = isatty(0);
12021  stdout_is_console = isatty(1);
12022#endif
12023
12024#if !defined(_WIN32_WCE)
12025  if( getenv("SQLITE_DEBUG_BREAK") ){
12026    if( isatty(0) && isatty(2) ){
12027      fprintf(stderr,
12028          "attach debugger to process %d and press any key to continue.\n",
12029          GETPID());
12030      fgetc(stdin);
12031    }else{
12032#if defined(_WIN32) || defined(WIN32)
12033#if SQLITE_OS_WINRT
12034      __debugbreak();
12035#else
12036      DebugBreak();
12037#endif
12038#elif defined(SIGTRAP)
12039      raise(SIGTRAP);
12040#endif
12041    }
12042  }
12043#endif
12044
12045#if USE_SYSTEM_SQLITE+0!=1
12046  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12047    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12048            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12049    exit(1);
12050  }
12051#endif
12052  main_init(&data);
12053
12054  /* On Windows, we must translate command-line arguments into UTF-8.
12055  ** The SQLite memory allocator subsystem has to be enabled in order to
12056  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12057  ** subsequent sqlite3_config() calls will work.  So copy all results into
12058  ** memory that does not come from the SQLite memory allocator.
12059  */
12060#if !SQLITE_SHELL_IS_UTF8
12061  sqlite3_initialize();
12062  argvToFree = malloc(sizeof(argv[0])*argc*2);
12063  shell_check_oom(argvToFree);
12064  argcToFree = argc;
12065  argv = argvToFree + argc;
12066  for(i=0; i<argc; i++){
12067    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12068    int n;
12069    shell_check_oom(z);
12070    n = (int)strlen(z);
12071    argv[i] = malloc( n+1 );
12072    shell_check_oom(argv[i]);
12073    memcpy(argv[i], z, n+1);
12074    argvToFree[i] = argv[i];
12075    sqlite3_free(z);
12076  }
12077  sqlite3_shutdown();
12078#endif
12079
12080  assert( argc>=1 && argv && argv[0] );
12081  Argv0 = argv[0];
12082
12083  /* Make sure we have a valid signal handler early, before anything
12084  ** else is done.
12085  */
12086#ifdef SIGINT
12087  signal(SIGINT, interrupt_handler);
12088#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12089  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12090#endif
12091
12092#ifdef SQLITE_SHELL_DBNAME_PROC
12093  {
12094    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12095    ** of a C-function that will provide the name of the database file.  Use
12096    ** this compile-time option to embed this shell program in larger
12097    ** applications. */
12098    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12099    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12100    warnInmemoryDb = 0;
12101  }
12102#endif
12103
12104  /* Do an initial pass through the command-line argument to locate
12105  ** the name of the database file, the name of the initialization file,
12106  ** the size of the alternative malloc heap,
12107  ** and the first command to execute.
12108  */
12109  verify_uninitialized();
12110  for(i=1; i<argc; i++){
12111    char *z;
12112    z = argv[i];
12113    if( z[0]!='-' ){
12114      if( data.aAuxDb->zDbFilename==0 ){
12115        data.aAuxDb->zDbFilename = z;
12116      }else{
12117        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12118        ** mean that nothing is read from stdin */
12119        readStdin = 0;
12120        nCmd++;
12121        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12122        shell_check_oom(azCmd);
12123        azCmd[nCmd-1] = z;
12124      }
12125    }
12126    if( z[1]=='-' ) z++;
12127    if( strcmp(z,"-separator")==0
12128     || strcmp(z,"-nullvalue")==0
12129     || strcmp(z,"-newline")==0
12130     || strcmp(z,"-cmd")==0
12131    ){
12132      (void)cmdline_option_value(argc, argv, ++i);
12133    }else if( strcmp(z,"-init")==0 ){
12134      zInitFile = cmdline_option_value(argc, argv, ++i);
12135    }else if( strcmp(z,"-batch")==0 ){
12136      /* Need to check for batch mode here to so we can avoid printing
12137      ** informational messages (like from process_sqliterc) before
12138      ** we do the actual processing of arguments later in a second pass.
12139      */
12140      stdin_is_interactive = 0;
12141    }else if( strcmp(z,"-heap")==0 ){
12142#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12143      const char *zSize;
12144      sqlite3_int64 szHeap;
12145
12146      zSize = cmdline_option_value(argc, argv, ++i);
12147      szHeap = integerValue(zSize);
12148      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12149      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12150#else
12151      (void)cmdline_option_value(argc, argv, ++i);
12152#endif
12153    }else if( strcmp(z,"-pagecache")==0 ){
12154      sqlite3_int64 n, sz;
12155      sz = integerValue(cmdline_option_value(argc,argv,++i));
12156      if( sz>70000 ) sz = 70000;
12157      if( sz<0 ) sz = 0;
12158      n = integerValue(cmdline_option_value(argc,argv,++i));
12159      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12160        n = 0xffffffffffffLL/sz;
12161      }
12162      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12163                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12164      data.shellFlgs |= SHFLG_Pagecache;
12165    }else if( strcmp(z,"-lookaside")==0 ){
12166      int n, sz;
12167      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12168      if( sz<0 ) sz = 0;
12169      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12170      if( n<0 ) n = 0;
12171      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12172      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12173    }else if( strcmp(z,"-threadsafe")==0 ){
12174      int n;
12175      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12176      switch( n ){
12177         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12178         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12179         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12180      }
12181#ifdef SQLITE_ENABLE_VFSTRACE
12182    }else if( strcmp(z,"-vfstrace")==0 ){
12183      extern int vfstrace_register(
12184         const char *zTraceName,
12185         const char *zOldVfsName,
12186         int (*xOut)(const char*,void*),
12187         void *pOutArg,
12188         int makeDefault
12189      );
12190      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12191#endif
12192#ifdef SQLITE_ENABLE_MULTIPLEX
12193    }else if( strcmp(z,"-multiplex")==0 ){
12194      extern int sqlite3_multiple_initialize(const char*,int);
12195      sqlite3_multiplex_initialize(0, 1);
12196#endif
12197    }else if( strcmp(z,"-mmap")==0 ){
12198      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12199      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12200#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12201    }else if( strcmp(z,"-sorterref")==0 ){
12202      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12203      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12204#endif
12205    }else if( strcmp(z,"-vfs")==0 ){
12206      zVfs = cmdline_option_value(argc, argv, ++i);
12207#ifdef SQLITE_HAVE_ZLIB
12208    }else if( strcmp(z,"-zip")==0 ){
12209      data.openMode = SHELL_OPEN_ZIPFILE;
12210#endif
12211    }else if( strcmp(z,"-append")==0 ){
12212      data.openMode = SHELL_OPEN_APPENDVFS;
12213#ifndef SQLITE_OMIT_DESERIALIZE
12214    }else if( strcmp(z,"-deserialize")==0 ){
12215      data.openMode = SHELL_OPEN_DESERIALIZE;
12216    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12217      data.szMax = integerValue(argv[++i]);
12218#endif
12219    }else if( strcmp(z,"-readonly")==0 ){
12220      data.openMode = SHELL_OPEN_READONLY;
12221    }else if( strcmp(z,"-nofollow")==0 ){
12222      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12223#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12224    }else if( strncmp(z, "-A",2)==0 ){
12225      /* All remaining command-line arguments are passed to the ".archive"
12226      ** command, so ignore them */
12227      break;
12228#endif
12229    }else if( strcmp(z, "-memtrace")==0 ){
12230      sqlite3MemTraceActivate(stderr);
12231    }else if( strcmp(z,"-bail")==0 ){
12232      bail_on_error = 1;
12233    }else if( strcmp(z,"-nonce")==0 ){
12234      free(data.zNonce);
12235      data.zNonce = strdup(argv[++i]);
12236    }else if( strcmp(z,"-safe")==0 ){
12237      /* no-op - catch this on the second pass */
12238    }
12239  }
12240  verify_uninitialized();
12241
12242
12243#ifdef SQLITE_SHELL_INIT_PROC
12244  {
12245    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12246    ** of a C-function that will perform initialization actions on SQLite that
12247    ** occur just before or after sqlite3_initialize(). Use this compile-time
12248    ** option to embed this shell program in larger applications. */
12249    extern void SQLITE_SHELL_INIT_PROC(void);
12250    SQLITE_SHELL_INIT_PROC();
12251  }
12252#else
12253  /* All the sqlite3_config() calls have now been made. So it is safe
12254  ** to call sqlite3_initialize() and process any command line -vfs option. */
12255  sqlite3_initialize();
12256#endif
12257
12258  if( zVfs ){
12259    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12260    if( pVfs ){
12261      sqlite3_vfs_register(pVfs, 1);
12262    }else{
12263      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12264      exit(1);
12265    }
12266  }
12267
12268  if( data.pAuxDb->zDbFilename==0 ){
12269#ifndef SQLITE_OMIT_MEMORYDB
12270    data.pAuxDb->zDbFilename = ":memory:";
12271    warnInmemoryDb = argc==1;
12272#else
12273    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12274    return 1;
12275#endif
12276  }
12277  data.out = stdout;
12278#ifndef SQLITE_SHELL_WASM_MODE
12279  sqlite3_appendvfs_init(0,0,0);
12280#endif
12281
12282  /* Go ahead and open the database file if it already exists.  If the
12283  ** file does not exist, delay opening it.  This prevents empty database
12284  ** files from being created if a user mistypes the database name argument
12285  ** to the sqlite command-line tool.
12286  */
12287  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12288    open_db(&data, 0);
12289  }
12290
12291  /* Process the initialization file if there is one.  If no -init option
12292  ** is given on the command line, look for a file named ~/.sqliterc and
12293  ** try to process it.
12294  */
12295  process_sqliterc(&data,zInitFile);
12296
12297  /* Make a second pass through the command-line argument and set
12298  ** options.  This second pass is delayed until after the initialization
12299  ** file is processed so that the command-line arguments will override
12300  ** settings in the initialization file.
12301  */
12302  for(i=1; i<argc; i++){
12303    char *z = argv[i];
12304    if( z[0]!='-' ) continue;
12305    if( z[1]=='-' ){ z++; }
12306    if( strcmp(z,"-init")==0 ){
12307      i++;
12308    }else if( strcmp(z,"-html")==0 ){
12309      data.mode = MODE_Html;
12310    }else if( strcmp(z,"-list")==0 ){
12311      data.mode = MODE_List;
12312    }else if( strcmp(z,"-quote")==0 ){
12313      data.mode = MODE_Quote;
12314      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12315      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12316    }else if( strcmp(z,"-line")==0 ){
12317      data.mode = MODE_Line;
12318    }else if( strcmp(z,"-column")==0 ){
12319      data.mode = MODE_Column;
12320    }else if( strcmp(z,"-json")==0 ){
12321      data.mode = MODE_Json;
12322    }else if( strcmp(z,"-markdown")==0 ){
12323      data.mode = MODE_Markdown;
12324    }else if( strcmp(z,"-table")==0 ){
12325      data.mode = MODE_Table;
12326    }else if( strcmp(z,"-box")==0 ){
12327      data.mode = MODE_Box;
12328    }else if( strcmp(z,"-csv")==0 ){
12329      data.mode = MODE_Csv;
12330      memcpy(data.colSeparator,",",2);
12331#ifdef SQLITE_HAVE_ZLIB
12332    }else if( strcmp(z,"-zip")==0 ){
12333      data.openMode = SHELL_OPEN_ZIPFILE;
12334#endif
12335    }else if( strcmp(z,"-append")==0 ){
12336      data.openMode = SHELL_OPEN_APPENDVFS;
12337#ifndef SQLITE_OMIT_DESERIALIZE
12338    }else if( strcmp(z,"-deserialize")==0 ){
12339      data.openMode = SHELL_OPEN_DESERIALIZE;
12340    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12341      data.szMax = integerValue(argv[++i]);
12342#endif
12343    }else if( strcmp(z,"-readonly")==0 ){
12344      data.openMode = SHELL_OPEN_READONLY;
12345    }else if( strcmp(z,"-nofollow")==0 ){
12346      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12347    }else if( strcmp(z,"-ascii")==0 ){
12348      data.mode = MODE_Ascii;
12349      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12350      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12351    }else if( strcmp(z,"-tabs")==0 ){
12352      data.mode = MODE_List;
12353      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12354      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12355    }else if( strcmp(z,"-separator")==0 ){
12356      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12357                       "%s",cmdline_option_value(argc,argv,++i));
12358    }else if( strcmp(z,"-newline")==0 ){
12359      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12360                       "%s",cmdline_option_value(argc,argv,++i));
12361    }else if( strcmp(z,"-nullvalue")==0 ){
12362      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12363                       "%s",cmdline_option_value(argc,argv,++i));
12364    }else if( strcmp(z,"-header")==0 ){
12365      data.showHeader = 1;
12366      ShellSetFlag(&data, SHFLG_HeaderSet);
12367     }else if( strcmp(z,"-noheader")==0 ){
12368      data.showHeader = 0;
12369      ShellSetFlag(&data, SHFLG_HeaderSet);
12370    }else if( strcmp(z,"-echo")==0 ){
12371      ShellSetFlag(&data, SHFLG_Echo);
12372    }else if( strcmp(z,"-eqp")==0 ){
12373      data.autoEQP = AUTOEQP_on;
12374    }else if( strcmp(z,"-eqpfull")==0 ){
12375      data.autoEQP = AUTOEQP_full;
12376    }else if( strcmp(z,"-stats")==0 ){
12377      data.statsOn = 1;
12378    }else if( strcmp(z,"-scanstats")==0 ){
12379      data.scanstatsOn = 1;
12380    }else if( strcmp(z,"-backslash")==0 ){
12381      /* Undocumented command-line option: -backslash
12382      ** Causes C-style backslash escapes to be evaluated in SQL statements
12383      ** prior to sending the SQL into SQLite.  Useful for injecting
12384      ** crazy bytes in the middle of SQL statements for testing and debugging.
12385      */
12386      ShellSetFlag(&data, SHFLG_Backslash);
12387    }else if( strcmp(z,"-bail")==0 ){
12388      /* No-op.  The bail_on_error flag should already be set. */
12389    }else if( strcmp(z,"-version")==0 ){
12390      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12391      return 0;
12392    }else if( strcmp(z,"-interactive")==0 ){
12393      stdin_is_interactive = 1;
12394    }else if( strcmp(z,"-batch")==0 ){
12395      stdin_is_interactive = 0;
12396    }else if( strcmp(z,"-heap")==0 ){
12397      i++;
12398    }else if( strcmp(z,"-pagecache")==0 ){
12399      i+=2;
12400    }else if( strcmp(z,"-lookaside")==0 ){
12401      i+=2;
12402    }else if( strcmp(z,"-threadsafe")==0 ){
12403      i+=2;
12404    }else if( strcmp(z,"-nonce")==0 ){
12405      i += 2;
12406    }else if( strcmp(z,"-mmap")==0 ){
12407      i++;
12408    }else if( strcmp(z,"-memtrace")==0 ){
12409      i++;
12410#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12411    }else if( strcmp(z,"-sorterref")==0 ){
12412      i++;
12413#endif
12414    }else if( strcmp(z,"-vfs")==0 ){
12415      i++;
12416#ifdef SQLITE_ENABLE_VFSTRACE
12417    }else if( strcmp(z,"-vfstrace")==0 ){
12418      i++;
12419#endif
12420#ifdef SQLITE_ENABLE_MULTIPLEX
12421    }else if( strcmp(z,"-multiplex")==0 ){
12422      i++;
12423#endif
12424    }else if( strcmp(z,"-help")==0 ){
12425      usage(1);
12426    }else if( strcmp(z,"-cmd")==0 ){
12427      /* Run commands that follow -cmd first and separately from commands
12428      ** that simply appear on the command-line.  This seems goofy.  It would
12429      ** be better if all commands ran in the order that they appear.  But
12430      ** we retain the goofy behavior for historical compatibility. */
12431      if( i==argc-1 ) break;
12432      z = cmdline_option_value(argc,argv,++i);
12433      if( z[0]=='.' ){
12434        rc = do_meta_command(z, &data);
12435        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12436      }else{
12437        open_db(&data, 0);
12438        rc = shell_exec(&data, z, &zErrMsg);
12439        if( zErrMsg!=0 ){
12440          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12441          if( bail_on_error ) return rc!=0 ? rc : 1;
12442        }else if( rc!=0 ){
12443          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12444          if( bail_on_error ) return rc;
12445        }
12446      }
12447#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12448    }else if( strncmp(z, "-A", 2)==0 ){
12449      if( nCmd>0 ){
12450        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12451                            " with \"%s\"\n", z);
12452        return 1;
12453      }
12454      open_db(&data, OPEN_DB_ZIPFILE);
12455      if( z[2] ){
12456        argv[i] = &z[2];
12457        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12458      }else{
12459        arDotCommand(&data, 1, argv+i, argc-i);
12460      }
12461      readStdin = 0;
12462      break;
12463#endif
12464    }else if( strcmp(z,"-safe")==0 ){
12465      data.bSafeMode = data.bSafeModePersist = 1;
12466    }else{
12467      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12468      raw_printf(stderr,"Use -help for a list of options.\n");
12469      return 1;
12470    }
12471    data.cMode = data.mode;
12472  }
12473
12474  if( !readStdin ){
12475    /* Run all arguments that do not begin with '-' as if they were separate
12476    ** command-line inputs, except for the argToSkip argument which contains
12477    ** the database filename.
12478    */
12479    for(i=0; i<nCmd; i++){
12480      if( azCmd[i][0]=='.' ){
12481        rc = do_meta_command(azCmd[i], &data);
12482        if( rc ){
12483          free(azCmd);
12484          return rc==2 ? 0 : rc;
12485        }
12486      }else{
12487        open_db(&data, 0);
12488        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12489        if( zErrMsg || rc ){
12490          if( zErrMsg!=0 ){
12491            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12492          }else{
12493            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12494          }
12495          sqlite3_free(zErrMsg);
12496          free(azCmd);
12497          return rc!=0 ? rc : 1;
12498        }
12499      }
12500    }
12501  }else{
12502    /* Run commands received from standard input
12503    */
12504    if( stdin_is_interactive ){
12505      char *zHome;
12506      char *zHistory;
12507      int nHistory;
12508      printf(
12509        "SQLite version %s %.19s\n" /*extra-version-info*/
12510        "Enter \".help\" for usage hints.\n",
12511        sqlite3_libversion(), sqlite3_sourceid()
12512      );
12513      if( warnInmemoryDb ){
12514        printf("Connected to a ");
12515        printBold("transient in-memory database");
12516        printf(".\nUse \".open FILENAME\" to reopen on a "
12517               "persistent database.\n");
12518      }
12519      zHistory = getenv("SQLITE_HISTORY");
12520      if( zHistory ){
12521        zHistory = strdup(zHistory);
12522      }else if( (zHome = find_home_dir(0))!=0 ){
12523        nHistory = strlen30(zHome) + 20;
12524        if( (zHistory = malloc(nHistory))!=0 ){
12525          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12526        }
12527      }
12528      if( zHistory ){ shell_read_history(zHistory); }
12529#if HAVE_READLINE || HAVE_EDITLINE
12530      rl_attempted_completion_function = readline_completion;
12531#elif HAVE_LINENOISE
12532      linenoiseSetCompletionCallback(linenoise_completion);
12533#endif
12534      data.in = 0;
12535      rc = process_input(&data);
12536      if( zHistory ){
12537        shell_stifle_history(2000);
12538        shell_write_history(zHistory);
12539        free(zHistory);
12540      }
12541    }else{
12542      data.in = stdin;
12543      rc = process_input(&data);
12544    }
12545  }
12546#ifndef SQLITE_SHELL_WASM_MODE
12547  /* In WASM mode we have to leave the db state in place so that
12548  ** client code can "push" SQL into it after this call returns. */
12549  free(azCmd);
12550  set_table_name(&data, 0);
12551  if( data.db ){
12552    session_close_all(&data, -1);
12553    close_db(data.db);
12554  }
12555  for(i=0; i<ArraySize(data.aAuxDb); i++){
12556    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12557    if( data.aAuxDb[i].db ){
12558      session_close_all(&data, i);
12559      close_db(data.aAuxDb[i].db);
12560    }
12561  }
12562  find_home_dir(1);
12563  output_reset(&data);
12564  data.doXdgOpen = 0;
12565  clearTempFile(&data);
12566#if !SQLITE_SHELL_IS_UTF8
12567  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12568  free(argvToFree);
12569#endif
12570  free(data.colWidth);
12571  free(data.zNonce);
12572  /* Clear the global data structure so that valgrind will detect memory
12573  ** leaks */
12574  memset(&data, 0, sizeof(data));
12575#ifdef SQLITE_DEBUG
12576  if( sqlite3_memory_used()>mem_main_enter ){
12577    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12578                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12579  }
12580#endif
12581#endif /* !SQLITE_SHELL_WASM_MODE */
12582  return rc;
12583}
12584
12585
12586#ifdef SQLITE_SHELL_WASM_MODE
12587/* Only for emcc experimentation purposes. */
12588int fiddle_experiment(int a,int b){
12589   return a + b;
12590}
12591
12592/* Only for emcc experimentation purposes.
12593
12594  Define this function in JS using:
12595
12596  emcc ... --js-library somefile.js
12597
12598  containing:
12599
12600mergeInto(LibraryManager.library, {
12601    my_foo: function(){
12602        console.debug("my_foo()",arguments);
12603    }
12604});
12605*/
12606/*extern void my_foo(sqlite3 *);*/
12607/* Only for emcc experimentation purposes. */
12608sqlite3 * fiddle_the_db(){
12609    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12610    /*my_foo(globalDb);*/
12611    return globalDb;
12612}
12613/* Only for emcc experimentation purposes. */
12614sqlite3 * fiddle_db_arg(sqlite3 *arg){
12615    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12616    return arg;
12617}
12618
12619/*
12620** Intended to be called via a SharedWorker() while a separate
12621** SharedWorker() (which manages the wasm module) is performing work
12622** which should be interrupted. Unfortunately, SharedWorker is not
12623** portable enough to make real use of.
12624*/
12625void fiddle_interrupt(void){
12626  if(globalDb) sqlite3_interrupt(globalDb);
12627}
12628
12629/*
12630** Returns the filename of the given db name, assuming "main" if
12631** zDbName is NULL. Returns NULL if globalDb is not opened.
12632*/
12633const char * fiddle_db_filename(const char * zDbName){
12634    return globalDb
12635      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12636      : NULL;
12637}
12638
12639/*
12640** Closes, unlinks, and reopens the db using its current filename (or
12641** the default if the db is currently closed). It is assumed, for
12642** purposes of the fiddle build, that the file is in a transient
12643** virtual filesystem within the browser.
12644*/
12645void fiddle_reset_db(void){
12646  char *zFilename = 0;
12647  if(0==globalDb){
12648    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12649  }else{
12650    zFilename =
12651      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12652    shell_check_oom(zFilename);
12653    close_db(globalDb);
12654    shellDeleteFile(zFilename);
12655    shellState.db = 0;
12656    shellState.pAuxDb->zDbFilename = zFilename;
12657  }
12658  open_db(&shellState, 0);
12659  sqlite3_free(zFilename);
12660}
12661
12662/*
12663** Trivial exportable function for emscripten. Needs to be exported using:
12664**
12665** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12666**
12667** (Note the underscore before the function name.) It processes zSql
12668** as if it were input to the sqlite3 shell and redirects all output
12669** to the wasm binding.
12670*/
12671void fiddle_exec(const char * zSql){
12672  static int once = 0;
12673  int rc = 0;
12674  if(!once){
12675    /* Simulate an argv array for main() */
12676    static char * argv[] = {"fiddle",
12677                            "-bail",
12678                            "-safe"};
12679    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12680    once = rc ? -1 : 1;
12681    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12682    printf(
12683        "SQLite version %s %.19s\n" /*extra-version-info*/,
12684        sqlite3_libversion(), sqlite3_sourceid()
12685    );
12686    puts("WASM shell");
12687    puts("Enter \".help\" for usage hints.");
12688    if(once>0){
12689      fiddle_reset_db();
12690    }
12691    if(shellState.db){
12692      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12693    }else{
12694      fprintf(stderr,"ERROR initializing db!\n");
12695      return;
12696    }
12697  }
12698  if(once<0){
12699    puts("DB init failed. Not executing SQL.");
12700  }else if(zSql && *zSql){
12701    shellState.wasm.zInput = zSql;
12702    shellState.wasm.zPos = zSql;
12703    process_input(&shellState);
12704    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12705  }
12706}
12707#endif /* SQLITE_SHELL_WASM_MODE */
12708