xref: /sqlite-3.40.0/src/shell.c.in (revision cf2ad7ae)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code.  In place of
5** a legal notice, here is a blessing:
6**
7**    May you do good and not evil.
8**    May you find forgiveness for yourself and forgive others.
9**    May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Optionally #include a user-defined header, whereby compilation options
22** may be set prior to where they take effect, but after platform setup.
23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include
24** file. Note that this macro has a like effect on sqlite3.c compilation.
25*/
26# define SHELL_STRINGIFY_(f) #f
27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f)
28#ifdef SQLITE_CUSTOM_INCLUDE
29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE)
30#endif
31
32/*
33** Determine if we are dealing with WinRT, which provides only a subset of
34** the full Win32 API.
35*/
36#if !defined(SQLITE_OS_WINRT)
37# define SQLITE_OS_WINRT 0
38#endif
39
40/*
41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified
42** somewhat for use as a WASM module in a web browser. This flag
43** should only be used when building the "fiddle" web application, as
44** the browser-mode build has much different user input requirements
45** and this build mode rewires the user input subsystem to account for
46** that.
47*/
48
49/*
50** Warning pragmas copied from msvc.h in the core.
51*/
52#if defined(_MSC_VER)
53#pragma warning(disable : 4054)
54#pragma warning(disable : 4055)
55#pragma warning(disable : 4100)
56#pragma warning(disable : 4127)
57#pragma warning(disable : 4130)
58#pragma warning(disable : 4152)
59#pragma warning(disable : 4189)
60#pragma warning(disable : 4206)
61#pragma warning(disable : 4210)
62#pragma warning(disable : 4232)
63#pragma warning(disable : 4244)
64#pragma warning(disable : 4305)
65#pragma warning(disable : 4306)
66#pragma warning(disable : 4702)
67#pragma warning(disable : 4706)
68#endif /* defined(_MSC_VER) */
69
70/*
71** No support for loadable extensions in VxWorks.
72*/
73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
74# define SQLITE_OMIT_LOAD_EXTENSION 1
75#endif
76
77/*
78** Enable large-file support for fopen() and friends on unix.
79*/
80#ifndef SQLITE_DISABLE_LFS
81# define _LARGE_FILE       1
82# ifndef _FILE_OFFSET_BITS
83#   define _FILE_OFFSET_BITS 64
84# endif
85# define _LARGEFILE_SOURCE 1
86#endif
87
88#include <stdlib.h>
89#include <string.h>
90#include <stdio.h>
91#include <assert.h>
92#include "sqlite3.h"
93typedef sqlite3_int64 i64;
94typedef sqlite3_uint64 u64;
95typedef unsigned char u8;
96#if SQLITE_USER_AUTHENTICATION
97# include "sqlite3userauth.h"
98#endif
99#include <ctype.h>
100#include <stdarg.h>
101
102#if !defined(_WIN32) && !defined(WIN32)
103# include <signal.h>
104# if !defined(__RTP__) && !defined(_WRS_KERNEL)
105#  include <pwd.h>
106# endif
107#endif
108#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
109# include <unistd.h>
110# include <dirent.h>
111# define GETPID getpid
112# if defined(__MINGW32__)
113#  define DIRENT dirent
114#  ifndef S_ISLNK
115#   define S_ISLNK(mode) (0)
116#  endif
117# endif
118#else
119# define GETPID (int)GetCurrentProcessId
120#endif
121#include <sys/types.h>
122#include <sys/stat.h>
123
124#if HAVE_READLINE
125# include <readline/readline.h>
126# include <readline/history.h>
127#endif
128
129#if HAVE_EDITLINE
130# include <editline/readline.h>
131#endif
132
133#if HAVE_EDITLINE || HAVE_READLINE
134
135# define shell_add_history(X) add_history(X)
136# define shell_read_history(X) read_history(X)
137# define shell_write_history(X) write_history(X)
138# define shell_stifle_history(X) stifle_history(X)
139# define shell_readline(X) readline(X)
140
141#elif HAVE_LINENOISE
142
143# include "linenoise.h"
144# define shell_add_history(X) linenoiseHistoryAdd(X)
145# define shell_read_history(X) linenoiseHistoryLoad(X)
146# define shell_write_history(X) linenoiseHistorySave(X)
147# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
148# define shell_readline(X) linenoise(X)
149
150#else
151
152# define shell_read_history(X)
153# define shell_write_history(X)
154# define shell_stifle_history(X)
155
156# define SHELL_USE_LOCAL_GETLINE 1
157#endif
158
159
160#if defined(_WIN32) || defined(WIN32)
161# if SQLITE_OS_WINRT
162#  define SQLITE_OMIT_POPEN 1
163# else
164#  include <io.h>
165#  include <fcntl.h>
166#  define isatty(h) _isatty(h)
167#  ifndef access
168#   define access(f,m) _access((f),(m))
169#  endif
170#  ifndef unlink
171#   define unlink _unlink
172#  endif
173#  ifndef strdup
174#   define strdup _strdup
175#  endif
176#  undef popen
177#  define popen _popen
178#  undef pclose
179#  define pclose _pclose
180# endif
181#else
182 /* Make sure isatty() has a prototype. */
183 extern int isatty(int);
184
185# if !defined(__RTP__) && !defined(_WRS_KERNEL)
186  /* popen and pclose are not C89 functions and so are
187  ** sometimes omitted from the <stdio.h> header */
188   extern FILE *popen(const char*,const char*);
189   extern int pclose(FILE*);
190# else
191#  define SQLITE_OMIT_POPEN 1
192# endif
193#endif
194
195#if defined(_WIN32_WCE)
196/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
197 * thus we always assume that we have a console. That can be
198 * overridden with the -batch command line option.
199 */
200#define isatty(x) 1
201#endif
202
203/* ctype macros that work with signed characters */
204#define IsSpace(X)  isspace((unsigned char)X)
205#define IsDigit(X)  isdigit((unsigned char)X)
206#define ToLower(X)  (char)tolower((unsigned char)X)
207
208#if defined(_WIN32) || defined(WIN32)
209#if SQLITE_OS_WINRT
210#include <intrin.h>
211#endif
212#include <windows.h>
213
214/* string conversion routines only needed on Win32 */
215extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
216extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
217extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
218extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
219#endif
220
221/* On Windows, we normally run with output mode of TEXT so that \n characters
222** are automatically translated into \r\n.  However, this behavior needs
223** to be disabled in some cases (ex: when generating CSV output and when
224** rendering quoted strings that contain \n characters).  The following
225** routines take care of that.
226*/
227#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
228static void setBinaryMode(FILE *file, int isOutput){
229  if( isOutput ) fflush(file);
230  _setmode(_fileno(file), _O_BINARY);
231}
232static void setTextMode(FILE *file, int isOutput){
233  if( isOutput ) fflush(file);
234  _setmode(_fileno(file), _O_TEXT);
235}
236#else
237# define setBinaryMode(X,Y)
238# define setTextMode(X,Y)
239#endif
240
241/* True if the timer is enabled */
242static int enableTimer = 0;
243
244/* Return the current wall-clock time */
245static sqlite3_int64 timeOfDay(void){
246  static sqlite3_vfs *clockVfs = 0;
247  sqlite3_int64 t;
248  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
249  if( clockVfs==0 ) return 0;  /* Never actually happens */
250  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
251    clockVfs->xCurrentTimeInt64(clockVfs, &t);
252  }else{
253    double r;
254    clockVfs->xCurrentTime(clockVfs, &r);
255    t = (sqlite3_int64)(r*86400000.0);
256  }
257  return t;
258}
259
260#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
261#include <sys/time.h>
262#include <sys/resource.h>
263
264/* VxWorks does not support getrusage() as far as we can determine */
265#if defined(_WRS_KERNEL) || defined(__RTP__)
266struct rusage {
267  struct timeval ru_utime; /* user CPU time used */
268  struct timeval ru_stime; /* system CPU time used */
269};
270#define getrusage(A,B) memset(B,0,sizeof(*B))
271#endif
272
273/* Saved resource information for the beginning of an operation */
274static struct rusage sBegin;  /* CPU time at start */
275static sqlite3_int64 iBegin;  /* Wall-clock time at start */
276
277/*
278** Begin timing an operation
279*/
280static void beginTimer(void){
281  if( enableTimer ){
282    getrusage(RUSAGE_SELF, &sBegin);
283    iBegin = timeOfDay();
284  }
285}
286
287/* Return the difference of two time_structs in seconds */
288static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
289  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
290         (double)(pEnd->tv_sec - pStart->tv_sec);
291}
292
293/*
294** Print the timing results.
295*/
296static void endTimer(void){
297  if( enableTimer ){
298    sqlite3_int64 iEnd = timeOfDay();
299    struct rusage sEnd;
300    getrusage(RUSAGE_SELF, &sEnd);
301    printf("Run Time: real %.3f user %f sys %f\n",
302       (iEnd - iBegin)*0.001,
303       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
304       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
305  }
306}
307
308#define BEGIN_TIMER beginTimer()
309#define END_TIMER endTimer()
310#define HAS_TIMER 1
311
312#elif (defined(_WIN32) || defined(WIN32))
313
314/* Saved resource information for the beginning of an operation */
315static HANDLE hProcess;
316static FILETIME ftKernelBegin;
317static FILETIME ftUserBegin;
318static sqlite3_int64 ftWallBegin;
319typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
320                                    LPFILETIME, LPFILETIME);
321static GETPROCTIMES getProcessTimesAddr = NULL;
322
323/*
324** Check to see if we have timer support.  Return 1 if necessary
325** support found (or found previously).
326*/
327static int hasTimer(void){
328  if( getProcessTimesAddr ){
329    return 1;
330  } else {
331#if !SQLITE_OS_WINRT
332    /* GetProcessTimes() isn't supported in WIN95 and some other Windows
333    ** versions. See if the version we are running on has it, and if it
334    ** does, save off a pointer to it and the current process handle.
335    */
336    hProcess = GetCurrentProcess();
337    if( hProcess ){
338      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
339      if( NULL != hinstLib ){
340        getProcessTimesAddr =
341            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
342        if( NULL != getProcessTimesAddr ){
343          return 1;
344        }
345        FreeLibrary(hinstLib);
346      }
347    }
348#endif
349  }
350  return 0;
351}
352
353/*
354** Begin timing an operation
355*/
356static void beginTimer(void){
357  if( enableTimer && getProcessTimesAddr ){
358    FILETIME ftCreation, ftExit;
359    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
360                        &ftKernelBegin,&ftUserBegin);
361    ftWallBegin = timeOfDay();
362  }
363}
364
365/* Return the difference of two FILETIME structs in seconds */
366static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
367  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
368  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
369  return (double) ((i64End - i64Start) / 10000000.0);
370}
371
372/*
373** Print the timing results.
374*/
375static void endTimer(void){
376  if( enableTimer && getProcessTimesAddr){
377    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
378    sqlite3_int64 ftWallEnd = timeOfDay();
379    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
380    printf("Run Time: real %.3f user %f sys %f\n",
381       (ftWallEnd - ftWallBegin)*0.001,
382       timeDiff(&ftUserBegin, &ftUserEnd),
383       timeDiff(&ftKernelBegin, &ftKernelEnd));
384  }
385}
386
387#define BEGIN_TIMER beginTimer()
388#define END_TIMER endTimer()
389#define HAS_TIMER hasTimer()
390
391#else
392#define BEGIN_TIMER
393#define END_TIMER
394#define HAS_TIMER 0
395#endif
396
397/*
398** Used to prevent warnings about unused parameters
399*/
400#define UNUSED_PARAMETER(x) (void)(x)
401
402/*
403** Number of elements in an array
404*/
405#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
406
407/*
408** If the following flag is set, then command execution stops
409** at an error if we are not interactive.
410*/
411static int bail_on_error = 0;
412
413/*
414** Threat stdin as an interactive input if the following variable
415** is true.  Otherwise, assume stdin is connected to a file or pipe.
416*/
417static int stdin_is_interactive = 1;
418
419/*
420** On Windows systems we have to know if standard output is a console
421** in order to translate UTF-8 into MBCS.  The following variable is
422** true if translation is required.
423*/
424static int stdout_is_console = 1;
425
426/*
427** The following is the open SQLite database.  We make a pointer
428** to this database a static variable so that it can be accessed
429** by the SIGINT handler to interrupt database processing.
430*/
431static sqlite3 *globalDb = 0;
432
433/*
434** True if an interrupt (Control-C) has been received.
435*/
436static volatile int seenInterrupt = 0;
437
438/*
439** This is the name of our program. It is set in main(), used
440** in a number of other places, mostly for error messages.
441*/
442static char *Argv0;
443
444/*
445** Prompt strings. Initialized in main. Settable with
446**   .prompt main continue
447*/
448static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
449static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
450
451/*
452** Render output like fprintf().  Except, if the output is going to the
453** console and if this is running on a Windows machine, translate the
454** output from UTF-8 into MBCS.
455*/
456#if defined(_WIN32) || defined(WIN32)
457void utf8_printf(FILE *out, const char *zFormat, ...){
458  va_list ap;
459  va_start(ap, zFormat);
460  if( stdout_is_console && (out==stdout || out==stderr) ){
461    char *z1 = sqlite3_vmprintf(zFormat, ap);
462    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
463    sqlite3_free(z1);
464    fputs(z2, out);
465    sqlite3_free(z2);
466  }else{
467    vfprintf(out, zFormat, ap);
468  }
469  va_end(ap);
470}
471#elif !defined(utf8_printf)
472# define utf8_printf fprintf
473#endif
474
475/*
476** Render output like fprintf().  This should not be used on anything that
477** includes string formatting (e.g. "%s").
478*/
479#if !defined(raw_printf)
480# define raw_printf fprintf
481#endif
482
483/* Indicate out-of-memory and exit. */
484static void shell_out_of_memory(void){
485  raw_printf(stderr,"Error: out of memory\n");
486  exit(1);
487}
488
489/* Check a pointer to see if it is NULL.  If it is NULL, exit with an
490** out-of-memory error.
491*/
492static void shell_check_oom(void *p){
493  if( p==0 ) shell_out_of_memory();
494}
495
496/*
497** Write I/O traces to the following stream.
498*/
499#ifdef SQLITE_ENABLE_IOTRACE
500static FILE *iotrace = 0;
501#endif
502
503/*
504** This routine works like printf in that its first argument is a
505** format string and subsequent arguments are values to be substituted
506** in place of % fields.  The result of formatting this string
507** is written to iotrace.
508*/
509#ifdef SQLITE_ENABLE_IOTRACE
510static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
511  va_list ap;
512  char *z;
513  if( iotrace==0 ) return;
514  va_start(ap, zFormat);
515  z = sqlite3_vmprintf(zFormat, ap);
516  va_end(ap);
517  utf8_printf(iotrace, "%s", z);
518  sqlite3_free(z);
519}
520#endif
521
522/*
523** Output string zUtf to stream pOut as w characters.  If w is negative,
524** then right-justify the text.  W is the width in UTF-8 characters, not
525** in bytes.  This is different from the %*.*s specification in printf
526** since with %*.*s the width is measured in bytes, not characters.
527*/
528static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
529  int i;
530  int n;
531  int aw = w<0 ? -w : w;
532  for(i=n=0; zUtf[i]; i++){
533    if( (zUtf[i]&0xc0)!=0x80 ){
534      n++;
535      if( n==aw ){
536        do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
537        break;
538      }
539    }
540  }
541  if( n>=aw ){
542    utf8_printf(pOut, "%.*s", i, zUtf);
543  }else if( w<0 ){
544    utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
545  }else{
546    utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
547  }
548}
549
550
551/*
552** Determines if a string is a number of not.
553*/
554static int isNumber(const char *z, int *realnum){
555  if( *z=='-' || *z=='+' ) z++;
556  if( !IsDigit(*z) ){
557    return 0;
558  }
559  z++;
560  if( realnum ) *realnum = 0;
561  while( IsDigit(*z) ){ z++; }
562  if( *z=='.' ){
563    z++;
564    if( !IsDigit(*z) ) return 0;
565    while( IsDigit(*z) ){ z++; }
566    if( realnum ) *realnum = 1;
567  }
568  if( *z=='e' || *z=='E' ){
569    z++;
570    if( *z=='+' || *z=='-' ) z++;
571    if( !IsDigit(*z) ) return 0;
572    while( IsDigit(*z) ){ z++; }
573    if( realnum ) *realnum = 1;
574  }
575  return *z==0;
576}
577
578/*
579** Compute a string length that is limited to what can be stored in
580** lower 30 bits of a 32-bit signed integer.
581*/
582static int strlen30(const char *z){
583  const char *z2 = z;
584  while( *z2 ){ z2++; }
585  return 0x3fffffff & (int)(z2 - z);
586}
587
588/*
589** Return the length of a string in characters.  Multibyte UTF8 characters
590** count as a single character.
591*/
592static int strlenChar(const char *z){
593  int n = 0;
594  while( *z ){
595    if( (0xc0&*(z++))!=0x80 ) n++;
596  }
597  return n;
598}
599
600/*
601** Return open FILE * if zFile exists, can be opened for read
602** and is an ordinary file or a character stream source.
603** Otherwise return 0.
604*/
605static FILE * openChrSource(const char *zFile){
606#ifdef _WIN32
607  struct _stat x = {0};
608# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
609  /* On Windows, open first, then check the stream nature. This order
610  ** is necessary because _stat() and sibs, when checking a named pipe,
611  ** effectively break the pipe as its supplier sees it. */
612  FILE *rv = fopen(zFile, "rb");
613  if( rv==0 ) return 0;
614  if( _fstat(_fileno(rv), &x) != 0
615      || !STAT_CHR_SRC(x.st_mode)){
616    fclose(rv);
617    rv = 0;
618  }
619  return rv;
620#else
621  struct stat x = {0};
622  int rc = stat(zFile, &x);
623# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode))
624  if( rc!=0 ) return 0;
625  if( STAT_CHR_SRC(x.st_mode) ){
626    return fopen(zFile, "rb");
627  }else{
628    return 0;
629  }
630#endif
631#undef STAT_CHR_SRC
632}
633
634/*
635** This routine reads a line of text from FILE in, stores
636** the text in memory obtained from malloc() and returns a pointer
637** to the text.  NULL is returned at end of file, or if malloc()
638** fails.
639**
640** If zLine is not NULL then it is a malloced buffer returned from
641** a previous call to this routine that may be reused.
642*/
643static char *local_getline(char *zLine, FILE *in){
644  int nLine = zLine==0 ? 0 : 100;
645  int n = 0;
646
647  while( 1 ){
648    if( n+100>nLine ){
649      nLine = nLine*2 + 100;
650      zLine = realloc(zLine, nLine);
651      shell_check_oom(zLine);
652    }
653    if( fgets(&zLine[n], nLine - n, in)==0 ){
654      if( n==0 ){
655        free(zLine);
656        return 0;
657      }
658      zLine[n] = 0;
659      break;
660    }
661    while( zLine[n] ) n++;
662    if( n>0 && zLine[n-1]=='\n' ){
663      n--;
664      if( n>0 && zLine[n-1]=='\r' ) n--;
665      zLine[n] = 0;
666      break;
667    }
668  }
669#if defined(_WIN32) || defined(WIN32)
670  /* For interactive input on Windows systems, translate the
671  ** multi-byte characterset characters into UTF-8. */
672  if( stdin_is_interactive && in==stdin ){
673    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
674    if( zTrans ){
675      int nTrans = strlen30(zTrans)+1;
676      if( nTrans>nLine ){
677        zLine = realloc(zLine, nTrans);
678        shell_check_oom(zLine);
679      }
680      memcpy(zLine, zTrans, nTrans);
681      sqlite3_free(zTrans);
682    }
683  }
684#endif /* defined(_WIN32) || defined(WIN32) */
685  return zLine;
686}
687
688/*
689** Retrieve a single line of input text.
690**
691** If in==0 then read from standard input and prompt before each line.
692** If isContinuation is true, then a continuation prompt is appropriate.
693** If isContinuation is zero, then the main prompt should be used.
694**
695** If zPrior is not NULL then it is a buffer from a prior call to this
696** routine that can be reused.
697**
698** The result is stored in space obtained from malloc() and must either
699** be freed by the caller or else passed back into this routine via the
700** zPrior argument for reuse.
701*/
702#ifndef SQLITE_SHELL_FIDDLE
703static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
704  char *zPrompt;
705  char *zResult;
706  if( in!=0 ){
707    zResult = local_getline(zPrior, in);
708  }else{
709    zPrompt = isContinuation ? continuePrompt : mainPrompt;
710#if SHELL_USE_LOCAL_GETLINE
711    printf("%s", zPrompt);
712    fflush(stdout);
713    zResult = local_getline(zPrior, stdin);
714#else
715    free(zPrior);
716    zResult = shell_readline(zPrompt);
717    if( zResult && *zResult ) shell_add_history(zResult);
718#endif
719  }
720  return zResult;
721}
722#endif /* !SQLITE_SHELL_FIDDLE */
723
724/*
725** Return the value of a hexadecimal digit.  Return -1 if the input
726** is not a hex digit.
727*/
728static int hexDigitValue(char c){
729  if( c>='0' && c<='9' ) return c - '0';
730  if( c>='a' && c<='f' ) return c - 'a' + 10;
731  if( c>='A' && c<='F' ) return c - 'A' + 10;
732  return -1;
733}
734
735/*
736** Interpret zArg as an integer value, possibly with suffixes.
737*/
738static sqlite3_int64 integerValue(const char *zArg){
739  sqlite3_int64 v = 0;
740  static const struct { char *zSuffix; int iMult; } aMult[] = {
741    { "KiB", 1024 },
742    { "MiB", 1024*1024 },
743    { "GiB", 1024*1024*1024 },
744    { "KB",  1000 },
745    { "MB",  1000000 },
746    { "GB",  1000000000 },
747    { "K",   1000 },
748    { "M",   1000000 },
749    { "G",   1000000000 },
750  };
751  int i;
752  int isNeg = 0;
753  if( zArg[0]=='-' ){
754    isNeg = 1;
755    zArg++;
756  }else if( zArg[0]=='+' ){
757    zArg++;
758  }
759  if( zArg[0]=='0' && zArg[1]=='x' ){
760    int x;
761    zArg += 2;
762    while( (x = hexDigitValue(zArg[0]))>=0 ){
763      v = (v<<4) + x;
764      zArg++;
765    }
766  }else{
767    while( IsDigit(zArg[0]) ){
768      v = v*10 + zArg[0] - '0';
769      zArg++;
770    }
771  }
772  for(i=0; i<ArraySize(aMult); i++){
773    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
774      v *= aMult[i].iMult;
775      break;
776    }
777  }
778  return isNeg? -v : v;
779}
780
781/*
782** A variable length string to which one can append text.
783*/
784typedef struct ShellText ShellText;
785struct ShellText {
786  char *z;
787  int n;
788  int nAlloc;
789};
790
791/*
792** Initialize and destroy a ShellText object
793*/
794static void initText(ShellText *p){
795  memset(p, 0, sizeof(*p));
796}
797static void freeText(ShellText *p){
798  free(p->z);
799  initText(p);
800}
801
802/* zIn is either a pointer to a NULL-terminated string in memory obtained
803** from malloc(), or a NULL pointer. The string pointed to by zAppend is
804** added to zIn, and the result returned in memory obtained from malloc().
805** zIn, if it was not NULL, is freed.
806**
807** If the third argument, quote, is not '\0', then it is used as a
808** quote character for zAppend.
809*/
810static void appendText(ShellText *p, const char *zAppend, char quote){
811  int len;
812  int i;
813  int nAppend = strlen30(zAppend);
814
815  len = nAppend+p->n+1;
816  if( quote ){
817    len += 2;
818    for(i=0; i<nAppend; i++){
819      if( zAppend[i]==quote ) len++;
820    }
821  }
822
823  if( p->z==0 || p->n+len>=p->nAlloc ){
824    p->nAlloc = p->nAlloc*2 + len + 20;
825    p->z = realloc(p->z, p->nAlloc);
826    shell_check_oom(p->z);
827  }
828
829  if( quote ){
830    char *zCsr = p->z+p->n;
831    *zCsr++ = quote;
832    for(i=0; i<nAppend; i++){
833      *zCsr++ = zAppend[i];
834      if( zAppend[i]==quote ) *zCsr++ = quote;
835    }
836    *zCsr++ = quote;
837    p->n = (int)(zCsr - p->z);
838    *zCsr = '\0';
839  }else{
840    memcpy(p->z+p->n, zAppend, nAppend);
841    p->n += nAppend;
842    p->z[p->n] = '\0';
843  }
844}
845
846/*
847** Attempt to determine if identifier zName needs to be quoted, either
848** because it contains non-alphanumeric characters, or because it is an
849** SQLite keyword.  Be conservative in this estimate:  When in doubt assume
850** that quoting is required.
851**
852** Return '"' if quoting is required.  Return 0 if no quoting is required.
853*/
854static char quoteChar(const char *zName){
855  int i;
856  if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
857  for(i=0; zName[i]; i++){
858    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
859  }
860  return sqlite3_keyword_check(zName, i) ? '"' : 0;
861}
862
863/*
864** Construct a fake object name and column list to describe the structure
865** of the view, virtual table, or table valued function zSchema.zName.
866*/
867static char *shellFakeSchema(
868  sqlite3 *db,            /* The database connection containing the vtab */
869  const char *zSchema,    /* Schema of the database holding the vtab */
870  const char *zName       /* The name of the virtual table */
871){
872  sqlite3_stmt *pStmt = 0;
873  char *zSql;
874  ShellText s;
875  char cQuote;
876  char *zDiv = "(";
877  int nRow = 0;
878
879  zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
880                         zSchema ? zSchema : "main", zName);
881  shell_check_oom(zSql);
882  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
883  sqlite3_free(zSql);
884  initText(&s);
885  if( zSchema ){
886    cQuote = quoteChar(zSchema);
887    if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
888    appendText(&s, zSchema, cQuote);
889    appendText(&s, ".", 0);
890  }
891  cQuote = quoteChar(zName);
892  appendText(&s, zName, cQuote);
893  while( sqlite3_step(pStmt)==SQLITE_ROW ){
894    const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
895    nRow++;
896    appendText(&s, zDiv, 0);
897    zDiv = ",";
898    if( zCol==0 ) zCol = "";
899    cQuote = quoteChar(zCol);
900    appendText(&s, zCol, cQuote);
901  }
902  appendText(&s, ")", 0);
903  sqlite3_finalize(pStmt);
904  if( nRow==0 ){
905    freeText(&s);
906    s.z = 0;
907  }
908  return s.z;
909}
910
911/*
912** SQL function:  shell_module_schema(X)
913**
914** Return a fake schema for the table-valued function or eponymous virtual
915** table X.
916*/
917static void shellModuleSchema(
918  sqlite3_context *pCtx,
919  int nVal,
920  sqlite3_value **apVal
921){
922  const char *zName;
923  char *zFake;
924  UNUSED_PARAMETER(nVal);
925  zName = (const char*)sqlite3_value_text(apVal[0]);
926  zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0;
927  if( zFake ){
928    sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
929                        -1, sqlite3_free);
930    free(zFake);
931  }
932}
933
934/*
935** SQL function:  shell_add_schema(S,X)
936**
937** Add the schema name X to the CREATE statement in S and return the result.
938** Examples:
939**
940**    CREATE TABLE t1(x)   ->   CREATE TABLE xyz.t1(x);
941**
942** Also works on
943**
944**    CREATE INDEX
945**    CREATE UNIQUE INDEX
946**    CREATE VIEW
947**    CREATE TRIGGER
948**    CREATE VIRTUAL TABLE
949**
950** This UDF is used by the .schema command to insert the schema name of
951** attached databases into the middle of the sqlite_schema.sql field.
952*/
953static void shellAddSchemaName(
954  sqlite3_context *pCtx,
955  int nVal,
956  sqlite3_value **apVal
957){
958  static const char *aPrefix[] = {
959     "TABLE",
960     "INDEX",
961     "UNIQUE INDEX",
962     "VIEW",
963     "TRIGGER",
964     "VIRTUAL TABLE"
965  };
966  int i = 0;
967  const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
968  const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
969  const char *zName = (const char*)sqlite3_value_text(apVal[2]);
970  sqlite3 *db = sqlite3_context_db_handle(pCtx);
971  UNUSED_PARAMETER(nVal);
972  if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
973    for(i=0; i<ArraySize(aPrefix); i++){
974      int n = strlen30(aPrefix[i]);
975      if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
976        char *z = 0;
977        char *zFake = 0;
978        if( zSchema ){
979          char cQuote = quoteChar(zSchema);
980          if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
981            z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
982          }else{
983            z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
984          }
985        }
986        if( zName
987         && aPrefix[i][0]=='V'
988         && (zFake = shellFakeSchema(db, zSchema, zName))!=0
989        ){
990          if( z==0 ){
991            z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
992          }else{
993            z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
994          }
995          free(zFake);
996        }
997        if( z ){
998          sqlite3_result_text(pCtx, z, -1, sqlite3_free);
999          return;
1000        }
1001      }
1002    }
1003  }
1004  sqlite3_result_value(pCtx, apVal[0]);
1005}
1006
1007/*
1008** The source code for several run-time loadable extensions is inserted
1009** below by the ../tool/mkshellc.tcl script.  Before processing that included
1010** code, we need to override some macros to make the included program code
1011** work here in the middle of this regular program.
1012*/
1013#define SQLITE_EXTENSION_INIT1
1014#define SQLITE_EXTENSION_INIT2(X) (void)(X)
1015
1016#if defined(_WIN32) && defined(_MSC_VER)
1017INCLUDE test_windirent.h
1018INCLUDE test_windirent.c
1019#define dirent DIRENT
1020#endif
1021INCLUDE ../ext/misc/memtrace.c
1022INCLUDE ../ext/misc/shathree.c
1023INCLUDE ../ext/misc/uint.c
1024INCLUDE ../ext/misc/decimal.c
1025INCLUDE ../ext/misc/ieee754.c
1026INCLUDE ../ext/misc/series.c
1027INCLUDE ../ext/misc/regexp.c
1028#ifndef SQLITE_SHELL_FIDDLE
1029INCLUDE ../ext/misc/fileio.c
1030INCLUDE ../ext/misc/completion.c
1031INCLUDE ../ext/misc/appendvfs.c
1032#endif
1033#ifdef SQLITE_HAVE_ZLIB
1034INCLUDE ../ext/misc/zipfile.c
1035INCLUDE ../ext/misc/sqlar.c
1036#endif
1037INCLUDE ../ext/expert/sqlite3expert.h
1038INCLUDE ../ext/expert/sqlite3expert.c
1039
1040#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
1041INCLUDE ../ext/misc/dbdata.c
1042#endif
1043
1044#if defined(SQLITE_ENABLE_SESSION)
1045/*
1046** State information for a single open session
1047*/
1048typedef struct OpenSession OpenSession;
1049struct OpenSession {
1050  char *zName;             /* Symbolic name for this session */
1051  int nFilter;             /* Number of xFilter rejection GLOB patterns */
1052  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
1053  sqlite3_session *p;      /* The open session */
1054};
1055#endif
1056
1057typedef struct ExpertInfo ExpertInfo;
1058struct ExpertInfo {
1059  sqlite3expert *pExpert;
1060  int bVerbose;
1061};
1062
1063/* A single line in the EQP output */
1064typedef struct EQPGraphRow EQPGraphRow;
1065struct EQPGraphRow {
1066  int iEqpId;           /* ID for this row */
1067  int iParentId;        /* ID of the parent row */
1068  EQPGraphRow *pNext;   /* Next row in sequence */
1069  char zText[1];        /* Text to display for this row */
1070};
1071
1072/* All EQP output is collected into an instance of the following */
1073typedef struct EQPGraph EQPGraph;
1074struct EQPGraph {
1075  EQPGraphRow *pRow;    /* Linked list of all rows of the EQP output */
1076  EQPGraphRow *pLast;   /* Last element of the pRow list */
1077  char zPrefix[100];    /* Graph prefix */
1078};
1079
1080/* Parameters affecting columnar mode result display (defaulting together) */
1081typedef struct ColModeOpts {
1082  int iWrap;            /* In columnar modes, wrap lines reaching this limit */
1083  u8 bQuote;            /* Quote results for .mode box and table */
1084  u8 bWordWrap;         /* In columnar modes, wrap at word boundaries  */
1085} ColModeOpts;
1086#define ColModeOpts_default { 60, 0, 0 }
1087#define ColModeOpts_default_qbox { 60, 1, 0 }
1088
1089/*
1090** State information about the database connection is contained in an
1091** instance of the following structure.
1092*/
1093typedef struct ShellState ShellState;
1094struct ShellState {
1095  sqlite3 *db;           /* The database */
1096  u8 autoExplain;        /* Automatically turn on .explain mode */
1097  u8 autoEQP;            /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1098  u8 autoEQPtest;        /* autoEQP is in test mode */
1099  u8 autoEQPtrace;       /* autoEQP is in trace mode */
1100  u8 scanstatsOn;        /* True to display scan stats before each finalize */
1101  u8 openMode;           /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1102  u8 doXdgOpen;          /* Invoke start/open/xdg-open in output_reset() */
1103  u8 nEqpLevel;          /* Depth of the EQP output graph */
1104  u8 eTraceType;         /* SHELL_TRACE_* value for type of trace */
1105  u8 bSafeMode;          /* True to prohibit unsafe operations */
1106  u8 bSafeModePersist;   /* The long-term value of bSafeMode */
1107  ColModeOpts cmOpts;    /* Option values affecting columnar mode output */
1108  unsigned statsOn;      /* True to display memory stats before each finalize */
1109  unsigned mEqpLines;    /* Mask of veritical lines in the EQP output graph */
1110  int inputNesting;      /* Track nesting level of .read and other redirects */
1111  int outCount;          /* Revert to stdout when reaching zero */
1112  int cnt;               /* Number of records displayed so far */
1113  int lineno;            /* Line number of last line read from in */
1114  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
1115  FILE *in;              /* Read commands from this stream */
1116  FILE *out;             /* Write results here */
1117  FILE *traceOut;        /* Output for sqlite3_trace() */
1118  int nErr;              /* Number of errors seen */
1119  int mode;              /* An output mode setting */
1120  int modePrior;         /* Saved mode */
1121  int cMode;             /* temporary output mode for the current query */
1122  int normalMode;        /* Output mode before ".explain on" */
1123  int writableSchema;    /* True if PRAGMA writable_schema=ON */
1124  int showHeader;        /* True to show column names in List or Column mode */
1125  int nCheck;            /* Number of ".check" commands run */
1126  unsigned nProgress;    /* Number of progress callbacks encountered */
1127  unsigned mxProgress;   /* Maximum progress callbacks before failing */
1128  unsigned flgProgress;  /* Flags for the progress callback */
1129  unsigned shellFlgs;    /* Various flags */
1130  unsigned priorShFlgs;  /* Saved copy of flags */
1131  sqlite3_int64 szMax;   /* --maxsize argument to .open */
1132  char *zDestTable;      /* Name of destination table when MODE_Insert */
1133  char *zTempFile;       /* Temporary file that might need deleting */
1134  char zTestcase[30];    /* Name of current test case */
1135  char colSeparator[20]; /* Column separator character for several modes */
1136  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1137  char colSepPrior[20];  /* Saved column separator */
1138  char rowSepPrior[20];  /* Saved row separator */
1139  int *colWidth;         /* Requested width of each column in columnar modes */
1140  int *actualWidth;      /* Actual width of each column */
1141  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
1142  char nullValue[20];    /* The text to print when a NULL comes back from
1143                         ** the database */
1144  char outfile[FILENAME_MAX]; /* Filename for *out */
1145  sqlite3_stmt *pStmt;   /* Current statement if any. */
1146  FILE *pLog;            /* Write log output here */
1147  struct AuxDb {         /* Storage space for auxiliary database connections */
1148    sqlite3 *db;               /* Connection pointer */
1149    const char *zDbFilename;   /* Filename used to open the connection */
1150    char *zFreeOnClose;        /* Free this memory allocation on close */
1151#if defined(SQLITE_ENABLE_SESSION)
1152    int nSession;              /* Number of active sessions */
1153    OpenSession aSession[4];   /* Array of sessions.  [0] is in focus. */
1154#endif
1155  } aAuxDb[5],           /* Array of all database connections */
1156    *pAuxDb;             /* Currently active database connection */
1157  int *aiIndent;         /* Array of indents used in MODE_Explain */
1158  int nIndent;           /* Size of array aiIndent[] */
1159  int iIndent;           /* Index of current op in aiIndent[] */
1160  char *zNonce;          /* Nonce for temporary safe-mode excapes */
1161  EQPGraph sGraph;       /* Information for the graphical EXPLAIN QUERY PLAN */
1162  ExpertInfo expert;     /* Valid if previous command was ".expert OPT..." */
1163#ifdef SQLITE_SHELL_FIDDLE
1164  struct {
1165    const char * zInput; /* Input string from wasm/JS proxy */
1166    const char * zPos;   /* Cursor pos into zInput */
1167  } wasm;
1168#endif
1169};
1170
1171#ifdef SQLITE_SHELL_FIDDLE
1172static ShellState shellState;
1173#endif
1174
1175
1176/* Allowed values for ShellState.autoEQP
1177*/
1178#define AUTOEQP_off      0           /* Automatic EXPLAIN QUERY PLAN is off */
1179#define AUTOEQP_on       1           /* Automatic EQP is on */
1180#define AUTOEQP_trigger  2           /* On and also show plans for triggers */
1181#define AUTOEQP_full     3           /* Show full EXPLAIN */
1182
1183/* Allowed values for ShellState.openMode
1184*/
1185#define SHELL_OPEN_UNSPEC      0      /* No open-mode specified */
1186#define SHELL_OPEN_NORMAL      1      /* Normal database file */
1187#define SHELL_OPEN_APPENDVFS   2      /* Use appendvfs */
1188#define SHELL_OPEN_ZIPFILE     3      /* Use the zipfile virtual table */
1189#define SHELL_OPEN_READONLY    4      /* Open a normal database read-only */
1190#define SHELL_OPEN_DESERIALIZE 5      /* Open using sqlite3_deserialize() */
1191#define SHELL_OPEN_HEXDB       6      /* Use "dbtotxt" output as data source */
1192
1193/* Allowed values for ShellState.eTraceType
1194*/
1195#define SHELL_TRACE_PLAIN      0      /* Show input SQL text */
1196#define SHELL_TRACE_EXPANDED   1      /* Show expanded SQL text */
1197#define SHELL_TRACE_NORMALIZED 2      /* Show normalized SQL text */
1198
1199/* Bits in the ShellState.flgProgress variable */
1200#define SHELL_PROGRESS_QUIET 0x01  /* Omit announcing every progress callback */
1201#define SHELL_PROGRESS_RESET 0x02  /* Reset the count when the progres
1202                                   ** callback limit is reached, and for each
1203                                   ** top-level SQL statement */
1204#define SHELL_PROGRESS_ONCE  0x04  /* Cancel the --limit after firing once */
1205
1206/*
1207** These are the allowed shellFlgs values
1208*/
1209#define SHFLG_Pagecache      0x00000001 /* The --pagecache option is used */
1210#define SHFLG_Lookaside      0x00000002 /* Lookaside memory is used */
1211#define SHFLG_Backslash      0x00000004 /* The --backslash option is used */
1212#define SHFLG_PreserveRowid  0x00000008 /* .dump preserves rowid values */
1213#define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
1214#define SHFLG_CountChanges   0x00000020 /* .changes setting */
1215#define SHFLG_Echo           0x00000040 /* .echo on/off, or --echo setting */
1216#define SHFLG_HeaderSet      0x00000080 /* showHeader has been specified */
1217#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
1218#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
1219
1220/*
1221** Macros for testing and setting shellFlgs
1222*/
1223#define ShellHasFlag(P,X)    (((P)->shellFlgs & (X))!=0)
1224#define ShellSetFlag(P,X)    ((P)->shellFlgs|=(X))
1225#define ShellClearFlag(P,X)  ((P)->shellFlgs&=(~(X)))
1226
1227/*
1228** These are the allowed modes.
1229*/
1230#define MODE_Line     0  /* One column per line.  Blank line between records */
1231#define MODE_Column   1  /* One record per line in neat columns */
1232#define MODE_List     2  /* One record per line with a separator */
1233#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
1234#define MODE_Html     4  /* Generate an XHTML table */
1235#define MODE_Insert   5  /* Generate SQL "insert" statements */
1236#define MODE_Quote    6  /* Quote values as for SQL */
1237#define MODE_Tcl      7  /* Generate ANSI-C or TCL quoted elements */
1238#define MODE_Csv      8  /* Quote strings, numbers are plain */
1239#define MODE_Explain  9  /* Like MODE_Column, but do not truncate data */
1240#define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
1241#define MODE_Pretty  11  /* Pretty-print schemas */
1242#define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
1243#define MODE_Json    13  /* Output JSON */
1244#define MODE_Markdown 14 /* Markdown formatting */
1245#define MODE_Table   15  /* MySQL-style table formatting */
1246#define MODE_Box     16  /* Unicode box-drawing characters */
1247#define MODE_Count   17  /* Output only a count of the rows of output */
1248#define MODE_Off     18  /* No query output shown */
1249
1250static const char *modeDescr[] = {
1251  "line",
1252  "column",
1253  "list",
1254  "semi",
1255  "html",
1256  "insert",
1257  "quote",
1258  "tcl",
1259  "csv",
1260  "explain",
1261  "ascii",
1262  "prettyprint",
1263  "eqp",
1264  "json",
1265  "markdown",
1266  "table",
1267  "box",
1268  "count",
1269  "off"
1270};
1271
1272/*
1273** These are the column/row/line separators used by the various
1274** import/export modes.
1275*/
1276#define SEP_Column    "|"
1277#define SEP_Row       "\n"
1278#define SEP_Tab       "\t"
1279#define SEP_Space     " "
1280#define SEP_Comma     ","
1281#define SEP_CrLf      "\r\n"
1282#define SEP_Unit      "\x1F"
1283#define SEP_Record    "\x1E"
1284
1285/*
1286** Limit input nesting via .read or any other input redirect.
1287** It's not too expensive, so a generous allowance can be made.
1288*/
1289#define MAX_INPUT_NESTING 25
1290
1291/*
1292** A callback for the sqlite3_log() interface.
1293*/
1294static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1295  ShellState *p = (ShellState*)pArg;
1296  if( p->pLog==0 ) return;
1297  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1298  fflush(p->pLog);
1299}
1300
1301/*
1302** SQL function:  shell_putsnl(X)
1303**
1304** Write the text X to the screen (or whatever output is being directed)
1305** adding a newline at the end, and then return X.
1306*/
1307static void shellPutsFunc(
1308  sqlite3_context *pCtx,
1309  int nVal,
1310  sqlite3_value **apVal
1311){
1312  ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1313  (void)nVal;
1314  utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1315  sqlite3_result_value(pCtx, apVal[0]);
1316}
1317
1318/*
1319** If in safe mode, print an error message described by the arguments
1320** and exit immediately.
1321*/
1322static void failIfSafeMode(
1323  ShellState *p,
1324  const char *zErrMsg,
1325  ...
1326){
1327  if( p->bSafeMode ){
1328    va_list ap;
1329    char *zMsg;
1330    va_start(ap, zErrMsg);
1331    zMsg = sqlite3_vmprintf(zErrMsg, ap);
1332    va_end(ap);
1333    raw_printf(stderr, "line %d: ", p->lineno);
1334    utf8_printf(stderr, "%s\n", zMsg);
1335    exit(1);
1336  }
1337}
1338
1339/*
1340** SQL function:   edit(VALUE)
1341**                 edit(VALUE,EDITOR)
1342**
1343** These steps:
1344**
1345**     (1) Write VALUE into a temporary file.
1346**     (2) Run program EDITOR on that temporary file.
1347**     (3) Read the temporary file back and return its content as the result.
1348**     (4) Delete the temporary file
1349**
1350** If the EDITOR argument is omitted, use the value in the VISUAL
1351** environment variable.  If still there is no EDITOR, through an error.
1352**
1353** Also throw an error if the EDITOR program returns a non-zero exit code.
1354*/
1355#ifndef SQLITE_NOHAVE_SYSTEM
1356static void editFunc(
1357  sqlite3_context *context,
1358  int argc,
1359  sqlite3_value **argv
1360){
1361  const char *zEditor;
1362  char *zTempFile = 0;
1363  sqlite3 *db;
1364  char *zCmd = 0;
1365  int bBin;
1366  int rc;
1367  int hasCRNL = 0;
1368  FILE *f = 0;
1369  sqlite3_int64 sz;
1370  sqlite3_int64 x;
1371  unsigned char *p = 0;
1372
1373  if( argc==2 ){
1374    zEditor = (const char*)sqlite3_value_text(argv[1]);
1375  }else{
1376    zEditor = getenv("VISUAL");
1377  }
1378  if( zEditor==0 ){
1379    sqlite3_result_error(context, "no editor for edit()", -1);
1380    return;
1381  }
1382  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1383    sqlite3_result_error(context, "NULL input to edit()", -1);
1384    return;
1385  }
1386  db = sqlite3_context_db_handle(context);
1387  zTempFile = 0;
1388  sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1389  if( zTempFile==0 ){
1390    sqlite3_uint64 r = 0;
1391    sqlite3_randomness(sizeof(r), &r);
1392    zTempFile = sqlite3_mprintf("temp%llx", r);
1393    if( zTempFile==0 ){
1394      sqlite3_result_error_nomem(context);
1395      return;
1396    }
1397  }
1398  bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1399  /* When writing the file to be edited, do \n to \r\n conversions on systems
1400  ** that want \r\n line endings */
1401  f = fopen(zTempFile, bBin ? "wb" : "w");
1402  if( f==0 ){
1403    sqlite3_result_error(context, "edit() cannot open temp file", -1);
1404    goto edit_func_end;
1405  }
1406  sz = sqlite3_value_bytes(argv[0]);
1407  if( bBin ){
1408    x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
1409  }else{
1410    const char *z = (const char*)sqlite3_value_text(argv[0]);
1411    /* Remember whether or not the value originally contained \r\n */
1412    if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
1413    x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
1414  }
1415  fclose(f);
1416  f = 0;
1417  if( x!=sz ){
1418    sqlite3_result_error(context, "edit() could not write the whole file", -1);
1419    goto edit_func_end;
1420  }
1421  zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1422  if( zCmd==0 ){
1423    sqlite3_result_error_nomem(context);
1424    goto edit_func_end;
1425  }
1426  rc = system(zCmd);
1427  sqlite3_free(zCmd);
1428  if( rc ){
1429    sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1430    goto edit_func_end;
1431  }
1432  f = fopen(zTempFile, "rb");
1433  if( f==0 ){
1434    sqlite3_result_error(context,
1435      "edit() cannot reopen temp file after edit", -1);
1436    goto edit_func_end;
1437  }
1438  fseek(f, 0, SEEK_END);
1439  sz = ftell(f);
1440  rewind(f);
1441  p = sqlite3_malloc64( sz+1 );
1442  if( p==0 ){
1443    sqlite3_result_error_nomem(context);
1444    goto edit_func_end;
1445  }
1446  x = fread(p, 1, (size_t)sz, f);
1447  fclose(f);
1448  f = 0;
1449  if( x!=sz ){
1450    sqlite3_result_error(context, "could not read back the whole file", -1);
1451    goto edit_func_end;
1452  }
1453  if( bBin ){
1454    sqlite3_result_blob64(context, p, sz, sqlite3_free);
1455  }else{
1456    sqlite3_int64 i, j;
1457    if( hasCRNL ){
1458      /* If the original contains \r\n then do no conversions back to \n */
1459    }else{
1460      /* If the file did not originally contain \r\n then convert any new
1461      ** \r\n back into \n */
1462      for(i=j=0; i<sz; i++){
1463        if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1464        p[j++] = p[i];
1465      }
1466      sz = j;
1467      p[sz] = 0;
1468    }
1469    sqlite3_result_text64(context, (const char*)p, sz,
1470                          sqlite3_free, SQLITE_UTF8);
1471  }
1472  p = 0;
1473
1474edit_func_end:
1475  if( f ) fclose(f);
1476  unlink(zTempFile);
1477  sqlite3_free(zTempFile);
1478  sqlite3_free(p);
1479}
1480#endif /* SQLITE_NOHAVE_SYSTEM */
1481
1482/*
1483** Save or restore the current output mode
1484*/
1485static void outputModePush(ShellState *p){
1486  p->modePrior = p->mode;
1487  p->priorShFlgs = p->shellFlgs;
1488  memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1489  memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1490}
1491static void outputModePop(ShellState *p){
1492  p->mode = p->modePrior;
1493  p->shellFlgs = p->priorShFlgs;
1494  memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1495  memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1496}
1497
1498/*
1499** Output the given string as a hex-encoded blob (eg. X'1234' )
1500*/
1501static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1502  int i;
1503  char *zBlob = (char *)pBlob;
1504  raw_printf(out,"X'");
1505  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1506  raw_printf(out,"'");
1507}
1508
1509/*
1510** Find a string that is not found anywhere in z[].  Return a pointer
1511** to that string.
1512**
1513** Try to use zA and zB first.  If both of those are already found in z[]
1514** then make up some string and store it in the buffer zBuf.
1515*/
1516static const char *unused_string(
1517  const char *z,                    /* Result must not appear anywhere in z */
1518  const char *zA, const char *zB,   /* Try these first */
1519  char *zBuf                        /* Space to store a generated string */
1520){
1521  unsigned i = 0;
1522  if( strstr(z, zA)==0 ) return zA;
1523  if( strstr(z, zB)==0 ) return zB;
1524  do{
1525    sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1526  }while( strstr(z,zBuf)!=0 );
1527  return zBuf;
1528}
1529
1530/*
1531** Output the given string as a quoted string using SQL quoting conventions.
1532**
1533** See also: output_quoted_escaped_string()
1534*/
1535static void output_quoted_string(FILE *out, const char *z){
1536  int i;
1537  char c;
1538  setBinaryMode(out, 1);
1539  for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1540  if( c==0 ){
1541    utf8_printf(out,"'%s'",z);
1542  }else{
1543    raw_printf(out, "'");
1544    while( *z ){
1545      for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1546      if( c=='\'' ) i++;
1547      if( i ){
1548        utf8_printf(out, "%.*s", i, z);
1549        z += i;
1550      }
1551      if( c=='\'' ){
1552        raw_printf(out, "'");
1553        continue;
1554      }
1555      if( c==0 ){
1556        break;
1557      }
1558      z++;
1559    }
1560    raw_printf(out, "'");
1561  }
1562  setTextMode(out, 1);
1563}
1564
1565/*
1566** Output the given string as a quoted string using SQL quoting conventions.
1567** Additionallly , escape the "\n" and "\r" characters so that they do not
1568** get corrupted by end-of-line translation facilities in some operating
1569** systems.
1570**
1571** This is like output_quoted_string() but with the addition of the \r\n
1572** escape mechanism.
1573*/
1574static void output_quoted_escaped_string(FILE *out, const char *z){
1575  int i;
1576  char c;
1577  setBinaryMode(out, 1);
1578  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1579  if( c==0 ){
1580    utf8_printf(out,"'%s'",z);
1581  }else{
1582    const char *zNL = 0;
1583    const char *zCR = 0;
1584    int nNL = 0;
1585    int nCR = 0;
1586    char zBuf1[20], zBuf2[20];
1587    for(i=0; z[i]; i++){
1588      if( z[i]=='\n' ) nNL++;
1589      if( z[i]=='\r' ) nCR++;
1590    }
1591    if( nNL ){
1592      raw_printf(out, "replace(");
1593      zNL = unused_string(z, "\\n", "\\012", zBuf1);
1594    }
1595    if( nCR ){
1596      raw_printf(out, "replace(");
1597      zCR = unused_string(z, "\\r", "\\015", zBuf2);
1598    }
1599    raw_printf(out, "'");
1600    while( *z ){
1601      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1602      if( c=='\'' ) i++;
1603      if( i ){
1604        utf8_printf(out, "%.*s", i, z);
1605        z += i;
1606      }
1607      if( c=='\'' ){
1608        raw_printf(out, "'");
1609        continue;
1610      }
1611      if( c==0 ){
1612        break;
1613      }
1614      z++;
1615      if( c=='\n' ){
1616        raw_printf(out, "%s", zNL);
1617        continue;
1618      }
1619      raw_printf(out, "%s", zCR);
1620    }
1621    raw_printf(out, "'");
1622    if( nCR ){
1623      raw_printf(out, ",'%s',char(13))", zCR);
1624    }
1625    if( nNL ){
1626      raw_printf(out, ",'%s',char(10))", zNL);
1627    }
1628  }
1629  setTextMode(out, 1);
1630}
1631
1632/*
1633** Output the given string as a quoted according to C or TCL quoting rules.
1634*/
1635static void output_c_string(FILE *out, const char *z){
1636  unsigned int c;
1637  fputc('"', out);
1638  while( (c = *(z++))!=0 ){
1639    if( c=='\\' ){
1640      fputc(c, out);
1641      fputc(c, out);
1642    }else if( c=='"' ){
1643      fputc('\\', out);
1644      fputc('"', out);
1645    }else if( c=='\t' ){
1646      fputc('\\', out);
1647      fputc('t', out);
1648    }else if( c=='\n' ){
1649      fputc('\\', out);
1650      fputc('n', out);
1651    }else if( c=='\r' ){
1652      fputc('\\', out);
1653      fputc('r', out);
1654    }else if( !isprint(c&0xff) ){
1655      raw_printf(out, "\\%03o", c&0xff);
1656    }else{
1657      fputc(c, out);
1658    }
1659  }
1660  fputc('"', out);
1661}
1662
1663/*
1664** Output the given string as a quoted according to JSON quoting rules.
1665*/
1666static void output_json_string(FILE *out, const char *z, int n){
1667  unsigned int c;
1668  if( n<0 ) n = (int)strlen(z);
1669  fputc('"', out);
1670  while( n-- ){
1671    c = *(z++);
1672    if( c=='\\' || c=='"' ){
1673      fputc('\\', out);
1674      fputc(c, out);
1675    }else if( c<=0x1f ){
1676      fputc('\\', out);
1677      if( c=='\b' ){
1678        fputc('b', out);
1679      }else if( c=='\f' ){
1680        fputc('f', out);
1681      }else if( c=='\n' ){
1682        fputc('n', out);
1683      }else if( c=='\r' ){
1684        fputc('r', out);
1685      }else if( c=='\t' ){
1686        fputc('t', out);
1687      }else{
1688         raw_printf(out, "u%04x",c);
1689      }
1690    }else{
1691      fputc(c, out);
1692    }
1693  }
1694  fputc('"', out);
1695}
1696
1697/*
1698** Output the given string with characters that are special to
1699** HTML escaped.
1700*/
1701static void output_html_string(FILE *out, const char *z){
1702  int i;
1703  if( z==0 ) z = "";
1704  while( *z ){
1705    for(i=0;   z[i]
1706            && z[i]!='<'
1707            && z[i]!='&'
1708            && z[i]!='>'
1709            && z[i]!='\"'
1710            && z[i]!='\'';
1711        i++){}
1712    if( i>0 ){
1713      utf8_printf(out,"%.*s",i,z);
1714    }
1715    if( z[i]=='<' ){
1716      raw_printf(out,"&lt;");
1717    }else if( z[i]=='&' ){
1718      raw_printf(out,"&amp;");
1719    }else if( z[i]=='>' ){
1720      raw_printf(out,"&gt;");
1721    }else if( z[i]=='\"' ){
1722      raw_printf(out,"&quot;");
1723    }else if( z[i]=='\'' ){
1724      raw_printf(out,"&#39;");
1725    }else{
1726      break;
1727    }
1728    z += i + 1;
1729  }
1730}
1731
1732/*
1733** If a field contains any character identified by a 1 in the following
1734** array, then the string must be quoted for CSV.
1735*/
1736static const char needCsvQuote[] = {
1737  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1738  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1739  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
1740  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
1741  0, 0, 0, 0, 0, 0, 0, 0,   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, 1,
1745  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
1746  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 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};
1754
1755/*
1756** Output a single term of CSV.  Actually, p->colSeparator is used for
1757** the separator, which may or may not be a comma.  p->nullValue is
1758** the null value.  Strings are quoted if necessary.  The separator
1759** is only issued if bSep is true.
1760*/
1761static void output_csv(ShellState *p, const char *z, int bSep){
1762  FILE *out = p->out;
1763  if( z==0 ){
1764    utf8_printf(out,"%s",p->nullValue);
1765  }else{
1766    unsigned i;
1767    for(i=0; z[i]; i++){
1768      if( needCsvQuote[((unsigned char*)z)[i]] ){
1769        i = 0;
1770        break;
1771      }
1772    }
1773    if( i==0 || strstr(z, p->colSeparator)!=0 ){
1774      char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1775      shell_check_oom(zQuoted);
1776      utf8_printf(out, "%s", zQuoted);
1777      sqlite3_free(zQuoted);
1778    }else{
1779      utf8_printf(out, "%s", z);
1780    }
1781  }
1782  if( bSep ){
1783    utf8_printf(p->out, "%s", p->colSeparator);
1784  }
1785}
1786
1787/*
1788** This routine runs when the user presses Ctrl-C
1789*/
1790static void interrupt_handler(int NotUsed){
1791  UNUSED_PARAMETER(NotUsed);
1792  seenInterrupt++;
1793  if( seenInterrupt>2 ) exit(1);
1794  if( globalDb ) sqlite3_interrupt(globalDb);
1795}
1796
1797#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1798/*
1799** This routine runs for console events (e.g. Ctrl-C) on Win32
1800*/
1801static BOOL WINAPI ConsoleCtrlHandler(
1802  DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1803){
1804  if( dwCtrlType==CTRL_C_EVENT ){
1805    interrupt_handler(0);
1806    return TRUE;
1807  }
1808  return FALSE;
1809}
1810#endif
1811
1812#ifndef SQLITE_OMIT_AUTHORIZATION
1813/*
1814** This authorizer runs in safe mode.
1815*/
1816static int safeModeAuth(
1817  void *pClientData,
1818  int op,
1819  const char *zA1,
1820  const char *zA2,
1821  const char *zA3,
1822  const char *zA4
1823){
1824  ShellState *p = (ShellState*)pClientData;
1825  static const char *azProhibitedFunctions[] = {
1826    "edit",
1827    "fts3_tokenizer",
1828    "load_extension",
1829    "readfile",
1830    "writefile",
1831    "zipfile",
1832    "zipfile_cds",
1833  };
1834  UNUSED_PARAMETER(zA2);
1835  UNUSED_PARAMETER(zA3);
1836  UNUSED_PARAMETER(zA4);
1837  switch( op ){
1838    case SQLITE_ATTACH: {
1839#ifndef SQLITE_SHELL_FIDDLE
1840      /* In WASM builds the filesystem is a virtual sandbox, so
1841      ** there's no harm in using ATTACH. */
1842      failIfSafeMode(p, "cannot run ATTACH in safe mode");
1843#endif
1844      break;
1845    }
1846    case SQLITE_FUNCTION: {
1847      int i;
1848      for(i=0; i<ArraySize(azProhibitedFunctions); i++){
1849        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
1850          failIfSafeMode(p, "cannot use the %s() function in safe mode",
1851                         azProhibitedFunctions[i]);
1852        }
1853      }
1854      break;
1855    }
1856  }
1857  return SQLITE_OK;
1858}
1859
1860/*
1861** When the ".auth ON" is set, the following authorizer callback is
1862** invoked.  It always returns SQLITE_OK.
1863*/
1864static int shellAuth(
1865  void *pClientData,
1866  int op,
1867  const char *zA1,
1868  const char *zA2,
1869  const char *zA3,
1870  const char *zA4
1871){
1872  ShellState *p = (ShellState*)pClientData;
1873  static const char *azAction[] = { 0,
1874     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
1875     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
1876     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
1877     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
1878     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
1879     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
1880     "PRAGMA",               "READ",                 "SELECT",
1881     "TRANSACTION",          "UPDATE",               "ATTACH",
1882     "DETACH",               "ALTER_TABLE",          "REINDEX",
1883     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
1884     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
1885  };
1886  int i;
1887  const char *az[4];
1888  az[0] = zA1;
1889  az[1] = zA2;
1890  az[2] = zA3;
1891  az[3] = zA4;
1892  utf8_printf(p->out, "authorizer: %s", azAction[op]);
1893  for(i=0; i<4; i++){
1894    raw_printf(p->out, " ");
1895    if( az[i] ){
1896      output_c_string(p->out, az[i]);
1897    }else{
1898      raw_printf(p->out, "NULL");
1899    }
1900  }
1901  raw_printf(p->out, "\n");
1902  if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4);
1903  return SQLITE_OK;
1904}
1905#endif
1906
1907/*
1908** Print a schema statement.  Part of MODE_Semi and MODE_Pretty output.
1909**
1910** This routine converts some CREATE TABLE statements for shadow tables
1911** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1912*/
1913static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1914  if( z==0 ) return;
1915  if( zTail==0 ) return;
1916  if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1917    utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1918  }else{
1919    utf8_printf(out, "%s%s", z, zTail);
1920  }
1921}
1922static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1923  char c = z[n];
1924  z[n] = 0;
1925  printSchemaLine(out, z, zTail);
1926  z[n] = c;
1927}
1928
1929/*
1930** Return true if string z[] has nothing but whitespace and comments to the
1931** end of the first line.
1932*/
1933static int wsToEol(const char *z){
1934  int i;
1935  for(i=0; z[i]; i++){
1936    if( z[i]=='\n' ) return 1;
1937    if( IsSpace(z[i]) ) continue;
1938    if( z[i]=='-' && z[i+1]=='-' ) return 1;
1939    return 0;
1940  }
1941  return 1;
1942}
1943
1944/*
1945** Add a new entry to the EXPLAIN QUERY PLAN data
1946*/
1947static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
1948  EQPGraphRow *pNew;
1949  int nText = strlen30(zText);
1950  if( p->autoEQPtest ){
1951    utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1952  }
1953  pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1954  shell_check_oom(pNew);
1955  pNew->iEqpId = iEqpId;
1956  pNew->iParentId = p2;
1957  memcpy(pNew->zText, zText, nText+1);
1958  pNew->pNext = 0;
1959  if( p->sGraph.pLast ){
1960    p->sGraph.pLast->pNext = pNew;
1961  }else{
1962    p->sGraph.pRow = pNew;
1963  }
1964  p->sGraph.pLast = pNew;
1965}
1966
1967/*
1968** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1969** in p->sGraph.
1970*/
1971static void eqp_reset(ShellState *p){
1972  EQPGraphRow *pRow, *pNext;
1973  for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1974    pNext = pRow->pNext;
1975    sqlite3_free(pRow);
1976  }
1977  memset(&p->sGraph, 0, sizeof(p->sGraph));
1978}
1979
1980/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1981** pOld, or return the first such line if pOld is NULL
1982*/
1983static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
1984  EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
1985  while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
1986  return pRow;
1987}
1988
1989/* Render a single level of the graph that has iEqpId as its parent.  Called
1990** recursively to render sublevels.
1991*/
1992static void eqp_render_level(ShellState *p, int iEqpId){
1993  EQPGraphRow *pRow, *pNext;
1994  int n = strlen30(p->sGraph.zPrefix);
1995  char *z;
1996  for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1997    pNext = eqp_next_row(p, iEqpId, pRow);
1998    z = pRow->zText;
1999    utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
2000                pNext ? "|--" : "`--", z);
2001    if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
2002      memcpy(&p->sGraph.zPrefix[n], pNext ? "|  " : "   ", 4);
2003      eqp_render_level(p, pRow->iEqpId);
2004      p->sGraph.zPrefix[n] = 0;
2005    }
2006  }
2007}
2008
2009/*
2010** Display and reset the EXPLAIN QUERY PLAN data
2011*/
2012static void eqp_render(ShellState *p){
2013  EQPGraphRow *pRow = p->sGraph.pRow;
2014  if( pRow ){
2015    if( pRow->zText[0]=='-' ){
2016      if( pRow->pNext==0 ){
2017        eqp_reset(p);
2018        return;
2019      }
2020      utf8_printf(p->out, "%s\n", pRow->zText+3);
2021      p->sGraph.pRow = pRow->pNext;
2022      sqlite3_free(pRow);
2023    }else{
2024      utf8_printf(p->out, "QUERY PLAN\n");
2025    }
2026    p->sGraph.zPrefix[0] = 0;
2027    eqp_render_level(p, 0);
2028    eqp_reset(p);
2029  }
2030}
2031
2032#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2033/*
2034** Progress handler callback.
2035*/
2036static int progress_handler(void *pClientData) {
2037  ShellState *p = (ShellState*)pClientData;
2038  p->nProgress++;
2039  if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
2040    raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
2041    if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
2042    if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
2043    return 1;
2044  }
2045  if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
2046    raw_printf(p->out, "Progress %u\n", p->nProgress);
2047  }
2048  return 0;
2049}
2050#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
2051
2052/*
2053** Print N dashes
2054*/
2055static void print_dashes(FILE *out, int N){
2056  const char zDash[] = "--------------------------------------------------";
2057  const int nDash = sizeof(zDash) - 1;
2058  while( N>nDash ){
2059    fputs(zDash, out);
2060    N -= nDash;
2061  }
2062  raw_printf(out, "%.*s", N, zDash);
2063}
2064
2065/*
2066** Print a markdown or table-style row separator using ascii-art
2067*/
2068static void print_row_separator(
2069  ShellState *p,
2070  int nArg,
2071  const char *zSep
2072){
2073  int i;
2074  if( nArg>0 ){
2075    fputs(zSep, p->out);
2076    print_dashes(p->out, p->actualWidth[0]+2);
2077    for(i=1; i<nArg; i++){
2078      fputs(zSep, p->out);
2079      print_dashes(p->out, p->actualWidth[i]+2);
2080    }
2081    fputs(zSep, p->out);
2082  }
2083  fputs("\n", p->out);
2084}
2085
2086/*
2087** This is the callback routine that the shell
2088** invokes for each row of a query result.
2089*/
2090static int shell_callback(
2091  void *pArg,
2092  int nArg,        /* Number of result columns */
2093  char **azArg,    /* Text of each result column */
2094  char **azCol,    /* Column names */
2095  int *aiType      /* Column types.  Might be NULL */
2096){
2097  int i;
2098  ShellState *p = (ShellState*)pArg;
2099
2100  if( azArg==0 ) return 0;
2101  switch( p->cMode ){
2102    case MODE_Count:
2103    case MODE_Off: {
2104      break;
2105    }
2106    case MODE_Line: {
2107      int w = 5;
2108      if( azArg==0 ) break;
2109      for(i=0; i<nArg; i++){
2110        int len = strlen30(azCol[i] ? azCol[i] : "");
2111        if( len>w ) w = len;
2112      }
2113      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2114      for(i=0; i<nArg; i++){
2115        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2116                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2117      }
2118      break;
2119    }
2120    case MODE_Explain: {
2121      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
2122      if( nArg>ArraySize(aExplainWidth) ){
2123        nArg = ArraySize(aExplainWidth);
2124      }
2125      if( p->cnt++==0 ){
2126        for(i=0; i<nArg; i++){
2127          int w = aExplainWidth[i];
2128          utf8_width_print(p->out, w, azCol[i]);
2129          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2130        }
2131        for(i=0; i<nArg; i++){
2132          int w = aExplainWidth[i];
2133          print_dashes(p->out, w);
2134          fputs(i==nArg-1 ? "\n" : "  ", p->out);
2135        }
2136      }
2137      if( azArg==0 ) break;
2138      for(i=0; i<nArg; i++){
2139        int w = aExplainWidth[i];
2140        if( i==nArg-1 ) w = 0;
2141        if( azArg[i] && strlenChar(azArg[i])>w ){
2142          w = strlenChar(azArg[i]);
2143        }
2144        if( i==1 && p->aiIndent && p->pStmt ){
2145          if( p->iIndent<p->nIndent ){
2146            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2147          }
2148          p->iIndent++;
2149        }
2150        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2151        fputs(i==nArg-1 ? "\n" : "  ", p->out);
2152      }
2153      break;
2154    }
2155    case MODE_Semi: {   /* .schema and .fullschema output */
2156      printSchemaLine(p->out, azArg[0], ";\n");
2157      break;
2158    }
2159    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
2160      char *z;
2161      int j;
2162      int nParen = 0;
2163      char cEnd = 0;
2164      char c;
2165      int nLine = 0;
2166      assert( nArg==1 );
2167      if( azArg[0]==0 ) break;
2168      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2169       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2170      ){
2171        utf8_printf(p->out, "%s;\n", azArg[0]);
2172        break;
2173      }
2174      z = sqlite3_mprintf("%s", azArg[0]);
2175      shell_check_oom(z);
2176      j = 0;
2177      for(i=0; IsSpace(z[i]); i++){}
2178      for(; (c = z[i])!=0; i++){
2179        if( IsSpace(c) ){
2180          if( z[j-1]=='\r' ) z[j-1] = '\n';
2181          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2182        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2183          j--;
2184        }
2185        z[j++] = c;
2186      }
2187      while( j>0 && IsSpace(z[j-1]) ){ j--; }
2188      z[j] = 0;
2189      if( strlen30(z)>=79 ){
2190        for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
2191          if( c==cEnd ){
2192            cEnd = 0;
2193          }else if( c=='"' || c=='\'' || c=='`' ){
2194            cEnd = c;
2195          }else if( c=='[' ){
2196            cEnd = ']';
2197          }else if( c=='-' && z[i+1]=='-' ){
2198            cEnd = '\n';
2199          }else if( c=='(' ){
2200            nParen++;
2201          }else if( c==')' ){
2202            nParen--;
2203            if( nLine>0 && nParen==0 && j>0 ){
2204              printSchemaLineN(p->out, z, j, "\n");
2205              j = 0;
2206            }
2207          }
2208          z[j++] = c;
2209          if( nParen==1 && cEnd==0
2210           && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
2211          ){
2212            if( c=='\n' ) j--;
2213            printSchemaLineN(p->out, z, j, "\n  ");
2214            j = 0;
2215            nLine++;
2216            while( IsSpace(z[i+1]) ){ i++; }
2217          }
2218        }
2219        z[j] = 0;
2220      }
2221      printSchemaLine(p->out, z, ";\n");
2222      sqlite3_free(z);
2223      break;
2224    }
2225    case MODE_List: {
2226      if( p->cnt++==0 && p->showHeader ){
2227        for(i=0; i<nArg; i++){
2228          utf8_printf(p->out,"%s%s",azCol[i],
2229                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
2230        }
2231      }
2232      if( azArg==0 ) break;
2233      for(i=0; i<nArg; i++){
2234        char *z = azArg[i];
2235        if( z==0 ) z = p->nullValue;
2236        utf8_printf(p->out, "%s", z);
2237        if( i<nArg-1 ){
2238          utf8_printf(p->out, "%s", p->colSeparator);
2239        }else{
2240          utf8_printf(p->out, "%s", p->rowSeparator);
2241        }
2242      }
2243      break;
2244    }
2245    case MODE_Html: {
2246      if( p->cnt++==0 && p->showHeader ){
2247        raw_printf(p->out,"<TR>");
2248        for(i=0; i<nArg; i++){
2249          raw_printf(p->out,"<TH>");
2250          output_html_string(p->out, azCol[i]);
2251          raw_printf(p->out,"</TH>\n");
2252        }
2253        raw_printf(p->out,"</TR>\n");
2254      }
2255      if( azArg==0 ) break;
2256      raw_printf(p->out,"<TR>");
2257      for(i=0; i<nArg; i++){
2258        raw_printf(p->out,"<TD>");
2259        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2260        raw_printf(p->out,"</TD>\n");
2261      }
2262      raw_printf(p->out,"</TR>\n");
2263      break;
2264    }
2265    case MODE_Tcl: {
2266      if( p->cnt++==0 && p->showHeader ){
2267        for(i=0; i<nArg; i++){
2268          output_c_string(p->out,azCol[i] ? azCol[i] : "");
2269          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2270        }
2271        utf8_printf(p->out, "%s", p->rowSeparator);
2272      }
2273      if( azArg==0 ) break;
2274      for(i=0; i<nArg; i++){
2275        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2276        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2277      }
2278      utf8_printf(p->out, "%s", p->rowSeparator);
2279      break;
2280    }
2281    case MODE_Csv: {
2282      setBinaryMode(p->out, 1);
2283      if( p->cnt++==0 && p->showHeader ){
2284        for(i=0; i<nArg; i++){
2285          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2286        }
2287        utf8_printf(p->out, "%s", p->rowSeparator);
2288      }
2289      if( nArg>0 ){
2290        for(i=0; i<nArg; i++){
2291          output_csv(p, azArg[i], i<nArg-1);
2292        }
2293        utf8_printf(p->out, "%s", p->rowSeparator);
2294      }
2295      setTextMode(p->out, 1);
2296      break;
2297    }
2298    case MODE_Insert: {
2299      if( azArg==0 ) break;
2300      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2301      if( p->showHeader ){
2302        raw_printf(p->out,"(");
2303        for(i=0; i<nArg; i++){
2304          if( i>0 ) raw_printf(p->out, ",");
2305          if( quoteChar(azCol[i]) ){
2306            char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2307            shell_check_oom(z);
2308            utf8_printf(p->out, "%s", z);
2309            sqlite3_free(z);
2310          }else{
2311            raw_printf(p->out, "%s", azCol[i]);
2312          }
2313        }
2314        raw_printf(p->out,")");
2315      }
2316      p->cnt++;
2317      for(i=0; i<nArg; i++){
2318        raw_printf(p->out, i>0 ? "," : " VALUES(");
2319        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2320          utf8_printf(p->out,"NULL");
2321        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2322          if( ShellHasFlag(p, SHFLG_Newlines) ){
2323            output_quoted_string(p->out, azArg[i]);
2324          }else{
2325            output_quoted_escaped_string(p->out, azArg[i]);
2326          }
2327        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2328          utf8_printf(p->out,"%s", azArg[i]);
2329        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2330          char z[50];
2331          double r = sqlite3_column_double(p->pStmt, i);
2332          sqlite3_uint64 ur;
2333          memcpy(&ur,&r,sizeof(r));
2334          if( ur==0x7ff0000000000000LL ){
2335            raw_printf(p->out, "1e999");
2336          }else if( ur==0xfff0000000000000LL ){
2337            raw_printf(p->out, "-1e999");
2338          }else{
2339            sqlite3_int64 ir = (sqlite3_int64)r;
2340            if( r==(double)ir ){
2341              sqlite3_snprintf(50,z,"%lld.0", ir);
2342            }else{
2343              sqlite3_snprintf(50,z,"%!.20g", r);
2344            }
2345            raw_printf(p->out, "%s", z);
2346          }
2347        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2348          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2349          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2350          output_hex_blob(p->out, pBlob, nBlob);
2351        }else if( isNumber(azArg[i], 0) ){
2352          utf8_printf(p->out,"%s", azArg[i]);
2353        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2354          output_quoted_string(p->out, azArg[i]);
2355        }else{
2356          output_quoted_escaped_string(p->out, azArg[i]);
2357        }
2358      }
2359      raw_printf(p->out,");\n");
2360      break;
2361    }
2362    case MODE_Json: {
2363      if( azArg==0 ) break;
2364      if( p->cnt==0 ){
2365        fputs("[{", p->out);
2366      }else{
2367        fputs(",\n{", p->out);
2368      }
2369      p->cnt++;
2370      for(i=0; i<nArg; i++){
2371        output_json_string(p->out, azCol[i], -1);
2372        putc(':', p->out);
2373        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2374          fputs("null",p->out);
2375        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2376          char z[50];
2377          double r = sqlite3_column_double(p->pStmt, i);
2378          sqlite3_uint64 ur;
2379          memcpy(&ur,&r,sizeof(r));
2380          if( ur==0x7ff0000000000000LL ){
2381            raw_printf(p->out, "1e999");
2382          }else if( ur==0xfff0000000000000LL ){
2383            raw_printf(p->out, "-1e999");
2384          }else{
2385            sqlite3_snprintf(50,z,"%!.20g", r);
2386            raw_printf(p->out, "%s", z);
2387          }
2388        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2389          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2390          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2391          output_json_string(p->out, pBlob, nBlob);
2392        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2393          output_json_string(p->out, azArg[i], -1);
2394        }else{
2395          utf8_printf(p->out,"%s", azArg[i]);
2396        }
2397        if( i<nArg-1 ){
2398          putc(',', p->out);
2399        }
2400      }
2401      putc('}', p->out);
2402      break;
2403    }
2404    case MODE_Quote: {
2405      if( azArg==0 ) break;
2406      if( p->cnt==0 && p->showHeader ){
2407        for(i=0; i<nArg; i++){
2408          if( i>0 ) fputs(p->colSeparator, p->out);
2409          output_quoted_string(p->out, azCol[i]);
2410        }
2411        fputs(p->rowSeparator, p->out);
2412      }
2413      p->cnt++;
2414      for(i=0; i<nArg; i++){
2415        if( i>0 ) fputs(p->colSeparator, p->out);
2416        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2417          utf8_printf(p->out,"NULL");
2418        }else if( aiType && aiType[i]==SQLITE_TEXT ){
2419          output_quoted_string(p->out, azArg[i]);
2420        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2421          utf8_printf(p->out,"%s", azArg[i]);
2422        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2423          char z[50];
2424          double r = sqlite3_column_double(p->pStmt, i);
2425          sqlite3_snprintf(50,z,"%!.20g", r);
2426          raw_printf(p->out, "%s", z);
2427        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2428          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2429          int nBlob = sqlite3_column_bytes(p->pStmt, i);
2430          output_hex_blob(p->out, pBlob, nBlob);
2431        }else if( isNumber(azArg[i], 0) ){
2432          utf8_printf(p->out,"%s", azArg[i]);
2433        }else{
2434          output_quoted_string(p->out, azArg[i]);
2435        }
2436      }
2437      fputs(p->rowSeparator, p->out);
2438      break;
2439    }
2440    case MODE_Ascii: {
2441      if( p->cnt++==0 && p->showHeader ){
2442        for(i=0; i<nArg; i++){
2443          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2444          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2445        }
2446        utf8_printf(p->out, "%s", p->rowSeparator);
2447      }
2448      if( azArg==0 ) break;
2449      for(i=0; i<nArg; i++){
2450        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2451        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2452      }
2453      utf8_printf(p->out, "%s", p->rowSeparator);
2454      break;
2455    }
2456    case MODE_EQP: {
2457      eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
2458      break;
2459    }
2460  }
2461  return 0;
2462}
2463
2464/*
2465** This is the callback routine that the SQLite library
2466** invokes for each row of a query result.
2467*/
2468static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2469  /* since we don't have type info, call the shell_callback with a NULL value */
2470  return shell_callback(pArg, nArg, azArg, azCol, NULL);
2471}
2472
2473/*
2474** This is the callback routine from sqlite3_exec() that appends all
2475** output onto the end of a ShellText object.
2476*/
2477static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2478  ShellText *p = (ShellText*)pArg;
2479  int i;
2480  UNUSED_PARAMETER(az);
2481  if( azArg==0 ) return 0;
2482  if( p->n ) appendText(p, "|", 0);
2483  for(i=0; i<nArg; i++){
2484    if( i ) appendText(p, ",", 0);
2485    if( azArg[i] ) appendText(p, azArg[i], 0);
2486  }
2487  return 0;
2488}
2489
2490/*
2491** Generate an appropriate SELFTEST table in the main database.
2492*/
2493static void createSelftestTable(ShellState *p){
2494  char *zErrMsg = 0;
2495  sqlite3_exec(p->db,
2496    "SAVEPOINT selftest_init;\n"
2497    "CREATE TABLE IF NOT EXISTS selftest(\n"
2498    "  tno INTEGER PRIMARY KEY,\n"   /* Test number */
2499    "  op TEXT,\n"                   /* Operator:  memo run */
2500    "  cmd TEXT,\n"                  /* Command text */
2501    "  ans TEXT\n"                   /* Desired answer */
2502    ");"
2503    "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2504    "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2505    "  VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2506    "         'memo','Tests generated by --init');\n"
2507    "INSERT INTO [_shell$self]\n"
2508    "  SELECT 'run',\n"
2509    "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2510                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
2511    "    hex(sha3_query('SELECT type,name,tbl_name,sql "
2512                          "FROM sqlite_schema ORDER BY 2',224));\n"
2513    "INSERT INTO [_shell$self]\n"
2514    "  SELECT 'run',"
2515    "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2516    "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2517    "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2518    "  FROM (\n"
2519    "    SELECT name FROM sqlite_schema\n"
2520    "     WHERE type='table'\n"
2521    "       AND name<>'selftest'\n"
2522    "       AND coalesce(rootpage,0)>0\n"
2523    "  )\n"
2524    " ORDER BY name;\n"
2525    "INSERT INTO [_shell$self]\n"
2526    "  VALUES('run','PRAGMA integrity_check','ok');\n"
2527    "INSERT INTO selftest(tno,op,cmd,ans)"
2528    "  SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2529    "DROP TABLE [_shell$self];"
2530    ,0,0,&zErrMsg);
2531  if( zErrMsg ){
2532    utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2533    sqlite3_free(zErrMsg);
2534  }
2535  sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2536}
2537
2538
2539/*
2540** Set the destination table field of the ShellState structure to
2541** the name of the table given.  Escape any quote characters in the
2542** table name.
2543*/
2544static void set_table_name(ShellState *p, const char *zName){
2545  int i, n;
2546  char cQuote;
2547  char *z;
2548
2549  if( p->zDestTable ){
2550    free(p->zDestTable);
2551    p->zDestTable = 0;
2552  }
2553  if( zName==0 ) return;
2554  cQuote = quoteChar(zName);
2555  n = strlen30(zName);
2556  if( cQuote ) n += n+2;
2557  z = p->zDestTable = malloc( n+1 );
2558  shell_check_oom(z);
2559  n = 0;
2560  if( cQuote ) z[n++] = cQuote;
2561  for(i=0; zName[i]; i++){
2562    z[n++] = zName[i];
2563    if( zName[i]==cQuote ) z[n++] = cQuote;
2564  }
2565  if( cQuote ) z[n++] = cQuote;
2566  z[n] = 0;
2567}
2568
2569/*
2570** Maybe construct two lines of text that point out the position of a
2571** syntax error.  Return a pointer to the text, in memory obtained from
2572** sqlite3_malloc().  Or, if the most recent error does not involve a
2573** specific token that we can point to, return an empty string.
2574**
2575** In all cases, the memory returned is obtained from sqlite3_malloc64()
2576** and should be released by the caller invoking sqlite3_free().
2577*/
2578static char *shell_error_context(const char *zSql, sqlite3 *db){
2579  int iOffset;
2580  size_t len;
2581  char *zCode;
2582  char *zMsg;
2583  int i;
2584  if( db==0
2585   || zSql==0
2586   || (iOffset = sqlite3_error_offset(db))<0
2587  ){
2588    return sqlite3_mprintf("");
2589  }
2590  while( iOffset>50 ){
2591    iOffset--;
2592    zSql++;
2593    while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; }
2594  }
2595  len = strlen(zSql);
2596  if( len>78 ){
2597    len = 78;
2598    while( (zSql[len]&0xc0)==0x80 ) len--;
2599  }
2600  zCode = sqlite3_mprintf("%.*s", len, zSql);
2601  for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; }
2602  if( iOffset<25 ){
2603    zMsg = sqlite3_mprintf("\n  %z\n  %*s^--- error here", zCode, iOffset, "");
2604  }else{
2605    zMsg = sqlite3_mprintf("\n  %z\n  %*serror here ---^", zCode, iOffset-14, "");
2606  }
2607  return zMsg;
2608}
2609
2610
2611/*
2612** Execute a query statement that will generate SQL output.  Print
2613** the result columns, comma-separated, on a line and then add a
2614** semicolon terminator to the end of that line.
2615**
2616** If the number of columns is 1 and that column contains text "--"
2617** then write the semicolon on a separate line.  That way, if a
2618** "--" comment occurs at the end of the statement, the comment
2619** won't consume the semicolon terminator.
2620*/
2621static int run_table_dump_query(
2622  ShellState *p,           /* Query context */
2623  const char *zSelect      /* SELECT statement to extract content */
2624){
2625  sqlite3_stmt *pSelect;
2626  int rc;
2627  int nResult;
2628  int i;
2629  const char *z;
2630  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2631  if( rc!=SQLITE_OK || !pSelect ){
2632    char *zContext = shell_error_context(zSelect, p->db);
2633    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc,
2634                sqlite3_errmsg(p->db), zContext);
2635    sqlite3_free(zContext);
2636    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2637    return rc;
2638  }
2639  rc = sqlite3_step(pSelect);
2640  nResult = sqlite3_column_count(pSelect);
2641  while( rc==SQLITE_ROW ){
2642    z = (const char*)sqlite3_column_text(pSelect, 0);
2643    utf8_printf(p->out, "%s", z);
2644    for(i=1; i<nResult; i++){
2645      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2646    }
2647    if( z==0 ) z = "";
2648    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2649    if( z[0] ){
2650      raw_printf(p->out, "\n;\n");
2651    }else{
2652      raw_printf(p->out, ";\n");
2653    }
2654    rc = sqlite3_step(pSelect);
2655  }
2656  rc = sqlite3_finalize(pSelect);
2657  if( rc!=SQLITE_OK ){
2658    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2659                sqlite3_errmsg(p->db));
2660    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2661  }
2662  return rc;
2663}
2664
2665/*
2666** Allocate space and save off string indicating current error.
2667*/
2668static char *save_err_msg(
2669  sqlite3 *db,           /* Database to query */
2670  const char *zPhase,    /* When the error occcurs */
2671  int rc,                /* Error code returned from API */
2672  const char *zSql       /* SQL string, or NULL */
2673){
2674  char *zErr;
2675  char *zContext;
2676  sqlite3_str *pStr = sqlite3_str_new(0);
2677  sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db));
2678  if( rc>1 ){
2679    sqlite3_str_appendf(pStr, " (%d)", rc);
2680  }
2681  zContext = shell_error_context(zSql, db);
2682  if( zContext ){
2683    sqlite3_str_appendall(pStr, zContext);
2684    sqlite3_free(zContext);
2685  }
2686  zErr = sqlite3_str_finish(pStr);
2687  shell_check_oom(zErr);
2688  return zErr;
2689}
2690
2691#ifdef __linux__
2692/*
2693** Attempt to display I/O stats on Linux using /proc/PID/io
2694*/
2695static void displayLinuxIoStats(FILE *out){
2696  FILE *in;
2697  char z[200];
2698  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2699  in = fopen(z, "rb");
2700  if( in==0 ) return;
2701  while( fgets(z, sizeof(z), in)!=0 ){
2702    static const struct {
2703      const char *zPattern;
2704      const char *zDesc;
2705    } aTrans[] = {
2706      { "rchar: ",                  "Bytes received by read():" },
2707      { "wchar: ",                  "Bytes sent to write():"    },
2708      { "syscr: ",                  "Read() system calls:"      },
2709      { "syscw: ",                  "Write() system calls:"     },
2710      { "read_bytes: ",             "Bytes read from storage:"  },
2711      { "write_bytes: ",            "Bytes written to storage:" },
2712      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
2713    };
2714    int i;
2715    for(i=0; i<ArraySize(aTrans); i++){
2716      int n = strlen30(aTrans[i].zPattern);
2717      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2718        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2719        break;
2720      }
2721    }
2722  }
2723  fclose(in);
2724}
2725#endif
2726
2727/*
2728** Display a single line of status using 64-bit values.
2729*/
2730static void displayStatLine(
2731  ShellState *p,            /* The shell context */
2732  char *zLabel,             /* Label for this one line */
2733  char *zFormat,            /* Format for the result */
2734  int iStatusCtrl,          /* Which status to display */
2735  int bReset                /* True to reset the stats */
2736){
2737  sqlite3_int64 iCur = -1;
2738  sqlite3_int64 iHiwtr = -1;
2739  int i, nPercent;
2740  char zLine[200];
2741  sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2742  for(i=0, nPercent=0; zFormat[i]; i++){
2743    if( zFormat[i]=='%' ) nPercent++;
2744  }
2745  if( nPercent>1 ){
2746    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2747  }else{
2748    sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2749  }
2750  raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2751}
2752
2753/*
2754** Display memory stats.
2755*/
2756static int display_stats(
2757  sqlite3 *db,                /* Database to query */
2758  ShellState *pArg,           /* Pointer to ShellState */
2759  int bReset                  /* True to reset the stats */
2760){
2761  int iCur;
2762  int iHiwtr;
2763  FILE *out;
2764  if( pArg==0 || pArg->out==0 ) return 0;
2765  out = pArg->out;
2766
2767  if( pArg->pStmt && pArg->statsOn==2 ){
2768    int nCol, i, x;
2769    sqlite3_stmt *pStmt = pArg->pStmt;
2770    char z[100];
2771    nCol = sqlite3_column_count(pStmt);
2772    raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2773    for(i=0; i<nCol; i++){
2774      sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2775      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2776#ifndef SQLITE_OMIT_DECLTYPE
2777      sqlite3_snprintf(30, z+x, "declared type:");
2778      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2779#endif
2780#ifdef SQLITE_ENABLE_COLUMN_METADATA
2781      sqlite3_snprintf(30, z+x, "database name:");
2782      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2783      sqlite3_snprintf(30, z+x, "table name:");
2784      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2785      sqlite3_snprintf(30, z+x, "origin name:");
2786      utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2787#endif
2788    }
2789  }
2790
2791  if( pArg->statsOn==3 ){
2792    if( pArg->pStmt ){
2793      iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2794      raw_printf(pArg->out, "VM-steps: %d\n", iCur);
2795    }
2796    return 0;
2797  }
2798
2799  displayStatLine(pArg, "Memory Used:",
2800     "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2801  displayStatLine(pArg, "Number of Outstanding Allocations:",
2802     "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2803  if( pArg->shellFlgs & SHFLG_Pagecache ){
2804    displayStatLine(pArg, "Number of Pcache Pages Used:",
2805       "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2806  }
2807  displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2808     "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2809  displayStatLine(pArg, "Largest Allocation:",
2810     "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2811  displayStatLine(pArg, "Largest Pcache Allocation:",
2812     "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2813#ifdef YYTRACKMAXSTACKDEPTH
2814  displayStatLine(pArg, "Deepest Parser Stack:",
2815     "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2816#endif
2817
2818  if( db ){
2819    if( pArg->shellFlgs & SHFLG_Lookaside ){
2820      iHiwtr = iCur = -1;
2821      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2822                        &iCur, &iHiwtr, bReset);
2823      raw_printf(pArg->out,
2824              "Lookaside Slots Used:                %d (max %d)\n",
2825              iCur, iHiwtr);
2826      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2827                        &iCur, &iHiwtr, bReset);
2828      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
2829              iHiwtr);
2830      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2831                        &iCur, &iHiwtr, bReset);
2832      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
2833              iHiwtr);
2834      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2835                        &iCur, &iHiwtr, bReset);
2836      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
2837              iHiwtr);
2838    }
2839    iHiwtr = iCur = -1;
2840    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2841    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
2842            iCur);
2843    iHiwtr = iCur = -1;
2844    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2845    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
2846    iHiwtr = iCur = -1;
2847    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2848    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
2849    iHiwtr = iCur = -1;
2850    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2851    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
2852    iHiwtr = iCur = -1;
2853    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2854    raw_printf(pArg->out, "Page cache spills:                   %d\n", iCur);
2855    iHiwtr = iCur = -1;
2856    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2857    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
2858            iCur);
2859    iHiwtr = iCur = -1;
2860    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2861    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
2862            iCur);
2863  }
2864
2865  if( pArg->pStmt ){
2866    int iHit, iMiss;
2867    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2868                               bReset);
2869    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
2870    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2871    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
2872    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2873    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
2874    iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset);
2875    iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset);
2876    if( iHit || iMiss ){
2877      raw_printf(pArg->out, "Bloom filter bypass taken:           %d/%d\n",
2878            iHit, iHit+iMiss);
2879    }
2880    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2881    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
2882    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
2883    raw_printf(pArg->out, "Reprepare operations:                %d\n", iCur);
2884    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2885    raw_printf(pArg->out, "Number of times run:                 %d\n", iCur);
2886    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2887    raw_printf(pArg->out, "Memory used by prepared stmt:        %d\n", iCur);
2888  }
2889
2890#ifdef __linux__
2891  displayLinuxIoStats(pArg->out);
2892#endif
2893
2894  /* Do not remove this machine readable comment: extra-stats-output-here */
2895
2896  return 0;
2897}
2898
2899/*
2900** Display scan stats.
2901*/
2902static void display_scanstats(
2903  sqlite3 *db,                    /* Database to query */
2904  ShellState *pArg                /* Pointer to ShellState */
2905){
2906#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2907  UNUSED_PARAMETER(db);
2908  UNUSED_PARAMETER(pArg);
2909#else
2910  int i, k, n, mx;
2911  raw_printf(pArg->out, "-------- scanstats --------\n");
2912  mx = 0;
2913  for(k=0; k<=mx; k++){
2914    double rEstLoop = 1.0;
2915    for(i=n=0; 1; i++){
2916      sqlite3_stmt *p = pArg->pStmt;
2917      sqlite3_int64 nLoop, nVisit;
2918      double rEst;
2919      int iSid;
2920      const char *zExplain;
2921      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2922        break;
2923      }
2924      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2925      if( iSid>mx ) mx = iSid;
2926      if( iSid!=k ) continue;
2927      if( n==0 ){
2928        rEstLoop = (double)nLoop;
2929        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2930      }
2931      n++;
2932      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2933      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2934      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2935      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2936      rEstLoop *= rEst;
2937      raw_printf(pArg->out,
2938          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2939          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2940      );
2941    }
2942  }
2943  raw_printf(pArg->out, "---------------------------\n");
2944#endif
2945}
2946
2947/*
2948** Parameter azArray points to a zero-terminated array of strings. zStr
2949** points to a single nul-terminated string. Return non-zero if zStr
2950** is equal, according to strcmp(), to any of the strings in the array.
2951** Otherwise, return zero.
2952*/
2953static int str_in_array(const char *zStr, const char **azArray){
2954  int i;
2955  for(i=0; azArray[i]; i++){
2956    if( 0==strcmp(zStr, azArray[i]) ) return 1;
2957  }
2958  return 0;
2959}
2960
2961/*
2962** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2963** and populate the ShellState.aiIndent[] array with the number of
2964** spaces each opcode should be indented before it is output.
2965**
2966** The indenting rules are:
2967**
2968**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2969**       all opcodes that occur between the p2 jump destination and the opcode
2970**       itself by 2 spaces.
2971**
2972**     * Do the previous for "Return" instructions for when P2 is positive.
2973**       See tag-20220407a in wherecode.c and vdbe.c.
2974**
2975**     * For each "Goto", if the jump destination is earlier in the program
2976**       and ends on one of:
2977**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
2978**       or if the P1 parameter is one instead of zero,
2979**       then indent all opcodes between the earlier instruction
2980**       and "Goto" by 2 spaces.
2981*/
2982static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2983  const char *zSql;               /* The text of the SQL statement */
2984  const char *z;                  /* Used to check if this is an EXPLAIN */
2985  int *abYield = 0;               /* True if op is an OP_Yield */
2986  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
2987  int iOp;                        /* Index of operation in p->aiIndent[] */
2988
2989  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2990                           "Return", 0 };
2991  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2992                            "Rewind", 0 };
2993  const char *azGoto[] = { "Goto", 0 };
2994
2995  /* Try to figure out if this is really an EXPLAIN statement. If this
2996  ** cannot be verified, return early.  */
2997  if( sqlite3_column_count(pSql)!=8 ){
2998    p->cMode = p->mode;
2999    return;
3000  }
3001  zSql = sqlite3_sql(pSql);
3002  if( zSql==0 ) return;
3003  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
3004  if( sqlite3_strnicmp(z, "explain", 7) ){
3005    p->cMode = p->mode;
3006    return;
3007  }
3008
3009  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3010    int i;
3011    int iAddr = sqlite3_column_int(pSql, 0);
3012    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
3013
3014    /* Set p2 to the P2 field of the current opcode. Then, assuming that
3015    ** p2 is an instruction address, set variable p2op to the index of that
3016    ** instruction in the aiIndent[] array. p2 and p2op may be different if
3017    ** the current instruction is part of a sub-program generated by an
3018    ** SQL trigger or foreign key.  */
3019    int p2 = sqlite3_column_int(pSql, 3);
3020    int p2op = (p2 + (iOp-iAddr));
3021
3022    /* Grow the p->aiIndent array as required */
3023    if( iOp>=nAlloc ){
3024      if( iOp==0 ){
3025        /* Do further verfication that this is explain output.  Abort if
3026        ** it is not */
3027        static const char *explainCols[] = {
3028           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3029        int jj;
3030        for(jj=0; jj<ArraySize(explainCols); jj++){
3031          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3032            p->cMode = p->mode;
3033            sqlite3_reset(pSql);
3034            return;
3035          }
3036        }
3037      }
3038      nAlloc += 100;
3039      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3040      shell_check_oom(p->aiIndent);
3041      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
3042      shell_check_oom(abYield);
3043    }
3044    abYield[iOp] = str_in_array(zOp, azYield);
3045    p->aiIndent[iOp] = 0;
3046    p->nIndent = iOp+1;
3047
3048    if( str_in_array(zOp, azNext) && p2op>0 ){
3049      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3050    }
3051    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3052     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3053    ){
3054      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
3055    }
3056  }
3057
3058  p->iIndent = 0;
3059  sqlite3_free(abYield);
3060  sqlite3_reset(pSql);
3061}
3062
3063/*
3064** Free the array allocated by explain_data_prepare().
3065*/
3066static void explain_data_delete(ShellState *p){
3067  sqlite3_free(p->aiIndent);
3068  p->aiIndent = 0;
3069  p->nIndent = 0;
3070  p->iIndent = 0;
3071}
3072
3073/*
3074** Disable and restore .wheretrace and .treetrace/.selecttrace settings.
3075*/
3076static unsigned int savedSelectTrace;
3077static unsigned int savedWhereTrace;
3078static void disable_debug_trace_modes(void){
3079  unsigned int zero = 0;
3080  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
3081  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
3082  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
3083  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
3084}
3085static void restore_debug_trace_modes(void){
3086  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
3087  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
3088}
3089
3090/* Create the TEMP table used to store parameter bindings */
3091static void bind_table_init(ShellState *p){
3092  int wrSchema = 0;
3093  int defensiveMode = 0;
3094  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
3095  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
3096  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
3097  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
3098  sqlite3_exec(p->db,
3099    "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
3100    "  key TEXT PRIMARY KEY,\n"
3101    "  value\n"
3102    ") WITHOUT ROWID;",
3103    0, 0, 0);
3104  sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
3105  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
3106}
3107
3108/*
3109** Bind parameters on a prepared statement.
3110**
3111** Parameter bindings are taken from a TEMP table of the form:
3112**
3113**    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
3114**    WITHOUT ROWID;
3115**
3116** No bindings occur if this table does not exist.  The name of the table
3117** begins with "sqlite_" so that it will not collide with ordinary application
3118** tables.  The table must be in the TEMP schema.
3119*/
3120static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
3121  int nVar;
3122  int i;
3123  int rc;
3124  sqlite3_stmt *pQ = 0;
3125
3126  nVar = sqlite3_bind_parameter_count(pStmt);
3127  if( nVar==0 ) return;  /* Nothing to do */
3128  if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
3129                                    "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
3130    return; /* Parameter table does not exist */
3131  }
3132  rc = sqlite3_prepare_v2(pArg->db,
3133          "SELECT value FROM temp.sqlite_parameters"
3134          " WHERE key=?1", -1, &pQ, 0);
3135  if( rc || pQ==0 ) return;
3136  for(i=1; i<=nVar; i++){
3137    char zNum[30];
3138    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
3139    if( zVar==0 ){
3140      sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
3141      zVar = zNum;
3142    }
3143    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
3144    if( sqlite3_step(pQ)==SQLITE_ROW ){
3145      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
3146    }else{
3147      sqlite3_bind_null(pStmt, i);
3148    }
3149    sqlite3_reset(pQ);
3150  }
3151  sqlite3_finalize(pQ);
3152}
3153
3154/*
3155** UTF8 box-drawing characters.  Imagine box lines like this:
3156**
3157**           1
3158**           |
3159**       4 --+-- 2
3160**           |
3161**           3
3162**
3163** Each box characters has between 2 and 4 of the lines leading from
3164** the center.  The characters are here identified by the numbers of
3165** their corresponding lines.
3166*/
3167#define BOX_24   "\342\224\200"  /* U+2500 --- */
3168#define BOX_13   "\342\224\202"  /* U+2502  |  */
3169#define BOX_23   "\342\224\214"  /* U+250c  ,- */
3170#define BOX_34   "\342\224\220"  /* U+2510 -,  */
3171#define BOX_12   "\342\224\224"  /* U+2514  '- */
3172#define BOX_14   "\342\224\230"  /* U+2518 -'  */
3173#define BOX_123  "\342\224\234"  /* U+251c  |- */
3174#define BOX_134  "\342\224\244"  /* U+2524 -|  */
3175#define BOX_234  "\342\224\254"  /* U+252c -,- */
3176#define BOX_124  "\342\224\264"  /* U+2534 -'- */
3177#define BOX_1234 "\342\224\274"  /* U+253c -|- */
3178
3179/* Draw horizontal line N characters long using unicode box
3180** characters
3181*/
3182static void print_box_line(FILE *out, int N){
3183  const char zDash[] =
3184      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
3185      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
3186  const int nDash = sizeof(zDash) - 1;
3187  N *= 3;
3188  while( N>nDash ){
3189    utf8_printf(out, zDash);
3190    N -= nDash;
3191  }
3192  utf8_printf(out, "%.*s", N, zDash);
3193}
3194
3195/*
3196** Draw a horizontal separator for a MODE_Box table.
3197*/
3198static void print_box_row_separator(
3199  ShellState *p,
3200  int nArg,
3201  const char *zSep1,
3202  const char *zSep2,
3203  const char *zSep3
3204){
3205  int i;
3206  if( nArg>0 ){
3207    utf8_printf(p->out, "%s", zSep1);
3208    print_box_line(p->out, p->actualWidth[0]+2);
3209    for(i=1; i<nArg; i++){
3210      utf8_printf(p->out, "%s", zSep2);
3211      print_box_line(p->out, p->actualWidth[i]+2);
3212    }
3213    utf8_printf(p->out, "%s", zSep3);
3214  }
3215  fputs("\n", p->out);
3216}
3217
3218/*
3219** z[] is a line of text that is to be displayed the .mode box or table or
3220** similar tabular formats.  z[] might contain control characters such
3221** as \n, \t, \f, or \r.
3222**
3223** Compute characters to display on the first line of z[].  Stop at the
3224** first \r, \n, or \f.  Expand \t into spaces.  Return a copy (obtained
3225** from malloc()) of that first line, which caller should free sometime.
3226** Write anything to display on the next line into *pzTail.  If this is
3227** the last line, write a NULL into *pzTail. (*pzTail is not allocated.)
3228*/
3229static char *translateForDisplayAndDup(
3230  const unsigned char *z,            /* Input text to be transformed */
3231  const unsigned char **pzTail,      /* OUT: Tail of the input for next line */
3232  int mxWidth,                       /* Max width.  0 means no limit */
3233  u8 bWordWrap                       /* If true, avoid breaking mid-word */
3234){
3235  int i;                 /* Input bytes consumed */
3236  int j;                 /* Output bytes generated */
3237  int k;                 /* Input bytes to be displayed */
3238  int n;                 /* Output column number */
3239  unsigned char *zOut;   /* Output text */
3240
3241  if( z==0 ){
3242    *pzTail = 0;
3243    return 0;
3244  }
3245  if( mxWidth<0 ) mxWidth = -mxWidth;
3246  if( mxWidth==0 ) mxWidth = 1000000;
3247  i = j = n = 0;
3248  while( n<mxWidth ){
3249    if( z[i]>=' ' ){
3250      n++;
3251      do{ i++; j++; }while( (z[i]&0xc0)==0x80 );
3252      continue;
3253    }
3254    if( z[i]=='\t' ){
3255      do{
3256        n++;
3257        j++;
3258      }while( (n&7)!=0 && n<mxWidth );
3259      i++;
3260      continue;
3261    }
3262    break;
3263  }
3264  if( n>=mxWidth && bWordWrap  ){
3265    /* Perhaps try to back up to a better place to break the line */
3266    for(k=i; k>i/2; k--){
3267      if( isspace(z[k-1]) ) break;
3268    }
3269    if( k<=i/2 ){
3270      for(k=i; k>i/2; k--){
3271        if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break;
3272      }
3273    }
3274    if( k<=i/2 ){
3275      k = i;
3276    }else{
3277      i = k;
3278      while( z[i]==' ' ) i++;
3279    }
3280  }else{
3281    k = i;
3282  }
3283  if( n>=mxWidth && z[i]>=' ' ){
3284   *pzTail = &z[i];
3285  }else if( z[i]=='\r' && z[i+1]=='\n' ){
3286    *pzTail = z[i+2] ? &z[i+2] : 0;
3287  }else if( z[i]==0 || z[i+1]==0 ){
3288    *pzTail = 0;
3289  }else{
3290    *pzTail = &z[i+1];
3291  }
3292  zOut = malloc( j+1 );
3293  shell_check_oom(zOut);
3294  i = j = n = 0;
3295  while( i<k ){
3296    if( z[i]>=' ' ){
3297      n++;
3298      do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 );
3299      continue;
3300    }
3301    if( z[i]=='\t' ){
3302      do{
3303        n++;
3304        zOut[j++] = ' ';
3305      }while( (n&7)!=0 && n<mxWidth );
3306      i++;
3307      continue;
3308    }
3309    break;
3310  }
3311  zOut[j] = 0;
3312  return (char*)zOut;
3313}
3314
3315/* Extract the value of the i-th current column for pStmt as an SQL literal
3316** value.  Memory is obtained from sqlite3_malloc64() and must be freed by
3317** the caller.
3318*/
3319static char *quoted_column(sqlite3_stmt *pStmt, int i){
3320  switch( sqlite3_column_type(pStmt, i) ){
3321    case SQLITE_NULL: {
3322      return sqlite3_mprintf("NULL");
3323    }
3324    case SQLITE_INTEGER:
3325    case SQLITE_FLOAT: {
3326      return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i));
3327    }
3328    case SQLITE_TEXT: {
3329      return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i));
3330    }
3331    case SQLITE_BLOB: {
3332      int j;
3333      sqlite3_str *pStr = sqlite3_str_new(0);
3334      const unsigned char *a = sqlite3_column_blob(pStmt,i);
3335      int n = sqlite3_column_bytes(pStmt,i);
3336      sqlite3_str_append(pStr, "x'", 2);
3337      for(j=0; j<n; j++){
3338        sqlite3_str_appendf(pStr, "%02x", a[j]);
3339      }
3340      sqlite3_str_append(pStr, "'", 1);
3341      return sqlite3_str_finish(pStr);
3342    }
3343  }
3344  return 0; /* Not reached */
3345}
3346
3347/*
3348** Run a prepared statement and output the result in one of the
3349** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
3350** or MODE_Box.
3351**
3352** This is different from ordinary exec_prepared_stmt() in that
3353** it has to run the entire query and gather the results into memory
3354** first, in order to determine column widths, before providing
3355** any output.
3356*/
3357static void exec_prepared_stmt_columnar(
3358  ShellState *p,                        /* Pointer to ShellState */
3359  sqlite3_stmt *pStmt                   /* Statment to run */
3360){
3361  sqlite3_int64 nRow = 0;
3362  int nColumn = 0;
3363  char **azData = 0;
3364  sqlite3_int64 nAlloc = 0;
3365  char *abRowDiv = 0;
3366  const unsigned char *uz;
3367  const char *z;
3368  char **azQuoted = 0;
3369  int rc;
3370  sqlite3_int64 i, nData;
3371  int j, nTotal, w, n;
3372  const char *colSep = 0;
3373  const char *rowSep = 0;
3374  const unsigned char **azNextLine = 0;
3375  int bNextLine = 0;
3376  int bMultiLineRowExists = 0;
3377  int bw = p->cmOpts.bWordWrap;
3378  const char *zEmpty = "";
3379  const char *zShowNull = p->nullValue;
3380
3381  rc = sqlite3_step(pStmt);
3382  if( rc!=SQLITE_ROW ) return;
3383  nColumn = sqlite3_column_count(pStmt);
3384  nAlloc = nColumn*4;
3385  if( nAlloc<=0 ) nAlloc = 1;
3386  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
3387  shell_check_oom(azData);
3388  azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) );
3389  shell_check_oom((void*)azNextLine);
3390  memset((void*)azNextLine, 0, nColumn*sizeof(char*) );
3391  if( p->cmOpts.bQuote ){
3392    azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) );
3393    shell_check_oom(azQuoted);
3394    memset(azQuoted, 0, nColumn*sizeof(char*) );
3395  }
3396  abRowDiv = sqlite3_malloc64( nAlloc/nColumn );
3397  shell_check_oom(abRowDiv);
3398  if( nColumn>p->nWidth ){
3399    p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int));
3400    shell_check_oom(p->colWidth);
3401    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
3402    p->nWidth = nColumn;
3403    p->actualWidth = &p->colWidth[nColumn];
3404  }
3405  memset(p->actualWidth, 0, nColumn*sizeof(int));
3406  for(i=0; i<nColumn; i++){
3407    w = p->colWidth[i];
3408    if( w<0 ) w = -w;
3409    p->actualWidth[i] = w;
3410  }
3411  for(i=0; i<nColumn; i++){
3412    const unsigned char *zNotUsed;
3413    int wx = p->colWidth[i];
3414    if( wx==0 ){
3415      wx = p->cmOpts.iWrap;
3416    }
3417    if( wx<0 ) wx = -wx;
3418    uz = (const unsigned char*)sqlite3_column_name(pStmt,i);
3419    azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw);
3420  }
3421  do{
3422    int useNextLine = bNextLine;
3423    bNextLine = 0;
3424    if( (nRow+2)*nColumn >= nAlloc ){
3425      nAlloc *= 2;
3426      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
3427      shell_check_oom(azData);
3428      abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn);
3429      shell_check_oom(abRowDiv);
3430    }
3431    abRowDiv[nRow] = 1;
3432    nRow++;
3433    for(i=0; i<nColumn; i++){
3434      int wx = p->colWidth[i];
3435      if( wx==0 ){
3436        wx = p->cmOpts.iWrap;
3437      }
3438      if( wx<0 ) wx = -wx;
3439      if( useNextLine ){
3440        uz = azNextLine[i];
3441        if( uz==0 ) uz = (u8*)zEmpty;
3442      }else if( p->cmOpts.bQuote ){
3443        sqlite3_free(azQuoted[i]);
3444        azQuoted[i] = quoted_column(pStmt,i);
3445        uz = (const unsigned char*)azQuoted[i];
3446      }else{
3447        uz = (const unsigned char*)sqlite3_column_text(pStmt,i);
3448        if( uz==0 ) uz = (u8*)zShowNull;
3449      }
3450      azData[nRow*nColumn + i]
3451        = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw);
3452      if( azNextLine[i] ){
3453        bNextLine = 1;
3454        abRowDiv[nRow-1] = 0;
3455        bMultiLineRowExists = 1;
3456      }
3457    }
3458  }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW );
3459  nTotal = nColumn*(nRow+1);
3460  for(i=0; i<nTotal; i++){
3461    z = azData[i];
3462    if( z==0 ) z = (char*)zEmpty;
3463    n = strlenChar(z);
3464    j = i%nColumn;
3465    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
3466  }
3467  if( seenInterrupt ) goto columnar_end;
3468  if( nColumn==0 ) goto columnar_end;
3469  switch( p->cMode ){
3470    case MODE_Column: {
3471      colSep = "  ";
3472      rowSep = "\n";
3473      if( p->showHeader ){
3474        for(i=0; i<nColumn; i++){
3475          w = p->actualWidth[i];
3476          if( p->colWidth[i]<0 ) w = -w;
3477          utf8_width_print(p->out, w, azData[i]);
3478          fputs(i==nColumn-1?"\n":"  ", p->out);
3479        }
3480        for(i=0; i<nColumn; i++){
3481          print_dashes(p->out, p->actualWidth[i]);
3482          fputs(i==nColumn-1?"\n":"  ", p->out);
3483        }
3484      }
3485      break;
3486    }
3487    case MODE_Table: {
3488      colSep = " | ";
3489      rowSep = " |\n";
3490      print_row_separator(p, nColumn, "+");
3491      fputs("| ", p->out);
3492      for(i=0; i<nColumn; i++){
3493        w = p->actualWidth[i];
3494        n = strlenChar(azData[i]);
3495        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3496        fputs(i==nColumn-1?" |\n":" | ", p->out);
3497      }
3498      print_row_separator(p, nColumn, "+");
3499      break;
3500    }
3501    case MODE_Markdown: {
3502      colSep = " | ";
3503      rowSep = " |\n";
3504      fputs("| ", p->out);
3505      for(i=0; i<nColumn; i++){
3506        w = p->actualWidth[i];
3507        n = strlenChar(azData[i]);
3508        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
3509        fputs(i==nColumn-1?" |\n":" | ", p->out);
3510      }
3511      print_row_separator(p, nColumn, "|");
3512      break;
3513    }
3514    case MODE_Box: {
3515      colSep = " " BOX_13 " ";
3516      rowSep = " " BOX_13 "\n";
3517      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
3518      utf8_printf(p->out, BOX_13 " ");
3519      for(i=0; i<nColumn; i++){
3520        w = p->actualWidth[i];
3521        n = strlenChar(azData[i]);
3522        utf8_printf(p->out, "%*s%s%*s%s",
3523            (w-n)/2, "", azData[i], (w-n+1)/2, "",
3524            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
3525      }
3526      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3527      break;
3528    }
3529  }
3530  for(i=nColumn, j=0; i<nTotal; i++, j++){
3531    if( j==0 && p->cMode!=MODE_Column ){
3532      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
3533    }
3534    z = azData[i];
3535    if( z==0 ) z = p->nullValue;
3536    w = p->actualWidth[j];
3537    if( p->colWidth[j]<0 ) w = -w;
3538    utf8_width_print(p->out, w, z);
3539    if( j==nColumn-1 ){
3540      utf8_printf(p->out, "%s", rowSep);
3541      if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){
3542        if( p->cMode==MODE_Table ){
3543          print_row_separator(p, nColumn, "+");
3544        }else if( p->cMode==MODE_Box ){
3545          print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
3546        }else if( p->cMode==MODE_Column ){
3547          raw_printf(p->out, "\n");
3548        }
3549      }
3550      j = -1;
3551      if( seenInterrupt ) goto columnar_end;
3552    }else{
3553      utf8_printf(p->out, "%s", colSep);
3554    }
3555  }
3556  if( p->cMode==MODE_Table ){
3557    print_row_separator(p, nColumn, "+");
3558  }else if( p->cMode==MODE_Box ){
3559    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
3560  }
3561columnar_end:
3562  if( seenInterrupt ){
3563    utf8_printf(p->out, "Interrupt\n");
3564  }
3565  nData = (nRow+1)*nColumn;
3566  for(i=0; i<nData; i++){
3567    z = azData[i];
3568    if( z!=zEmpty && z!=zShowNull ) free(azData[i]);
3569  }
3570  sqlite3_free(azData);
3571  sqlite3_free((void*)azNextLine);
3572  sqlite3_free(abRowDiv);
3573  if( azQuoted ){
3574    for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]);
3575    sqlite3_free(azQuoted);
3576  }
3577}
3578
3579/*
3580** Run a prepared statement
3581*/
3582static void exec_prepared_stmt(
3583  ShellState *pArg,                                /* Pointer to ShellState */
3584  sqlite3_stmt *pStmt                              /* Statment to run */
3585){
3586  int rc;
3587  sqlite3_uint64 nRow = 0;
3588
3589  if( pArg->cMode==MODE_Column
3590   || pArg->cMode==MODE_Table
3591   || pArg->cMode==MODE_Box
3592   || pArg->cMode==MODE_Markdown
3593  ){
3594    exec_prepared_stmt_columnar(pArg, pStmt);
3595    return;
3596  }
3597
3598  /* perform the first step.  this will tell us if we
3599  ** have a result set or not and how wide it is.
3600  */
3601  rc = sqlite3_step(pStmt);
3602  /* if we have a result set... */
3603  if( SQLITE_ROW == rc ){
3604    /* allocate space for col name ptr, value ptr, and type */
3605    int nCol = sqlite3_column_count(pStmt);
3606    void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3607    if( !pData ){
3608      shell_out_of_memory();
3609    }else{
3610      char **azCols = (char **)pData;      /* Names of result columns */
3611      char **azVals = &azCols[nCol];       /* Results */
3612      int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3613      int i, x;
3614      assert(sizeof(int) <= sizeof(char *));
3615      /* save off ptrs to column names */
3616      for(i=0; i<nCol; i++){
3617        azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3618      }
3619      do{
3620        nRow++;
3621        /* extract the data and data types */
3622        for(i=0; i<nCol; i++){
3623          aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3624          if( x==SQLITE_BLOB
3625           && pArg
3626           && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote)
3627          ){
3628            azVals[i] = "";
3629          }else{
3630            azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3631          }
3632          if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3633            rc = SQLITE_NOMEM;
3634            break; /* from for */
3635          }
3636        } /* end for */
3637
3638        /* if data and types extracted successfully... */
3639        if( SQLITE_ROW == rc ){
3640          /* call the supplied callback with the result row data */
3641          if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
3642            rc = SQLITE_ABORT;
3643          }else{
3644            rc = sqlite3_step(pStmt);
3645          }
3646        }
3647      } while( SQLITE_ROW == rc );
3648      sqlite3_free(pData);
3649      if( pArg->cMode==MODE_Json ){
3650        fputs("]\n", pArg->out);
3651      }else if( pArg->cMode==MODE_Count ){
3652        char zBuf[200];
3653        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
3654                         nRow, nRow!=1 ? "s" : "");
3655        printf("%s", zBuf);
3656      }
3657    }
3658  }
3659}
3660
3661#ifndef SQLITE_OMIT_VIRTUALTABLE
3662/*
3663** This function is called to process SQL if the previous shell command
3664** was ".expert". It passes the SQL in the second argument directly to
3665** the sqlite3expert object.
3666**
3667** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3668** code. In this case, (*pzErr) may be set to point to a buffer containing
3669** an English language error message. It is the responsibility of the
3670** caller to eventually free this buffer using sqlite3_free().
3671*/
3672static int expertHandleSQL(
3673  ShellState *pState,
3674  const char *zSql,
3675  char **pzErr
3676){
3677  assert( pState->expert.pExpert );
3678  assert( pzErr==0 || *pzErr==0 );
3679  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
3680}
3681
3682/*
3683** This function is called either to silently clean up the object
3684** created by the ".expert" command (if bCancel==1), or to generate a
3685** report from it and then clean it up (if bCancel==0).
3686**
3687** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
3688** code. In this case, (*pzErr) may be set to point to a buffer containing
3689** an English language error message. It is the responsibility of the
3690** caller to eventually free this buffer using sqlite3_free().
3691*/
3692static int expertFinish(
3693  ShellState *pState,
3694  int bCancel,
3695  char **pzErr
3696){
3697  int rc = SQLITE_OK;
3698  sqlite3expert *p = pState->expert.pExpert;
3699  assert( p );
3700  assert( bCancel || pzErr==0 || *pzErr==0 );
3701  if( bCancel==0 ){
3702    FILE *out = pState->out;
3703    int bVerbose = pState->expert.bVerbose;
3704
3705    rc = sqlite3_expert_analyze(p, pzErr);
3706    if( rc==SQLITE_OK ){
3707      int nQuery = sqlite3_expert_count(p);
3708      int i;
3709
3710      if( bVerbose ){
3711        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
3712        raw_printf(out, "-- Candidates -----------------------------\n");
3713        raw_printf(out, "%s\n", zCand);
3714      }
3715      for(i=0; i<nQuery; i++){
3716        const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
3717        const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
3718        const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
3719        if( zIdx==0 ) zIdx = "(no new indexes)\n";
3720        if( bVerbose ){
3721          raw_printf(out, "-- Query %d --------------------------------\n",i+1);
3722          raw_printf(out, "%s\n\n", zSql);
3723        }
3724        raw_printf(out, "%s\n", zIdx);
3725        raw_printf(out, "%s\n", zEQP);
3726      }
3727    }
3728  }
3729  sqlite3_expert_destroy(p);
3730  pState->expert.pExpert = 0;
3731  return rc;
3732}
3733
3734/*
3735** Implementation of ".expert" dot command.
3736*/
3737static int expertDotCommand(
3738  ShellState *pState,             /* Current shell tool state */
3739  char **azArg,                   /* Array of arguments passed to dot command */
3740  int nArg                        /* Number of entries in azArg[] */
3741){
3742  int rc = SQLITE_OK;
3743  char *zErr = 0;
3744  int i;
3745  int iSample = 0;
3746
3747  assert( pState->expert.pExpert==0 );
3748  memset(&pState->expert, 0, sizeof(ExpertInfo));
3749
3750  for(i=1; rc==SQLITE_OK && i<nArg; i++){
3751    char *z = azArg[i];
3752    int n;
3753    if( z[0]=='-' && z[1]=='-' ) z++;
3754    n = strlen30(z);
3755    if( n>=2 && 0==strncmp(z, "-verbose", n) ){
3756      pState->expert.bVerbose = 1;
3757    }
3758    else if( n>=2 && 0==strncmp(z, "-sample", n) ){
3759      if( i==(nArg-1) ){
3760        raw_printf(stderr, "option requires an argument: %s\n", z);
3761        rc = SQLITE_ERROR;
3762      }else{
3763        iSample = (int)integerValue(azArg[++i]);
3764        if( iSample<0 || iSample>100 ){
3765          raw_printf(stderr, "value out of range: %s\n", azArg[i]);
3766          rc = SQLITE_ERROR;
3767        }
3768      }
3769    }
3770    else{
3771      raw_printf(stderr, "unknown option: %s\n", z);
3772      rc = SQLITE_ERROR;
3773    }
3774  }
3775
3776  if( rc==SQLITE_OK ){
3777    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
3778    if( pState->expert.pExpert==0 ){
3779      raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
3780      rc = SQLITE_ERROR;
3781    }else{
3782      sqlite3_expert_config(
3783          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3784      );
3785    }
3786  }
3787  sqlite3_free(zErr);
3788
3789  return rc;
3790}
3791#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
3792
3793/*
3794** Execute a statement or set of statements.  Print
3795** any result rows/columns depending on the current mode
3796** set via the supplied callback.
3797**
3798** This is very similar to SQLite's built-in sqlite3_exec()
3799** function except it takes a slightly different callback
3800** and callback data argument.
3801*/
3802static int shell_exec(
3803  ShellState *pArg,                         /* Pointer to ShellState */
3804  const char *zSql,                         /* SQL to be evaluated */
3805  char **pzErrMsg                           /* Error msg written here */
3806){
3807  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
3808  int rc = SQLITE_OK;             /* Return Code */
3809  int rc2;
3810  const char *zLeftover;          /* Tail of unprocessed SQL */
3811  sqlite3 *db = pArg->db;
3812
3813  if( pzErrMsg ){
3814    *pzErrMsg = NULL;
3815  }
3816
3817#ifndef SQLITE_OMIT_VIRTUALTABLE
3818  if( pArg->expert.pExpert ){
3819    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3820    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3821  }
3822#endif
3823
3824  while( zSql[0] && (SQLITE_OK == rc) ){
3825    static const char *zStmtSql;
3826    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3827    if( SQLITE_OK != rc ){
3828      if( pzErrMsg ){
3829        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
3830      }
3831    }else{
3832      if( !pStmt ){
3833        /* this happens for a comment or white-space */
3834        zSql = zLeftover;
3835        while( IsSpace(zSql[0]) ) zSql++;
3836        continue;
3837      }
3838      zStmtSql = sqlite3_sql(pStmt);
3839      if( zStmtSql==0 ) zStmtSql = "";
3840      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3841
3842      /* save off the prepared statment handle and reset row count */
3843      if( pArg ){
3844        pArg->pStmt = pStmt;
3845        pArg->cnt = 0;
3846      }
3847
3848      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3849      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
3850        sqlite3_stmt *pExplain;
3851        char *zEQP;
3852        int triggerEQP = 0;
3853        disable_debug_trace_modes();
3854        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3855        if( pArg->autoEQP>=AUTOEQP_trigger ){
3856          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3857        }
3858        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3859        shell_check_oom(zEQP);
3860        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3861        if( rc==SQLITE_OK ){
3862          while( sqlite3_step(pExplain)==SQLITE_ROW ){
3863            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
3864            int iEqpId = sqlite3_column_int(pExplain, 0);
3865            int iParentId = sqlite3_column_int(pExplain, 1);
3866            if( zEQPLine==0 ) zEQPLine = "";
3867            if( zEQPLine[0]=='-' ) eqp_render(pArg);
3868            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
3869          }
3870          eqp_render(pArg);
3871        }
3872        sqlite3_finalize(pExplain);
3873        sqlite3_free(zEQP);
3874        if( pArg->autoEQP>=AUTOEQP_full ){
3875          /* Also do an EXPLAIN for ".eqp full" mode */
3876          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3877          shell_check_oom(zEQP);
3878          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3879          if( rc==SQLITE_OK ){
3880            pArg->cMode = MODE_Explain;
3881            explain_data_prepare(pArg, pExplain);
3882            exec_prepared_stmt(pArg, pExplain);
3883            explain_data_delete(pArg);
3884          }
3885          sqlite3_finalize(pExplain);
3886          sqlite3_free(zEQP);
3887        }
3888        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3889          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3890          /* Reprepare pStmt before reactiving trace modes */
3891          sqlite3_finalize(pStmt);
3892          sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3893          if( pArg ) pArg->pStmt = pStmt;
3894        }
3895        restore_debug_trace_modes();
3896      }
3897
3898      if( pArg ){
3899        pArg->cMode = pArg->mode;
3900        if( pArg->autoExplain ){
3901          if( sqlite3_stmt_isexplain(pStmt)==1 ){
3902            pArg->cMode = MODE_Explain;
3903          }
3904          if( sqlite3_stmt_isexplain(pStmt)==2 ){
3905            pArg->cMode = MODE_EQP;
3906          }
3907        }
3908
3909        /* If the shell is currently in ".explain" mode, gather the extra
3910        ** data required to add indents to the output.*/
3911        if( pArg->cMode==MODE_Explain ){
3912          explain_data_prepare(pArg, pStmt);
3913        }
3914      }
3915
3916      bind_prepared_stmt(pArg, pStmt);
3917      exec_prepared_stmt(pArg, pStmt);
3918      explain_data_delete(pArg);
3919      eqp_render(pArg);
3920
3921      /* print usage stats if stats on */
3922      if( pArg && pArg->statsOn ){
3923        display_stats(db, pArg, 0);
3924      }
3925
3926      /* print loop-counters if required */
3927      if( pArg && pArg->scanstatsOn ){
3928        display_scanstats(db, pArg);
3929      }
3930
3931      /* Finalize the statement just executed. If this fails, save a
3932      ** copy of the error message. Otherwise, set zSql to point to the
3933      ** next statement to execute. */
3934      rc2 = sqlite3_finalize(pStmt);
3935      if( rc!=SQLITE_NOMEM ) rc = rc2;
3936      if( rc==SQLITE_OK ){
3937        zSql = zLeftover;
3938        while( IsSpace(zSql[0]) ) zSql++;
3939      }else if( pzErrMsg ){
3940        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
3941      }
3942
3943      /* clear saved stmt handle */
3944      if( pArg ){
3945        pArg->pStmt = NULL;
3946      }
3947    }
3948  } /* end while */
3949
3950  return rc;
3951}
3952
3953/*
3954** Release memory previously allocated by tableColumnList().
3955*/
3956static void freeColumnList(char **azCol){
3957  int i;
3958  for(i=1; azCol[i]; i++){
3959    sqlite3_free(azCol[i]);
3960  }
3961  /* azCol[0] is a static string */
3962  sqlite3_free(azCol);
3963}
3964
3965/*
3966** Return a list of pointers to strings which are the names of all
3967** columns in table zTab.   The memory to hold the names is dynamically
3968** allocated and must be released by the caller using a subsequent call
3969** to freeColumnList().
3970**
3971** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
3972** value that needs to be preserved, then azCol[0] is filled in with the
3973** name of the rowid column.
3974**
3975** The first regular column in the table is azCol[1].  The list is terminated
3976** by an entry with azCol[i]==0.
3977*/
3978static char **tableColumnList(ShellState *p, const char *zTab){
3979  char **azCol = 0;
3980  sqlite3_stmt *pStmt;
3981  char *zSql;
3982  int nCol = 0;
3983  int nAlloc = 0;
3984  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
3985  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
3986  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3987  int rc;
3988
3989  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3990  shell_check_oom(zSql);
3991  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3992  sqlite3_free(zSql);
3993  if( rc ) return 0;
3994  while( sqlite3_step(pStmt)==SQLITE_ROW ){
3995    if( nCol>=nAlloc-2 ){
3996      nAlloc = nAlloc*2 + nCol + 10;
3997      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3998      shell_check_oom(azCol);
3999    }
4000    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
4001    shell_check_oom(azCol[nCol]);
4002    if( sqlite3_column_int(pStmt, 5) ){
4003      nPK++;
4004      if( nPK==1
4005       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
4006                          "INTEGER")==0
4007      ){
4008        isIPK = 1;
4009      }else{
4010        isIPK = 0;
4011      }
4012    }
4013  }
4014  sqlite3_finalize(pStmt);
4015  if( azCol==0 ) return 0;
4016  azCol[0] = 0;
4017  azCol[nCol+1] = 0;
4018
4019  /* The decision of whether or not a rowid really needs to be preserved
4020  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
4021  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
4022  ** rowids on tables where the rowid is inaccessible because there are other
4023  ** columns in the table named "rowid", "_rowid_", and "oid".
4024  */
4025  if( preserveRowid && isIPK ){
4026    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
4027    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
4028    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
4029    ** ROWID aliases.  To distinguish these cases, check to see if
4030    ** there is a "pk" entry in "PRAGMA index_list".  There will be
4031    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
4032    */
4033    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
4034                           " WHERE origin='pk'", zTab);
4035    shell_check_oom(zSql);
4036    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4037    sqlite3_free(zSql);
4038    if( rc ){
4039      freeColumnList(azCol);
4040      return 0;
4041    }
4042    rc = sqlite3_step(pStmt);
4043    sqlite3_finalize(pStmt);
4044    preserveRowid = rc==SQLITE_ROW;
4045  }
4046  if( preserveRowid ){
4047    /* Only preserve the rowid if we can find a name to use for the
4048    ** rowid */
4049    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
4050    int i, j;
4051    for(j=0; j<3; j++){
4052      for(i=1; i<=nCol; i++){
4053        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
4054      }
4055      if( i>nCol ){
4056        /* At this point, we know that azRowid[j] is not the name of any
4057        ** ordinary column in the table.  Verify that azRowid[j] is a valid
4058        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
4059        ** tables will fail this last check */
4060        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
4061        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
4062        break;
4063      }
4064    }
4065  }
4066  return azCol;
4067}
4068
4069/*
4070** Toggle the reverse_unordered_selects setting.
4071*/
4072static void toggleSelectOrder(sqlite3 *db){
4073  sqlite3_stmt *pStmt = 0;
4074  int iSetting = 0;
4075  char zStmt[100];
4076  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
4077  if( sqlite3_step(pStmt)==SQLITE_ROW ){
4078    iSetting = sqlite3_column_int(pStmt, 0);
4079  }
4080  sqlite3_finalize(pStmt);
4081  sqlite3_snprintf(sizeof(zStmt), zStmt,
4082       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
4083  sqlite3_exec(db, zStmt, 0, 0, 0);
4084}
4085
4086/*
4087** This is a different callback routine used for dumping the database.
4088** Each row received by this callback consists of a table name,
4089** the table type ("index" or "table") and SQL to create the table.
4090** This routine should print text sufficient to recreate the table.
4091*/
4092static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
4093  int rc;
4094  const char *zTable;
4095  const char *zType;
4096  const char *zSql;
4097  ShellState *p = (ShellState *)pArg;
4098  int dataOnly;
4099  int noSys;
4100
4101  UNUSED_PARAMETER(azNotUsed);
4102  if( nArg!=3 || azArg==0 ) return 0;
4103  zTable = azArg[0];
4104  zType = azArg[1];
4105  zSql = azArg[2];
4106  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
4107  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
4108
4109  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
4110    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
4111  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
4112    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
4113  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
4114    return 0;
4115  }else if( dataOnly ){
4116    /* no-op */
4117  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
4118    char *zIns;
4119    if( !p->writableSchema ){
4120      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
4121      p->writableSchema = 1;
4122    }
4123    zIns = sqlite3_mprintf(
4124       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
4125       "VALUES('table','%q','%q',0,'%q');",
4126       zTable, zTable, zSql);
4127    shell_check_oom(zIns);
4128    utf8_printf(p->out, "%s\n", zIns);
4129    sqlite3_free(zIns);
4130    return 0;
4131  }else{
4132    printSchemaLine(p->out, zSql, ";\n");
4133  }
4134
4135  if( strcmp(zType, "table")==0 ){
4136    ShellText sSelect;
4137    ShellText sTable;
4138    char **azCol;
4139    int i;
4140    char *savedDestTable;
4141    int savedMode;
4142
4143    azCol = tableColumnList(p, zTable);
4144    if( azCol==0 ){
4145      p->nErr++;
4146      return 0;
4147    }
4148
4149    /* Always quote the table name, even if it appears to be pure ascii,
4150    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
4151    initText(&sTable);
4152    appendText(&sTable, zTable, quoteChar(zTable));
4153    /* If preserving the rowid, add a column list after the table name.
4154    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
4155    ** instead of the usual "INSERT INTO tab VALUES(...)".
4156    */
4157    if( azCol[0] ){
4158      appendText(&sTable, "(", 0);
4159      appendText(&sTable, azCol[0], 0);
4160      for(i=1; azCol[i]; i++){
4161        appendText(&sTable, ",", 0);
4162        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
4163      }
4164      appendText(&sTable, ")", 0);
4165    }
4166
4167    /* Build an appropriate SELECT statement */
4168    initText(&sSelect);
4169    appendText(&sSelect, "SELECT ", 0);
4170    if( azCol[0] ){
4171      appendText(&sSelect, azCol[0], 0);
4172      appendText(&sSelect, ",", 0);
4173    }
4174    for(i=1; azCol[i]; i++){
4175      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
4176      if( azCol[i+1] ){
4177        appendText(&sSelect, ",", 0);
4178      }
4179    }
4180    freeColumnList(azCol);
4181    appendText(&sSelect, " FROM ", 0);
4182    appendText(&sSelect, zTable, quoteChar(zTable));
4183
4184    savedDestTable = p->zDestTable;
4185    savedMode = p->mode;
4186    p->zDestTable = sTable.z;
4187    p->mode = p->cMode = MODE_Insert;
4188    rc = shell_exec(p, sSelect.z, 0);
4189    if( (rc&0xff)==SQLITE_CORRUPT ){
4190      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4191      toggleSelectOrder(p->db);
4192      shell_exec(p, sSelect.z, 0);
4193      toggleSelectOrder(p->db);
4194    }
4195    p->zDestTable = savedDestTable;
4196    p->mode = savedMode;
4197    freeText(&sTable);
4198    freeText(&sSelect);
4199    if( rc ) p->nErr++;
4200  }
4201  return 0;
4202}
4203
4204/*
4205** Run zQuery.  Use dump_callback() as the callback routine so that
4206** the contents of the query are output as SQL statements.
4207**
4208** If we get a SQLITE_CORRUPT error, rerun the query after appending
4209** "ORDER BY rowid DESC" to the end.
4210*/
4211static int run_schema_dump_query(
4212  ShellState *p,
4213  const char *zQuery
4214){
4215  int rc;
4216  char *zErr = 0;
4217  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
4218  if( rc==SQLITE_CORRUPT ){
4219    char *zQ2;
4220    int len = strlen30(zQuery);
4221    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
4222    if( zErr ){
4223      utf8_printf(p->out, "/****** %s ******/\n", zErr);
4224      sqlite3_free(zErr);
4225      zErr = 0;
4226    }
4227    zQ2 = malloc( len+100 );
4228    if( zQ2==0 ) return rc;
4229    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
4230    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4231    if( rc ){
4232      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
4233    }else{
4234      rc = SQLITE_CORRUPT;
4235    }
4236    sqlite3_free(zErr);
4237    free(zQ2);
4238  }
4239  return rc;
4240}
4241
4242/*
4243** Text of help messages.
4244**
4245** The help text for each individual command begins with a line that starts
4246** with ".".  Subsequent lines are supplemental information.
4247**
4248** There must be two or more spaces between the end of the command and the
4249** start of the description of what that command does.
4250*/
4251static const char *(azHelp[]) = {
4252#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
4253  && !defined(SQLITE_SHELL_FIDDLE)
4254  ".archive ...             Manage SQL archives",
4255  "   Each command must have exactly one of the following options:",
4256  "     -c, --create               Create a new archive",
4257  "     -u, --update               Add or update files with changed mtime",
4258  "     -i, --insert               Like -u but always add even if unchanged",
4259  "     -r, --remove               Remove files from archive",
4260  "     -t, --list                 List contents of archive",
4261  "     -x, --extract              Extract files from archive",
4262  "   Optional arguments:",
4263  "     -v, --verbose              Print each filename as it is processed",
4264  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
4265  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
4266  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
4267  "     -g, --glob                 Use glob matching for names in archive",
4268  "     -n, --dryrun               Show the SQL that would have occurred",
4269  "   Examples:",
4270  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
4271  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
4272  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
4273  "   See also:",
4274  "      http://sqlite.org/cli.html#sqlite_archive_support",
4275#endif
4276#ifndef SQLITE_OMIT_AUTHORIZATION
4277  ".auth ON|OFF             Show authorizer callbacks",
4278#endif
4279#ifndef SQLITE_SHELL_FIDDLE
4280  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
4281  "   Options:",
4282  "       --append            Use the appendvfs",
4283  "       --async             Write to FILE without journal and fsync()",
4284#endif
4285  ".bail on|off             Stop after hitting an error.  Default OFF",
4286  ".binary on|off           Turn binary output on or off.  Default OFF",
4287#ifndef SQLITE_SHELL_FIDDLE
4288  ".cd DIRECTORY            Change the working directory to DIRECTORY",
4289#endif
4290  ".changes on|off          Show number of rows changed by SQL",
4291#ifndef SQLITE_SHELL_FIDDLE
4292  ".check GLOB              Fail if output since .testcase does not match",
4293  ".clone NEWDB             Clone data into NEWDB from the existing database",
4294#endif
4295  ".connection [close] [#]  Open or close an auxiliary database connection",
4296  ".databases               List names and files of attached databases",
4297  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
4298#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4299  ".dbinfo ?DB?             Show status information about the database",
4300#endif
4301  ".dump ?OBJECTS?          Render database content as SQL",
4302  "   Options:",
4303  "     --data-only            Output only INSERT statements",
4304  "     --newlines             Allow unescaped newline characters in output",
4305  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
4306  "     --preserve-rowids      Include ROWID values in the output",
4307  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
4308  "   Additional LIKE patterns can be given in subsequent arguments",
4309  ".echo on|off             Turn command echo on or off",
4310  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
4311  "   Other Modes:",
4312#ifdef SQLITE_DEBUG
4313  "      test                  Show raw EXPLAIN QUERY PLAN output",
4314  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
4315#endif
4316  "      trigger               Like \"full\" but also show trigger bytecode",
4317#ifndef SQLITE_SHELL_FIDDLE
4318  ".excel                   Display the output of next command in spreadsheet",
4319  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
4320#endif
4321#ifndef SQLITE_SHELL_FIDDLE
4322  ".exit ?CODE?             Exit this program with return-code CODE",
4323#endif
4324  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
4325  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
4326  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
4327  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
4328  "   --help                  Show CMD details",
4329  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
4330  ".headers on|off          Turn display of headers on or off",
4331  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
4332#ifndef SQLITE_SHELL_FIDDLE
4333  ".import FILE TABLE       Import data from FILE into TABLE",
4334  "   Options:",
4335  "     --ascii               Use \\037 and \\036 as column and row separators",
4336  "     --csv                 Use , and \\n as column and row separators",
4337  "     --skip N              Skip the first N rows of input",
4338  "     --schema S            Target table to be S.TABLE",
4339  "     -v                    \"Verbose\" - increase auxiliary output",
4340  "   Notes:",
4341  "     *  If TABLE does not exist, it is created.  The first row of input",
4342  "        determines the column names.",
4343  "     *  If neither --csv or --ascii are used, the input mode is derived",
4344  "        from the \".mode\" output mode",
4345  "     *  If FILE begins with \"|\" then it is a command that generates the",
4346  "        input text.",
4347#endif
4348#ifndef SQLITE_OMIT_TEST_CONTROL
4349  ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
4350#endif
4351  ".indexes ?TABLE?         Show names of indexes",
4352  "                           If TABLE is specified, only show indexes for",
4353  "                           tables matching TABLE using the LIKE operator.",
4354#ifdef SQLITE_ENABLE_IOTRACE
4355  ".iotrace FILE            Enable I/O diagnostic logging to FILE",
4356#endif
4357  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
4358  ".lint OPTIONS            Report potential schema issues.",
4359  "     Options:",
4360  "        fkey-indexes     Find missing foreign key indexes",
4361#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
4362  ".load FILE ?ENTRY?       Load an extension library",
4363#endif
4364#ifndef SQLITE_SHELL_FIDDLE
4365  ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
4366#endif
4367  ".mode MODE ?OPTIONS?     Set output mode",
4368  "   MODE is one of:",
4369  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
4370  "     box         Tables using unicode box-drawing characters",
4371  "     csv         Comma-separated values",
4372  "     column      Output in columns.  (See .width)",
4373  "     html        HTML <table> code",
4374  "     insert      SQL insert statements for TABLE",
4375  "     json        Results in a JSON array",
4376  "     line        One value per line",
4377  "     list        Values delimited by \"|\"",
4378  "     markdown    Markdown table format",
4379  "     qbox        Shorthand for \"box --width 60 --quote\"",
4380  "     quote       Escape answers as for SQL",
4381  "     table       ASCII-art table",
4382  "     tabs        Tab-separated values",
4383  "     tcl         TCL list elements",
4384  "   OPTIONS: (for columnar modes or insert mode):",
4385  "     --wrap N       Wrap output lines to no longer than N characters",
4386  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
4387  "     --ww           Shorthand for \"--wordwrap 1\"",
4388  "     --quote        Quote output text as SQL literals",
4389  "     --noquote      Do not quote output text",
4390  "     TABLE          The name of SQL table used for \"insert\" mode",
4391#ifndef SQLITE_SHELL_FIDDLE
4392  ".nonce STRING            Suspend safe mode for one command if nonce matches",
4393#endif
4394  ".nullvalue STRING        Use STRING in place of NULL values",
4395#ifndef SQLITE_SHELL_FIDDLE
4396  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
4397  "     If FILE begins with '|' then open as a pipe",
4398  "       --bom  Put a UTF8 byte-order mark at the beginning",
4399  "       -e     Send output to the system text editor",
4400  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
4401  /* Note that .open is (partially) available in WASM builds but is
4402  ** currently only intended to be used by the fiddle tool, not
4403  ** end users, so is "undocumented." */
4404  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
4405  "     Options:",
4406  "        --append        Use appendvfs to append database to the end of FILE",
4407#endif
4408#ifndef SQLITE_OMIT_DESERIALIZE
4409  "        --deserialize   Load into memory using sqlite3_deserialize()",
4410  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
4411  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
4412#endif
4413  "        --new           Initialize FILE to an empty database",
4414  "        --nofollow      Do not follow symbolic links",
4415  "        --readonly      Open FILE readonly",
4416  "        --zip           FILE is a ZIP archive",
4417#ifndef SQLITE_SHELL_FIDDLE
4418  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
4419  "   If FILE begins with '|' then open it as a pipe.",
4420  "   Options:",
4421  "     --bom                 Prefix output with a UTF8 byte-order mark",
4422  "     -e                    Send output to the system text editor",
4423  "     -x                    Send output as CSV to a spreadsheet",
4424#endif
4425  ".parameter CMD ...       Manage SQL parameter bindings",
4426  "   clear                   Erase all bindings",
4427  "   init                    Initialize the TEMP table that holds bindings",
4428  "   list                    List the current parameter bindings",
4429  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
4430  "                           PARAMETER should start with one of: $ : @ ?",
4431  "   unset PARAMETER         Remove PARAMETER from the binding table",
4432  ".print STRING...         Print literal STRING",
4433#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4434  ".progress N              Invoke progress handler after every N opcodes",
4435  "   --limit N                 Interrupt after N progress callbacks",
4436  "   --once                    Do no more than one progress interrupt",
4437  "   --quiet|-q                No output except at interrupts",
4438  "   --reset                   Reset the count for each input and interrupt",
4439#endif
4440  ".prompt MAIN CONTINUE    Replace the standard prompts",
4441#ifndef SQLITE_SHELL_FIDDLE
4442  ".quit                    Exit this program",
4443  ".read FILE               Read input from FILE or command output",
4444  "    If FILE begins with \"|\", it is a command that generates the input.",
4445#endif
4446#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
4447  ".recover                 Recover as much data as possible from corrupt db.",
4448  "   --freelist-corrupt       Assume the freelist is corrupt",
4449  "   --recovery-db NAME       Store recovery metadata in database file NAME",
4450  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
4451  "   --no-rowids              Do not attempt to recover rowid values",
4452  "                            that are not also INTEGER PRIMARY KEYs",
4453#endif
4454#ifndef SQLITE_SHELL_FIDDLE
4455  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
4456  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
4457#endif
4458  ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
4459  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
4460  "   Options:",
4461  "      --indent             Try to pretty-print the schema",
4462  "      --nosys              Omit objects whose names start with \"sqlite_\"",
4463  ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
4464  "    Options:",
4465  "       --init               Create a new SELFTEST table",
4466  "       -v                   Verbose output",
4467  ".separator COL ?ROW?     Change the column and row separators",
4468#if defined(SQLITE_ENABLE_SESSION)
4469  ".session ?NAME? CMD ...  Create or control sessions",
4470  "   Subcommands:",
4471  "     attach TABLE             Attach TABLE",
4472  "     changeset FILE           Write a changeset into FILE",
4473  "     close                    Close one session",
4474  "     enable ?BOOLEAN?         Set or query the enable bit",
4475  "     filter GLOB...           Reject tables matching GLOBs",
4476  "     indirect ?BOOLEAN?       Mark or query the indirect status",
4477  "     isempty                  Query whether the session is empty",
4478  "     list                     List currently open session names",
4479  "     open DB NAME             Open a new session on DB",
4480  "     patchset FILE            Write a patchset into FILE",
4481  "   If ?NAME? is omitted, the first defined session is used.",
4482#endif
4483  ".sha3sum ...             Compute a SHA3 hash of database content",
4484  "    Options:",
4485  "      --schema              Also hash the sqlite_schema table",
4486  "      --sha3-224            Use the sha3-224 algorithm",
4487  "      --sha3-256            Use the sha3-256 algorithm (default)",
4488  "      --sha3-384            Use the sha3-384 algorithm",
4489  "      --sha3-512            Use the sha3-512 algorithm",
4490  "    Any other argument is a LIKE pattern for tables to hash",
4491#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4492  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
4493#endif
4494  ".show                    Show the current values for various settings",
4495  ".stats ?ARG?             Show stats or turn stats on or off",
4496  "   off                      Turn off automatic stat display",
4497  "   on                       Turn on automatic stat display",
4498  "   stmt                     Show statement stats",
4499  "   vmstep                   Show the virtual machine step count only",
4500#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
4501  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
4502#endif
4503  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
4504#ifndef SQLITE_SHELL_FIDDLE
4505  ".testcase NAME           Begin redirecting output to 'testcase-out.txt'",
4506#endif
4507  ".testctrl CMD ...        Run various sqlite3_test_control() operations",
4508  "                           Run \".testctrl\" with no arguments for details",
4509  ".timeout MS              Try opening locked tables for MS milliseconds",
4510  ".timer on|off            Turn SQL timer on or off",
4511#ifndef SQLITE_OMIT_TRACE
4512  ".trace ?OPTIONS?         Output each SQL statement as it is run",
4513  "    FILE                    Send output to FILE",
4514  "    stdout                  Send output to stdout",
4515  "    stderr                  Send output to stderr",
4516  "    off                     Disable tracing",
4517  "    --expanded              Expand query parameters",
4518#ifdef SQLITE_ENABLE_NORMALIZE
4519  "    --normalized            Normal the SQL statements",
4520#endif
4521  "    --plain                 Show SQL as it is input",
4522  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
4523  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
4524  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
4525  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
4526#endif /* SQLITE_OMIT_TRACE */
4527#ifdef SQLITE_DEBUG
4528  ".unmodule NAME ...       Unregister virtual table modules",
4529  "    --allexcept             Unregister everything except those named",
4530#endif
4531  ".vfsinfo ?AUX?           Information about the top-level VFS",
4532  ".vfslist                 List all available VFSes",
4533  ".vfsname ?AUX?           Print the name of the VFS stack",
4534  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
4535  "     Negative values right-justify",
4536};
4537
4538/*
4539** Output help text.
4540**
4541** zPattern describes the set of commands for which help text is provided.
4542** If zPattern is NULL, then show all commands, but only give a one-line
4543** description of each.
4544**
4545** Return the number of matches.
4546*/
4547static int showHelp(FILE *out, const char *zPattern){
4548  int i = 0;
4549  int j = 0;
4550  int n = 0;
4551  char *zPat;
4552  if( zPattern==0
4553   || zPattern[0]=='0'
4554   || strcmp(zPattern,"-a")==0
4555   || strcmp(zPattern,"-all")==0
4556   || strcmp(zPattern,"--all")==0
4557  ){
4558    /* Show all commands, but only one line per command */
4559    if( zPattern==0 ) zPattern = "";
4560    for(i=0; i<ArraySize(azHelp); i++){
4561      if( azHelp[i][0]=='.' || zPattern[0] ){
4562        utf8_printf(out, "%s\n", azHelp[i]);
4563        n++;
4564      }
4565    }
4566  }else{
4567    /* Look for commands that for which zPattern is an exact prefix */
4568    zPat = sqlite3_mprintf(".%s*", zPattern);
4569    shell_check_oom(zPat);
4570    for(i=0; i<ArraySize(azHelp); i++){
4571      if( sqlite3_strglob(zPat, azHelp[i])==0 ){
4572        utf8_printf(out, "%s\n", azHelp[i]);
4573        j = i+1;
4574        n++;
4575      }
4576    }
4577    sqlite3_free(zPat);
4578    if( n ){
4579      if( n==1 ){
4580        /* when zPattern is a prefix of exactly one command, then include the
4581        ** details of that command, which should begin at offset j */
4582        while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
4583          utf8_printf(out, "%s\n", azHelp[j]);
4584          j++;
4585        }
4586      }
4587      return n;
4588    }
4589    /* Look for commands that contain zPattern anywhere.  Show the complete
4590    ** text of all commands that match. */
4591    zPat = sqlite3_mprintf("%%%s%%", zPattern);
4592    shell_check_oom(zPat);
4593    for(i=0; i<ArraySize(azHelp); i++){
4594      if( azHelp[i][0]=='.' ) j = i;
4595      if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
4596        utf8_printf(out, "%s\n", azHelp[j]);
4597        while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
4598          j++;
4599          utf8_printf(out, "%s\n", azHelp[j]);
4600        }
4601        i = j;
4602        n++;
4603      }
4604    }
4605    sqlite3_free(zPat);
4606  }
4607  return n;
4608}
4609
4610/* Forward reference */
4611static int process_input(ShellState *p);
4612
4613/*
4614** Read the content of file zName into memory obtained from sqlite3_malloc64()
4615** and return a pointer to the buffer. The caller is responsible for freeing
4616** the memory.
4617**
4618** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4619** read.
4620**
4621** For convenience, a nul-terminator byte is always appended to the data read
4622** from the file before the buffer is returned. This byte is not included in
4623** the final value of (*pnByte), if applicable.
4624**
4625** NULL is returned if any error is encountered. The final value of *pnByte
4626** is undefined in this case.
4627*/
4628static char *readFile(const char *zName, int *pnByte){
4629  FILE *in = fopen(zName, "rb");
4630  long nIn;
4631  size_t nRead;
4632  char *pBuf;
4633  if( in==0 ) return 0;
4634  fseek(in, 0, SEEK_END);
4635  nIn = ftell(in);
4636  rewind(in);
4637  pBuf = sqlite3_malloc64( nIn+1 );
4638  if( pBuf==0 ){ fclose(in); return 0; }
4639  nRead = fread(pBuf, nIn, 1, in);
4640  fclose(in);
4641  if( nRead!=1 ){
4642    sqlite3_free(pBuf);
4643    return 0;
4644  }
4645  pBuf[nIn] = 0;
4646  if( pnByte ) *pnByte = nIn;
4647  return pBuf;
4648}
4649
4650#if defined(SQLITE_ENABLE_SESSION)
4651/*
4652** Close a single OpenSession object and release all of its associated
4653** resources.
4654*/
4655static void session_close(OpenSession *pSession){
4656  int i;
4657  sqlite3session_delete(pSession->p);
4658  sqlite3_free(pSession->zName);
4659  for(i=0; i<pSession->nFilter; i++){
4660    sqlite3_free(pSession->azFilter[i]);
4661  }
4662  sqlite3_free(pSession->azFilter);
4663  memset(pSession, 0, sizeof(OpenSession));
4664}
4665#endif
4666
4667/*
4668** Close all OpenSession objects and release all associated resources.
4669*/
4670#if defined(SQLITE_ENABLE_SESSION)
4671static void session_close_all(ShellState *p, int i){
4672  int j;
4673  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
4674  for(j=0; j<pAuxDb->nSession; j++){
4675    session_close(&pAuxDb->aSession[j]);
4676  }
4677  pAuxDb->nSession = 0;
4678}
4679#else
4680# define session_close_all(X,Y)
4681#endif
4682
4683/*
4684** Implementation of the xFilter function for an open session.  Omit
4685** any tables named by ".session filter" but let all other table through.
4686*/
4687#if defined(SQLITE_ENABLE_SESSION)
4688static int session_filter(void *pCtx, const char *zTab){
4689  OpenSession *pSession = (OpenSession*)pCtx;
4690  int i;
4691  for(i=0; i<pSession->nFilter; i++){
4692    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4693  }
4694  return 1;
4695}
4696#endif
4697
4698/*
4699** Try to deduce the type of file for zName based on its content.  Return
4700** one of the SHELL_OPEN_* constants.
4701**
4702** If the file does not exist or is empty but its name looks like a ZIP
4703** archive and the dfltZip flag is true, then assume it is a ZIP archive.
4704** Otherwise, assume an ordinary database regardless of the filename if
4705** the type cannot be determined from content.
4706*/
4707int deduceDatabaseType(const char *zName, int dfltZip){
4708  FILE *f = fopen(zName, "rb");
4709  size_t n;
4710  int rc = SHELL_OPEN_UNSPEC;
4711  char zBuf[100];
4712  if( f==0 ){
4713    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4714       return SHELL_OPEN_ZIPFILE;
4715    }else{
4716       return SHELL_OPEN_NORMAL;
4717    }
4718  }
4719  n = fread(zBuf, 16, 1, f);
4720  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
4721    fclose(f);
4722    return SHELL_OPEN_NORMAL;
4723  }
4724  fseek(f, -25, SEEK_END);
4725  n = fread(zBuf, 25, 1, f);
4726  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
4727    rc = SHELL_OPEN_APPENDVFS;
4728  }else{
4729    fseek(f, -22, SEEK_END);
4730    n = fread(zBuf, 22, 1, f);
4731    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
4732       && zBuf[3]==0x06 ){
4733      rc = SHELL_OPEN_ZIPFILE;
4734    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
4735      rc = SHELL_OPEN_ZIPFILE;
4736    }
4737  }
4738  fclose(f);
4739  return rc;
4740}
4741
4742#ifndef SQLITE_OMIT_DESERIALIZE
4743/*
4744** Reconstruct an in-memory database using the output from the "dbtotxt"
4745** program.  Read content from the file in p->aAuxDb[].zDbFilename.
4746** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
4747*/
4748static unsigned char *readHexDb(ShellState *p, int *pnData){
4749  unsigned char *a = 0;
4750  int nLine;
4751  int n = 0;
4752  int pgsz = 0;
4753  int iOffset = 0;
4754  int j, k;
4755  int rc;
4756  FILE *in;
4757  const char *zDbFilename = p->pAuxDb->zDbFilename;
4758  unsigned int x[16];
4759  char zLine[1000];
4760  if( zDbFilename ){
4761    in = fopen(zDbFilename, "r");
4762    if( in==0 ){
4763      utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename);
4764      return 0;
4765    }
4766    nLine = 0;
4767  }else{
4768    in = p->in;
4769    nLine = p->lineno;
4770    if( in==0 ) in = stdin;
4771  }
4772  *pnData = 0;
4773  nLine++;
4774  if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
4775  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
4776  if( rc!=2 ) goto readHexDb_error;
4777  if( n<0 ) goto readHexDb_error;
4778  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
4779  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
4780  a = sqlite3_malloc( n ? n : 1 );
4781  shell_check_oom(a);
4782  memset(a, 0, n);
4783  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
4784    utf8_printf(stderr, "invalid pagesize\n");
4785    goto readHexDb_error;
4786  }
4787  for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
4788    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
4789    if( rc==2 ){
4790      iOffset = k;
4791      continue;
4792    }
4793    if( strncmp(zLine, "| end ", 6)==0 ){
4794      break;
4795    }
4796    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
4797                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
4798                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
4799    if( rc==17 ){
4800      k = iOffset+j;
4801      if( k+16<=n && k>=0 ){
4802        int ii;
4803        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
4804      }
4805    }
4806  }
4807  *pnData = n;
4808  if( in!=p->in ){
4809    fclose(in);
4810  }else{
4811    p->lineno = nLine;
4812  }
4813  return a;
4814
4815readHexDb_error:
4816  if( in!=p->in ){
4817    fclose(in);
4818  }else{
4819    while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
4820      nLine++;
4821      if(strncmp(zLine, "| end ", 6)==0 ) break;
4822    }
4823    p->lineno = nLine;
4824  }
4825  sqlite3_free(a);
4826  utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
4827  return 0;
4828}
4829#endif /* SQLITE_OMIT_DESERIALIZE */
4830
4831/*
4832** Scalar function "shell_int32". The first argument to this function
4833** must be a blob. The second a non-negative integer. This function
4834** reads and returns a 32-bit big-endian integer from byte
4835** offset (4*<arg2>) of the blob.
4836*/
4837static void shellInt32(
4838  sqlite3_context *context,
4839  int argc,
4840  sqlite3_value **argv
4841){
4842  const unsigned char *pBlob;
4843  int nBlob;
4844  int iInt;
4845
4846  UNUSED_PARAMETER(argc);
4847  nBlob = sqlite3_value_bytes(argv[0]);
4848  pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
4849  iInt = sqlite3_value_int(argv[1]);
4850
4851  if( iInt>=0 && (iInt+1)*4<=nBlob ){
4852    const unsigned char *a = &pBlob[iInt*4];
4853    sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
4854                       + ((sqlite3_int64)a[1]<<16)
4855                       + ((sqlite3_int64)a[2]<< 8)
4856                       + ((sqlite3_int64)a[3]<< 0);
4857    sqlite3_result_int64(context, iVal);
4858  }
4859}
4860
4861/*
4862** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
4863** using "..." with internal double-quote characters doubled.
4864*/
4865static void shellIdQuote(
4866  sqlite3_context *context,
4867  int argc,
4868  sqlite3_value **argv
4869){
4870  const char *zName = (const char*)sqlite3_value_text(argv[0]);
4871  UNUSED_PARAMETER(argc);
4872  if( zName ){
4873    char *z = sqlite3_mprintf("\"%w\"", zName);
4874    sqlite3_result_text(context, z, -1, sqlite3_free);
4875  }
4876}
4877
4878/*
4879** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
4880*/
4881static void shellUSleepFunc(
4882  sqlite3_context *context,
4883  int argcUnused,
4884  sqlite3_value **argv
4885){
4886  int sleep = sqlite3_value_int(argv[0]);
4887  (void)argcUnused;
4888  sqlite3_sleep(sleep/1000);
4889  sqlite3_result_int(context, sleep);
4890}
4891
4892/*
4893** Scalar function "shell_escape_crnl" used by the .recover command.
4894** The argument passed to this function is the output of built-in
4895** function quote(). If the first character of the input is "'",
4896** indicating that the value passed to quote() was a text value,
4897** then this function searches the input for "\n" and "\r" characters
4898** and adds a wrapper similar to the following:
4899**
4900**   replace(replace(<input>, '\n', char(10), '\r', char(13));
4901**
4902** Or, if the first character of the input is not "'", then a copy
4903** of the input is returned.
4904*/
4905static void shellEscapeCrnl(
4906  sqlite3_context *context,
4907  int argc,
4908  sqlite3_value **argv
4909){
4910  const char *zText = (const char*)sqlite3_value_text(argv[0]);
4911  UNUSED_PARAMETER(argc);
4912  if( zText && zText[0]=='\'' ){
4913    int nText = sqlite3_value_bytes(argv[0]);
4914    int i;
4915    char zBuf1[20];
4916    char zBuf2[20];
4917    const char *zNL = 0;
4918    const char *zCR = 0;
4919    int nCR = 0;
4920    int nNL = 0;
4921
4922    for(i=0; zText[i]; i++){
4923      if( zNL==0 && zText[i]=='\n' ){
4924        zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4925        nNL = (int)strlen(zNL);
4926      }
4927      if( zCR==0 && zText[i]=='\r' ){
4928        zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4929        nCR = (int)strlen(zCR);
4930      }
4931    }
4932
4933    if( zNL || zCR ){
4934      int iOut = 0;
4935      i64 nMax = (nNL > nCR) ? nNL : nCR;
4936      i64 nAlloc = nMax * nText + (nMax+64)*2;
4937      char *zOut = (char*)sqlite3_malloc64(nAlloc);
4938      if( zOut==0 ){
4939        sqlite3_result_error_nomem(context);
4940        return;
4941      }
4942
4943      if( zNL && zCR ){
4944        memcpy(&zOut[iOut], "replace(replace(", 16);
4945        iOut += 16;
4946      }else{
4947        memcpy(&zOut[iOut], "replace(", 8);
4948        iOut += 8;
4949      }
4950      for(i=0; zText[i]; i++){
4951        if( zText[i]=='\n' ){
4952          memcpy(&zOut[iOut], zNL, nNL);
4953          iOut += nNL;
4954        }else if( zText[i]=='\r' ){
4955          memcpy(&zOut[iOut], zCR, nCR);
4956          iOut += nCR;
4957        }else{
4958          zOut[iOut] = zText[i];
4959          iOut++;
4960        }
4961      }
4962
4963      if( zNL ){
4964        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4965        memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4966        memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4967      }
4968      if( zCR ){
4969        memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4970        memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4971        memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4972      }
4973
4974      sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4975      sqlite3_free(zOut);
4976      return;
4977    }
4978  }
4979
4980  sqlite3_result_value(context, argv[0]);
4981}
4982
4983/* Flags for open_db().
4984**
4985** The default behavior of open_db() is to exit(1) if the database fails to
4986** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4987** but still returns without calling exit.
4988**
4989** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4990** ZIP archive if the file does not exist or is empty and its name matches
4991** the *.zip pattern.
4992*/
4993#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
4994#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
4995
4996/*
4997** Make sure the database is open.  If it is not, then open it.  If
4998** the database fails to open, print an error message and exit.
4999*/
5000static void open_db(ShellState *p, int openFlags){
5001  if( p->db==0 ){
5002    const char *zDbFilename = p->pAuxDb->zDbFilename;
5003    if( p->openMode==SHELL_OPEN_UNSPEC ){
5004      if( zDbFilename==0 || zDbFilename[0]==0 ){
5005        p->openMode = SHELL_OPEN_NORMAL;
5006      }else{
5007        p->openMode = (u8)deduceDatabaseType(zDbFilename,
5008                             (openFlags & OPEN_DB_ZIPFILE)!=0);
5009      }
5010    }
5011    switch( p->openMode ){
5012      case SHELL_OPEN_APPENDVFS: {
5013        sqlite3_open_v2(zDbFilename, &p->db,
5014           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
5015        break;
5016      }
5017      case SHELL_OPEN_HEXDB:
5018      case SHELL_OPEN_DESERIALIZE: {
5019        sqlite3_open(0, &p->db);
5020        break;
5021      }
5022      case SHELL_OPEN_ZIPFILE: {
5023        sqlite3_open(":memory:", &p->db);
5024        break;
5025      }
5026      case SHELL_OPEN_READONLY: {
5027        sqlite3_open_v2(zDbFilename, &p->db,
5028            SQLITE_OPEN_READONLY|p->openFlags, 0);
5029        break;
5030      }
5031      case SHELL_OPEN_UNSPEC:
5032      case SHELL_OPEN_NORMAL: {
5033        sqlite3_open_v2(zDbFilename, &p->db,
5034           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
5035        break;
5036      }
5037    }
5038    globalDb = p->db;
5039    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
5040      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
5041          zDbFilename, sqlite3_errmsg(p->db));
5042      if( openFlags & OPEN_DB_KEEPALIVE ){
5043        sqlite3_open(":memory:", &p->db);
5044        return;
5045      }
5046      exit(1);
5047    }
5048#ifndef SQLITE_OMIT_LOAD_EXTENSION
5049    sqlite3_enable_load_extension(p->db, 1);
5050#endif
5051    sqlite3_shathree_init(p->db, 0, 0);
5052    sqlite3_uint_init(p->db, 0, 0);
5053    sqlite3_decimal_init(p->db, 0, 0);
5054    sqlite3_regexp_init(p->db, 0, 0);
5055    sqlite3_ieee_init(p->db, 0, 0);
5056    sqlite3_series_init(p->db, 0, 0);
5057#ifndef SQLITE_SHELL_FIDDLE
5058    sqlite3_fileio_init(p->db, 0, 0);
5059    sqlite3_completion_init(p->db, 0, 0);
5060#endif
5061#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5062    sqlite3_dbdata_init(p->db, 0, 0);
5063#endif
5064#ifdef SQLITE_HAVE_ZLIB
5065    if( !p->bSafeModePersist ){
5066      sqlite3_zipfile_init(p->db, 0, 0);
5067      sqlite3_sqlar_init(p->db, 0, 0);
5068    }
5069#endif
5070    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
5071                            shellAddSchemaName, 0, 0);
5072    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
5073                            shellModuleSchema, 0, 0);
5074    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
5075                            shellPutsFunc, 0, 0);
5076    sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
5077                            shellEscapeCrnl, 0, 0);
5078    sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
5079                            shellInt32, 0, 0);
5080    sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
5081                            shellIdQuote, 0, 0);
5082    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
5083                            shellUSleepFunc, 0, 0);
5084#ifndef SQLITE_NOHAVE_SYSTEM
5085    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
5086                            editFunc, 0, 0);
5087    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
5088                            editFunc, 0, 0);
5089#endif
5090    if( p->openMode==SHELL_OPEN_ZIPFILE ){
5091      char *zSql = sqlite3_mprintf(
5092         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
5093      shell_check_oom(zSql);
5094      sqlite3_exec(p->db, zSql, 0, 0, 0);
5095      sqlite3_free(zSql);
5096    }
5097#ifndef SQLITE_OMIT_DESERIALIZE
5098    else
5099    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
5100      int rc;
5101      int nData = 0;
5102      unsigned char *aData;
5103      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
5104        aData = (unsigned char*)readFile(zDbFilename, &nData);
5105      }else{
5106        aData = readHexDb(p, &nData);
5107        if( aData==0 ){
5108          return;
5109        }
5110      }
5111      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
5112                   SQLITE_DESERIALIZE_RESIZEABLE |
5113                   SQLITE_DESERIALIZE_FREEONCLOSE);
5114      if( rc ){
5115        utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
5116      }
5117      if( p->szMax>0 ){
5118        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
5119      }
5120    }
5121#endif
5122  }
5123  if( p->bSafeModePersist && p->db!=0 ){
5124    sqlite3_set_authorizer(p->db, safeModeAuth, p);
5125  }
5126}
5127
5128/*
5129** Attempt to close the databaes connection.  Report errors.
5130*/
5131void close_db(sqlite3 *db){
5132  int rc = sqlite3_close(db);
5133  if( rc ){
5134    utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
5135        rc, sqlite3_errmsg(db));
5136  }
5137}
5138
5139#if HAVE_READLINE || HAVE_EDITLINE
5140/*
5141** Readline completion callbacks
5142*/
5143static char *readline_completion_generator(const char *text, int state){
5144  static sqlite3_stmt *pStmt = 0;
5145  char *zRet;
5146  if( state==0 ){
5147    char *zSql;
5148    sqlite3_finalize(pStmt);
5149    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5150                           "  FROM completion(%Q) ORDER BY 1", text);
5151    shell_check_oom(zSql);
5152    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5153    sqlite3_free(zSql);
5154  }
5155  if( sqlite3_step(pStmt)==SQLITE_ROW ){
5156    const char *z = (const char*)sqlite3_column_text(pStmt,0);
5157    zRet = z ? strdup(z) : 0;
5158  }else{
5159    sqlite3_finalize(pStmt);
5160    pStmt = 0;
5161    zRet = 0;
5162  }
5163  return zRet;
5164}
5165static char **readline_completion(const char *zText, int iStart, int iEnd){
5166  rl_attempted_completion_over = 1;
5167  return rl_completion_matches(zText, readline_completion_generator);
5168}
5169
5170#elif HAVE_LINENOISE
5171/*
5172** Linenoise completion callback
5173*/
5174static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
5175  int nLine = strlen30(zLine);
5176  int i, iStart;
5177  sqlite3_stmt *pStmt = 0;
5178  char *zSql;
5179  char zBuf[1000];
5180
5181  if( nLine>sizeof(zBuf)-30 ) return;
5182  if( zLine[0]=='.' || zLine[0]=='#') return;
5183  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
5184  if( i==nLine-1 ) return;
5185  iStart = i+1;
5186  memcpy(zBuf, zLine, iStart);
5187  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
5188                         "  FROM completion(%Q,%Q) ORDER BY 1",
5189                         &zLine[iStart], zLine);
5190  shell_check_oom(zSql);
5191  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
5192  sqlite3_free(zSql);
5193  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
5194  while( sqlite3_step(pStmt)==SQLITE_ROW ){
5195    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
5196    int nCompletion = sqlite3_column_bytes(pStmt, 0);
5197    if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){
5198      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
5199      linenoiseAddCompletion(lc, zBuf);
5200    }
5201  }
5202  sqlite3_finalize(pStmt);
5203}
5204#endif
5205
5206/*
5207** Do C-language style dequoting.
5208**
5209**    \a    -> alarm
5210**    \b    -> backspace
5211**    \t    -> tab
5212**    \n    -> newline
5213**    \v    -> vertical tab
5214**    \f    -> form feed
5215**    \r    -> carriage return
5216**    \s    -> space
5217**    \"    -> "
5218**    \'    -> '
5219**    \\    -> backslash
5220**    \NNN  -> ascii character NNN in octal
5221*/
5222static void resolve_backslashes(char *z){
5223  int i, j;
5224  char c;
5225  while( *z && *z!='\\' ) z++;
5226  for(i=j=0; (c = z[i])!=0; i++, j++){
5227    if( c=='\\' && z[i+1]!=0 ){
5228      c = z[++i];
5229      if( c=='a' ){
5230        c = '\a';
5231      }else if( c=='b' ){
5232        c = '\b';
5233      }else if( c=='t' ){
5234        c = '\t';
5235      }else if( c=='n' ){
5236        c = '\n';
5237      }else if( c=='v' ){
5238        c = '\v';
5239      }else if( c=='f' ){
5240        c = '\f';
5241      }else if( c=='r' ){
5242        c = '\r';
5243      }else if( c=='"' ){
5244        c = '"';
5245      }else if( c=='\'' ){
5246        c = '\'';
5247      }else if( c=='\\' ){
5248        c = '\\';
5249      }else if( c>='0' && c<='7' ){
5250        c -= '0';
5251        if( z[i+1]>='0' && z[i+1]<='7' ){
5252          i++;
5253          c = (c<<3) + z[i] - '0';
5254          if( z[i+1]>='0' && z[i+1]<='7' ){
5255            i++;
5256            c = (c<<3) + z[i] - '0';
5257          }
5258        }
5259      }
5260    }
5261    z[j] = c;
5262  }
5263  if( j<i ) z[j] = 0;
5264}
5265
5266/*
5267** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
5268** for TRUE and FALSE.  Return the integer value if appropriate.
5269*/
5270static int booleanValue(const char *zArg){
5271  int i;
5272  if( zArg[0]=='0' && zArg[1]=='x' ){
5273    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
5274  }else{
5275    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
5276  }
5277  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
5278  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
5279    return 1;
5280  }
5281  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
5282    return 0;
5283  }
5284  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
5285          zArg);
5286  return 0;
5287}
5288
5289/*
5290** Set or clear a shell flag according to a boolean value.
5291*/
5292static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
5293  if( booleanValue(zArg) ){
5294    ShellSetFlag(p, mFlag);
5295  }else{
5296    ShellClearFlag(p, mFlag);
5297  }
5298}
5299
5300/*
5301** Close an output file, assuming it is not stderr or stdout
5302*/
5303static void output_file_close(FILE *f){
5304  if( f && f!=stdout && f!=stderr ) fclose(f);
5305}
5306
5307/*
5308** Try to open an output file.   The names "stdout" and "stderr" are
5309** recognized and do the right thing.  NULL is returned if the output
5310** filename is "off".
5311*/
5312static FILE *output_file_open(const char *zFile, int bTextMode){
5313  FILE *f;
5314  if( strcmp(zFile,"stdout")==0 ){
5315    f = stdout;
5316  }else if( strcmp(zFile, "stderr")==0 ){
5317    f = stderr;
5318  }else if( strcmp(zFile, "off")==0 ){
5319    f = 0;
5320  }else{
5321    f = fopen(zFile, bTextMode ? "w" : "wb");
5322    if( f==0 ){
5323      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5324    }
5325  }
5326  return f;
5327}
5328
5329#ifndef SQLITE_OMIT_TRACE
5330/*
5331** A routine for handling output from sqlite3_trace().
5332*/
5333static int sql_trace_callback(
5334  unsigned mType,         /* The trace type */
5335  void *pArg,             /* The ShellState pointer */
5336  void *pP,               /* Usually a pointer to sqlite_stmt */
5337  void *pX                /* Auxiliary output */
5338){
5339  ShellState *p = (ShellState*)pArg;
5340  sqlite3_stmt *pStmt;
5341  const char *zSql;
5342  int nSql;
5343  if( p->traceOut==0 ) return 0;
5344  if( mType==SQLITE_TRACE_CLOSE ){
5345    utf8_printf(p->traceOut, "-- closing database connection\n");
5346    return 0;
5347  }
5348  if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
5349    zSql = (const char*)pX;
5350  }else{
5351    pStmt = (sqlite3_stmt*)pP;
5352    switch( p->eTraceType ){
5353      case SHELL_TRACE_EXPANDED: {
5354        zSql = sqlite3_expanded_sql(pStmt);
5355        break;
5356      }
5357#ifdef SQLITE_ENABLE_NORMALIZE
5358      case SHELL_TRACE_NORMALIZED: {
5359        zSql = sqlite3_normalized_sql(pStmt);
5360        break;
5361      }
5362#endif
5363      default: {
5364        zSql = sqlite3_sql(pStmt);
5365        break;
5366      }
5367    }
5368  }
5369  if( zSql==0 ) return 0;
5370  nSql = strlen30(zSql);
5371  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
5372  switch( mType ){
5373    case SQLITE_TRACE_ROW:
5374    case SQLITE_TRACE_STMT: {
5375      utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
5376      break;
5377    }
5378    case SQLITE_TRACE_PROFILE: {
5379      sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
5380      utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
5381      break;
5382    }
5383  }
5384  return 0;
5385}
5386#endif
5387
5388/*
5389** A no-op routine that runs with the ".breakpoint" doc-command.  This is
5390** a useful spot to set a debugger breakpoint.
5391*/
5392static void test_breakpoint(void){
5393  static int nCall = 0;
5394  nCall++;
5395}
5396
5397/*
5398** An object used to read a CSV and other files for import.
5399*/
5400typedef struct ImportCtx ImportCtx;
5401struct ImportCtx {
5402  const char *zFile;  /* Name of the input file */
5403  FILE *in;           /* Read the CSV text from this input stream */
5404  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
5405  char *z;            /* Accumulated text for a field */
5406  int n;              /* Number of bytes in z */
5407  int nAlloc;         /* Space allocated for z[] */
5408  int nLine;          /* Current line number */
5409  int nRow;           /* Number of rows imported */
5410  int nErr;           /* Number of errors encountered */
5411  int bNotFirst;      /* True if one or more bytes already read */
5412  int cTerm;          /* Character that terminated the most recent field */
5413  int cColSep;        /* The column separator character.  (Usually ",") */
5414  int cRowSep;        /* The row separator character.  (Usually "\n") */
5415};
5416
5417/* Clean up resourced used by an ImportCtx */
5418static void import_cleanup(ImportCtx *p){
5419  if( p->in!=0 && p->xCloser!=0 ){
5420    p->xCloser(p->in);
5421    p->in = 0;
5422  }
5423  sqlite3_free(p->z);
5424  p->z = 0;
5425}
5426
5427/* Append a single byte to z[] */
5428static void import_append_char(ImportCtx *p, int c){
5429  if( p->n+1>=p->nAlloc ){
5430    p->nAlloc += p->nAlloc + 100;
5431    p->z = sqlite3_realloc64(p->z, p->nAlloc);
5432    shell_check_oom(p->z);
5433  }
5434  p->z[p->n++] = (char)c;
5435}
5436
5437/* Read a single field of CSV text.  Compatible with rfc4180 and extended
5438** with the option of having a separator other than ",".
5439**
5440**   +  Input comes from p->in.
5441**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5442**      from sqlite3_malloc64().
5443**   +  Use p->cSep as the column separator.  The default is ",".
5444**   +  Use p->rSep as the row separator.  The default is "\n".
5445**   +  Keep track of the line number in p->nLine.
5446**   +  Store the character that terminates the field in p->cTerm.  Store
5447**      EOF on end-of-file.
5448**   +  Report syntax errors on stderr
5449*/
5450static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
5451  int c;
5452  int cSep = p->cColSep;
5453  int rSep = p->cRowSep;
5454  p->n = 0;
5455  c = fgetc(p->in);
5456  if( c==EOF || seenInterrupt ){
5457    p->cTerm = EOF;
5458    return 0;
5459  }
5460  if( c=='"' ){
5461    int pc, ppc;
5462    int startLine = p->nLine;
5463    int cQuote = c;
5464    pc = ppc = 0;
5465    while( 1 ){
5466      c = fgetc(p->in);
5467      if( c==rSep ) p->nLine++;
5468      if( c==cQuote ){
5469        if( pc==cQuote ){
5470          pc = 0;
5471          continue;
5472        }
5473      }
5474      if( (c==cSep && pc==cQuote)
5475       || (c==rSep && pc==cQuote)
5476       || (c==rSep && pc=='\r' && ppc==cQuote)
5477       || (c==EOF && pc==cQuote)
5478      ){
5479        do{ p->n--; }while( p->z[p->n]!=cQuote );
5480        p->cTerm = c;
5481        break;
5482      }
5483      if( pc==cQuote && c!='\r' ){
5484        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
5485                p->zFile, p->nLine, cQuote);
5486      }
5487      if( c==EOF ){
5488        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
5489                p->zFile, startLine, cQuote);
5490        p->cTerm = c;
5491        break;
5492      }
5493      import_append_char(p, c);
5494      ppc = pc;
5495      pc = c;
5496    }
5497  }else{
5498    /* If this is the first field being parsed and it begins with the
5499    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
5500    if( (c&0xff)==0xef && p->bNotFirst==0 ){
5501      import_append_char(p, c);
5502      c = fgetc(p->in);
5503      if( (c&0xff)==0xbb ){
5504        import_append_char(p, c);
5505        c = fgetc(p->in);
5506        if( (c&0xff)==0xbf ){
5507          p->bNotFirst = 1;
5508          p->n = 0;
5509          return csv_read_one_field(p);
5510        }
5511      }
5512    }
5513    while( c!=EOF && c!=cSep && c!=rSep ){
5514      import_append_char(p, c);
5515      c = fgetc(p->in);
5516    }
5517    if( c==rSep ){
5518      p->nLine++;
5519      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
5520    }
5521    p->cTerm = c;
5522  }
5523  if( p->z ) p->z[p->n] = 0;
5524  p->bNotFirst = 1;
5525  return p->z;
5526}
5527
5528/* Read a single field of ASCII delimited text.
5529**
5530**   +  Input comes from p->in.
5531**   +  Store results in p->z of length p->n.  Space to hold p->z comes
5532**      from sqlite3_malloc64().
5533**   +  Use p->cSep as the column separator.  The default is "\x1F".
5534**   +  Use p->rSep as the row separator.  The default is "\x1E".
5535**   +  Keep track of the row number in p->nLine.
5536**   +  Store the character that terminates the field in p->cTerm.  Store
5537**      EOF on end-of-file.
5538**   +  Report syntax errors on stderr
5539*/
5540static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
5541  int c;
5542  int cSep = p->cColSep;
5543  int rSep = p->cRowSep;
5544  p->n = 0;
5545  c = fgetc(p->in);
5546  if( c==EOF || seenInterrupt ){
5547    p->cTerm = EOF;
5548    return 0;
5549  }
5550  while( c!=EOF && c!=cSep && c!=rSep ){
5551    import_append_char(p, c);
5552    c = fgetc(p->in);
5553  }
5554  if( c==rSep ){
5555    p->nLine++;
5556  }
5557  p->cTerm = c;
5558  if( p->z ) p->z[p->n] = 0;
5559  return p->z;
5560}
5561
5562/*
5563** Try to transfer data for table zTable.  If an error is seen while
5564** moving forward, try to go backwards.  The backwards movement won't
5565** work for WITHOUT ROWID tables.
5566*/
5567static void tryToCloneData(
5568  ShellState *p,
5569  sqlite3 *newDb,
5570  const char *zTable
5571){
5572  sqlite3_stmt *pQuery = 0;
5573  sqlite3_stmt *pInsert = 0;
5574  char *zQuery = 0;
5575  char *zInsert = 0;
5576  int rc;
5577  int i, j, n;
5578  int nTable = strlen30(zTable);
5579  int k = 0;
5580  int cnt = 0;
5581  const int spinRate = 10000;
5582
5583  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
5584  shell_check_oom(zQuery);
5585  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5586  if( rc ){
5587    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5588            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5589            zQuery);
5590    goto end_data_xfer;
5591  }
5592  n = sqlite3_column_count(pQuery);
5593  zInsert = sqlite3_malloc64(200 + nTable + n*3);
5594  shell_check_oom(zInsert);
5595  sqlite3_snprintf(200+nTable,zInsert,
5596                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
5597  i = strlen30(zInsert);
5598  for(j=1; j<n; j++){
5599    memcpy(zInsert+i, ",?", 2);
5600    i += 2;
5601  }
5602  memcpy(zInsert+i, ");", 3);
5603  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
5604  if( rc ){
5605    utf8_printf(stderr, "Error %d: %s on [%s]\n",
5606            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
5607            zQuery);
5608    goto end_data_xfer;
5609  }
5610  for(k=0; k<2; k++){
5611    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5612      for(i=0; i<n; i++){
5613        switch( sqlite3_column_type(pQuery, i) ){
5614          case SQLITE_NULL: {
5615            sqlite3_bind_null(pInsert, i+1);
5616            break;
5617          }
5618          case SQLITE_INTEGER: {
5619            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
5620            break;
5621          }
5622          case SQLITE_FLOAT: {
5623            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
5624            break;
5625          }
5626          case SQLITE_TEXT: {
5627            sqlite3_bind_text(pInsert, i+1,
5628                             (const char*)sqlite3_column_text(pQuery,i),
5629                             -1, SQLITE_STATIC);
5630            break;
5631          }
5632          case SQLITE_BLOB: {
5633            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
5634                                            sqlite3_column_bytes(pQuery,i),
5635                                            SQLITE_STATIC);
5636            break;
5637          }
5638        }
5639      } /* End for */
5640      rc = sqlite3_step(pInsert);
5641      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
5642        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
5643                        sqlite3_errmsg(newDb));
5644      }
5645      sqlite3_reset(pInsert);
5646      cnt++;
5647      if( (cnt%spinRate)==0 ){
5648        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
5649        fflush(stdout);
5650      }
5651    } /* End while */
5652    if( rc==SQLITE_DONE ) break;
5653    sqlite3_finalize(pQuery);
5654    sqlite3_free(zQuery);
5655    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
5656                             zTable);
5657    shell_check_oom(zQuery);
5658    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5659    if( rc ){
5660      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
5661      break;
5662    }
5663  } /* End for(k=0...) */
5664
5665end_data_xfer:
5666  sqlite3_finalize(pQuery);
5667  sqlite3_finalize(pInsert);
5668  sqlite3_free(zQuery);
5669  sqlite3_free(zInsert);
5670}
5671
5672
5673/*
5674** Try to transfer all rows of the schema that match zWhere.  For
5675** each row, invoke xForEach() on the object defined by that row.
5676** If an error is encountered while moving forward through the
5677** sqlite_schema table, try again moving backwards.
5678*/
5679static void tryToCloneSchema(
5680  ShellState *p,
5681  sqlite3 *newDb,
5682  const char *zWhere,
5683  void (*xForEach)(ShellState*,sqlite3*,const char*)
5684){
5685  sqlite3_stmt *pQuery = 0;
5686  char *zQuery = 0;
5687  int rc;
5688  const unsigned char *zName;
5689  const unsigned char *zSql;
5690  char *zErrMsg = 0;
5691
5692  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5693                           " WHERE %s", zWhere);
5694  shell_check_oom(zQuery);
5695  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5696  if( rc ){
5697    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5698                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5699                    zQuery);
5700    goto end_schema_xfer;
5701  }
5702  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
5703    zName = sqlite3_column_text(pQuery, 0);
5704    zSql = sqlite3_column_text(pQuery, 1);
5705    if( zName==0 || zSql==0 ) continue;
5706    printf("%s... ", zName); fflush(stdout);
5707    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5708    if( zErrMsg ){
5709      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5710      sqlite3_free(zErrMsg);
5711      zErrMsg = 0;
5712    }
5713    if( xForEach ){
5714      xForEach(p, newDb, (const char*)zName);
5715    }
5716    printf("done\n");
5717  }
5718  if( rc!=SQLITE_DONE ){
5719    sqlite3_finalize(pQuery);
5720    sqlite3_free(zQuery);
5721    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
5722                             " WHERE %s ORDER BY rowid DESC", zWhere);
5723    shell_check_oom(zQuery);
5724    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
5725    if( rc ){
5726      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
5727                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
5728                      zQuery);
5729      goto end_schema_xfer;
5730    }
5731    while( sqlite3_step(pQuery)==SQLITE_ROW ){
5732      zName = sqlite3_column_text(pQuery, 0);
5733      zSql = sqlite3_column_text(pQuery, 1);
5734      if( zName==0 || zSql==0 ) continue;
5735      printf("%s... ", zName); fflush(stdout);
5736      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
5737      if( zErrMsg ){
5738        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
5739        sqlite3_free(zErrMsg);
5740        zErrMsg = 0;
5741      }
5742      if( xForEach ){
5743        xForEach(p, newDb, (const char*)zName);
5744      }
5745      printf("done\n");
5746    }
5747  }
5748end_schema_xfer:
5749  sqlite3_finalize(pQuery);
5750  sqlite3_free(zQuery);
5751}
5752
5753/*
5754** Open a new database file named "zNewDb".  Try to recover as much information
5755** as possible out of the main database (which might be corrupt) and write it
5756** into zNewDb.
5757*/
5758static void tryToClone(ShellState *p, const char *zNewDb){
5759  int rc;
5760  sqlite3 *newDb = 0;
5761  if( access(zNewDb,0)==0 ){
5762    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
5763    return;
5764  }
5765  rc = sqlite3_open(zNewDb, &newDb);
5766  if( rc ){
5767    utf8_printf(stderr, "Cannot create output database: %s\n",
5768            sqlite3_errmsg(newDb));
5769  }else{
5770    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
5771    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
5772    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
5773    tryToCloneSchema(p, newDb, "type!='table'", 0);
5774    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
5775    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5776  }
5777  close_db(newDb);
5778}
5779
5780/*
5781** Change the output file back to stdout.
5782**
5783** If the p->doXdgOpen flag is set, that means the output was being
5784** redirected to a temporary file named by p->zTempFile.  In that case,
5785** launch start/open/xdg-open on that temporary file.
5786*/
5787static void output_reset(ShellState *p){
5788  if( p->outfile[0]=='|' ){
5789#ifndef SQLITE_OMIT_POPEN
5790    pclose(p->out);
5791#endif
5792  }else{
5793    output_file_close(p->out);
5794#ifndef SQLITE_NOHAVE_SYSTEM
5795    if( p->doXdgOpen ){
5796      const char *zXdgOpenCmd =
5797#if defined(_WIN32)
5798      "start";
5799#elif defined(__APPLE__)
5800      "open";
5801#else
5802      "xdg-open";
5803#endif
5804      char *zCmd;
5805      zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
5806      if( system(zCmd) ){
5807        utf8_printf(stderr, "Failed: [%s]\n", zCmd);
5808      }else{
5809        /* Give the start/open/xdg-open command some time to get
5810        ** going before we continue, and potential delete the
5811        ** p->zTempFile data file out from under it */
5812        sqlite3_sleep(2000);
5813      }
5814      sqlite3_free(zCmd);
5815      outputModePop(p);
5816      p->doXdgOpen = 0;
5817    }
5818#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
5819  }
5820  p->outfile[0] = 0;
5821  p->out = stdout;
5822}
5823
5824/*
5825** Run an SQL command and return the single integer result.
5826*/
5827static int db_int(sqlite3 *db, const char *zSql){
5828  sqlite3_stmt *pStmt;
5829  int res = 0;
5830  sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
5831  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
5832    res = sqlite3_column_int(pStmt,0);
5833  }
5834  sqlite3_finalize(pStmt);
5835  return res;
5836}
5837
5838#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
5839/*
5840** Convert a 2-byte or 4-byte big-endian integer into a native integer
5841*/
5842static unsigned int get2byteInt(unsigned char *a){
5843  return (a[0]<<8) + a[1];
5844}
5845static unsigned int get4byteInt(unsigned char *a){
5846  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
5847}
5848
5849/*
5850** Implementation of the ".dbinfo" command.
5851**
5852** Return 1 on error, 2 to exit, and 0 otherwise.
5853*/
5854static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
5855  static const struct { const char *zName; int ofst; } aField[] = {
5856     { "file change counter:",  24  },
5857     { "database page count:",  28  },
5858     { "freelist page count:",  36  },
5859     { "schema cookie:",        40  },
5860     { "schema format:",        44  },
5861     { "default cache size:",   48  },
5862     { "autovacuum top root:",  52  },
5863     { "incremental vacuum:",   64  },
5864     { "text encoding:",        56  },
5865     { "user version:",         60  },
5866     { "application id:",       68  },
5867     { "software version:",     96  },
5868  };
5869  static const struct { const char *zName; const char *zSql; } aQuery[] = {
5870     { "number of tables:",
5871       "SELECT count(*) FROM %s WHERE type='table'" },
5872     { "number of indexes:",
5873       "SELECT count(*) FROM %s WHERE type='index'" },
5874     { "number of triggers:",
5875       "SELECT count(*) FROM %s WHERE type='trigger'" },
5876     { "number of views:",
5877       "SELECT count(*) FROM %s WHERE type='view'" },
5878     { "schema size:",
5879       "SELECT total(length(sql)) FROM %s" },
5880  };
5881  int i, rc;
5882  unsigned iDataVersion;
5883  char *zSchemaTab;
5884  char *zDb = nArg>=2 ? azArg[1] : "main";
5885  sqlite3_stmt *pStmt = 0;
5886  unsigned char aHdr[100];
5887  open_db(p, 0);
5888  if( p->db==0 ) return 1;
5889  rc = sqlite3_prepare_v2(p->db,
5890             "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
5891             -1, &pStmt, 0);
5892  if( rc ){
5893    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
5894    sqlite3_finalize(pStmt);
5895    return 1;
5896  }
5897  sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
5898  if( sqlite3_step(pStmt)==SQLITE_ROW
5899   && sqlite3_column_bytes(pStmt,0)>100
5900  ){
5901    memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
5902    sqlite3_finalize(pStmt);
5903  }else{
5904    raw_printf(stderr, "unable to read database header\n");
5905    sqlite3_finalize(pStmt);
5906    return 1;
5907  }
5908  i = get2byteInt(aHdr+16);
5909  if( i==1 ) i = 65536;
5910  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
5911  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
5912  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
5913  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
5914  for(i=0; i<ArraySize(aField); i++){
5915    int ofst = aField[i].ofst;
5916    unsigned int val = get4byteInt(aHdr + ofst);
5917    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
5918    switch( ofst ){
5919      case 56: {
5920        if( val==1 ) raw_printf(p->out, " (utf8)");
5921        if( val==2 ) raw_printf(p->out, " (utf16le)");
5922        if( val==3 ) raw_printf(p->out, " (utf16be)");
5923      }
5924    }
5925    raw_printf(p->out, "\n");
5926  }
5927  if( zDb==0 ){
5928    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
5929  }else if( strcmp(zDb,"temp")==0 ){
5930    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
5931  }else{
5932    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
5933  }
5934  for(i=0; i<ArraySize(aQuery); i++){
5935    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5936    int val = db_int(p->db, zSql);
5937    sqlite3_free(zSql);
5938    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5939  }
5940  sqlite3_free(zSchemaTab);
5941  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5942  utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
5943  return 0;
5944}
5945#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE)
5946          && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
5947
5948/*
5949** Print the current sqlite3_errmsg() value to stderr and return 1.
5950*/
5951static int shellDatabaseError(sqlite3 *db){
5952  const char *zErr = sqlite3_errmsg(db);
5953  utf8_printf(stderr, "Error: %s\n", zErr);
5954  return 1;
5955}
5956
5957/*
5958** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
5959** if they match and FALSE (0) if they do not match.
5960**
5961** Globbing rules:
5962**
5963**      '*'       Matches any sequence of zero or more characters.
5964**
5965**      '?'       Matches exactly one character.
5966**
5967**     [...]      Matches one character from the enclosed list of
5968**                characters.
5969**
5970**     [^...]     Matches one character not in the enclosed list.
5971**
5972**      '#'       Matches any sequence of one or more digits with an
5973**                optional + or - sign in front
5974**
5975**      ' '       Any span of whitespace matches any other span of
5976**                whitespace.
5977**
5978** Extra whitespace at the end of z[] is ignored.
5979*/
5980static int testcase_glob(const char *zGlob, const char *z){
5981  int c, c2;
5982  int invert;
5983  int seen;
5984
5985  while( (c = (*(zGlob++)))!=0 ){
5986    if( IsSpace(c) ){
5987      if( !IsSpace(*z) ) return 0;
5988      while( IsSpace(*zGlob) ) zGlob++;
5989      while( IsSpace(*z) ) z++;
5990    }else if( c=='*' ){
5991      while( (c=(*(zGlob++))) == '*' || c=='?' ){
5992        if( c=='?' && (*(z++))==0 ) return 0;
5993      }
5994      if( c==0 ){
5995        return 1;
5996      }else if( c=='[' ){
5997        while( *z && testcase_glob(zGlob-1,z)==0 ){
5998          z++;
5999        }
6000        return (*z)!=0;
6001      }
6002      while( (c2 = (*(z++)))!=0 ){
6003        while( c2!=c ){
6004          c2 = *(z++);
6005          if( c2==0 ) return 0;
6006        }
6007        if( testcase_glob(zGlob,z) ) return 1;
6008      }
6009      return 0;
6010    }else if( c=='?' ){
6011      if( (*(z++))==0 ) return 0;
6012    }else if( c=='[' ){
6013      int prior_c = 0;
6014      seen = 0;
6015      invert = 0;
6016      c = *(z++);
6017      if( c==0 ) return 0;
6018      c2 = *(zGlob++);
6019      if( c2=='^' ){
6020        invert = 1;
6021        c2 = *(zGlob++);
6022      }
6023      if( c2==']' ){
6024        if( c==']' ) seen = 1;
6025        c2 = *(zGlob++);
6026      }
6027      while( c2 && c2!=']' ){
6028        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6029          c2 = *(zGlob++);
6030          if( c>=prior_c && c<=c2 ) seen = 1;
6031          prior_c = 0;
6032        }else{
6033          if( c==c2 ){
6034            seen = 1;
6035          }
6036          prior_c = c2;
6037        }
6038        c2 = *(zGlob++);
6039      }
6040      if( c2==0 || (seen ^ invert)==0 ) return 0;
6041    }else if( c=='#' ){
6042      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
6043      if( !IsDigit(z[0]) ) return 0;
6044      z++;
6045      while( IsDigit(z[0]) ){ z++; }
6046    }else{
6047      if( c!=(*(z++)) ) return 0;
6048    }
6049  }
6050  while( IsSpace(*z) ){ z++; }
6051  return *z==0;
6052}
6053
6054
6055/*
6056** Compare the string as a command-line option with either one or two
6057** initial "-" characters.
6058*/
6059static int optionMatch(const char *zStr, const char *zOpt){
6060  if( zStr[0]!='-' ) return 0;
6061  zStr++;
6062  if( zStr[0]=='-' ) zStr++;
6063  return strcmp(zStr, zOpt)==0;
6064}
6065
6066/*
6067** Delete a file.
6068*/
6069int shellDeleteFile(const char *zFilename){
6070  int rc;
6071#ifdef _WIN32
6072  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
6073  rc = _wunlink(z);
6074  sqlite3_free(z);
6075#else
6076  rc = unlink(zFilename);
6077#endif
6078  return rc;
6079}
6080
6081/*
6082** Try to delete the temporary file (if there is one) and free the
6083** memory used to hold the name of the temp file.
6084*/
6085static void clearTempFile(ShellState *p){
6086  if( p->zTempFile==0 ) return;
6087  if( p->doXdgOpen ) return;
6088  if( shellDeleteFile(p->zTempFile) ) return;
6089  sqlite3_free(p->zTempFile);
6090  p->zTempFile = 0;
6091}
6092
6093/*
6094** Create a new temp file name with the given suffix.
6095*/
6096static void newTempFile(ShellState *p, const char *zSuffix){
6097  clearTempFile(p);
6098  sqlite3_free(p->zTempFile);
6099  p->zTempFile = 0;
6100  if( p->db ){
6101    sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
6102  }
6103  if( p->zTempFile==0 ){
6104    /* If p->db is an in-memory database then the TEMPFILENAME file-control
6105    ** will not work and we will need to fallback to guessing */
6106    char *zTemp;
6107    sqlite3_uint64 r;
6108    sqlite3_randomness(sizeof(r), &r);
6109    zTemp = getenv("TEMP");
6110    if( zTemp==0 ) zTemp = getenv("TMP");
6111    if( zTemp==0 ){
6112#ifdef _WIN32
6113      zTemp = "\\tmp";
6114#else
6115      zTemp = "/tmp";
6116#endif
6117    }
6118    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
6119  }else{
6120    p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
6121  }
6122  shell_check_oom(p->zTempFile);
6123}
6124
6125
6126/*
6127** The implementation of SQL scalar function fkey_collate_clause(), used
6128** by the ".lint fkey-indexes" command. This scalar function is always
6129** called with four arguments - the parent table name, the parent column name,
6130** the child table name and the child column name.
6131**
6132**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
6133**
6134** If either of the named tables or columns do not exist, this function
6135** returns an empty string. An empty string is also returned if both tables
6136** and columns exist but have the same default collation sequence. Or,
6137** if both exist but the default collation sequences are different, this
6138** function returns the string " COLLATE <parent-collation>", where
6139** <parent-collation> is the default collation sequence of the parent column.
6140*/
6141static void shellFkeyCollateClause(
6142  sqlite3_context *pCtx,
6143  int nVal,
6144  sqlite3_value **apVal
6145){
6146  sqlite3 *db = sqlite3_context_db_handle(pCtx);
6147  const char *zParent;
6148  const char *zParentCol;
6149  const char *zParentSeq;
6150  const char *zChild;
6151  const char *zChildCol;
6152  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
6153  int rc;
6154
6155  assert( nVal==4 );
6156  zParent = (const char*)sqlite3_value_text(apVal[0]);
6157  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
6158  zChild = (const char*)sqlite3_value_text(apVal[2]);
6159  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
6160
6161  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
6162  rc = sqlite3_table_column_metadata(
6163      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
6164  );
6165  if( rc==SQLITE_OK ){
6166    rc = sqlite3_table_column_metadata(
6167        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
6168    );
6169  }
6170
6171  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
6172    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
6173    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
6174    sqlite3_free(z);
6175  }
6176}
6177
6178
6179/*
6180** The implementation of dot-command ".lint fkey-indexes".
6181*/
6182static int lintFkeyIndexes(
6183  ShellState *pState,             /* Current shell tool state */
6184  char **azArg,                   /* Array of arguments passed to dot command */
6185  int nArg                        /* Number of entries in azArg[] */
6186){
6187  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
6188  FILE *out = pState->out;        /* Stream to write non-error output to */
6189  int bVerbose = 0;               /* If -verbose is present */
6190  int bGroupByParent = 0;         /* If -groupbyparent is present */
6191  int i;                          /* To iterate through azArg[] */
6192  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
6193  int rc;                         /* Return code */
6194  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
6195
6196  /*
6197  ** This SELECT statement returns one row for each foreign key constraint
6198  ** in the schema of the main database. The column values are:
6199  **
6200  ** 0. The text of an SQL statement similar to:
6201  **
6202  **      "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
6203  **
6204  **    This SELECT is similar to the one that the foreign keys implementation
6205  **    needs to run internally on child tables. If there is an index that can
6206  **    be used to optimize this query, then it can also be used by the FK
6207  **    implementation to optimize DELETE or UPDATE statements on the parent
6208  **    table.
6209  **
6210  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
6211  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
6212  **    contains an index that can be used to optimize the query.
6213  **
6214  ** 2. Human readable text that describes the child table and columns. e.g.
6215  **
6216  **       "child_table(child_key1, child_key2)"
6217  **
6218  ** 3. Human readable text that describes the parent table and columns. e.g.
6219  **
6220  **       "parent_table(parent_key1, parent_key2)"
6221  **
6222  ** 4. A full CREATE INDEX statement for an index that could be used to
6223  **    optimize DELETE or UPDATE statements on the parent table. e.g.
6224  **
6225  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
6226  **
6227  ** 5. The name of the parent table.
6228  **
6229  ** These six values are used by the C logic below to generate the report.
6230  */
6231  const char *zSql =
6232  "SELECT "
6233    "     'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
6234    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
6235    "  || fkey_collate_clause("
6236    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
6237    ", "
6238    "     'SEARCH ' || s.name || ' USING COVERING INDEX*('"
6239    "  || group_concat('*=?', ' AND ') || ')'"
6240    ", "
6241    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
6242    ", "
6243    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
6244    ", "
6245    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
6246    "  || ' ON ' || quote(s.name) || '('"
6247    "  || group_concat(quote(f.[from]) ||"
6248    "        fkey_collate_clause("
6249    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
6250    "  || ');'"
6251    ", "
6252    "     f.[table] "
6253    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
6254    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
6255    "GROUP BY s.name, f.id "
6256    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
6257  ;
6258  const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)";
6259
6260  for(i=2; i<nArg; i++){
6261    int n = strlen30(azArg[i]);
6262    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
6263      bVerbose = 1;
6264    }
6265    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
6266      bGroupByParent = 1;
6267      zIndent = "    ";
6268    }
6269    else{
6270      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
6271          azArg[0], azArg[1]
6272      );
6273      return SQLITE_ERROR;
6274    }
6275  }
6276
6277  /* Register the fkey_collate_clause() SQL function */
6278  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
6279      0, shellFkeyCollateClause, 0, 0
6280  );
6281
6282
6283  if( rc==SQLITE_OK ){
6284    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
6285  }
6286  if( rc==SQLITE_OK ){
6287    sqlite3_bind_int(pSql, 1, bGroupByParent);
6288  }
6289
6290  if( rc==SQLITE_OK ){
6291    int rc2;
6292    char *zPrev = 0;
6293    while( SQLITE_ROW==sqlite3_step(pSql) ){
6294      int res = -1;
6295      sqlite3_stmt *pExplain = 0;
6296      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
6297      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
6298      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
6299      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
6300      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
6301      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
6302
6303      if( zEQP==0 ) continue;
6304      if( zGlob==0 ) continue;
6305      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
6306      if( rc!=SQLITE_OK ) break;
6307      if( SQLITE_ROW==sqlite3_step(pExplain) ){
6308        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
6309        res = zPlan!=0 && (  0==sqlite3_strglob(zGlob, zPlan)
6310                          || 0==sqlite3_strglob(zGlobIPK, zPlan));
6311      }
6312      rc = sqlite3_finalize(pExplain);
6313      if( rc!=SQLITE_OK ) break;
6314
6315      if( res<0 ){
6316        raw_printf(stderr, "Error: internal error");
6317        break;
6318      }else{
6319        if( bGroupByParent
6320        && (bVerbose || res==0)
6321        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
6322        ){
6323          raw_printf(out, "-- Parent table %s\n", zParent);
6324          sqlite3_free(zPrev);
6325          zPrev = sqlite3_mprintf("%s", zParent);
6326        }
6327
6328        if( res==0 ){
6329          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
6330        }else if( bVerbose ){
6331          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
6332              zIndent, zFrom, zTarget
6333          );
6334        }
6335      }
6336    }
6337    sqlite3_free(zPrev);
6338
6339    if( rc!=SQLITE_OK ){
6340      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6341    }
6342
6343    rc2 = sqlite3_finalize(pSql);
6344    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
6345      rc = rc2;
6346      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6347    }
6348  }else{
6349    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
6350  }
6351
6352  return rc;
6353}
6354
6355/*
6356** Implementation of ".lint" dot command.
6357*/
6358static int lintDotCommand(
6359  ShellState *pState,             /* Current shell tool state */
6360  char **azArg,                   /* Array of arguments passed to dot command */
6361  int nArg                        /* Number of entries in azArg[] */
6362){
6363  int n;
6364  n = (nArg>=2 ? strlen30(azArg[1]) : 0);
6365  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
6366  return lintFkeyIndexes(pState, azArg, nArg);
6367
6368 usage:
6369  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
6370  raw_printf(stderr, "Where sub-commands are:\n");
6371  raw_printf(stderr, "    fkey-indexes\n");
6372  return SQLITE_ERROR;
6373}
6374
6375#if !defined SQLITE_OMIT_VIRTUALTABLE
6376static void shellPrepare(
6377  sqlite3 *db,
6378  int *pRc,
6379  const char *zSql,
6380  sqlite3_stmt **ppStmt
6381){
6382  *ppStmt = 0;
6383  if( *pRc==SQLITE_OK ){
6384    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6385    if( rc!=SQLITE_OK ){
6386      raw_printf(stderr, "sql error: %s (%d)\n",
6387          sqlite3_errmsg(db), sqlite3_errcode(db)
6388      );
6389      *pRc = rc;
6390    }
6391  }
6392}
6393
6394/*
6395** Create a prepared statement using printf-style arguments for the SQL.
6396**
6397** This routine is could be marked "static".  But it is not always used,
6398** depending on compile-time options.  By omitting the "static", we avoid
6399** nuisance compiler warnings about "defined but not used".
6400*/
6401void shellPreparePrintf(
6402  sqlite3 *db,
6403  int *pRc,
6404  sqlite3_stmt **ppStmt,
6405  const char *zFmt,
6406  ...
6407){
6408  *ppStmt = 0;
6409  if( *pRc==SQLITE_OK ){
6410    va_list ap;
6411    char *z;
6412    va_start(ap, zFmt);
6413    z = sqlite3_vmprintf(zFmt, ap);
6414    va_end(ap);
6415    if( z==0 ){
6416      *pRc = SQLITE_NOMEM;
6417    }else{
6418      shellPrepare(db, pRc, z, ppStmt);
6419      sqlite3_free(z);
6420    }
6421  }
6422}
6423
6424/* Finalize the prepared statement created using shellPreparePrintf().
6425**
6426** This routine is could be marked "static".  But it is not always used,
6427** depending on compile-time options.  By omitting the "static", we avoid
6428** nuisance compiler warnings about "defined but not used".
6429*/
6430void shellFinalize(
6431  int *pRc,
6432  sqlite3_stmt *pStmt
6433){
6434  if( pStmt ){
6435    sqlite3 *db = sqlite3_db_handle(pStmt);
6436    int rc = sqlite3_finalize(pStmt);
6437    if( *pRc==SQLITE_OK ){
6438      if( rc!=SQLITE_OK ){
6439        raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6440      }
6441      *pRc = rc;
6442    }
6443  }
6444}
6445
6446/* Reset the prepared statement created using shellPreparePrintf().
6447**
6448** This routine is could be marked "static".  But it is not always used,
6449** depending on compile-time options.  By omitting the "static", we avoid
6450** nuisance compiler warnings about "defined but not used".
6451*/
6452void shellReset(
6453  int *pRc,
6454  sqlite3_stmt *pStmt
6455){
6456  int rc = sqlite3_reset(pStmt);
6457  if( *pRc==SQLITE_OK ){
6458    if( rc!=SQLITE_OK ){
6459      sqlite3 *db = sqlite3_db_handle(pStmt);
6460      raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
6461    }
6462    *pRc = rc;
6463  }
6464}
6465#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
6466
6467#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6468/******************************************************************************
6469** The ".archive" or ".ar" command.
6470*/
6471/*
6472** Structure representing a single ".ar" command.
6473*/
6474typedef struct ArCommand ArCommand;
6475struct ArCommand {
6476  u8 eCmd;                        /* An AR_CMD_* value */
6477  u8 bVerbose;                    /* True if --verbose */
6478  u8 bZip;                        /* True if the archive is a ZIP */
6479  u8 bDryRun;                     /* True if --dry-run */
6480  u8 bAppend;                     /* True if --append */
6481  u8 bGlob;                       /* True if --glob */
6482  u8 fromCmdLine;                 /* Run from -A instead of .archive */
6483  int nArg;                       /* Number of command arguments */
6484  char *zSrcTable;                /* "sqlar", "zipfile($file)" or "zip" */
6485  const char *zFile;              /* --file argument, or NULL */
6486  const char *zDir;               /* --directory argument, or NULL */
6487  char **azArg;                   /* Array of command arguments */
6488  ShellState *p;                  /* Shell state */
6489  sqlite3 *db;                    /* Database containing the archive */
6490};
6491
6492/*
6493** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
6494*/
6495static int arUsage(FILE *f){
6496  showHelp(f,"archive");
6497  return SQLITE_ERROR;
6498}
6499
6500/*
6501** Print an error message for the .ar command to stderr and return
6502** SQLITE_ERROR.
6503*/
6504static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
6505  va_list ap;
6506  char *z;
6507  va_start(ap, zFmt);
6508  z = sqlite3_vmprintf(zFmt, ap);
6509  va_end(ap);
6510  utf8_printf(stderr, "Error: %s\n", z);
6511  if( pAr->fromCmdLine ){
6512    utf8_printf(stderr, "Use \"-A\" for more help\n");
6513  }else{
6514    utf8_printf(stderr, "Use \".archive --help\" for more help\n");
6515  }
6516  sqlite3_free(z);
6517  return SQLITE_ERROR;
6518}
6519
6520/*
6521** Values for ArCommand.eCmd.
6522*/
6523#define AR_CMD_CREATE       1
6524#define AR_CMD_UPDATE       2
6525#define AR_CMD_INSERT       3
6526#define AR_CMD_EXTRACT      4
6527#define AR_CMD_LIST         5
6528#define AR_CMD_HELP         6
6529#define AR_CMD_REMOVE       7
6530
6531/*
6532** Other (non-command) switches.
6533*/
6534#define AR_SWITCH_VERBOSE     8
6535#define AR_SWITCH_FILE        9
6536#define AR_SWITCH_DIRECTORY  10
6537#define AR_SWITCH_APPEND     11
6538#define AR_SWITCH_DRYRUN     12
6539#define AR_SWITCH_GLOB       13
6540
6541static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
6542  switch( eSwitch ){
6543    case AR_CMD_CREATE:
6544    case AR_CMD_EXTRACT:
6545    case AR_CMD_LIST:
6546    case AR_CMD_REMOVE:
6547    case AR_CMD_UPDATE:
6548    case AR_CMD_INSERT:
6549    case AR_CMD_HELP:
6550      if( pAr->eCmd ){
6551        return arErrorMsg(pAr, "multiple command options");
6552      }
6553      pAr->eCmd = eSwitch;
6554      break;
6555
6556    case AR_SWITCH_DRYRUN:
6557      pAr->bDryRun = 1;
6558      break;
6559    case AR_SWITCH_GLOB:
6560      pAr->bGlob = 1;
6561      break;
6562    case AR_SWITCH_VERBOSE:
6563      pAr->bVerbose = 1;
6564      break;
6565    case AR_SWITCH_APPEND:
6566      pAr->bAppend = 1;
6567      /* Fall thru into --file */
6568    case AR_SWITCH_FILE:
6569      pAr->zFile = zArg;
6570      break;
6571    case AR_SWITCH_DIRECTORY:
6572      pAr->zDir = zArg;
6573      break;
6574  }
6575
6576  return SQLITE_OK;
6577}
6578
6579/*
6580** Parse the command line for an ".ar" command. The results are written into
6581** structure (*pAr). SQLITE_OK is returned if the command line is parsed
6582** successfully, otherwise an error message is written to stderr and
6583** SQLITE_ERROR returned.
6584*/
6585static int arParseCommand(
6586  char **azArg,                   /* Array of arguments passed to dot command */
6587  int nArg,                       /* Number of entries in azArg[] */
6588  ArCommand *pAr                  /* Populate this object */
6589){
6590  struct ArSwitch {
6591    const char *zLong;
6592    char cShort;
6593    u8 eSwitch;
6594    u8 bArg;
6595  } aSwitch[] = {
6596    { "create",    'c', AR_CMD_CREATE,       0 },
6597    { "extract",   'x', AR_CMD_EXTRACT,      0 },
6598    { "insert",    'i', AR_CMD_INSERT,       0 },
6599    { "list",      't', AR_CMD_LIST,         0 },
6600    { "remove",    'r', AR_CMD_REMOVE,       0 },
6601    { "update",    'u', AR_CMD_UPDATE,       0 },
6602    { "help",      'h', AR_CMD_HELP,         0 },
6603    { "verbose",   'v', AR_SWITCH_VERBOSE,   0 },
6604    { "file",      'f', AR_SWITCH_FILE,      1 },
6605    { "append",    'a', AR_SWITCH_APPEND,    1 },
6606    { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
6607    { "dryrun",    'n', AR_SWITCH_DRYRUN,    0 },
6608    { "glob",      'g', AR_SWITCH_GLOB,      0 },
6609  };
6610  int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
6611  struct ArSwitch *pEnd = &aSwitch[nSwitch];
6612
6613  if( nArg<=1 ){
6614    utf8_printf(stderr, "Wrong number of arguments.  Usage:\n");
6615    return arUsage(stderr);
6616  }else{
6617    char *z = azArg[1];
6618    if( z[0]!='-' ){
6619      /* Traditional style [tar] invocation */
6620      int i;
6621      int iArg = 2;
6622      for(i=0; z[i]; i++){
6623        const char *zArg = 0;
6624        struct ArSwitch *pOpt;
6625        for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6626          if( z[i]==pOpt->cShort ) break;
6627        }
6628        if( pOpt==pEnd ){
6629          return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6630        }
6631        if( pOpt->bArg ){
6632          if( iArg>=nArg ){
6633            return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
6634          }
6635          zArg = azArg[iArg++];
6636        }
6637        if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6638      }
6639      pAr->nArg = nArg-iArg;
6640      if( pAr->nArg>0 ){
6641        pAr->azArg = &azArg[iArg];
6642      }
6643    }else{
6644      /* Non-traditional invocation */
6645      int iArg;
6646      for(iArg=1; iArg<nArg; iArg++){
6647        int n;
6648        z = azArg[iArg];
6649        if( z[0]!='-' ){
6650          /* All remaining command line words are command arguments. */
6651          pAr->azArg = &azArg[iArg];
6652          pAr->nArg = nArg-iArg;
6653          break;
6654        }
6655        n = strlen30(z);
6656
6657        if( z[1]!='-' ){
6658          int i;
6659          /* One or more short options */
6660          for(i=1; i<n; i++){
6661            const char *zArg = 0;
6662            struct ArSwitch *pOpt;
6663            for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6664              if( z[i]==pOpt->cShort ) break;
6665            }
6666            if( pOpt==pEnd ){
6667              return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
6668            }
6669            if( pOpt->bArg ){
6670              if( i<(n-1) ){
6671                zArg = &z[i+1];
6672                i = n;
6673              }else{
6674                if( iArg>=(nArg-1) ){
6675                  return arErrorMsg(pAr, "option requires an argument: %c",
6676                                    z[i]);
6677                }
6678                zArg = azArg[++iArg];
6679              }
6680            }
6681            if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
6682          }
6683        }else if( z[2]=='\0' ){
6684          /* A -- option, indicating that all remaining command line words
6685          ** are command arguments.  */
6686          pAr->azArg = &azArg[iArg+1];
6687          pAr->nArg = nArg-iArg-1;
6688          break;
6689        }else{
6690          /* A long option */
6691          const char *zArg = 0;             /* Argument for option, if any */
6692          struct ArSwitch *pMatch = 0;      /* Matching option */
6693          struct ArSwitch *pOpt;            /* Iterator */
6694          for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
6695            const char *zLong = pOpt->zLong;
6696            if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
6697              if( pMatch ){
6698                return arErrorMsg(pAr, "ambiguous option: %s",z);
6699              }else{
6700                pMatch = pOpt;
6701              }
6702            }
6703          }
6704
6705          if( pMatch==0 ){
6706            return arErrorMsg(pAr, "unrecognized option: %s", z);
6707          }
6708          if( pMatch->bArg ){
6709            if( iArg>=(nArg-1) ){
6710              return arErrorMsg(pAr, "option requires an argument: %s", z);
6711            }
6712            zArg = azArg[++iArg];
6713          }
6714          if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
6715        }
6716      }
6717    }
6718  }
6719
6720  return SQLITE_OK;
6721}
6722
6723/*
6724** This function assumes that all arguments within the ArCommand.azArg[]
6725** array refer to archive members, as for the --extract, --list or --remove
6726** commands. It checks that each of them are "present". If any specified
6727** file is not present in the archive, an error is printed to stderr and an
6728** error code returned. Otherwise, if all specified arguments are present
6729** in the archive, SQLITE_OK is returned. Here, "present" means either an
6730** exact equality when pAr->bGlob is false or a "name GLOB pattern" match
6731** when pAr->bGlob is true.
6732**
6733** This function strips any trailing '/' characters from each argument.
6734** This is consistent with the way the [tar] command seems to work on
6735** Linux.
6736*/
6737static int arCheckEntries(ArCommand *pAr){
6738  int rc = SQLITE_OK;
6739  if( pAr->nArg ){
6740    int i, j;
6741    sqlite3_stmt *pTest = 0;
6742    const char *zSel = (pAr->bGlob)
6743      ? "SELECT name FROM %s WHERE glob($name,name)"
6744      : "SELECT name FROM %s WHERE name=$name";
6745
6746    shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable);
6747    j = sqlite3_bind_parameter_index(pTest, "$name");
6748    for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
6749      char *z = pAr->azArg[i];
6750      int n = strlen30(z);
6751      int bOk = 0;
6752      while( n>0 && z[n-1]=='/' ) n--;
6753      z[n] = '\0';
6754      sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
6755      if( SQLITE_ROW==sqlite3_step(pTest) ){
6756        bOk = 1;
6757      }
6758      shellReset(&rc, pTest);
6759      if( rc==SQLITE_OK && bOk==0 ){
6760        utf8_printf(stderr, "not found in archive: %s\n", z);
6761        rc = SQLITE_ERROR;
6762      }
6763    }
6764    shellFinalize(&rc, pTest);
6765  }
6766  return rc;
6767}
6768
6769/*
6770** Format a WHERE clause that can be used against the "sqlar" table to
6771** identify all archive members that match the command arguments held
6772** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
6773** The caller is responsible for eventually calling sqlite3_free() on
6774** any non-NULL (*pzWhere) value. Here, "match" means strict equality
6775** when pAr->bGlob is false and GLOB match when pAr->bGlob is true.
6776*/
6777static void arWhereClause(
6778  int *pRc,
6779  ArCommand *pAr,
6780  char **pzWhere                  /* OUT: New WHERE clause */
6781){
6782  char *zWhere = 0;
6783  const char *zSameOp = (pAr->bGlob)? "GLOB" : "=";
6784  if( *pRc==SQLITE_OK ){
6785    if( pAr->nArg==0 ){
6786      zWhere = sqlite3_mprintf("1");
6787    }else{
6788      int i;
6789      const char *zSep = "";
6790      for(i=0; i<pAr->nArg; i++){
6791        const char *z = pAr->azArg[i];
6792        zWhere = sqlite3_mprintf(
6793          "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'",
6794          zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z
6795        );
6796        if( zWhere==0 ){
6797          *pRc = SQLITE_NOMEM;
6798          break;
6799        }
6800        zSep = " OR ";
6801      }
6802    }
6803  }
6804  *pzWhere = zWhere;
6805}
6806
6807/*
6808** Implementation of .ar "lisT" command.
6809*/
6810static int arListCommand(ArCommand *pAr){
6811  const char *zSql = "SELECT %s FROM %s WHERE %s";
6812  const char *azCols[] = {
6813    "name",
6814    "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
6815  };
6816
6817  char *zWhere = 0;
6818  sqlite3_stmt *pSql = 0;
6819  int rc;
6820
6821  rc = arCheckEntries(pAr);
6822  arWhereClause(&rc, pAr, &zWhere);
6823
6824  shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
6825                     pAr->zSrcTable, zWhere);
6826  if( pAr->bDryRun ){
6827    utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6828  }else{
6829    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6830      if( pAr->bVerbose ){
6831        utf8_printf(pAr->p->out, "%s % 10d  %s  %s\n",
6832            sqlite3_column_text(pSql, 0),
6833            sqlite3_column_int(pSql, 1),
6834            sqlite3_column_text(pSql, 2),
6835            sqlite3_column_text(pSql, 3)
6836        );
6837      }else{
6838        utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6839      }
6840    }
6841  }
6842  shellFinalize(&rc, pSql);
6843  sqlite3_free(zWhere);
6844  return rc;
6845}
6846
6847
6848/*
6849** Implementation of .ar "Remove" command.
6850*/
6851static int arRemoveCommand(ArCommand *pAr){
6852  int rc = 0;
6853  char *zSql = 0;
6854  char *zWhere = 0;
6855
6856  if( pAr->nArg ){
6857    /* Verify that args actually exist within the archive before proceeding.
6858    ** And formulate a WHERE clause to match them.  */
6859    rc = arCheckEntries(pAr);
6860    arWhereClause(&rc, pAr, &zWhere);
6861  }
6862  if( rc==SQLITE_OK ){
6863    zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;",
6864                           pAr->zSrcTable, zWhere);
6865    if( pAr->bDryRun ){
6866      utf8_printf(pAr->p->out, "%s\n", zSql);
6867    }else{
6868      char *zErr = 0;
6869      rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0);
6870      if( rc==SQLITE_OK ){
6871        rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6872        if( rc!=SQLITE_OK ){
6873          sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
6874        }else{
6875          rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0);
6876        }
6877      }
6878      if( zErr ){
6879        utf8_printf(stdout, "ERROR: %s\n", zErr);
6880        sqlite3_free(zErr);
6881      }
6882    }
6883  }
6884  sqlite3_free(zWhere);
6885  sqlite3_free(zSql);
6886  return rc;
6887}
6888
6889/*
6890** Implementation of .ar "eXtract" command.
6891*/
6892static int arExtractCommand(ArCommand *pAr){
6893  const char *zSql1 =
6894    "SELECT "
6895    " ($dir || name),"
6896    " writefile(($dir || name), %s, mode, mtime) "
6897    "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
6898    " AND name NOT GLOB '*..[/\\]*'";
6899
6900  const char *azExtraArg[] = {
6901    "sqlar_uncompress(data, sz)",
6902    "data"
6903  };
6904
6905  sqlite3_stmt *pSql = 0;
6906  int rc = SQLITE_OK;
6907  char *zDir = 0;
6908  char *zWhere = 0;
6909  int i, j;
6910
6911  /* If arguments are specified, check that they actually exist within
6912  ** the archive before proceeding. And formulate a WHERE clause to
6913  ** match them.  */
6914  rc = arCheckEntries(pAr);
6915  arWhereClause(&rc, pAr, &zWhere);
6916
6917  if( rc==SQLITE_OK ){
6918    if( pAr->zDir ){
6919      zDir = sqlite3_mprintf("%s/", pAr->zDir);
6920    }else{
6921      zDir = sqlite3_mprintf("");
6922    }
6923    if( zDir==0 ) rc = SQLITE_NOMEM;
6924  }
6925
6926  shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
6927      azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
6928  );
6929
6930  if( rc==SQLITE_OK ){
6931    j = sqlite3_bind_parameter_index(pSql, "$dir");
6932    sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
6933
6934    /* Run the SELECT statement twice. The first time, writefile() is called
6935    ** for all archive members that should be extracted. The second time,
6936    ** only for the directories. This is because the timestamps for
6937    ** extracted directories must be reset after they are populated (as
6938    ** populating them changes the timestamp).  */
6939    for(i=0; i<2; i++){
6940      j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
6941      sqlite3_bind_int(pSql, j, i);
6942      if( pAr->bDryRun ){
6943        utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
6944      }else{
6945        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
6946          if( i==0 && pAr->bVerbose ){
6947            utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
6948          }
6949        }
6950      }
6951      shellReset(&rc, pSql);
6952    }
6953    shellFinalize(&rc, pSql);
6954  }
6955
6956  sqlite3_free(zDir);
6957  sqlite3_free(zWhere);
6958  return rc;
6959}
6960
6961/*
6962** Run the SQL statement in zSql.  Or if doing a --dryrun, merely print it out.
6963*/
6964static int arExecSql(ArCommand *pAr, const char *zSql){
6965  int rc;
6966  if( pAr->bDryRun ){
6967    utf8_printf(pAr->p->out, "%s\n", zSql);
6968    rc = SQLITE_OK;
6969  }else{
6970    char *zErr = 0;
6971    rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
6972    if( zErr ){
6973      utf8_printf(stdout, "ERROR: %s\n", zErr);
6974      sqlite3_free(zErr);
6975    }
6976  }
6977  return rc;
6978}
6979
6980
6981/*
6982** Implementation of .ar "create", "insert", and "update" commands.
6983**
6984**     create    ->     Create a new SQL archive
6985**     insert    ->     Insert or reinsert all files listed
6986**     update    ->     Insert files that have changed or that were not
6987**                      previously in the archive
6988**
6989** Create the "sqlar" table in the database if it does not already exist.
6990** Then add each file in the azFile[] array to the archive. Directories
6991** are added recursively. If argument bVerbose is non-zero, a message is
6992** printed on stdout for each file archived.
6993**
6994** The create command is the same as update, except that it drops
6995** any existing "sqlar" table before beginning.  The "insert" command
6996** always overwrites every file named on the command-line, where as
6997** "update" only overwrites if the size or mtime or mode has changed.
6998*/
6999static int arCreateOrUpdateCommand(
7000  ArCommand *pAr,                 /* Command arguments and options */
7001  int bUpdate,                    /* true for a --create. */
7002  int bOnlyIfChanged              /* Only update if file has changed */
7003){
7004  const char *zCreate =
7005      "CREATE TABLE IF NOT EXISTS sqlar(\n"
7006      "  name TEXT PRIMARY KEY,  -- name of the file\n"
7007      "  mode INT,               -- access permissions\n"
7008      "  mtime INT,              -- last modification time\n"
7009      "  sz INT,                 -- original file size\n"
7010      "  data BLOB               -- compressed content\n"
7011      ")";
7012  const char *zDrop = "DROP TABLE IF EXISTS sqlar";
7013  const char *zInsertFmt[2] = {
7014     "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
7015     "  SELECT\n"
7016     "    %s,\n"
7017     "    mode,\n"
7018     "    mtime,\n"
7019     "    CASE substr(lsmode(mode),1,1)\n"
7020     "      WHEN '-' THEN length(data)\n"
7021     "      WHEN 'd' THEN 0\n"
7022     "      ELSE -1 END,\n"
7023     "    sqlar_compress(data)\n"
7024     "  FROM fsdir(%Q,%Q) AS disk\n"
7025     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7026     ,
7027     "REPLACE INTO %s(name,mode,mtime,data)\n"
7028     "  SELECT\n"
7029     "    %s,\n"
7030     "    mode,\n"
7031     "    mtime,\n"
7032     "    data\n"
7033     "  FROM fsdir(%Q,%Q) AS disk\n"
7034     "  WHERE lsmode(mode) NOT LIKE '?%%'%s;"
7035  };
7036  int i;                          /* For iterating through azFile[] */
7037  int rc;                         /* Return code */
7038  const char *zTab = 0;           /* SQL table into which to insert */
7039  char *zSql;
7040  char zTemp[50];
7041  char *zExists = 0;
7042
7043  arExecSql(pAr, "PRAGMA page_size=512");
7044  rc = arExecSql(pAr, "SAVEPOINT ar;");
7045  if( rc!=SQLITE_OK ) return rc;
7046  zTemp[0] = 0;
7047  if( pAr->bZip ){
7048    /* Initialize the zipfile virtual table, if necessary */
7049    if( pAr->zFile ){
7050      sqlite3_uint64 r;
7051      sqlite3_randomness(sizeof(r),&r);
7052      sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
7053      zTab = zTemp;
7054      zSql = sqlite3_mprintf(
7055         "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
7056         zTab, pAr->zFile
7057      );
7058      rc = arExecSql(pAr, zSql);
7059      sqlite3_free(zSql);
7060    }else{
7061      zTab = "zip";
7062    }
7063  }else{
7064    /* Initialize the table for an SQLAR */
7065    zTab = "sqlar";
7066    if( bUpdate==0 ){
7067      rc = arExecSql(pAr, zDrop);
7068      if( rc!=SQLITE_OK ) goto end_ar_transaction;
7069    }
7070    rc = arExecSql(pAr, zCreate);
7071  }
7072  if( bOnlyIfChanged ){
7073    zExists = sqlite3_mprintf(
7074      " AND NOT EXISTS("
7075          "SELECT 1 FROM %s AS mem"
7076          " WHERE mem.name=disk.name"
7077          " AND mem.mtime=disk.mtime"
7078          " AND mem.mode=disk.mode)", zTab);
7079  }else{
7080    zExists = sqlite3_mprintf("");
7081  }
7082  if( zExists==0 ) rc = SQLITE_NOMEM;
7083  for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
7084    char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
7085        pAr->bVerbose ? "shell_putsnl(name)" : "name",
7086        pAr->azArg[i], pAr->zDir, zExists);
7087    rc = arExecSql(pAr, zSql2);
7088    sqlite3_free(zSql2);
7089  }
7090end_ar_transaction:
7091  if( rc!=SQLITE_OK ){
7092    sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
7093  }else{
7094    rc = arExecSql(pAr, "RELEASE ar;");
7095    if( pAr->bZip && pAr->zFile ){
7096      zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
7097      arExecSql(pAr, zSql);
7098      sqlite3_free(zSql);
7099    }
7100  }
7101  sqlite3_free(zExists);
7102  return rc;
7103}
7104
7105/*
7106** Implementation of ".ar" dot command.
7107*/
7108static int arDotCommand(
7109  ShellState *pState,          /* Current shell tool state */
7110  int fromCmdLine,             /* True if -A command-line option, not .ar cmd */
7111  char **azArg,                /* Array of arguments passed to dot command */
7112  int nArg                     /* Number of entries in azArg[] */
7113){
7114  ArCommand cmd;
7115  int rc;
7116  memset(&cmd, 0, sizeof(cmd));
7117  cmd.fromCmdLine = fromCmdLine;
7118  rc = arParseCommand(azArg, nArg, &cmd);
7119  if( rc==SQLITE_OK ){
7120    int eDbType = SHELL_OPEN_UNSPEC;
7121    cmd.p = pState;
7122    cmd.db = pState->db;
7123    if( cmd.zFile ){
7124      eDbType = deduceDatabaseType(cmd.zFile, 1);
7125    }else{
7126      eDbType = pState->openMode;
7127    }
7128    if( eDbType==SHELL_OPEN_ZIPFILE ){
7129      if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
7130        if( cmd.zFile==0 ){
7131          cmd.zSrcTable = sqlite3_mprintf("zip");
7132        }else{
7133          cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
7134        }
7135      }
7136      cmd.bZip = 1;
7137    }else if( cmd.zFile ){
7138      int flags;
7139      if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
7140      if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
7141           || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){
7142        flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
7143      }else{
7144        flags = SQLITE_OPEN_READONLY;
7145      }
7146      cmd.db = 0;
7147      if( cmd.bDryRun ){
7148        utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
7149             eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
7150      }
7151      rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
7152             eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
7153      if( rc!=SQLITE_OK ){
7154        utf8_printf(stderr, "cannot open file: %s (%s)\n",
7155            cmd.zFile, sqlite3_errmsg(cmd.db)
7156        );
7157        goto end_ar_command;
7158      }
7159      sqlite3_fileio_init(cmd.db, 0, 0);
7160      sqlite3_sqlar_init(cmd.db, 0, 0);
7161      sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
7162                              shellPutsFunc, 0, 0);
7163
7164    }
7165    if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
7166      if( cmd.eCmd!=AR_CMD_CREATE
7167       && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
7168      ){
7169        utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
7170        rc = SQLITE_ERROR;
7171        goto end_ar_command;
7172      }
7173      cmd.zSrcTable = sqlite3_mprintf("sqlar");
7174    }
7175
7176    switch( cmd.eCmd ){
7177      case AR_CMD_CREATE:
7178        rc = arCreateOrUpdateCommand(&cmd, 0, 0);
7179        break;
7180
7181      case AR_CMD_EXTRACT:
7182        rc = arExtractCommand(&cmd);
7183        break;
7184
7185      case AR_CMD_LIST:
7186        rc = arListCommand(&cmd);
7187        break;
7188
7189      case AR_CMD_HELP:
7190        arUsage(pState->out);
7191        break;
7192
7193      case AR_CMD_INSERT:
7194        rc = arCreateOrUpdateCommand(&cmd, 1, 0);
7195        break;
7196
7197      case AR_CMD_REMOVE:
7198        rc = arRemoveCommand(&cmd);
7199        break;
7200
7201      default:
7202        assert( cmd.eCmd==AR_CMD_UPDATE );
7203        rc = arCreateOrUpdateCommand(&cmd, 1, 1);
7204        break;
7205    }
7206  }
7207end_ar_command:
7208  if( cmd.db!=pState->db ){
7209    close_db(cmd.db);
7210  }
7211  sqlite3_free(cmd.zSrcTable);
7212
7213  return rc;
7214}
7215/* End of the ".archive" or ".ar" command logic
7216*******************************************************************************/
7217#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
7218
7219#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
7220/*
7221** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
7222** Otherwise, the SQL statement or statements in zSql are executed using
7223** database connection db and the error code written to *pRc before
7224** this function returns.
7225*/
7226static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
7227  int rc = *pRc;
7228  if( rc==SQLITE_OK ){
7229    char *zErr = 0;
7230    rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
7231    if( rc!=SQLITE_OK ){
7232      raw_printf(stderr, "SQL error: %s\n", zErr);
7233    }
7234    sqlite3_free(zErr);
7235    *pRc = rc;
7236  }
7237}
7238
7239/*
7240** Like shellExec(), except that zFmt is a printf() style format string.
7241*/
7242static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
7243  char *z = 0;
7244  if( *pRc==SQLITE_OK ){
7245    va_list ap;
7246    va_start(ap, zFmt);
7247    z = sqlite3_vmprintf(zFmt, ap);
7248    va_end(ap);
7249    if( z==0 ){
7250      *pRc = SQLITE_NOMEM;
7251    }else{
7252      shellExec(db, pRc, z);
7253    }
7254    sqlite3_free(z);
7255  }
7256}
7257
7258/*
7259** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7260** Otherwise, an attempt is made to allocate, zero and return a pointer
7261** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
7262** to SQLITE_NOMEM and NULL returned.
7263*/
7264static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
7265  void *pRet = 0;
7266  if( *pRc==SQLITE_OK ){
7267    pRet = sqlite3_malloc64(nByte);
7268    if( pRet==0 ){
7269      *pRc = SQLITE_NOMEM;
7270    }else{
7271      memset(pRet, 0, nByte);
7272    }
7273  }
7274  return pRet;
7275}
7276
7277/*
7278** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
7279** Otherwise, zFmt is treated as a printf() style string. The result of
7280** formatting it along with any trailing arguments is written into a
7281** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
7282** It is the responsibility of the caller to eventually free this buffer
7283** using a call to sqlite3_free().
7284**
7285** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
7286** pointer returned.
7287*/
7288static char *shellMPrintf(int *pRc, const char *zFmt, ...){
7289  char *z = 0;
7290  if( *pRc==SQLITE_OK ){
7291    va_list ap;
7292    va_start(ap, zFmt);
7293    z = sqlite3_vmprintf(zFmt, ap);
7294    va_end(ap);
7295    if( z==0 ){
7296      *pRc = SQLITE_NOMEM;
7297    }
7298  }
7299  return z;
7300}
7301
7302
7303/*
7304** When running the ".recover" command, each output table, and the special
7305** orphaned row table if it is required, is represented by an instance
7306** of the following struct.
7307*/
7308typedef struct RecoverTable RecoverTable;
7309struct RecoverTable {
7310  char *zQuoted;                  /* Quoted version of table name */
7311  int nCol;                       /* Number of columns in table */
7312  char **azlCol;                  /* Array of column lists */
7313  int iPk;                        /* Index of IPK column */
7314};
7315
7316/*
7317** Free a RecoverTable object allocated by recoverFindTable() or
7318** recoverOrphanTable().
7319*/
7320static void recoverFreeTable(RecoverTable *pTab){
7321  if( pTab ){
7322    sqlite3_free(pTab->zQuoted);
7323    if( pTab->azlCol ){
7324      int i;
7325      for(i=0; i<=pTab->nCol; i++){
7326        sqlite3_free(pTab->azlCol[i]);
7327      }
7328      sqlite3_free(pTab->azlCol);
7329    }
7330    sqlite3_free(pTab);
7331  }
7332}
7333
7334/*
7335** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
7336** Otherwise, it allocates and returns a RecoverTable object based on the
7337** final four arguments passed to this function. It is the responsibility
7338** of the caller to eventually free the returned object using
7339** recoverFreeTable().
7340*/
7341static RecoverTable *recoverNewTable(
7342  int *pRc,                       /* IN/OUT: Error code */
7343  const char *zName,              /* Name of table */
7344  const char *zSql,               /* CREATE TABLE statement */
7345  int bIntkey,
7346  int nCol
7347){
7348  sqlite3 *dbtmp = 0;             /* sqlite3 handle for testing CREATE TABLE */
7349  int rc = *pRc;
7350  RecoverTable *pTab = 0;
7351
7352  pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
7353  if( rc==SQLITE_OK ){
7354    int nSqlCol = 0;
7355    int bSqlIntkey = 0;
7356    sqlite3_stmt *pStmt = 0;
7357
7358    rc = sqlite3_open("", &dbtmp);
7359    if( rc==SQLITE_OK ){
7360      sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
7361                              shellIdQuote, 0, 0);
7362    }
7363    if( rc==SQLITE_OK ){
7364      rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
7365    }
7366    if( rc==SQLITE_OK ){
7367      rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
7368      if( rc==SQLITE_ERROR ){
7369        rc = SQLITE_OK;
7370        goto finished;
7371      }
7372    }
7373    shellPreparePrintf(dbtmp, &rc, &pStmt,
7374        "SELECT count(*) FROM pragma_table_info(%Q)", zName
7375    );
7376    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7377      nSqlCol = sqlite3_column_int(pStmt, 0);
7378    }
7379    shellFinalize(&rc, pStmt);
7380
7381    if( rc!=SQLITE_OK || nSqlCol<nCol ){
7382      goto finished;
7383    }
7384
7385    shellPreparePrintf(dbtmp, &rc, &pStmt,
7386      "SELECT ("
7387      "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
7388      ") FROM sqlite_schema WHERE name = %Q", zName
7389    );
7390    if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7391      bSqlIntkey = sqlite3_column_int(pStmt, 0);
7392    }
7393    shellFinalize(&rc, pStmt);
7394
7395    if( bIntkey==bSqlIntkey ){
7396      int i;
7397      const char *zPk = "_rowid_";
7398      sqlite3_stmt *pPkFinder = 0;
7399
7400      /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
7401      ** set zPk to the name of the PK column, and pTab->iPk to the index
7402      ** of the column, where columns are 0-numbered from left to right.
7403      ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
7404      ** leave zPk as "_rowid_" and pTab->iPk at -2.  */
7405      pTab->iPk = -2;
7406      if( bIntkey ){
7407        shellPreparePrintf(dbtmp, &rc, &pPkFinder,
7408          "SELECT cid, name FROM pragma_table_info(%Q) "
7409          "  WHERE pk=1 AND type='integer' COLLATE nocase"
7410          "  AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
7411          , zName, zName
7412        );
7413        if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
7414          pTab->iPk = sqlite3_column_int(pPkFinder, 0);
7415          zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
7416          if( zPk==0 ){ zPk = "_";  /* Defensive.  Should never happen */ }
7417        }
7418      }
7419
7420      pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
7421      pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
7422      pTab->nCol = nSqlCol;
7423
7424      if( bIntkey ){
7425        pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
7426      }else{
7427        pTab->azlCol[0] = shellMPrintf(&rc, "");
7428      }
7429      i = 1;
7430      shellPreparePrintf(dbtmp, &rc, &pStmt,
7431          "SELECT %Q || group_concat(shell_idquote(name), ', ') "
7432          "  FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
7433          "FROM pragma_table_info(%Q)",
7434          bIntkey ? ", " : "", pTab->iPk,
7435          bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
7436          zName
7437      );
7438      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7439        const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
7440        pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
7441        i++;
7442      }
7443      shellFinalize(&rc, pStmt);
7444
7445      shellFinalize(&rc, pPkFinder);
7446    }
7447  }
7448
7449 finished:
7450  sqlite3_close(dbtmp);
7451  *pRc = rc;
7452  if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
7453    recoverFreeTable(pTab);
7454    pTab = 0;
7455  }
7456  return pTab;
7457}
7458
7459/*
7460** This function is called to search the schema recovered from the
7461** sqlite_schema table of the (possibly) corrupt database as part
7462** of a ".recover" command. Specifically, for a table with root page
7463** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
7464** table must be a WITHOUT ROWID table, or if non-zero, not one of
7465** those.
7466**
7467** If a table is found, a (RecoverTable*) object is returned. Or, if
7468** no such table is found, but bIntkey is false and iRoot is the
7469** root page of an index in the recovered schema, then (*pbNoop) is
7470** set to true and NULL returned. Or, if there is no such table or
7471** index, NULL is returned and (*pbNoop) set to 0, indicating that
7472** the caller should write data to the orphans table.
7473*/
7474static RecoverTable *recoverFindTable(
7475  ShellState *pState,             /* Shell state object */
7476  int *pRc,                       /* IN/OUT: Error code */
7477  int iRoot,                      /* Root page of table */
7478  int bIntkey,                    /* True for an intkey table */
7479  int nCol,                       /* Number of columns in table */
7480  int *pbNoop                     /* OUT: True if iRoot is root of index */
7481){
7482  sqlite3_stmt *pStmt = 0;
7483  RecoverTable *pRet = 0;
7484  int bNoop = 0;
7485  const char *zSql = 0;
7486  const char *zName = 0;
7487
7488  /* Search the recovered schema for an object with root page iRoot. */
7489  shellPreparePrintf(pState->db, pRc, &pStmt,
7490      "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
7491  );
7492  while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7493    const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
7494    if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
7495      bNoop = 1;
7496      break;
7497    }
7498    if( sqlite3_stricmp(zType, "table")==0 ){
7499      zName = (const char*)sqlite3_column_text(pStmt, 1);
7500      zSql = (const char*)sqlite3_column_text(pStmt, 2);
7501      if( zName!=0 && zSql!=0 ){
7502        pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
7503        break;
7504      }
7505    }
7506  }
7507
7508  shellFinalize(pRc, pStmt);
7509  *pbNoop = bNoop;
7510  return pRet;
7511}
7512
7513/*
7514** Return a RecoverTable object representing the orphans table.
7515*/
7516static RecoverTable *recoverOrphanTable(
7517  ShellState *pState,             /* Shell state object */
7518  int *pRc,                       /* IN/OUT: Error code */
7519  const char *zLostAndFound,      /* Base name for orphans table */
7520  int nCol                        /* Number of user data columns */
7521){
7522  RecoverTable *pTab = 0;
7523  if( nCol>=0 && *pRc==SQLITE_OK ){
7524    int i;
7525
7526    /* This block determines the name of the orphan table. The prefered
7527    ** name is zLostAndFound. But if that clashes with another name
7528    ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
7529    ** and so on until a non-clashing name is found.  */
7530    int iTab = 0;
7531    char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
7532    sqlite3_stmt *pTest = 0;
7533    shellPrepare(pState->db, pRc,
7534        "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
7535    );
7536    if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7537    while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
7538      shellReset(pRc, pTest);
7539      sqlite3_free(zTab);
7540      zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
7541      sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
7542    }
7543    shellFinalize(pRc, pTest);
7544
7545    pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
7546    if( pTab ){
7547      pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
7548      pTab->nCol = nCol;
7549      pTab->iPk = -2;
7550      if( nCol>0 ){
7551        pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
7552        if( pTab->azlCol ){
7553          pTab->azlCol[nCol] = shellMPrintf(pRc, "");
7554          for(i=nCol-1; i>=0; i--){
7555            pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
7556          }
7557        }
7558      }
7559
7560      if( *pRc!=SQLITE_OK ){
7561        recoverFreeTable(pTab);
7562        pTab = 0;
7563      }else{
7564        raw_printf(pState->out,
7565            "CREATE TABLE %s(rootpgno INTEGER, "
7566            "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
7567        );
7568        for(i=0; i<nCol; i++){
7569          raw_printf(pState->out, ", c%d", i);
7570        }
7571        raw_printf(pState->out, ");\n");
7572      }
7573    }
7574    sqlite3_free(zTab);
7575  }
7576  return pTab;
7577}
7578
7579/*
7580** This function is called to recover data from the database. A script
7581** to construct a new database containing all recovered data is output
7582** on stream pState->out.
7583*/
7584static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
7585  int rc = SQLITE_OK;
7586  sqlite3_stmt *pLoop = 0;        /* Loop through all root pages */
7587  sqlite3_stmt *pPages = 0;       /* Loop through all pages in a group */
7588  sqlite3_stmt *pCells = 0;       /* Loop through all cells in a page */
7589  const char *zRecoveryDb = "";   /* Name of "recovery" database */
7590  const char *zLostAndFound = "lost_and_found";
7591  int i;
7592  int nOrphan = -1;
7593  RecoverTable *pOrphan = 0;
7594
7595  int bFreelist = 1;              /* 0 if --freelist-corrupt is specified */
7596  int bRowids = 1;                /* 0 if --no-rowids */
7597  for(i=1; i<nArg; i++){
7598    char *z = azArg[i];
7599    int n;
7600    if( z[0]=='-' && z[1]=='-' ) z++;
7601    n = strlen30(z);
7602    if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
7603      bFreelist = 0;
7604    }else
7605    if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
7606      i++;
7607      zRecoveryDb = azArg[i];
7608    }else
7609    if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
7610      i++;
7611      zLostAndFound = azArg[i];
7612    }else
7613    if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
7614      bRowids = 0;
7615    }
7616    else{
7617      utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
7618      showHelp(pState->out, azArg[0]);
7619      return 1;
7620    }
7621  }
7622
7623  shellExecPrintf(pState->db, &rc,
7624    /* Attach an in-memory database named 'recovery'. Create an indexed
7625    ** cache of the sqlite_dbptr virtual table. */
7626    "PRAGMA writable_schema = on;"
7627    "ATTACH %Q AS recovery;"
7628    "DROP TABLE IF EXISTS recovery.dbptr;"
7629    "DROP TABLE IF EXISTS recovery.freelist;"
7630    "DROP TABLE IF EXISTS recovery.map;"
7631    "DROP TABLE IF EXISTS recovery.schema;"
7632    "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
7633  );
7634
7635  if( bFreelist ){
7636    shellExec(pState->db, &rc,
7637      "WITH trunk(pgno) AS ("
7638      "  SELECT shell_int32("
7639      "      (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
7640      "      WHERE x>0"
7641      "    UNION"
7642      "  SELECT shell_int32("
7643      "      (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
7644      "      FROM trunk WHERE x>0"
7645      "),"
7646      "freelist(data, n, freepgno) AS ("
7647      "  SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
7648      "      FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
7649      "    UNION ALL"
7650      "  SELECT data, n-1, shell_int32(data, 2+n) "
7651      "      FROM freelist WHERE n>=0"
7652      ")"
7653      "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
7654    );
7655  }
7656
7657  /* If this is an auto-vacuum database, add all pointer-map pages to
7658  ** the freelist table. Do this regardless of whether or not
7659  ** --freelist-corrupt was specified.  */
7660  shellExec(pState->db, &rc,
7661    "WITH ptrmap(pgno) AS ("
7662    "  SELECT 2 WHERE shell_int32("
7663    "    (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
7664    "  )"
7665    "    UNION ALL "
7666    "  SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
7667    "  FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
7668    ")"
7669    "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
7670  );
7671
7672  shellExec(pState->db, &rc,
7673    "CREATE TABLE recovery.dbptr("
7674    "      pgno, child, PRIMARY KEY(child, pgno)"
7675    ") WITHOUT ROWID;"
7676    "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
7677    "    SELECT * FROM sqlite_dbptr"
7678    "      WHERE pgno NOT IN freelist AND child NOT IN freelist;"
7679
7680    /* Delete any pointer to page 1. This ensures that page 1 is considered
7681    ** a root page, regardless of how corrupt the db is. */
7682    "DELETE FROM recovery.dbptr WHERE child = 1;"
7683
7684    /* Delete all pointers to any pages that have more than one pointer
7685    ** to them. Such pages will be treated as root pages when recovering
7686    ** data.  */
7687    "DELETE FROM recovery.dbptr WHERE child IN ("
7688    "  SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
7689    ");"
7690
7691    /* Create the "map" table that will (eventually) contain instructions
7692    ** for dealing with each page in the db that contains one or more
7693    ** records. */
7694    "CREATE TABLE recovery.map("
7695      "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
7696    ");"
7697
7698    /* Populate table [map]. If there are circular loops of pages in the
7699    ** database, the following adds all pages in such a loop to the map
7700    ** as individual root pages. This could be handled better.  */
7701    "WITH pages(i, maxlen) AS ("
7702    "  SELECT page_count, ("
7703    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
7704    "  ) FROM pragma_page_count WHERE page_count>0"
7705    "    UNION ALL"
7706    "  SELECT i-1, ("
7707    "    SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
7708    "  ) FROM pages WHERE i>=2"
7709    ")"
7710    "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
7711    "  SELECT i, maxlen, NULL, ("
7712    "    WITH p(orig, pgno, parent) AS ("
7713    "      SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
7714    "        UNION "
7715    "      SELECT i, p.parent, "
7716    "        (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
7717    "    )"
7718    "    SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
7719    ") "
7720    "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
7721    "UPDATE recovery.map AS o SET intkey = ("
7722    "  SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
7723    ");"
7724
7725    /* Extract data from page 1 and any linked pages into table
7726    ** recovery.schema. With the same schema as an sqlite_schema table.  */
7727    "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
7728    "INSERT INTO recovery.schema SELECT "
7729    "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
7730    "  max(CASE WHEN field=1 THEN value ELSE NULL END),"
7731    "  max(CASE WHEN field=2 THEN value ELSE NULL END),"
7732    "  max(CASE WHEN field=3 THEN value ELSE NULL END),"
7733    "  max(CASE WHEN field=4 THEN value ELSE NULL END)"
7734    "FROM sqlite_dbdata WHERE pgno IN ("
7735    "  SELECT pgno FROM recovery.map WHERE root=1"
7736    ")"
7737    "GROUP BY pgno, cell;"
7738    "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
7739  );
7740
7741  /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
7742  ** CREATE TABLE statements that extracted from the existing schema.  */
7743  if( rc==SQLITE_OK ){
7744    sqlite3_stmt *pStmt = 0;
7745    /* ".recover" might output content in an order which causes immediate
7746    ** foreign key constraints to be violated. So disable foreign-key
7747    ** constraint enforcement to prevent problems when running the output
7748    ** script. */
7749    raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
7750    raw_printf(pState->out, "BEGIN;\n");
7751    raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
7752    shellPrepare(pState->db, &rc,
7753        "SELECT sql FROM recovery.schema "
7754        "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
7755    );
7756    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7757      const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
7758      raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
7759          &zCreateTable[12]
7760      );
7761    }
7762    shellFinalize(&rc, pStmt);
7763  }
7764
7765  /* Figure out if an orphan table will be required. And if so, how many
7766  ** user columns it should contain */
7767  shellPrepare(pState->db, &rc,
7768      "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
7769      , &pLoop
7770  );
7771  if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7772    nOrphan = sqlite3_column_int(pLoop, 0);
7773  }
7774  shellFinalize(&rc, pLoop);
7775  pLoop = 0;
7776
7777  shellPrepare(pState->db, &rc,
7778      "SELECT pgno FROM recovery.map WHERE root=?", &pPages
7779  );
7780
7781  shellPrepare(pState->db, &rc,
7782      "SELECT max(field), group_concat(shell_escape_crnl(quote"
7783      "(case when (? AND field<0) then NULL else value end)"
7784      "), ', ')"
7785      ", min(field) "
7786      "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
7787      "GROUP BY cell", &pCells
7788  );
7789
7790  /* Loop through each root page. */
7791  shellPrepare(pState->db, &rc,
7792      "SELECT root, intkey, max(maxlen) FROM recovery.map"
7793      " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
7794      "  SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
7795      ")", &pLoop
7796  );
7797  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
7798    int iRoot = sqlite3_column_int(pLoop, 0);
7799    int bIntkey = sqlite3_column_int(pLoop, 1);
7800    int nCol = sqlite3_column_int(pLoop, 2);
7801    int bNoop = 0;
7802    RecoverTable *pTab;
7803
7804    assert( bIntkey==0 || bIntkey==1 );
7805    pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
7806    if( bNoop || rc ) continue;
7807    if( pTab==0 ){
7808      if( pOrphan==0 ){
7809        pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7810      }
7811      pTab = pOrphan;
7812      if( pTab==0 ) break;
7813    }
7814
7815    if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
7816      raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
7817    }
7818    sqlite3_bind_int(pPages, 1, iRoot);
7819    if( bRowids==0 && pTab->iPk<0 ){
7820      sqlite3_bind_int(pCells, 1, 1);
7821    }else{
7822      sqlite3_bind_int(pCells, 1, 0);
7823    }
7824    sqlite3_bind_int(pCells, 3, pTab->iPk);
7825
7826    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
7827      int iPgno = sqlite3_column_int(pPages, 0);
7828      sqlite3_bind_int(pCells, 2, iPgno);
7829      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
7830        int nField = sqlite3_column_int(pCells, 0);
7831        int iMin = sqlite3_column_int(pCells, 2);
7832        const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
7833
7834        RecoverTable *pTab2 = pTab;
7835        if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
7836          if( pOrphan==0 ){
7837            pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
7838          }
7839          pTab2 = pOrphan;
7840          if( pTab2==0 ) break;
7841        }
7842
7843        nField = nField+1;
7844        if( pTab2==pOrphan ){
7845          raw_printf(pState->out,
7846              "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
7847              pTab2->zQuoted, iRoot, iPgno, nField,
7848              iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
7849          );
7850        }else{
7851          raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
7852              pTab2->zQuoted, pTab2->azlCol[nField], zVal
7853          );
7854        }
7855      }
7856      shellReset(&rc, pCells);
7857    }
7858    shellReset(&rc, pPages);
7859    if( pTab!=pOrphan ) recoverFreeTable(pTab);
7860  }
7861  shellFinalize(&rc, pLoop);
7862  shellFinalize(&rc, pPages);
7863  shellFinalize(&rc, pCells);
7864  recoverFreeTable(pOrphan);
7865
7866  /* The rest of the schema */
7867  if( rc==SQLITE_OK ){
7868    sqlite3_stmt *pStmt = 0;
7869    shellPrepare(pState->db, &rc,
7870        "SELECT sql, name FROM recovery.schema "
7871        "WHERE sql NOT LIKE 'create table%'", &pStmt
7872    );
7873    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
7874      const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
7875      if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
7876        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
7877        char *zPrint = shellMPrintf(&rc,
7878          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
7879          zName, zName, zSql
7880        );
7881        raw_printf(pState->out, "%s;\n", zPrint);
7882        sqlite3_free(zPrint);
7883      }else{
7884        raw_printf(pState->out, "%s;\n", zSql);
7885      }
7886    }
7887    shellFinalize(&rc, pStmt);
7888  }
7889
7890  if( rc==SQLITE_OK ){
7891    raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
7892    raw_printf(pState->out, "COMMIT;\n");
7893  }
7894  sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
7895  return rc;
7896}
7897#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
7898
7899
7900/*
7901 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it.
7902 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE,
7903 *   close db and set it to 0, and return the columns spec, to later
7904 *   be sqlite3_free()'ed by the caller.
7905 * The return is 0 when either:
7906 *   (a) The db was not initialized and zCol==0 (There are no columns.)
7907 *   (b) zCol!=0  (Column was added, db initialized as needed.)
7908 * The 3rd argument, pRenamed, references an out parameter. If the
7909 * pointer is non-zero, its referent will be set to a summary of renames
7910 * done if renaming was necessary, or set to 0 if none was done. The out
7911 * string (if any) must be sqlite3_free()'ed by the caller.
7912 */
7913#ifdef SHELL_DEBUG
7914#define rc_err_oom_die(rc) \
7915  if( rc==SQLITE_NOMEM ) shell_check_oom(0); \
7916  else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \
7917    fprintf(stderr,"E:%d\n",rc), assert(0)
7918#else
7919static void rc_err_oom_die(int rc){
7920  if( rc==SQLITE_NOMEM ) shell_check_oom(0);
7921  assert(rc==SQLITE_OK||rc==SQLITE_DONE);
7922}
7923#endif
7924
7925#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */
7926static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB);
7927#else  /* Otherwise, memory is faster/better for the transient DB. */
7928static const char *zCOL_DB = ":memory:";
7929#endif
7930
7931/* Define character (as C string) to separate generated column ordinal
7932 * from protected part of incoming column names. This defaults to "_"
7933 * so that incoming column identifiers that did not need not be quoted
7934 * remain usable without being quoted. It must be one character.
7935 */
7936#ifndef SHELL_AUTOCOLUMN_SEP
7937# define AUTOCOLUMN_SEP "_"
7938#else
7939# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP)
7940#endif
7941
7942static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){
7943  /* Queries and D{D,M}L used here */
7944  static const char * const zTabMake = "\
7945CREATE TABLE ColNames(\
7946 cpos INTEGER PRIMARY KEY,\
7947 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\
7948CREATE VIEW RepeatedNames AS \
7949SELECT DISTINCT t.name FROM ColNames t \
7950WHERE t.name COLLATE NOCASE IN (\
7951 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\
7952);\
7953";
7954  static const char * const zTabFill = "\
7955INSERT INTO ColNames(name,nlen,chop,reps,suff)\
7956 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\
7957";
7958  static const char * const zHasDupes = "\
7959SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\
7960 <count(name) FROM ColNames\
7961";
7962#ifdef SHELL_COLUMN_RENAME_CLEAN
7963  static const char * const zDedoctor = "\
7964UPDATE ColNames SET chop=iif(\
7965  (substring(name,nlen,1) BETWEEN '0' AND '9')\
7966  AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\
7967 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\
7968 0\
7969)\
7970";
7971#endif
7972  static const char * const zSetReps = "\
7973UPDATE ColNames AS t SET reps=\
7974(SELECT count(*) FROM ColNames d \
7975 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\
7976 COLLATE NOCASE\
7977)\
7978";
7979#ifdef SQLITE_ENABLE_MATH_FUNCTIONS
7980  static const char * const zColDigits = "\
7981SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \
7982";
7983#else
7984  /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */
7985  static const char * const zColDigits = "\
7986SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \
7987 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \
7988 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \
7989";
7990#endif
7991  static const char * const zRenameRank =
7992#ifdef SHELL_COLUMN_RENAME_CLEAN
7993    "UPDATE ColNames AS t SET suff="
7994    "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')"
7995#else /* ...RENAME_MINIMAL_ONE_PASS */
7996"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */
7997"  SELECT 0 AS nlz"
7998"  UNION"
7999"  SELECT nlz+1 AS nlz FROM Lzn"
8000"  WHERE EXISTS("
8001"   SELECT 1"
8002"   FROM ColNames t, ColNames o"
8003"   WHERE"
8004"    iif(t.name IN (SELECT * FROM RepeatedNames),"
8005"     printf('%s"AUTOCOLUMN_SEP"%s',"
8006"      t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2)),"
8007"     t.name"
8008"    )"
8009"    ="
8010"    iif(o.name IN (SELECT * FROM RepeatedNames),"
8011"     printf('%s"AUTOCOLUMN_SEP"%s',"
8012"      o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2)),"
8013"     o.name"
8014"    )"
8015"    COLLATE NOCASE"
8016"    AND o.cpos<>t.cpos"
8017"   GROUP BY t.cpos"
8018"  )"
8019") UPDATE Colnames AS t SET"
8020" chop = 0," /* No chopping, never touch incoming names. */
8021" suff = iif(name IN (SELECT * FROM RepeatedNames),"
8022"  printf('"AUTOCOLUMN_SEP"%s', substring("
8023"   printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2)),"
8024"  ''"
8025" )"
8026#endif
8027    ;
8028  static const char * const zCollectVar = "\
8029SELECT\
8030 '('||x'0a'\
8031 || group_concat(\
8032  cname||' TEXT',\
8033  ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\
8034 ||')' AS ColsSpec \
8035FROM (\
8036 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \
8037 FROM ColNames ORDER BY cpos\
8038)";
8039  static const char * const zRenamesDone =
8040    "SELECT group_concat("
8041    " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff)),"
8042    " ','||x'0a')"
8043    "FROM ColNames WHERE suff<>'' OR chop!=0"
8044    ;
8045  int rc;
8046  sqlite3_stmt *pStmt = 0;
8047  assert(pDb!=0);
8048  if( zColNew ){
8049    /* Add initial or additional column. Init db if necessary. */
8050    if( *pDb==0 ){
8051      if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0;
8052#ifdef SHELL_COLFIX_DB
8053      if(*zCOL_DB!=':')
8054        sqlite3_exec(*pDb,"drop table if exists ColNames;"
8055                     "drop view if exists RepeatedNames;",0,0,0);
8056#endif
8057      rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0);
8058      rc_err_oom_die(rc);
8059    }
8060    assert(*pDb!=0);
8061    rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0);
8062    rc_err_oom_die(rc);
8063    rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0);
8064    rc_err_oom_die(rc);
8065    rc = sqlite3_step(pStmt);
8066    rc_err_oom_die(rc);
8067    sqlite3_finalize(pStmt);
8068    return 0;
8069  }else if( *pDb==0 ){
8070    return 0;
8071  }else{
8072    /* Formulate the columns spec, close the DB, zero *pDb. */
8073    char *zColsSpec = 0;
8074    int hasDupes = db_int(*pDb, zHasDupes);
8075    int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0;
8076    if( hasDupes ){
8077#ifdef SHELL_COLUMN_RENAME_CLEAN
8078      rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0);
8079      rc_err_oom_die(rc);
8080#endif
8081      rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0);
8082      rc_err_oom_die(rc);
8083      rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0);
8084      rc_err_oom_die(rc);
8085      sqlite3_bind_int(pStmt, 1, nDigits);
8086      rc = sqlite3_step(pStmt);
8087      sqlite3_finalize(pStmt);
8088      assert(rc==SQLITE_DONE);
8089    }
8090    assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */
8091    rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0);
8092    rc_err_oom_die(rc);
8093    rc = sqlite3_step(pStmt);
8094    if( rc==SQLITE_ROW ){
8095      zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8096    }else{
8097      zColsSpec = 0;
8098    }
8099    if( pzRenamed!=0 ){
8100      if( !hasDupes ) *pzRenamed = 0;
8101      else{
8102        sqlite3_finalize(pStmt);
8103        if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0)
8104            && SQLITE_ROW==sqlite3_step(pStmt) ){
8105          *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
8106        }else
8107          *pzRenamed = 0;
8108      }
8109    }
8110    sqlite3_finalize(pStmt);
8111    sqlite3_close(*pDb);
8112    *pDb = 0;
8113    return zColsSpec;
8114  }
8115}
8116
8117/*
8118** If an input line begins with "." then invoke this routine to
8119** process that line.
8120**
8121** Return 1 on error, 2 to exit, and 0 otherwise.
8122*/
8123static int do_meta_command(char *zLine, ShellState *p){
8124  int h = 1;
8125  int nArg = 0;
8126  int n, c;
8127  int rc = 0;
8128  char *azArg[52];
8129
8130#ifndef SQLITE_OMIT_VIRTUALTABLE
8131  if( p->expert.pExpert ){
8132    expertFinish(p, 1, 0);
8133  }
8134#endif
8135
8136  /* Parse the input line into tokens.
8137  */
8138  while( zLine[h] && nArg<ArraySize(azArg)-1 ){
8139    while( IsSpace(zLine[h]) ){ h++; }
8140    if( zLine[h]==0 ) break;
8141    if( zLine[h]=='\'' || zLine[h]=='"' ){
8142      int delim = zLine[h++];
8143      azArg[nArg++] = &zLine[h];
8144      while( zLine[h] && zLine[h]!=delim ){
8145        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
8146        h++;
8147      }
8148      if( zLine[h]==delim ){
8149        zLine[h++] = 0;
8150      }
8151      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
8152    }else{
8153      azArg[nArg++] = &zLine[h];
8154      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
8155      if( zLine[h] ) zLine[h++] = 0;
8156      resolve_backslashes(azArg[nArg-1]);
8157    }
8158  }
8159  azArg[nArg] = 0;
8160
8161  /* Process the input line.
8162  */
8163  if( nArg==0 ) return 0; /* no tokens, no error */
8164  n = strlen30(azArg[0]);
8165  c = azArg[0][0];
8166  clearTempFile(p);
8167
8168#ifndef SQLITE_OMIT_AUTHORIZATION
8169  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
8170    if( nArg!=2 ){
8171      raw_printf(stderr, "Usage: .auth ON|OFF\n");
8172      rc = 1;
8173      goto meta_command_exit;
8174    }
8175    open_db(p, 0);
8176    if( booleanValue(azArg[1]) ){
8177      sqlite3_set_authorizer(p->db, shellAuth, p);
8178    }else if( p->bSafeModePersist ){
8179      sqlite3_set_authorizer(p->db, safeModeAuth, p);
8180    }else{
8181      sqlite3_set_authorizer(p->db, 0, 0);
8182    }
8183  }else
8184#endif
8185
8186#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \
8187  && !defined(SQLITE_SHELL_FIDDLE)
8188  if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
8189    open_db(p, 0);
8190    failIfSafeMode(p, "cannot run .archive in safe mode");
8191    rc = arDotCommand(p, 0, azArg, nArg);
8192  }else
8193#endif
8194
8195#ifndef SQLITE_SHELL_FIDDLE
8196  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
8197   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
8198  ){
8199    const char *zDestFile = 0;
8200    const char *zDb = 0;
8201    sqlite3 *pDest;
8202    sqlite3_backup *pBackup;
8203    int j;
8204    int bAsync = 0;
8205    const char *zVfs = 0;
8206    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
8207    for(j=1; j<nArg; j++){
8208      const char *z = azArg[j];
8209      if( z[0]=='-' ){
8210        if( z[1]=='-' ) z++;
8211        if( strcmp(z, "-append")==0 ){
8212          zVfs = "apndvfs";
8213        }else
8214        if( strcmp(z, "-async")==0 ){
8215          bAsync = 1;
8216        }else
8217        {
8218          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
8219          return 1;
8220        }
8221      }else if( zDestFile==0 ){
8222        zDestFile = azArg[j];
8223      }else if( zDb==0 ){
8224        zDb = zDestFile;
8225        zDestFile = azArg[j];
8226      }else{
8227        raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
8228        return 1;
8229      }
8230    }
8231    if( zDestFile==0 ){
8232      raw_printf(stderr, "missing FILENAME argument on .backup\n");
8233      return 1;
8234    }
8235    if( zDb==0 ) zDb = "main";
8236    rc = sqlite3_open_v2(zDestFile, &pDest,
8237                  SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
8238    if( rc!=SQLITE_OK ){
8239      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
8240      close_db(pDest);
8241      return 1;
8242    }
8243    if( bAsync ){
8244      sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
8245                   0, 0, 0);
8246    }
8247    open_db(p, 0);
8248    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
8249    if( pBackup==0 ){
8250      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8251      close_db(pDest);
8252      return 1;
8253    }
8254    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
8255    sqlite3_backup_finish(pBackup);
8256    if( rc==SQLITE_DONE ){
8257      rc = 0;
8258    }else{
8259      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
8260      rc = 1;
8261    }
8262    close_db(pDest);
8263  }else
8264#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8265
8266  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
8267    if( nArg==2 ){
8268      bail_on_error = booleanValue(azArg[1]);
8269    }else{
8270      raw_printf(stderr, "Usage: .bail on|off\n");
8271      rc = 1;
8272    }
8273  }else
8274
8275  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
8276    if( nArg==2 ){
8277      if( booleanValue(azArg[1]) ){
8278        setBinaryMode(p->out, 1);
8279      }else{
8280        setTextMode(p->out, 1);
8281      }
8282    }else{
8283      raw_printf(stderr, "Usage: .binary on|off\n");
8284      rc = 1;
8285    }
8286  }else
8287
8288  /* The undocumented ".breakpoint" command causes a call to the no-op
8289  ** routine named test_breakpoint().
8290  */
8291  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
8292    test_breakpoint();
8293  }else
8294
8295#ifndef SQLITE_SHELL_FIDDLE
8296  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
8297    failIfSafeMode(p, "cannot run .cd in safe mode");
8298    if( nArg==2 ){
8299#if defined(_WIN32) || defined(WIN32)
8300      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
8301      rc = !SetCurrentDirectoryW(z);
8302      sqlite3_free(z);
8303#else
8304      rc = chdir(azArg[1]);
8305#endif
8306      if( rc ){
8307        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
8308        rc = 1;
8309      }
8310    }else{
8311      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
8312      rc = 1;
8313    }
8314  }else
8315#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8316
8317  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
8318    if( nArg==2 ){
8319      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
8320    }else{
8321      raw_printf(stderr, "Usage: .changes on|off\n");
8322      rc = 1;
8323    }
8324  }else
8325
8326#ifndef SQLITE_SHELL_FIDDLE
8327  /* Cancel output redirection, if it is currently set (by .testcase)
8328  ** Then read the content of the testcase-out.txt file and compare against
8329  ** azArg[1].  If there are differences, report an error and exit.
8330  */
8331  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
8332    char *zRes = 0;
8333    output_reset(p);
8334    if( nArg!=2 ){
8335      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
8336      rc = 2;
8337    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
8338      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
8339      rc = 2;
8340    }else if( testcase_glob(azArg[1],zRes)==0 ){
8341      utf8_printf(stderr,
8342                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
8343                 p->zTestcase, azArg[1], zRes);
8344      rc = 1;
8345    }else{
8346      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
8347      p->nCheck++;
8348    }
8349    sqlite3_free(zRes);
8350  }else
8351#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8352
8353#ifndef SQLITE_SHELL_FIDDLE
8354  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
8355    failIfSafeMode(p, "cannot run .clone in safe mode");
8356    if( nArg==2 ){
8357      tryToClone(p, azArg[1]);
8358    }else{
8359      raw_printf(stderr, "Usage: .clone FILENAME\n");
8360      rc = 1;
8361    }
8362  }else
8363#endif /* !defined(SQLITE_SHELL_FIDDLE) */
8364
8365  if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){
8366    if( nArg==1 ){
8367      /* List available connections */
8368      int i;
8369      for(i=0; i<ArraySize(p->aAuxDb); i++){
8370        const char *zFile = p->aAuxDb[i].zDbFilename;
8371        if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){
8372          zFile = "(not open)";
8373        }else if( zFile==0 ){
8374          zFile = "(memory)";
8375        }else if( zFile[0]==0 ){
8376          zFile = "(temporary-file)";
8377        }
8378        if( p->pAuxDb == &p->aAuxDb[i] ){
8379          utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile);
8380        }else if( p->aAuxDb[i].db!=0 ){
8381          utf8_printf(stdout, "       %d: %s\n", i, zFile);
8382        }
8383      }
8384    }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){
8385      int i = azArg[1][0] - '0';
8386      if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){
8387        p->pAuxDb->db = p->db;
8388        p->pAuxDb = &p->aAuxDb[i];
8389        globalDb = p->db = p->pAuxDb->db;
8390        p->pAuxDb->db = 0;
8391      }
8392    }else if( nArg==3 && strcmp(azArg[1], "close")==0
8393           && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){
8394      int i = azArg[2][0] - '0';
8395      if( i<0 || i>=ArraySize(p->aAuxDb) ){
8396        /* No-op */
8397      }else if( p->pAuxDb == &p->aAuxDb[i] ){
8398        raw_printf(stderr, "cannot close the active database connection\n");
8399        rc = 1;
8400      }else if( p->aAuxDb[i].db ){
8401        session_close_all(p, i);
8402        close_db(p->aAuxDb[i].db);
8403        p->aAuxDb[i].db = 0;
8404      }
8405    }else{
8406      raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n");
8407      rc = 1;
8408    }
8409  }else
8410
8411  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
8412    char **azName = 0;
8413    int nName = 0;
8414    sqlite3_stmt *pStmt;
8415    int i;
8416    open_db(p, 0);
8417    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
8418    if( rc ){
8419      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8420      rc = 1;
8421    }else{
8422      while( sqlite3_step(pStmt)==SQLITE_ROW ){
8423        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
8424        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
8425        if( zSchema==0 || zFile==0 ) continue;
8426        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
8427        shell_check_oom(azName);
8428        azName[nName*2] = strdup(zSchema);
8429        azName[nName*2+1] = strdup(zFile);
8430        nName++;
8431      }
8432    }
8433    sqlite3_finalize(pStmt);
8434    for(i=0; i<nName; i++){
8435      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
8436      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
8437      const char *z = azName[i*2+1];
8438      utf8_printf(p->out, "%s: %s %s%s\n",
8439         azName[i*2],
8440         z && z[0] ? z : "\"\"",
8441         bRdonly ? "r/o" : "r/w",
8442         eTxn==SQLITE_TXN_NONE ? "" :
8443            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
8444      free(azName[i*2]);
8445      free(azName[i*2+1]);
8446    }
8447    sqlite3_free(azName);
8448  }else
8449
8450  if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
8451    static const struct DbConfigChoices {
8452      const char *zName;
8453      int op;
8454    } aDbConfig[] = {
8455        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
8456        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
8457        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
8458        { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
8459        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
8460        { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
8461        { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
8462        { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
8463        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
8464        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
8465        { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
8466        { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
8467        { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
8468        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
8469        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
8470        { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
8471    };
8472    int ii, v;
8473    open_db(p, 0);
8474    for(ii=0; ii<ArraySize(aDbConfig); ii++){
8475      if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
8476      if( nArg>=3 ){
8477        sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
8478      }
8479      sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
8480      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
8481      if( nArg>1 ) break;
8482    }
8483    if( nArg>1 && ii==ArraySize(aDbConfig) ){
8484      utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
8485      utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
8486    }
8487  }else
8488
8489#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
8490  if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
8491    rc = shell_dbinfo_command(p, nArg, azArg);
8492  }else
8493
8494  if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
8495    open_db(p, 0);
8496    rc = recoverDatabaseCmd(p, nArg, azArg);
8497  }else
8498#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
8499
8500  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
8501    char *zLike = 0;
8502    char *zSql;
8503    int i;
8504    int savedShowHeader = p->showHeader;
8505    int savedShellFlags = p->shellFlgs;
8506    ShellClearFlag(p,
8507       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
8508       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
8509    for(i=1; i<nArg; i++){
8510      if( azArg[i][0]=='-' ){
8511        const char *z = azArg[i]+1;
8512        if( z[0]=='-' ) z++;
8513        if( strcmp(z,"preserve-rowids")==0 ){
8514#ifdef SQLITE_OMIT_VIRTUALTABLE
8515          raw_printf(stderr, "The --preserve-rowids option is not compatible"
8516                             " with SQLITE_OMIT_VIRTUALTABLE\n");
8517          rc = 1;
8518          sqlite3_free(zLike);
8519          goto meta_command_exit;
8520#else
8521          ShellSetFlag(p, SHFLG_PreserveRowid);
8522#endif
8523        }else
8524        if( strcmp(z,"newlines")==0 ){
8525          ShellSetFlag(p, SHFLG_Newlines);
8526        }else
8527        if( strcmp(z,"data-only")==0 ){
8528          ShellSetFlag(p, SHFLG_DumpDataOnly);
8529        }else
8530        if( strcmp(z,"nosys")==0 ){
8531          ShellSetFlag(p, SHFLG_DumpNoSys);
8532        }else
8533        {
8534          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
8535          rc = 1;
8536          sqlite3_free(zLike);
8537          goto meta_command_exit;
8538        }
8539      }else{
8540        /* azArg[i] contains a LIKE pattern. This ".dump" request should
8541        ** only dump data for tables for which either the table name matches
8542        ** the LIKE pattern, or the table appears to be a shadow table of
8543        ** a virtual table for which the name matches the LIKE pattern.
8544        */
8545        char *zExpr = sqlite3_mprintf(
8546            "name LIKE %Q ESCAPE '\\' OR EXISTS ("
8547            "  SELECT 1 FROM sqlite_schema WHERE "
8548            "    name LIKE %Q ESCAPE '\\' AND"
8549            "    sql LIKE 'CREATE VIRTUAL TABLE%%' AND"
8550            "    substr(o.name, 1, length(name)+1) == (name||'_')"
8551            ")", azArg[i], azArg[i]
8552        );
8553
8554        if( zLike ){
8555          zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr);
8556        }else{
8557          zLike = zExpr;
8558        }
8559      }
8560    }
8561
8562    open_db(p, 0);
8563
8564    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8565      /* When playing back a "dump", the content might appear in an order
8566      ** which causes immediate foreign key constraints to be violated.
8567      ** So disable foreign-key constraint enforcement to prevent problems. */
8568      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
8569      raw_printf(p->out, "BEGIN TRANSACTION;\n");
8570    }
8571    p->writableSchema = 0;
8572    p->showHeader = 0;
8573    /* Set writable_schema=ON since doing so forces SQLite to initialize
8574    ** as much of the schema as it can even if the sqlite_schema table is
8575    ** corrupt. */
8576    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
8577    p->nErr = 0;
8578    if( zLike==0 ) zLike = sqlite3_mprintf("true");
8579    zSql = sqlite3_mprintf(
8580      "SELECT name, type, sql FROM sqlite_schema AS o "
8581      "WHERE (%s) AND type=='table'"
8582      "  AND sql NOT NULL"
8583      " ORDER BY tbl_name='sqlite_sequence', rowid",
8584      zLike
8585    );
8586    run_schema_dump_query(p,zSql);
8587    sqlite3_free(zSql);
8588    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8589      zSql = sqlite3_mprintf(
8590        "SELECT sql FROM sqlite_schema AS o "
8591        "WHERE (%s) AND sql NOT NULL"
8592        "  AND type IN ('index','trigger','view')",
8593        zLike
8594      );
8595      run_table_dump_query(p, zSql);
8596      sqlite3_free(zSql);
8597    }
8598    sqlite3_free(zLike);
8599    if( p->writableSchema ){
8600      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
8601      p->writableSchema = 0;
8602    }
8603    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
8604    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
8605    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
8606      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
8607    }
8608    p->showHeader = savedShowHeader;
8609    p->shellFlgs = savedShellFlags;
8610  }else
8611
8612  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
8613    if( nArg==2 ){
8614      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
8615    }else{
8616      raw_printf(stderr, "Usage: .echo on|off\n");
8617      rc = 1;
8618    }
8619  }else
8620
8621  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
8622    if( nArg==2 ){
8623      p->autoEQPtest = 0;
8624      if( p->autoEQPtrace ){
8625        if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
8626        p->autoEQPtrace = 0;
8627      }
8628      if( strcmp(azArg[1],"full")==0 ){
8629        p->autoEQP = AUTOEQP_full;
8630      }else if( strcmp(azArg[1],"trigger")==0 ){
8631        p->autoEQP = AUTOEQP_trigger;
8632#ifdef SQLITE_DEBUG
8633      }else if( strcmp(azArg[1],"test")==0 ){
8634        p->autoEQP = AUTOEQP_on;
8635        p->autoEQPtest = 1;
8636      }else if( strcmp(azArg[1],"trace")==0 ){
8637        p->autoEQP = AUTOEQP_full;
8638        p->autoEQPtrace = 1;
8639        open_db(p, 0);
8640        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
8641        sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
8642#endif
8643      }else{
8644        p->autoEQP = (u8)booleanValue(azArg[1]);
8645      }
8646    }else{
8647      raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
8648      rc = 1;
8649    }
8650  }else
8651
8652#ifndef SQLITE_SHELL_FIDDLE
8653  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
8654    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
8655    rc = 2;
8656  }else
8657#endif
8658
8659  /* The ".explain" command is automatic now.  It is largely pointless.  It
8660  ** retained purely for backwards compatibility */
8661  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
8662    int val = 1;
8663    if( nArg>=2 ){
8664      if( strcmp(azArg[1],"auto")==0 ){
8665        val = 99;
8666      }else{
8667        val =  booleanValue(azArg[1]);
8668      }
8669    }
8670    if( val==1 && p->mode!=MODE_Explain ){
8671      p->normalMode = p->mode;
8672      p->mode = MODE_Explain;
8673      p->autoExplain = 0;
8674    }else if( val==0 ){
8675      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8676      p->autoExplain = 0;
8677    }else if( val==99 ){
8678      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
8679      p->autoExplain = 1;
8680    }
8681  }else
8682
8683#ifndef SQLITE_OMIT_VIRTUALTABLE
8684  if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
8685    if( p->bSafeMode ){
8686      raw_printf(stderr,
8687        "Cannot run experimental commands such as \"%s\" in safe mode\n",
8688        azArg[0]);
8689      rc = 1;
8690    }else{
8691      open_db(p, 0);
8692      expertDotCommand(p, azArg, nArg);
8693    }
8694  }else
8695#endif
8696
8697  if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
8698    static const struct {
8699       const char *zCtrlName;   /* Name of a test-control option */
8700       int ctrlCode;            /* Integer code for that option */
8701       const char *zUsage;      /* Usage notes */
8702    } aCtrl[] = {
8703      { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
8704      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
8705      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },
8706      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
8707      { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
8708   /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
8709      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
8710      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
8711      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
8712      { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
8713   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
8714    };
8715    int filectrl = -1;
8716    int iCtrl = -1;
8717    sqlite3_int64 iRes = 0;  /* Integer result to display if rc2==1 */
8718    int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
8719    int n2, i;
8720    const char *zCmd = 0;
8721    const char *zSchema = 0;
8722
8723    open_db(p, 0);
8724    zCmd = nArg>=2 ? azArg[1] : "help";
8725
8726    if( zCmd[0]=='-'
8727     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
8728     && nArg>=4
8729    ){
8730      zSchema = azArg[2];
8731      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
8732      nArg -= 2;
8733      zCmd = azArg[1];
8734    }
8735
8736    /* The argument can optionally begin with "-" or "--" */
8737    if( zCmd[0]=='-' && zCmd[1] ){
8738      zCmd++;
8739      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8740    }
8741
8742    /* --help lists all file-controls */
8743    if( strcmp(zCmd,"help")==0 ){
8744      utf8_printf(p->out, "Available file-controls:\n");
8745      for(i=0; i<ArraySize(aCtrl); i++){
8746        utf8_printf(p->out, "  .filectrl %s %s\n",
8747                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
8748      }
8749      rc = 1;
8750      goto meta_command_exit;
8751    }
8752
8753    /* convert filectrl text option to value. allow any unique prefix
8754    ** of the option name, or a numerical value. */
8755    n2 = strlen30(zCmd);
8756    for(i=0; i<ArraySize(aCtrl); i++){
8757      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
8758        if( filectrl<0 ){
8759          filectrl = aCtrl[i].ctrlCode;
8760          iCtrl = i;
8761        }else{
8762          utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
8763                              "Use \".filectrl --help\" for help\n", zCmd);
8764          rc = 1;
8765          goto meta_command_exit;
8766        }
8767      }
8768    }
8769    if( filectrl<0 ){
8770      utf8_printf(stderr,"Error: unknown file-control: %s\n"
8771                         "Use \".filectrl --help\" for help\n", zCmd);
8772    }else{
8773      switch(filectrl){
8774        case SQLITE_FCNTL_SIZE_LIMIT: {
8775          if( nArg!=2 && nArg!=3 ) break;
8776          iRes = nArg==3 ? integerValue(azArg[2]) : -1;
8777          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
8778          isOk = 1;
8779          break;
8780        }
8781        case SQLITE_FCNTL_LOCK_TIMEOUT:
8782        case SQLITE_FCNTL_CHUNK_SIZE: {
8783          int x;
8784          if( nArg!=3 ) break;
8785          x = (int)integerValue(azArg[2]);
8786          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8787          isOk = 2;
8788          break;
8789        }
8790        case SQLITE_FCNTL_PERSIST_WAL:
8791        case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
8792          int x;
8793          if( nArg!=2 && nArg!=3 ) break;
8794          x = nArg==3 ? booleanValue(azArg[2]) : -1;
8795          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8796          iRes = x;
8797          isOk = 1;
8798          break;
8799        }
8800        case SQLITE_FCNTL_DATA_VERSION:
8801        case SQLITE_FCNTL_HAS_MOVED: {
8802          int x;
8803          if( nArg!=2 ) break;
8804          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8805          iRes = x;
8806          isOk = 1;
8807          break;
8808        }
8809        case SQLITE_FCNTL_TEMPFILENAME: {
8810          char *z = 0;
8811          if( nArg!=2 ) break;
8812          sqlite3_file_control(p->db, zSchema, filectrl, &z);
8813          if( z ){
8814            utf8_printf(p->out, "%s\n", z);
8815            sqlite3_free(z);
8816          }
8817          isOk = 2;
8818          break;
8819        }
8820        case SQLITE_FCNTL_RESERVE_BYTES: {
8821          int x;
8822          if( nArg>=3 ){
8823            x = atoi(azArg[2]);
8824            sqlite3_file_control(p->db, zSchema, filectrl, &x);
8825          }
8826          x = -1;
8827          sqlite3_file_control(p->db, zSchema, filectrl, &x);
8828          utf8_printf(p->out,"%d\n", x);
8829          isOk = 2;
8830          break;
8831        }
8832      }
8833    }
8834    if( isOk==0 && iCtrl>=0 ){
8835      utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
8836      rc = 1;
8837    }else if( isOk==1 ){
8838      char zBuf[100];
8839      sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
8840      raw_printf(p->out, "%s\n", zBuf);
8841    }
8842  }else
8843
8844  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
8845    ShellState data;
8846    int doStats = 0;
8847    memcpy(&data, p, sizeof(data));
8848    data.showHeader = 0;
8849    data.cMode = data.mode = MODE_Semi;
8850    if( nArg==2 && optionMatch(azArg[1], "indent") ){
8851      data.cMode = data.mode = MODE_Pretty;
8852      nArg = 1;
8853    }
8854    if( nArg!=1 ){
8855      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
8856      rc = 1;
8857      goto meta_command_exit;
8858    }
8859    open_db(p, 0);
8860    rc = sqlite3_exec(p->db,
8861       "SELECT sql FROM"
8862       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
8863       "     FROM sqlite_schema UNION ALL"
8864       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
8865       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
8866       "ORDER BY x",
8867       callback, &data, 0
8868    );
8869    if( rc==SQLITE_OK ){
8870      sqlite3_stmt *pStmt;
8871      rc = sqlite3_prepare_v2(p->db,
8872               "SELECT rowid FROM sqlite_schema"
8873               " WHERE name GLOB 'sqlite_stat[134]'",
8874               -1, &pStmt, 0);
8875      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
8876      sqlite3_finalize(pStmt);
8877    }
8878    if( doStats==0 ){
8879      raw_printf(p->out, "/* No STAT tables available */\n");
8880    }else{
8881      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8882      data.cMode = data.mode = MODE_Insert;
8883      data.zDestTable = "sqlite_stat1";
8884      shell_exec(&data, "SELECT * FROM sqlite_stat1", 0);
8885      data.zDestTable = "sqlite_stat4";
8886      shell_exec(&data, "SELECT * FROM sqlite_stat4", 0);
8887      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
8888    }
8889  }else
8890
8891  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
8892    if( nArg==2 ){
8893      p->showHeader = booleanValue(azArg[1]);
8894      p->shellFlgs |= SHFLG_HeaderSet;
8895    }else{
8896      raw_printf(stderr, "Usage: .headers on|off\n");
8897      rc = 1;
8898    }
8899  }else
8900
8901  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
8902    if( nArg>=2 ){
8903      n = showHelp(p->out, azArg[1]);
8904      if( n==0 ){
8905        utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
8906      }
8907    }else{
8908      showHelp(p->out, 0);
8909    }
8910  }else
8911
8912#ifndef SQLITE_SHELL_FIDDLE
8913  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
8914    char *zTable = 0;           /* Insert data into this table */
8915    char *zSchema = 0;          /* within this schema (may default to "main") */
8916    char *zFile = 0;            /* Name of file to extra content from */
8917    sqlite3_stmt *pStmt = NULL; /* A statement */
8918    int nCol;                   /* Number of columns in the table */
8919    int nByte;                  /* Number of bytes in an SQL string */
8920    int i, j;                   /* Loop counters */
8921    int needCommit;             /* True to COMMIT or ROLLBACK at end */
8922    int nSep;                   /* Number of bytes in p->colSeparator[] */
8923    char *zSql;                 /* An SQL statement */
8924    char *zFullTabName;         /* Table name with schema if applicable */
8925    ImportCtx sCtx;             /* Reader context */
8926    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
8927    int eVerbose = 0;           /* Larger for more console output */
8928    int nSkip = 0;              /* Initial lines to skip */
8929    int useOutputMode = 1;      /* Use output mode to determine separators */
8930    char *zCreate = 0;          /* CREATE TABLE statement text */
8931
8932    failIfSafeMode(p, "cannot run .import in safe mode");
8933    memset(&sCtx, 0, sizeof(sCtx));
8934    if( p->mode==MODE_Ascii ){
8935      xRead = ascii_read_one_field;
8936    }else{
8937      xRead = csv_read_one_field;
8938    }
8939    rc = 1;
8940    for(i=1; i<nArg; i++){
8941      char *z = azArg[i];
8942      if( z[0]=='-' && z[1]=='-' ) z++;
8943      if( z[0]!='-' ){
8944        if( zFile==0 ){
8945          zFile = z;
8946        }else if( zTable==0 ){
8947          zTable = z;
8948        }else{
8949          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
8950          showHelp(p->out, "import");
8951          goto meta_command_exit;
8952        }
8953      }else if( strcmp(z,"-v")==0 ){
8954        eVerbose++;
8955      }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){
8956        zSchema = azArg[++i];
8957      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
8958        nSkip = integerValue(azArg[++i]);
8959      }else if( strcmp(z,"-ascii")==0 ){
8960        sCtx.cColSep = SEP_Unit[0];
8961        sCtx.cRowSep = SEP_Record[0];
8962        xRead = ascii_read_one_field;
8963        useOutputMode = 0;
8964      }else if( strcmp(z,"-csv")==0 ){
8965        sCtx.cColSep = ',';
8966        sCtx.cRowSep = '\n';
8967        xRead = csv_read_one_field;
8968        useOutputMode = 0;
8969      }else{
8970        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
8971        showHelp(p->out, "import");
8972        goto meta_command_exit;
8973      }
8974    }
8975    if( zTable==0 ){
8976      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
8977                  zFile==0 ? "FILE" : "TABLE");
8978      showHelp(p->out, "import");
8979      goto meta_command_exit;
8980    }
8981    seenInterrupt = 0;
8982    open_db(p, 0);
8983    if( useOutputMode ){
8984      /* If neither the --csv or --ascii options are specified, then set
8985      ** the column and row separator characters from the output mode. */
8986      nSep = strlen30(p->colSeparator);
8987      if( nSep==0 ){
8988        raw_printf(stderr,
8989                   "Error: non-null column separator required for import\n");
8990        goto meta_command_exit;
8991      }
8992      if( nSep>1 ){
8993        raw_printf(stderr,
8994              "Error: multi-character column separators not allowed"
8995              " for import\n");
8996        goto meta_command_exit;
8997      }
8998      nSep = strlen30(p->rowSeparator);
8999      if( nSep==0 ){
9000        raw_printf(stderr,
9001            "Error: non-null row separator required for import\n");
9002        goto meta_command_exit;
9003      }
9004      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
9005        /* When importing CSV (only), if the row separator is set to the
9006        ** default output row separator, change it to the default input
9007        ** row separator.  This avoids having to maintain different input
9008        ** and output row separators. */
9009        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9010        nSep = strlen30(p->rowSeparator);
9011      }
9012      if( nSep>1 ){
9013        raw_printf(stderr, "Error: multi-character row separators not allowed"
9014                           " for import\n");
9015        goto meta_command_exit;
9016      }
9017      sCtx.cColSep = p->colSeparator[0];
9018      sCtx.cRowSep = p->rowSeparator[0];
9019    }
9020    sCtx.zFile = zFile;
9021    sCtx.nLine = 1;
9022    if( sCtx.zFile[0]=='|' ){
9023#ifdef SQLITE_OMIT_POPEN
9024      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9025      goto meta_command_exit;
9026#else
9027      sCtx.in = popen(sCtx.zFile+1, "r");
9028      sCtx.zFile = "<pipe>";
9029      sCtx.xCloser = pclose;
9030#endif
9031    }else{
9032      sCtx.in = fopen(sCtx.zFile, "rb");
9033      sCtx.xCloser = fclose;
9034    }
9035    if( sCtx.in==0 ){
9036      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
9037      goto meta_command_exit;
9038    }
9039    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
9040      char zSep[2];
9041      zSep[1] = 0;
9042      zSep[0] = sCtx.cColSep;
9043      utf8_printf(p->out, "Column separator ");
9044      output_c_string(p->out, zSep);
9045      utf8_printf(p->out, ", row separator ");
9046      zSep[0] = sCtx.cRowSep;
9047      output_c_string(p->out, zSep);
9048      utf8_printf(p->out, "\n");
9049    }
9050    sCtx.z = sqlite3_malloc64(120);
9051    if( sCtx.z==0 ){
9052      import_cleanup(&sCtx);
9053      shell_out_of_memory();
9054    }
9055    /* Below, resources must be freed before exit. */
9056    while( (nSkip--)>0 ){
9057      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
9058    }
9059    if( zSchema!=0 ){
9060      zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable);
9061    }else{
9062      zFullTabName = sqlite3_mprintf("\"%w\"", zTable);
9063    }
9064    zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName);
9065    if( zSql==0 || zFullTabName==0 ){
9066      import_cleanup(&sCtx);
9067      shell_out_of_memory();
9068    }
9069    nByte = strlen30(zSql);
9070    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9071    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
9072    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
9073      sqlite3 *dbCols = 0;
9074      char *zRenames = 0;
9075      char *zColDefs;
9076      zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName);
9077      while( xRead(&sCtx) ){
9078        zAutoColumn(sCtx.z, &dbCols, 0);
9079        if( sCtx.cTerm!=sCtx.cColSep ) break;
9080      }
9081      zColDefs = zAutoColumn(0, &dbCols, &zRenames);
9082      if( zRenames!=0 ){
9083        utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr,
9084                    "Columns renamed during .import %s due to duplicates:\n"
9085                    "%s\n", sCtx.zFile, zRenames);
9086        sqlite3_free(zRenames);
9087      }
9088      assert(dbCols==0);
9089      if( zColDefs==0 ){
9090        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
9091      import_fail:
9092        sqlite3_free(zCreate);
9093        sqlite3_free(zSql);
9094        sqlite3_free(zFullTabName);
9095        import_cleanup(&sCtx);
9096        rc = 1;
9097        goto meta_command_exit;
9098      }
9099      zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs);
9100      if( eVerbose>=1 ){
9101        utf8_printf(p->out, "%s\n", zCreate);
9102      }
9103      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
9104      if( rc ){
9105        utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db));
9106        goto import_fail;
9107      }
9108      sqlite3_free(zCreate);
9109      zCreate = 0;
9110      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9111    }
9112    if( rc ){
9113      if (pStmt) sqlite3_finalize(pStmt);
9114      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
9115      goto import_fail;
9116    }
9117    sqlite3_free(zSql);
9118    nCol = sqlite3_column_count(pStmt);
9119    sqlite3_finalize(pStmt);
9120    pStmt = 0;
9121    if( nCol==0 ) return 0; /* no columns, no error */
9122    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
9123    if( zSql==0 ){
9124      import_cleanup(&sCtx);
9125      shell_out_of_memory();
9126    }
9127    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName);
9128    j = strlen30(zSql);
9129    for(i=1; i<nCol; i++){
9130      zSql[j++] = ',';
9131      zSql[j++] = '?';
9132    }
9133    zSql[j++] = ')';
9134    zSql[j] = 0;
9135    if( eVerbose>=2 ){
9136      utf8_printf(p->out, "Insert using: %s\n", zSql);
9137    }
9138    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9139    if( rc ){
9140      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
9141      if (pStmt) sqlite3_finalize(pStmt);
9142      goto import_fail;
9143    }
9144    sqlite3_free(zSql);
9145    sqlite3_free(zFullTabName);
9146    needCommit = sqlite3_get_autocommit(p->db);
9147    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
9148    do{
9149      int startLine = sCtx.nLine;
9150      for(i=0; i<nCol; i++){
9151        char *z = xRead(&sCtx);
9152        /*
9153        ** Did we reach end-of-file before finding any columns?
9154        ** If so, stop instead of NULL filling the remaining columns.
9155        */
9156        if( z==0 && i==0 ) break;
9157        /*
9158        ** Did we reach end-of-file OR end-of-line before finding any
9159        ** columns in ASCII mode?  If so, stop instead of NULL filling
9160        ** the remaining columns.
9161        */
9162        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
9163        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
9164        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
9165          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9166                          "filling the rest with NULL\n",
9167                          sCtx.zFile, startLine, nCol, i+1);
9168          i += 2;
9169          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
9170        }
9171      }
9172      if( sCtx.cTerm==sCtx.cColSep ){
9173        do{
9174          xRead(&sCtx);
9175          i++;
9176        }while( sCtx.cTerm==sCtx.cColSep );
9177        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
9178                        "extras ignored\n",
9179                        sCtx.zFile, startLine, nCol, i);
9180      }
9181      if( i>=nCol ){
9182        sqlite3_step(pStmt);
9183        rc = sqlite3_reset(pStmt);
9184        if( rc!=SQLITE_OK ){
9185          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
9186                      startLine, sqlite3_errmsg(p->db));
9187          sCtx.nErr++;
9188        }else{
9189          sCtx.nRow++;
9190        }
9191      }
9192    }while( sCtx.cTerm!=EOF );
9193
9194    import_cleanup(&sCtx);
9195    sqlite3_finalize(pStmt);
9196    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
9197    if( eVerbose>0 ){
9198      utf8_printf(p->out,
9199          "Added %d rows with %d errors using %d lines of input\n",
9200          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
9201    }
9202  }else
9203#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9204
9205#ifndef SQLITE_UNTESTABLE
9206  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
9207    char *zSql;
9208    char *zCollist = 0;
9209    sqlite3_stmt *pStmt;
9210    int tnum = 0;
9211    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
9212    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
9213    int i;
9214    if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
9215      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
9216                          "       .imposter off\n");
9217      /* Also allowed, but not documented:
9218      **
9219      **    .imposter TABLE IMPOSTER
9220      **
9221      ** where TABLE is a WITHOUT ROWID table.  In that case, the
9222      ** imposter is another WITHOUT ROWID table with the columns in
9223      ** storage order. */
9224      rc = 1;
9225      goto meta_command_exit;
9226    }
9227    open_db(p, 0);
9228    if( nArg==2 ){
9229      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
9230      goto meta_command_exit;
9231    }
9232    zSql = sqlite3_mprintf(
9233      "SELECT rootpage, 0 FROM sqlite_schema"
9234      " WHERE name='%q' AND type='index'"
9235      "UNION ALL "
9236      "SELECT rootpage, 1 FROM sqlite_schema"
9237      " WHERE name='%q' AND type='table'"
9238      "   AND sql LIKE '%%without%%rowid%%'",
9239      azArg[1], azArg[1]
9240    );
9241    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9242    sqlite3_free(zSql);
9243    if( sqlite3_step(pStmt)==SQLITE_ROW ){
9244      tnum = sqlite3_column_int(pStmt, 0);
9245      isWO = sqlite3_column_int(pStmt, 1);
9246    }
9247    sqlite3_finalize(pStmt);
9248    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
9249    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9250    sqlite3_free(zSql);
9251    i = 0;
9252    while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9253      char zLabel[20];
9254      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
9255      i++;
9256      if( zCol==0 ){
9257        if( sqlite3_column_int(pStmt,1)==-1 ){
9258          zCol = "_ROWID_";
9259        }else{
9260          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
9261          zCol = zLabel;
9262        }
9263      }
9264      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
9265        lenPK = (int)strlen(zCollist);
9266      }
9267      if( zCollist==0 ){
9268        zCollist = sqlite3_mprintf("\"%w\"", zCol);
9269      }else{
9270        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
9271      }
9272    }
9273    sqlite3_finalize(pStmt);
9274    if( i==0 || tnum==0 ){
9275      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
9276      rc = 1;
9277      sqlite3_free(zCollist);
9278      goto meta_command_exit;
9279    }
9280    if( lenPK==0 ) lenPK = 100000;
9281    zSql = sqlite3_mprintf(
9282          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
9283          azArg[2], zCollist, lenPK, zCollist);
9284    sqlite3_free(zCollist);
9285    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
9286    if( rc==SQLITE_OK ){
9287      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
9288      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
9289      if( rc ){
9290        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
9291      }else{
9292        utf8_printf(stdout, "%s;\n", zSql);
9293        raw_printf(stdout,
9294          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
9295          azArg[1], isWO ? "table" : "index"
9296        );
9297      }
9298    }else{
9299      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
9300      rc = 1;
9301    }
9302    sqlite3_free(zSql);
9303  }else
9304#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
9305
9306#ifdef SQLITE_ENABLE_IOTRACE
9307  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
9308    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
9309    if( iotrace && iotrace!=stdout ) fclose(iotrace);
9310    iotrace = 0;
9311    if( nArg<2 ){
9312      sqlite3IoTrace = 0;
9313    }else if( strcmp(azArg[1], "-")==0 ){
9314      sqlite3IoTrace = iotracePrintf;
9315      iotrace = stdout;
9316    }else{
9317      iotrace = fopen(azArg[1], "w");
9318      if( iotrace==0 ){
9319        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9320        sqlite3IoTrace = 0;
9321        rc = 1;
9322      }else{
9323        sqlite3IoTrace = iotracePrintf;
9324      }
9325    }
9326  }else
9327#endif
9328
9329  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
9330    static const struct {
9331       const char *zLimitName;   /* Name of a limit */
9332       int limitCode;            /* Integer code for that limit */
9333    } aLimit[] = {
9334      { "length",                SQLITE_LIMIT_LENGTH                    },
9335      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
9336      { "column",                SQLITE_LIMIT_COLUMN                    },
9337      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
9338      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
9339      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
9340      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
9341      { "attached",              SQLITE_LIMIT_ATTACHED                  },
9342      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
9343      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
9344      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
9345      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
9346    };
9347    int i, n2;
9348    open_db(p, 0);
9349    if( nArg==1 ){
9350      for(i=0; i<ArraySize(aLimit); i++){
9351        printf("%20s %d\n", aLimit[i].zLimitName,
9352               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
9353      }
9354    }else if( nArg>3 ){
9355      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
9356      rc = 1;
9357      goto meta_command_exit;
9358    }else{
9359      int iLimit = -1;
9360      n2 = strlen30(azArg[1]);
9361      for(i=0; i<ArraySize(aLimit); i++){
9362        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
9363          if( iLimit<0 ){
9364            iLimit = i;
9365          }else{
9366            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
9367            rc = 1;
9368            goto meta_command_exit;
9369          }
9370        }
9371      }
9372      if( iLimit<0 ){
9373        utf8_printf(stderr, "unknown limit: \"%s\"\n"
9374                        "enter \".limits\" with no arguments for a list.\n",
9375                         azArg[1]);
9376        rc = 1;
9377        goto meta_command_exit;
9378      }
9379      if( nArg==3 ){
9380        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
9381                      (int)integerValue(azArg[2]));
9382      }
9383      printf("%20s %d\n", aLimit[iLimit].zLimitName,
9384             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
9385    }
9386  }else
9387
9388  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
9389    open_db(p, 0);
9390    lintDotCommand(p, azArg, nArg);
9391  }else
9392
9393#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
9394  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
9395    const char *zFile, *zProc;
9396    char *zErrMsg = 0;
9397    failIfSafeMode(p, "cannot run .load in safe mode");
9398    if( nArg<2 ){
9399      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
9400      rc = 1;
9401      goto meta_command_exit;
9402    }
9403    zFile = azArg[1];
9404    zProc = nArg>=3 ? azArg[2] : 0;
9405    open_db(p, 0);
9406    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
9407    if( rc!=SQLITE_OK ){
9408      utf8_printf(stderr, "Error: %s\n", zErrMsg);
9409      sqlite3_free(zErrMsg);
9410      rc = 1;
9411    }
9412  }else
9413#endif
9414
9415#ifndef SQLITE_SHELL_FIDDLE
9416  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
9417    failIfSafeMode(p, "cannot run .log in safe mode");
9418    if( nArg!=2 ){
9419      raw_printf(stderr, "Usage: .log FILENAME\n");
9420      rc = 1;
9421    }else{
9422      const char *zFile = azArg[1];
9423      output_file_close(p->pLog);
9424      p->pLog = output_file_open(zFile, 0);
9425    }
9426  }else
9427#endif
9428
9429  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
9430    const char *zMode = 0;
9431    const char *zTabname = 0;
9432    int i, n2;
9433    ColModeOpts cmOpts = ColModeOpts_default;
9434    for(i=1; i<nArg; i++){
9435      const char *z = azArg[i];
9436      if( optionMatch(z,"wrap") && i+1<nArg ){
9437        cmOpts.iWrap = integerValue(azArg[++i]);
9438      }else if( optionMatch(z,"ww") ){
9439        cmOpts.bWordWrap = 1;
9440      }else if( optionMatch(z,"wordwrap") && i+1<nArg ){
9441        cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]);
9442      }else if( optionMatch(z,"quote") ){
9443        cmOpts.bQuote = 1;
9444      }else if( optionMatch(z,"noquote") ){
9445        cmOpts.bQuote = 0;
9446      }else if( zMode==0 ){
9447        zMode = z;
9448        /* Apply defaults for qbox pseudo-mods. If that
9449         * overwrites already-set values, user was informed of this.
9450         */
9451        if( strcmp(z, "qbox")==0 ){
9452          ColModeOpts cmo = ColModeOpts_default_qbox;
9453          zMode = "box";
9454          cmOpts = cmo;
9455        }
9456      }else if( zTabname==0 ){
9457        zTabname = z;
9458      }else if( z[0]=='-' ){
9459        utf8_printf(stderr, "unknown option: %s\n", z);
9460        utf8_printf(stderr, "options:\n"
9461                            "  --noquote\n"
9462                            "  --quote\n"
9463                            "  --wordwrap on/off\n"
9464                            "  --wrap N\n"
9465                            "  --ww\n");
9466        rc = 1;
9467        goto meta_command_exit;
9468      }else{
9469        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9470        rc = 1;
9471        goto meta_command_exit;
9472      }
9473    }
9474    if( zMode==0 ){
9475      if( p->mode==MODE_Column
9476       || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
9477      ){
9478        raw_printf
9479          (p->out,
9480           "current output mode: %s --wrap %d --wordwrap %s --%squote\n",
9481           modeDescr[p->mode], p->cmOpts.iWrap,
9482           p->cmOpts.bWordWrap ? "on" : "off",
9483           p->cmOpts.bQuote ? "" : "no");
9484      }else{
9485        raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
9486      }
9487      zMode = modeDescr[p->mode];
9488    }
9489    n2 = strlen30(zMode);
9490    if( strncmp(zMode,"lines",n2)==0 ){
9491      p->mode = MODE_Line;
9492      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9493    }else if( strncmp(zMode,"columns",n2)==0 ){
9494      p->mode = MODE_Column;
9495      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
9496        p->showHeader = 1;
9497      }
9498      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9499      p->cmOpts = cmOpts;
9500    }else if( strncmp(zMode,"list",n2)==0 ){
9501      p->mode = MODE_List;
9502      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
9503      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9504    }else if( strncmp(zMode,"html",n2)==0 ){
9505      p->mode = MODE_Html;
9506    }else if( strncmp(zMode,"tcl",n2)==0 ){
9507      p->mode = MODE_Tcl;
9508      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
9509      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9510    }else if( strncmp(zMode,"csv",n2)==0 ){
9511      p->mode = MODE_Csv;
9512      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9513      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9514    }else if( strncmp(zMode,"tabs",n2)==0 ){
9515      p->mode = MODE_List;
9516      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
9517    }else if( strncmp(zMode,"insert",n2)==0 ){
9518      p->mode = MODE_Insert;
9519      set_table_name(p, zTabname ? zTabname : "table");
9520    }else if( strncmp(zMode,"quote",n2)==0 ){
9521      p->mode = MODE_Quote;
9522      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9523      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
9524    }else if( strncmp(zMode,"ascii",n2)==0 ){
9525      p->mode = MODE_Ascii;
9526      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
9527      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
9528    }else if( strncmp(zMode,"markdown",n2)==0 ){
9529      p->mode = MODE_Markdown;
9530      p->cmOpts = cmOpts;
9531    }else if( strncmp(zMode,"table",n2)==0 ){
9532      p->mode = MODE_Table;
9533      p->cmOpts = cmOpts;
9534    }else if( strncmp(zMode,"box",n2)==0 ){
9535      p->mode = MODE_Box;
9536      p->cmOpts = cmOpts;
9537    }else if( strncmp(zMode,"count",n2)==0 ){
9538      p->mode = MODE_Count;
9539    }else if( strncmp(zMode,"off",n2)==0 ){
9540      p->mode = MODE_Off;
9541    }else if( strncmp(zMode,"json",n2)==0 ){
9542      p->mode = MODE_Json;
9543    }else{
9544      raw_printf(stderr, "Error: mode should be one of: "
9545         "ascii box column csv html insert json line list markdown "
9546         "qbox quote table tabs tcl\n");
9547      rc = 1;
9548    }
9549    p->cMode = p->mode;
9550  }else
9551
9552#ifndef SQLITE_SHELL_FIDDLE
9553  if( c=='n' && strcmp(azArg[0], "nonce")==0 ){
9554    if( nArg!=2 ){
9555      raw_printf(stderr, "Usage: .nonce NONCE\n");
9556      rc = 1;
9557    }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){
9558      raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n",
9559                 p->lineno, azArg[1]);
9560      exit(1);
9561    }else{
9562      p->bSafeMode = 0;
9563      return 0;  /* Return immediately to bypass the safe mode reset
9564                 ** at the end of this procedure */
9565    }
9566  }else
9567#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9568
9569  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
9570    if( nArg==2 ){
9571      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
9572                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
9573    }else{
9574      raw_printf(stderr, "Usage: .nullvalue STRING\n");
9575      rc = 1;
9576    }
9577  }else
9578
9579  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
9580    const char *zFN = 0;     /* Pointer to constant filename */
9581    char *zNewFilename = 0;  /* Name of the database file to open */
9582    int iName = 1;           /* Index in azArg[] of the filename */
9583    int newFlag = 0;         /* True to delete file before opening */
9584    int openMode = SHELL_OPEN_UNSPEC;
9585
9586    /* Check for command-line arguments */
9587    for(iName=1; iName<nArg; iName++){
9588      const char *z = azArg[iName];
9589#ifndef SQLITE_SHELL_FIDDLE
9590      if( optionMatch(z,"new") ){
9591        newFlag = 1;
9592#ifdef SQLITE_HAVE_ZLIB
9593      }else if( optionMatch(z, "zip") ){
9594        openMode = SHELL_OPEN_ZIPFILE;
9595#endif
9596      }else if( optionMatch(z, "append") ){
9597        openMode = SHELL_OPEN_APPENDVFS;
9598      }else if( optionMatch(z, "readonly") ){
9599        openMode = SHELL_OPEN_READONLY;
9600      }else if( optionMatch(z, "nofollow") ){
9601        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
9602#ifndef SQLITE_OMIT_DESERIALIZE
9603      }else if( optionMatch(z, "deserialize") ){
9604        openMode = SHELL_OPEN_DESERIALIZE;
9605      }else if( optionMatch(z, "hexdb") ){
9606        openMode = SHELL_OPEN_HEXDB;
9607      }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
9608        p->szMax = integerValue(azArg[++iName]);
9609#endif /* SQLITE_OMIT_DESERIALIZE */
9610      }else
9611#endif /* !SQLITE_SHELL_FIDDLE */
9612      if( z[0]=='-' ){
9613        utf8_printf(stderr, "unknown option: %s\n", z);
9614        rc = 1;
9615        goto meta_command_exit;
9616      }else if( zFN ){
9617        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
9618        rc = 1;
9619        goto meta_command_exit;
9620      }else{
9621        zFN = z;
9622      }
9623    }
9624
9625    /* Close the existing database */
9626    session_close_all(p, -1);
9627    close_db(p->db);
9628    p->db = 0;
9629    p->pAuxDb->zDbFilename = 0;
9630    sqlite3_free(p->pAuxDb->zFreeOnClose);
9631    p->pAuxDb->zFreeOnClose = 0;
9632    p->openMode = openMode;
9633    p->openFlags = 0;
9634    p->szMax = 0;
9635
9636    /* If a filename is specified, try to open it first */
9637    if( zFN || p->openMode==SHELL_OPEN_HEXDB ){
9638      if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN);
9639#ifndef SQLITE_SHELL_FIDDLE
9640      if( p->bSafeMode
9641       && p->openMode!=SHELL_OPEN_HEXDB
9642       && zFN
9643       && strcmp(zFN,":memory:")!=0
9644      ){
9645        failIfSafeMode(p, "cannot open disk-based database files in safe mode");
9646      }
9647#else
9648      /* WASM mode has its own sandboxed pseudo-filesystem. */
9649#endif
9650      if( zFN ){
9651        zNewFilename = sqlite3_mprintf("%s", zFN);
9652        shell_check_oom(zNewFilename);
9653      }else{
9654        zNewFilename = 0;
9655      }
9656      p->pAuxDb->zDbFilename = zNewFilename;
9657      open_db(p, OPEN_DB_KEEPALIVE);
9658      if( p->db==0 ){
9659        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
9660        sqlite3_free(zNewFilename);
9661      }else{
9662        p->pAuxDb->zFreeOnClose = zNewFilename;
9663      }
9664    }
9665    if( p->db==0 ){
9666      /* As a fall-back open a TEMP database */
9667      p->pAuxDb->zDbFilename = 0;
9668      open_db(p, 0);
9669    }
9670  }else
9671
9672#ifndef SQLITE_SHELL_FIDDLE
9673  if( (c=='o'
9674        && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
9675   || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
9676  ){
9677    char *zFile = 0;
9678    int bTxtMode = 0;
9679    int i;
9680    int eMode = 0;
9681    int bOnce = 0;            /* 0: .output, 1: .once, 2: .excel */
9682    unsigned char zBOM[4];    /* Byte-order mark to using if --bom is present */
9683
9684    zBOM[0] = 0;
9685    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
9686    if( c=='e' ){
9687      eMode = 'x';
9688      bOnce = 2;
9689    }else if( strncmp(azArg[0],"once",n)==0 ){
9690      bOnce = 1;
9691    }
9692    for(i=1; i<nArg; i++){
9693      char *z = azArg[i];
9694      if( z[0]=='-' ){
9695        if( z[1]=='-' ) z++;
9696        if( strcmp(z,"-bom")==0 ){
9697          zBOM[0] = 0xef;
9698          zBOM[1] = 0xbb;
9699          zBOM[2] = 0xbf;
9700          zBOM[3] = 0;
9701        }else if( c!='e' && strcmp(z,"-x")==0 ){
9702          eMode = 'x';  /* spreadsheet */
9703        }else if( c!='e' && strcmp(z,"-e")==0 ){
9704          eMode = 'e';  /* text editor */
9705        }else{
9706          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
9707                      azArg[i]);
9708          showHelp(p->out, azArg[0]);
9709          rc = 1;
9710          goto meta_command_exit;
9711        }
9712      }else if( zFile==0 && eMode!='e' && eMode!='x' ){
9713        zFile = sqlite3_mprintf("%s", z);
9714        if( zFile && zFile[0]=='|' ){
9715          while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]);
9716          break;
9717        }
9718      }else{
9719        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
9720                    azArg[i]);
9721        showHelp(p->out, azArg[0]);
9722        rc = 1;
9723        sqlite3_free(zFile);
9724        goto meta_command_exit;
9725      }
9726    }
9727    if( zFile==0 ){
9728      zFile = sqlite3_mprintf("stdout");
9729    }
9730    if( bOnce ){
9731      p->outCount = 2;
9732    }else{
9733      p->outCount = 0;
9734    }
9735    output_reset(p);
9736#ifndef SQLITE_NOHAVE_SYSTEM
9737    if( eMode=='e' || eMode=='x' ){
9738      p->doXdgOpen = 1;
9739      outputModePush(p);
9740      if( eMode=='x' ){
9741        /* spreadsheet mode.  Output as CSV. */
9742        newTempFile(p, "csv");
9743        ShellClearFlag(p, SHFLG_Echo);
9744        p->mode = MODE_Csv;
9745        sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
9746        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
9747      }else{
9748        /* text editor mode */
9749        newTempFile(p, "txt");
9750        bTxtMode = 1;
9751      }
9752      sqlite3_free(zFile);
9753      zFile = sqlite3_mprintf("%s", p->zTempFile);
9754    }
9755#endif /* SQLITE_NOHAVE_SYSTEM */
9756    shell_check_oom(zFile);
9757    if( zFile[0]=='|' ){
9758#ifdef SQLITE_OMIT_POPEN
9759      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9760      rc = 1;
9761      p->out = stdout;
9762#else
9763      p->out = popen(zFile + 1, "w");
9764      if( p->out==0 ){
9765        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
9766        p->out = stdout;
9767        rc = 1;
9768      }else{
9769        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9770        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9771      }
9772#endif
9773    }else{
9774      p->out = output_file_open(zFile, bTxtMode);
9775      if( p->out==0 ){
9776        if( strcmp(zFile,"off")!=0 ){
9777          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
9778        }
9779        p->out = stdout;
9780        rc = 1;
9781      } else {
9782        if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out);
9783        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
9784      }
9785    }
9786    sqlite3_free(zFile);
9787  }else
9788#endif /* !defined(SQLITE_SHELL_FIDDLE) */
9789
9790  if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
9791    open_db(p,0);
9792    if( nArg<=1 ) goto parameter_syntax_error;
9793
9794    /* .parameter clear
9795    ** Clear all bind parameters by dropping the TEMP table that holds them.
9796    */
9797    if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
9798      sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
9799                   0, 0, 0);
9800    }else
9801
9802    /* .parameter list
9803    ** List all bind parameters.
9804    */
9805    if( nArg==2 && strcmp(azArg[1],"list")==0 ){
9806      sqlite3_stmt *pStmt = 0;
9807      int rx;
9808      int len = 0;
9809      rx = sqlite3_prepare_v2(p->db,
9810             "SELECT max(length(key)) "
9811             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9812      if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9813        len = sqlite3_column_int(pStmt, 0);
9814        if( len>40 ) len = 40;
9815      }
9816      sqlite3_finalize(pStmt);
9817      pStmt = 0;
9818      if( len ){
9819        rx = sqlite3_prepare_v2(p->db,
9820             "SELECT key, quote(value) "
9821             "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
9822        while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
9823          utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
9824                      sqlite3_column_text(pStmt,1));
9825        }
9826        sqlite3_finalize(pStmt);
9827      }
9828    }else
9829
9830    /* .parameter init
9831    ** Make sure the TEMP table used to hold bind parameters exists.
9832    ** Create it if necessary.
9833    */
9834    if( nArg==2 && strcmp(azArg[1],"init")==0 ){
9835      bind_table_init(p);
9836    }else
9837
9838    /* .parameter set NAME VALUE
9839    ** Set or reset a bind parameter.  NAME should be the full parameter
9840    ** name exactly as it appears in the query.  (ex: $abc, @def).  The
9841    ** VALUE can be in either SQL literal notation, or if not it will be
9842    ** understood to be a text string.
9843    */
9844    if( nArg==4 && strcmp(azArg[1],"set")==0 ){
9845      int rx;
9846      char *zSql;
9847      sqlite3_stmt *pStmt;
9848      const char *zKey = azArg[2];
9849      const char *zValue = azArg[3];
9850      bind_table_init(p);
9851      zSql = sqlite3_mprintf(
9852                  "REPLACE INTO temp.sqlite_parameters(key,value)"
9853                  "VALUES(%Q,%s);", zKey, zValue);
9854      shell_check_oom(zSql);
9855      pStmt = 0;
9856      rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9857      sqlite3_free(zSql);
9858      if( rx!=SQLITE_OK ){
9859        sqlite3_finalize(pStmt);
9860        pStmt = 0;
9861        zSql = sqlite3_mprintf(
9862                   "REPLACE INTO temp.sqlite_parameters(key,value)"
9863                   "VALUES(%Q,%Q);", zKey, zValue);
9864        shell_check_oom(zSql);
9865        rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
9866        sqlite3_free(zSql);
9867        if( rx!=SQLITE_OK ){
9868          utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
9869          sqlite3_finalize(pStmt);
9870          pStmt = 0;
9871          rc = 1;
9872        }
9873      }
9874      sqlite3_step(pStmt);
9875      sqlite3_finalize(pStmt);
9876    }else
9877
9878    /* .parameter unset NAME
9879    ** Remove the NAME binding from the parameter binding table, if it
9880    ** exists.
9881    */
9882    if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
9883      char *zSql = sqlite3_mprintf(
9884          "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
9885      shell_check_oom(zSql);
9886      sqlite3_exec(p->db, zSql, 0, 0, 0);
9887      sqlite3_free(zSql);
9888    }else
9889    /* If no command name matches, show a syntax error */
9890    parameter_syntax_error:
9891    showHelp(p->out, "parameter");
9892  }else
9893
9894  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
9895    int i;
9896    for(i=1; i<nArg; i++){
9897      if( i>1 ) raw_printf(p->out, " ");
9898      utf8_printf(p->out, "%s", azArg[i]);
9899    }
9900    raw_printf(p->out, "\n");
9901  }else
9902
9903#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9904  if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
9905    int i;
9906    int nn = 0;
9907    p->flgProgress = 0;
9908    p->mxProgress = 0;
9909    p->nProgress = 0;
9910    for(i=1; i<nArg; i++){
9911      const char *z = azArg[i];
9912      if( z[0]=='-' ){
9913        z++;
9914        if( z[0]=='-' ) z++;
9915        if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
9916          p->flgProgress |= SHELL_PROGRESS_QUIET;
9917          continue;
9918        }
9919        if( strcmp(z,"reset")==0 ){
9920          p->flgProgress |= SHELL_PROGRESS_RESET;
9921          continue;
9922        }
9923        if( strcmp(z,"once")==0 ){
9924          p->flgProgress |= SHELL_PROGRESS_ONCE;
9925          continue;
9926        }
9927        if( strcmp(z,"limit")==0 ){
9928          if( i+1>=nArg ){
9929            utf8_printf(stderr, "Error: missing argument on --limit\n");
9930            rc = 1;
9931            goto meta_command_exit;
9932          }else{
9933            p->mxProgress = (int)integerValue(azArg[++i]);
9934          }
9935          continue;
9936        }
9937        utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
9938        rc = 1;
9939        goto meta_command_exit;
9940      }else{
9941        nn = (int)integerValue(z);
9942      }
9943    }
9944    open_db(p, 0);
9945    sqlite3_progress_handler(p->db, nn, progress_handler, p);
9946  }else
9947#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
9948
9949  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
9950    if( nArg >= 2) {
9951      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
9952    }
9953    if( nArg >= 3) {
9954      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
9955    }
9956  }else
9957
9958#ifndef SQLITE_SHELL_FIDDLE
9959  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
9960    rc = 2;
9961  }else
9962#endif
9963
9964#ifndef SQLITE_SHELL_FIDDLE
9965  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
9966    FILE *inSaved = p->in;
9967    int savedLineno = p->lineno;
9968    failIfSafeMode(p, "cannot run .read in safe mode");
9969    if( nArg!=2 ){
9970      raw_printf(stderr, "Usage: .read FILE\n");
9971      rc = 1;
9972      goto meta_command_exit;
9973    }
9974    if( azArg[1][0]=='|' ){
9975#ifdef SQLITE_OMIT_POPEN
9976      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
9977      rc = 1;
9978      p->out = stdout;
9979#else
9980      p->in = popen(azArg[1]+1, "r");
9981      if( p->in==0 ){
9982        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
9983        rc = 1;
9984      }else{
9985        rc = process_input(p);
9986        pclose(p->in);
9987      }
9988#endif
9989    }else if( (p->in = openChrSource(azArg[1]))==0 ){
9990      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
9991      rc = 1;
9992    }else{
9993      rc = process_input(p);
9994      fclose(p->in);
9995    }
9996    p->in = inSaved;
9997    p->lineno = savedLineno;
9998  }else
9999#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10000
10001#ifndef SQLITE_SHELL_FIDDLE
10002  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
10003    const char *zSrcFile;
10004    const char *zDb;
10005    sqlite3 *pSrc;
10006    sqlite3_backup *pBackup;
10007    int nTimeout = 0;
10008
10009    failIfSafeMode(p, "cannot run .restore in safe mode");
10010    if( nArg==2 ){
10011      zSrcFile = azArg[1];
10012      zDb = "main";
10013    }else if( nArg==3 ){
10014      zSrcFile = azArg[2];
10015      zDb = azArg[1];
10016    }else{
10017      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
10018      rc = 1;
10019      goto meta_command_exit;
10020    }
10021    rc = sqlite3_open(zSrcFile, &pSrc);
10022    if( rc!=SQLITE_OK ){
10023      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
10024      close_db(pSrc);
10025      return 1;
10026    }
10027    open_db(p, 0);
10028    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
10029    if( pBackup==0 ){
10030      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10031      close_db(pSrc);
10032      return 1;
10033    }
10034    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
10035          || rc==SQLITE_BUSY  ){
10036      if( rc==SQLITE_BUSY ){
10037        if( nTimeout++ >= 3 ) break;
10038        sqlite3_sleep(100);
10039      }
10040    }
10041    sqlite3_backup_finish(pBackup);
10042    if( rc==SQLITE_DONE ){
10043      rc = 0;
10044    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
10045      raw_printf(stderr, "Error: source database is busy\n");
10046      rc = 1;
10047    }else{
10048      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10049      rc = 1;
10050    }
10051    close_db(pSrc);
10052  }else
10053#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10054
10055  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
10056    if( nArg==2 ){
10057      p->scanstatsOn = (u8)booleanValue(azArg[1]);
10058#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10059      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
10060#endif
10061    }else{
10062      raw_printf(stderr, "Usage: .scanstats on|off\n");
10063      rc = 1;
10064    }
10065  }else
10066
10067  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
10068    ShellText sSelect;
10069    ShellState data;
10070    char *zErrMsg = 0;
10071    const char *zDiv = "(";
10072    const char *zName = 0;
10073    int iSchema = 0;
10074    int bDebug = 0;
10075    int bNoSystemTabs = 0;
10076    int ii;
10077
10078    open_db(p, 0);
10079    memcpy(&data, p, sizeof(data));
10080    data.showHeader = 0;
10081    data.cMode = data.mode = MODE_Semi;
10082    initText(&sSelect);
10083    for(ii=1; ii<nArg; ii++){
10084      if( optionMatch(azArg[ii],"indent") ){
10085        data.cMode = data.mode = MODE_Pretty;
10086      }else if( optionMatch(azArg[ii],"debug") ){
10087        bDebug = 1;
10088      }else if( optionMatch(azArg[ii],"nosys") ){
10089        bNoSystemTabs = 1;
10090      }else if( azArg[ii][0]=='-' ){
10091        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
10092        rc = 1;
10093        goto meta_command_exit;
10094      }else if( zName==0 ){
10095        zName = azArg[ii];
10096      }else{
10097        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
10098        rc = 1;
10099        goto meta_command_exit;
10100      }
10101    }
10102    if( zName!=0 ){
10103      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
10104                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
10105                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
10106                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
10107      if( isSchema ){
10108        char *new_argv[2], *new_colv[2];
10109        new_argv[0] = sqlite3_mprintf(
10110                      "CREATE TABLE %s (\n"
10111                      "  type text,\n"
10112                      "  name text,\n"
10113                      "  tbl_name text,\n"
10114                      "  rootpage integer,\n"
10115                      "  sql text\n"
10116                      ")", zName);
10117        shell_check_oom(new_argv[0]);
10118        new_argv[1] = 0;
10119        new_colv[0] = "sql";
10120        new_colv[1] = 0;
10121        callback(&data, 1, new_argv, new_colv);
10122        sqlite3_free(new_argv[0]);
10123      }
10124    }
10125    if( zDiv ){
10126      sqlite3_stmt *pStmt = 0;
10127      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
10128                              -1, &pStmt, 0);
10129      if( rc ){
10130        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
10131        sqlite3_finalize(pStmt);
10132        rc = 1;
10133        goto meta_command_exit;
10134      }
10135      appendText(&sSelect, "SELECT sql FROM", 0);
10136      iSchema = 0;
10137      while( sqlite3_step(pStmt)==SQLITE_ROW ){
10138        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
10139        char zScNum[30];
10140        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
10141        appendText(&sSelect, zDiv, 0);
10142        zDiv = " UNION ALL ";
10143        appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
10144        if( sqlite3_stricmp(zDb, "main")!=0 ){
10145          appendText(&sSelect, zDb, '\'');
10146        }else{
10147          appendText(&sSelect, "NULL", 0);
10148        }
10149        appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
10150        appendText(&sSelect, zScNum, 0);
10151        appendText(&sSelect, " AS snum, ", 0);
10152        appendText(&sSelect, zDb, '\'');
10153        appendText(&sSelect, " AS sname FROM ", 0);
10154        appendText(&sSelect, zDb, quoteChar(zDb));
10155        appendText(&sSelect, ".sqlite_schema", 0);
10156      }
10157      sqlite3_finalize(pStmt);
10158#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
10159      if( zName ){
10160        appendText(&sSelect,
10161           " UNION ALL SELECT shell_module_schema(name),"
10162           " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
10163        0);
10164      }
10165#endif
10166      appendText(&sSelect, ") WHERE ", 0);
10167      if( zName ){
10168        char *zQarg = sqlite3_mprintf("%Q", zName);
10169        int bGlob;
10170        shell_check_oom(zQarg);
10171        bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
10172                strchr(zName, '[') != 0;
10173        if( strchr(zName, '.') ){
10174          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
10175        }else{
10176          appendText(&sSelect, "lower(tbl_name)", 0);
10177        }
10178        appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
10179        appendText(&sSelect, zQarg, 0);
10180        if( !bGlob ){
10181          appendText(&sSelect, " ESCAPE '\\' ", 0);
10182        }
10183        appendText(&sSelect, " AND ", 0);
10184        sqlite3_free(zQarg);
10185      }
10186      if( bNoSystemTabs ){
10187        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
10188      }
10189      appendText(&sSelect, "sql IS NOT NULL"
10190                           " ORDER BY snum, rowid", 0);
10191      if( bDebug ){
10192        utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
10193      }else{
10194        rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
10195      }
10196      freeText(&sSelect);
10197    }
10198    if( zErrMsg ){
10199      utf8_printf(stderr,"Error: %s\n", zErrMsg);
10200      sqlite3_free(zErrMsg);
10201      rc = 1;
10202    }else if( rc != SQLITE_OK ){
10203      raw_printf(stderr,"Error: querying schema information\n");
10204      rc = 1;
10205    }else{
10206      rc = 0;
10207    }
10208  }else
10209
10210  if( (c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0)
10211   || (c=='t' && n==9  && strncmp(azArg[0], "treetrace", n)==0)
10212  ){
10213    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
10214    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
10215  }else
10216
10217#if defined(SQLITE_ENABLE_SESSION)
10218  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
10219    struct AuxDb *pAuxDb = p->pAuxDb;
10220    OpenSession *pSession = &pAuxDb->aSession[0];
10221    char **azCmd = &azArg[1];
10222    int iSes = 0;
10223    int nCmd = nArg - 1;
10224    int i;
10225    if( nArg<=1 ) goto session_syntax_error;
10226    open_db(p, 0);
10227    if( nArg>=3 ){
10228      for(iSes=0; iSes<pAuxDb->nSession; iSes++){
10229        if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break;
10230      }
10231      if( iSes<pAuxDb->nSession ){
10232        pSession = &pAuxDb->aSession[iSes];
10233        azCmd++;
10234        nCmd--;
10235      }else{
10236        pSession = &pAuxDb->aSession[0];
10237        iSes = 0;
10238      }
10239    }
10240
10241    /* .session attach TABLE
10242    ** Invoke the sqlite3session_attach() interface to attach a particular
10243    ** table so that it is never filtered.
10244    */
10245    if( strcmp(azCmd[0],"attach")==0 ){
10246      if( nCmd!=2 ) goto session_syntax_error;
10247      if( pSession->p==0 ){
10248        session_not_open:
10249        raw_printf(stderr, "ERROR: No sessions are open\n");
10250      }else{
10251        rc = sqlite3session_attach(pSession->p, azCmd[1]);
10252        if( rc ){
10253          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
10254          rc = 0;
10255        }
10256      }
10257    }else
10258
10259    /* .session changeset FILE
10260    ** .session patchset FILE
10261    ** Write a changeset or patchset into a file.  The file is overwritten.
10262    */
10263    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
10264      FILE *out = 0;
10265      failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]);
10266      if( nCmd!=2 ) goto session_syntax_error;
10267      if( pSession->p==0 ) goto session_not_open;
10268      out = fopen(azCmd[1], "wb");
10269      if( out==0 ){
10270        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
10271                    azCmd[1]);
10272      }else{
10273        int szChng;
10274        void *pChng;
10275        if( azCmd[0][0]=='c' ){
10276          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
10277        }else{
10278          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
10279        }
10280        if( rc ){
10281          printf("Error: error code %d\n", rc);
10282          rc = 0;
10283        }
10284        if( pChng
10285          && fwrite(pChng, szChng, 1, out)!=1 ){
10286          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
10287                  szChng);
10288        }
10289        sqlite3_free(pChng);
10290        fclose(out);
10291      }
10292    }else
10293
10294    /* .session close
10295    ** Close the identified session
10296    */
10297    if( strcmp(azCmd[0], "close")==0 ){
10298      if( nCmd!=1 ) goto session_syntax_error;
10299      if( pAuxDb->nSession ){
10300        session_close(pSession);
10301        pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession];
10302      }
10303    }else
10304
10305    /* .session enable ?BOOLEAN?
10306    ** Query or set the enable flag
10307    */
10308    if( strcmp(azCmd[0], "enable")==0 ){
10309      int ii;
10310      if( nCmd>2 ) goto session_syntax_error;
10311      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10312      if( pAuxDb->nSession ){
10313        ii = sqlite3session_enable(pSession->p, ii);
10314        utf8_printf(p->out, "session %s enable flag = %d\n",
10315                    pSession->zName, ii);
10316      }
10317    }else
10318
10319    /* .session filter GLOB ....
10320    ** Set a list of GLOB patterns of table names to be excluded.
10321    */
10322    if( strcmp(azCmd[0], "filter")==0 ){
10323      int ii, nByte;
10324      if( nCmd<2 ) goto session_syntax_error;
10325      if( pAuxDb->nSession ){
10326        for(ii=0; ii<pSession->nFilter; ii++){
10327          sqlite3_free(pSession->azFilter[ii]);
10328        }
10329        sqlite3_free(pSession->azFilter);
10330        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
10331        pSession->azFilter = sqlite3_malloc( nByte );
10332        if( pSession->azFilter==0 ){
10333          raw_printf(stderr, "Error: out or memory\n");
10334          exit(1);
10335        }
10336        for(ii=1; ii<nCmd; ii++){
10337          char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
10338          shell_check_oom(x);
10339        }
10340        pSession->nFilter = ii-1;
10341      }
10342    }else
10343
10344    /* .session indirect ?BOOLEAN?
10345    ** Query or set the indirect flag
10346    */
10347    if( strcmp(azCmd[0], "indirect")==0 ){
10348      int ii;
10349      if( nCmd>2 ) goto session_syntax_error;
10350      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
10351      if( pAuxDb->nSession ){
10352        ii = sqlite3session_indirect(pSession->p, ii);
10353        utf8_printf(p->out, "session %s indirect flag = %d\n",
10354                    pSession->zName, ii);
10355      }
10356    }else
10357
10358    /* .session isempty
10359    ** Determine if the session is empty
10360    */
10361    if( strcmp(azCmd[0], "isempty")==0 ){
10362      int ii;
10363      if( nCmd!=1 ) goto session_syntax_error;
10364      if( pAuxDb->nSession ){
10365        ii = sqlite3session_isempty(pSession->p);
10366        utf8_printf(p->out, "session %s isempty flag = %d\n",
10367                    pSession->zName, ii);
10368      }
10369    }else
10370
10371    /* .session list
10372    ** List all currently open sessions
10373    */
10374    if( strcmp(azCmd[0],"list")==0 ){
10375      for(i=0; i<pAuxDb->nSession; i++){
10376        utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName);
10377      }
10378    }else
10379
10380    /* .session open DB NAME
10381    ** Open a new session called NAME on the attached database DB.
10382    ** DB is normally "main".
10383    */
10384    if( strcmp(azCmd[0],"open")==0 ){
10385      char *zName;
10386      if( nCmd!=3 ) goto session_syntax_error;
10387      zName = azCmd[2];
10388      if( zName[0]==0 ) goto session_syntax_error;
10389      for(i=0; i<pAuxDb->nSession; i++){
10390        if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){
10391          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
10392          goto meta_command_exit;
10393        }
10394      }
10395      if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){
10396        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession));
10397        goto meta_command_exit;
10398      }
10399      pSession = &pAuxDb->aSession[pAuxDb->nSession];
10400      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
10401      if( rc ){
10402        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
10403        rc = 0;
10404        goto meta_command_exit;
10405      }
10406      pSession->nFilter = 0;
10407      sqlite3session_table_filter(pSession->p, session_filter, pSession);
10408      pAuxDb->nSession++;
10409      pSession->zName = sqlite3_mprintf("%s", zName);
10410      shell_check_oom(pSession->zName);
10411    }else
10412    /* If no command name matches, show a syntax error */
10413    session_syntax_error:
10414    showHelp(p->out, "session");
10415  }else
10416#endif
10417
10418#ifdef SQLITE_DEBUG
10419  /* Undocumented commands for internal testing.  Subject to change
10420  ** without notice. */
10421  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
10422    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
10423      int i, v;
10424      for(i=1; i<nArg; i++){
10425        v = booleanValue(azArg[i]);
10426        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
10427      }
10428    }
10429    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
10430      int i; sqlite3_int64 v;
10431      for(i=1; i<nArg; i++){
10432        char zBuf[200];
10433        v = integerValue(azArg[i]);
10434        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
10435        utf8_printf(p->out, "%s", zBuf);
10436      }
10437    }
10438  }else
10439#endif
10440
10441  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
10442    int bIsInit = 0;         /* True to initialize the SELFTEST table */
10443    int bVerbose = 0;        /* Verbose output */
10444    int bSelftestExists;     /* True if SELFTEST already exists */
10445    int i, k;                /* Loop counters */
10446    int nTest = 0;           /* Number of tests runs */
10447    int nErr = 0;            /* Number of errors seen */
10448    ShellText str;           /* Answer for a query */
10449    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
10450
10451    open_db(p,0);
10452    for(i=1; i<nArg; i++){
10453      const char *z = azArg[i];
10454      if( z[0]=='-' && z[1]=='-' ) z++;
10455      if( strcmp(z,"-init")==0 ){
10456        bIsInit = 1;
10457      }else
10458      if( strcmp(z,"-v")==0 ){
10459        bVerbose++;
10460      }else
10461      {
10462        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10463                    azArg[i], azArg[0]);
10464        raw_printf(stderr, "Should be one of: --init -v\n");
10465        rc = 1;
10466        goto meta_command_exit;
10467      }
10468    }
10469    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
10470           != SQLITE_OK ){
10471      bSelftestExists = 0;
10472    }else{
10473      bSelftestExists = 1;
10474    }
10475    if( bIsInit ){
10476      createSelftestTable(p);
10477      bSelftestExists = 1;
10478    }
10479    initText(&str);
10480    appendText(&str, "x", 0);
10481    for(k=bSelftestExists; k>=0; k--){
10482      if( k==1 ){
10483        rc = sqlite3_prepare_v2(p->db,
10484            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
10485            -1, &pStmt, 0);
10486      }else{
10487        rc = sqlite3_prepare_v2(p->db,
10488          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
10489          "      (1,'run','PRAGMA integrity_check','ok')",
10490          -1, &pStmt, 0);
10491      }
10492      if( rc ){
10493        raw_printf(stderr, "Error querying the selftest table\n");
10494        rc = 1;
10495        sqlite3_finalize(pStmt);
10496        goto meta_command_exit;
10497      }
10498      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
10499        int tno = sqlite3_column_int(pStmt, 0);
10500        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
10501        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
10502        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
10503
10504        if( zOp==0 ) continue;
10505        if( zSql==0 ) continue;
10506        if( zAns==0 ) continue;
10507        k = 0;
10508        if( bVerbose>0 ){
10509          printf("%d: %s %s\n", tno, zOp, zSql);
10510        }
10511        if( strcmp(zOp,"memo")==0 ){
10512          utf8_printf(p->out, "%s\n", zSql);
10513        }else
10514        if( strcmp(zOp,"run")==0 ){
10515          char *zErrMsg = 0;
10516          str.n = 0;
10517          str.z[0] = 0;
10518          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
10519          nTest++;
10520          if( bVerbose ){
10521            utf8_printf(p->out, "Result: %s\n", str.z);
10522          }
10523          if( rc || zErrMsg ){
10524            nErr++;
10525            rc = 1;
10526            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
10527            sqlite3_free(zErrMsg);
10528          }else if( strcmp(zAns,str.z)!=0 ){
10529            nErr++;
10530            rc = 1;
10531            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
10532            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
10533          }
10534        }else
10535        {
10536          utf8_printf(stderr,
10537            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
10538          rc = 1;
10539          break;
10540        }
10541      } /* End loop over rows of content from SELFTEST */
10542      sqlite3_finalize(pStmt);
10543    } /* End loop over k */
10544    freeText(&str);
10545    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
10546  }else
10547
10548  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
10549    if( nArg<2 || nArg>3 ){
10550      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
10551      rc = 1;
10552    }
10553    if( nArg>=2 ){
10554      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
10555                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
10556    }
10557    if( nArg>=3 ){
10558      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
10559                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
10560    }
10561  }else
10562
10563  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
10564    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
10565    int i;                   /* Loop counter */
10566    int bSchema = 0;         /* Also hash the schema */
10567    int bSeparate = 0;       /* Hash each table separately */
10568    int iSize = 224;         /* Hash algorithm to use */
10569    int bDebug = 0;          /* Only show the query that would have run */
10570    sqlite3_stmt *pStmt;     /* For querying tables names */
10571    char *zSql;              /* SQL to be run */
10572    char *zSep;              /* Separator */
10573    ShellText sSql;          /* Complete SQL for the query to run the hash */
10574    ShellText sQuery;        /* Set of queries used to read all content */
10575    open_db(p, 0);
10576    for(i=1; i<nArg; i++){
10577      const char *z = azArg[i];
10578      if( z[0]=='-' ){
10579        z++;
10580        if( z[0]=='-' ) z++;
10581        if( strcmp(z,"schema")==0 ){
10582          bSchema = 1;
10583        }else
10584        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
10585         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
10586        ){
10587          iSize = atoi(&z[5]);
10588        }else
10589        if( strcmp(z,"debug")==0 ){
10590          bDebug = 1;
10591        }else
10592        {
10593          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
10594                      azArg[i], azArg[0]);
10595          showHelp(p->out, azArg[0]);
10596          rc = 1;
10597          goto meta_command_exit;
10598        }
10599      }else if( zLike ){
10600        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
10601        rc = 1;
10602        goto meta_command_exit;
10603      }else{
10604        zLike = z;
10605        bSeparate = 1;
10606        if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
10607      }
10608    }
10609    if( bSchema ){
10610      zSql = "SELECT lower(name) FROM sqlite_schema"
10611             " WHERE type='table' AND coalesce(rootpage,0)>1"
10612             " UNION ALL SELECT 'sqlite_schema'"
10613             " ORDER BY 1 collate nocase";
10614    }else{
10615      zSql = "SELECT lower(name) FROM sqlite_schema"
10616             " WHERE type='table' AND coalesce(rootpage,0)>1"
10617             " AND name NOT LIKE 'sqlite_%'"
10618             " ORDER BY 1 collate nocase";
10619    }
10620    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10621    initText(&sQuery);
10622    initText(&sSql);
10623    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
10624    zSep = "VALUES(";
10625    while( SQLITE_ROW==sqlite3_step(pStmt) ){
10626      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
10627      if( zTab==0 ) continue;
10628      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
10629      if( strncmp(zTab, "sqlite_",7)!=0 ){
10630        appendText(&sQuery,"SELECT * FROM ", 0);
10631        appendText(&sQuery,zTab,'"');
10632        appendText(&sQuery," NOT INDEXED;", 0);
10633      }else if( strcmp(zTab, "sqlite_schema")==0 ){
10634        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
10635                           " ORDER BY name;", 0);
10636      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
10637        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
10638                           " ORDER BY name;", 0);
10639      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
10640        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
10641                           " ORDER BY tbl,idx;", 0);
10642      }else if( strcmp(zTab, "sqlite_stat4")==0 ){
10643        appendText(&sQuery, "SELECT * FROM ", 0);
10644        appendText(&sQuery, zTab, 0);
10645        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
10646      }
10647      appendText(&sSql, zSep, 0);
10648      appendText(&sSql, sQuery.z, '\'');
10649      sQuery.n = 0;
10650      appendText(&sSql, ",", 0);
10651      appendText(&sSql, zTab, '\'');
10652      zSep = "),(";
10653    }
10654    sqlite3_finalize(pStmt);
10655    if( bSeparate ){
10656      zSql = sqlite3_mprintf(
10657          "%s))"
10658          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
10659          "   FROM [sha3sum$query]",
10660          sSql.z, iSize);
10661    }else{
10662      zSql = sqlite3_mprintf(
10663          "%s))"
10664          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
10665          "   FROM [sha3sum$query]",
10666          sSql.z, iSize);
10667    }
10668    shell_check_oom(zSql);
10669    freeText(&sQuery);
10670    freeText(&sSql);
10671    if( bDebug ){
10672      utf8_printf(p->out, "%s\n", zSql);
10673    }else{
10674      shell_exec(p, zSql, 0);
10675    }
10676    sqlite3_free(zSql);
10677  }else
10678
10679#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
10680  if( c=='s'
10681   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
10682  ){
10683    char *zCmd;
10684    int i, x;
10685    failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]);
10686    if( nArg<2 ){
10687      raw_printf(stderr, "Usage: .system COMMAND\n");
10688      rc = 1;
10689      goto meta_command_exit;
10690    }
10691    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
10692    for(i=2; i<nArg && zCmd!=0; i++){
10693      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
10694                             zCmd, azArg[i]);
10695    }
10696    x = zCmd!=0 ? system(zCmd) : 1;
10697    sqlite3_free(zCmd);
10698    if( x ) raw_printf(stderr, "System command returns %d\n", x);
10699  }else
10700#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */
10701
10702  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
10703    static const char *azBool[] = { "off", "on", "trigger", "full"};
10704    const char *zOut;
10705    int i;
10706    if( nArg!=1 ){
10707      raw_printf(stderr, "Usage: .show\n");
10708      rc = 1;
10709      goto meta_command_exit;
10710    }
10711    utf8_printf(p->out, "%12.12s: %s\n","echo",
10712                azBool[ShellHasFlag(p, SHFLG_Echo)]);
10713    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
10714    utf8_printf(p->out, "%12.12s: %s\n","explain",
10715         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
10716    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
10717    if( p->mode==MODE_Column
10718     || (p->mode>=MODE_Markdown && p->mode<=MODE_Box)
10719    ){
10720      utf8_printf
10721        (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode",
10722         modeDescr[p->mode], p->cmOpts.iWrap,
10723         p->cmOpts.bWordWrap ? "on" : "off",
10724         p->cmOpts.bQuote ? "" : "no");
10725    }else{
10726      utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
10727    }
10728    utf8_printf(p->out, "%12.12s: ", "nullvalue");
10729      output_c_string(p->out, p->nullValue);
10730      raw_printf(p->out, "\n");
10731    utf8_printf(p->out,"%12.12s: %s\n","output",
10732            strlen30(p->outfile) ? p->outfile : "stdout");
10733    utf8_printf(p->out,"%12.12s: ", "colseparator");
10734      output_c_string(p->out, p->colSeparator);
10735      raw_printf(p->out, "\n");
10736    utf8_printf(p->out,"%12.12s: ", "rowseparator");
10737      output_c_string(p->out, p->rowSeparator);
10738      raw_printf(p->out, "\n");
10739    switch( p->statsOn ){
10740      case 0:  zOut = "off";     break;
10741      default: zOut = "on";      break;
10742      case 2:  zOut = "stmt";    break;
10743      case 3:  zOut = "vmstep";  break;
10744    }
10745    utf8_printf(p->out, "%12.12s: %s\n","stats", zOut);
10746    utf8_printf(p->out, "%12.12s: ", "width");
10747    for (i=0;i<p->nWidth;i++) {
10748      raw_printf(p->out, "%d ", p->colWidth[i]);
10749    }
10750    raw_printf(p->out, "\n");
10751    utf8_printf(p->out, "%12.12s: %s\n", "filename",
10752                p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : "");
10753  }else
10754
10755  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
10756    if( nArg==2 ){
10757      if( strcmp(azArg[1],"stmt")==0 ){
10758        p->statsOn = 2;
10759      }else if( strcmp(azArg[1],"vmstep")==0 ){
10760        p->statsOn = 3;
10761      }else{
10762        p->statsOn = (u8)booleanValue(azArg[1]);
10763      }
10764    }else if( nArg==1 ){
10765      display_stats(p->db, p, 0);
10766    }else{
10767      raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n");
10768      rc = 1;
10769    }
10770  }else
10771
10772  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
10773   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
10774                 || strncmp(azArg[0], "indexes", n)==0) )
10775  ){
10776    sqlite3_stmt *pStmt;
10777    char **azResult;
10778    int nRow, nAlloc;
10779    int ii;
10780    ShellText s;
10781    initText(&s);
10782    open_db(p, 0);
10783    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
10784    if( rc ){
10785      sqlite3_finalize(pStmt);
10786      return shellDatabaseError(p->db);
10787    }
10788
10789    if( nArg>2 && c=='i' ){
10790      /* It is an historical accident that the .indexes command shows an error
10791      ** when called with the wrong number of arguments whereas the .tables
10792      ** command does not. */
10793      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
10794      rc = 1;
10795      sqlite3_finalize(pStmt);
10796      goto meta_command_exit;
10797    }
10798    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
10799      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
10800      if( zDbName==0 ) continue;
10801      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
10802      if( sqlite3_stricmp(zDbName, "main")==0 ){
10803        appendText(&s, "SELECT name FROM ", 0);
10804      }else{
10805        appendText(&s, "SELECT ", 0);
10806        appendText(&s, zDbName, '\'');
10807        appendText(&s, "||'.'||name FROM ", 0);
10808      }
10809      appendText(&s, zDbName, '"');
10810      appendText(&s, ".sqlite_schema ", 0);
10811      if( c=='t' ){
10812        appendText(&s," WHERE type IN ('table','view')"
10813                      "   AND name NOT LIKE 'sqlite_%'"
10814                      "   AND name LIKE ?1", 0);
10815      }else{
10816        appendText(&s," WHERE type='index'"
10817                      "   AND tbl_name LIKE ?1", 0);
10818      }
10819    }
10820    rc = sqlite3_finalize(pStmt);
10821    if( rc==SQLITE_OK ){
10822      appendText(&s, " ORDER BY 1", 0);
10823      rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
10824    }
10825    freeText(&s);
10826    if( rc ) return shellDatabaseError(p->db);
10827
10828    /* Run the SQL statement prepared by the above block. Store the results
10829    ** as an array of nul-terminated strings in azResult[].  */
10830    nRow = nAlloc = 0;
10831    azResult = 0;
10832    if( nArg>1 ){
10833      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
10834    }else{
10835      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
10836    }
10837    while( sqlite3_step(pStmt)==SQLITE_ROW ){
10838      if( nRow>=nAlloc ){
10839        char **azNew;
10840        int n2 = nAlloc*2 + 10;
10841        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
10842        shell_check_oom(azNew);
10843        nAlloc = n2;
10844        azResult = azNew;
10845      }
10846      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
10847      shell_check_oom(azResult[nRow]);
10848      nRow++;
10849    }
10850    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
10851      rc = shellDatabaseError(p->db);
10852    }
10853
10854    /* Pretty-print the contents of array azResult[] to the output */
10855    if( rc==0 && nRow>0 ){
10856      int len, maxlen = 0;
10857      int i, j;
10858      int nPrintCol, nPrintRow;
10859      for(i=0; i<nRow; i++){
10860        len = strlen30(azResult[i]);
10861        if( len>maxlen ) maxlen = len;
10862      }
10863      nPrintCol = 80/(maxlen+2);
10864      if( nPrintCol<1 ) nPrintCol = 1;
10865      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
10866      for(i=0; i<nPrintRow; i++){
10867        for(j=i; j<nRow; j+=nPrintRow){
10868          char *zSp = j<nPrintRow ? "" : "  ";
10869          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
10870                      azResult[j] ? azResult[j]:"");
10871        }
10872        raw_printf(p->out, "\n");
10873      }
10874    }
10875
10876    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
10877    sqlite3_free(azResult);
10878  }else
10879
10880#ifndef SQLITE_SHELL_FIDDLE
10881  /* Begin redirecting output to the file "testcase-out.txt" */
10882  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
10883    output_reset(p);
10884    p->out = output_file_open("testcase-out.txt", 0);
10885    if( p->out==0 ){
10886      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
10887    }
10888    if( nArg>=2 ){
10889      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
10890    }else{
10891      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
10892    }
10893  }else
10894#endif /* !defined(SQLITE_SHELL_FIDDLE) */
10895
10896#ifndef SQLITE_UNTESTABLE
10897  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
10898    static const struct {
10899       const char *zCtrlName;   /* Name of a test-control option */
10900       int ctrlCode;            /* Integer code for that option */
10901       int unSafe;              /* Not valid for --safe mode */
10902       const char *zUsage;      /* Usage notes */
10903    } aCtrl[] = {
10904      { "always",             SQLITE_TESTCTRL_ALWAYS, 1,     "BOOLEAN"         },
10905      { "assert",             SQLITE_TESTCTRL_ASSERT, 1,     "BOOLEAN"         },
10906    /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, ""        },*/
10907    /*{ "bitvec_test",        SQLITE_TESTCTRL_BITVEC_TEST, 1,  ""              },*/
10908      { "byteorder",          SQLITE_TESTCTRL_BYTEORDER, 0,  ""                },
10909      { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN"  },
10910    /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, 1,""              },*/
10911      { "imposter",         SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
10912      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,""          },
10913      { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN"      },
10914      { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN"       },
10915      { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK"   },
10916#ifdef YYCOVERAGE
10917      { "parser_coverage",    SQLITE_TESTCTRL_PARSER_COVERAGE,0,""             },
10918#endif
10919      { "pending_byte",       SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET  "       },
10920      { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,0, ""               },
10921      { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,   0, ""               },
10922      { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,   0, "SEED ?db?"      },
10923      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,  0, ""               },
10924      { "sorter_mmap",        SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX"           },
10925      { "tune",               SQLITE_TESTCTRL_TUNE,        1, "ID VALUE"       },
10926    };
10927    int testctrl = -1;
10928    int iCtrl = -1;
10929    int rc2 = 0;    /* 0: usage.  1: %d  2: %x  3: no-output */
10930    int isOk = 0;
10931    int i, n2;
10932    const char *zCmd = 0;
10933
10934    open_db(p, 0);
10935    zCmd = nArg>=2 ? azArg[1] : "help";
10936
10937    /* The argument can optionally begin with "-" or "--" */
10938    if( zCmd[0]=='-' && zCmd[1] ){
10939      zCmd++;
10940      if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
10941    }
10942
10943    /* --help lists all test-controls */
10944    if( strcmp(zCmd,"help")==0 ){
10945      utf8_printf(p->out, "Available test-controls:\n");
10946      for(i=0; i<ArraySize(aCtrl); i++){
10947        utf8_printf(p->out, "  .testctrl %s %s\n",
10948                    aCtrl[i].zCtrlName, aCtrl[i].zUsage);
10949      }
10950      rc = 1;
10951      goto meta_command_exit;
10952    }
10953
10954    /* convert testctrl text option to value. allow any unique prefix
10955    ** of the option name, or a numerical value. */
10956    n2 = strlen30(zCmd);
10957    for(i=0; i<ArraySize(aCtrl); i++){
10958      if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
10959        if( testctrl<0 ){
10960          testctrl = aCtrl[i].ctrlCode;
10961          iCtrl = i;
10962        }else{
10963          utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
10964                              "Use \".testctrl --help\" for help\n", zCmd);
10965          rc = 1;
10966          goto meta_command_exit;
10967        }
10968      }
10969    }
10970    if( testctrl<0 ){
10971      utf8_printf(stderr,"Error: unknown test-control: %s\n"
10972                         "Use \".testctrl --help\" for help\n", zCmd);
10973    }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){
10974      utf8_printf(stderr,
10975         "line %d: \".testctrl %s\" may not be used in safe mode\n",
10976         p->lineno, aCtrl[iCtrl].zCtrlName);
10977      exit(1);
10978    }else{
10979      switch(testctrl){
10980
10981        /* sqlite3_test_control(int, db, int) */
10982        case SQLITE_TESTCTRL_OPTIMIZATIONS:
10983          if( nArg==3 ){
10984            unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0);
10985            rc2 = sqlite3_test_control(testctrl, p->db, opt);
10986            isOk = 3;
10987          }
10988          break;
10989
10990        /* sqlite3_test_control(int) */
10991        case SQLITE_TESTCTRL_PRNG_SAVE:
10992        case SQLITE_TESTCTRL_PRNG_RESTORE:
10993        case SQLITE_TESTCTRL_BYTEORDER:
10994          if( nArg==2 ){
10995            rc2 = sqlite3_test_control(testctrl);
10996            isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
10997          }
10998          break;
10999
11000        /* sqlite3_test_control(int, uint) */
11001        case SQLITE_TESTCTRL_PENDING_BYTE:
11002          if( nArg==3 ){
11003            unsigned int opt = (unsigned int)integerValue(azArg[2]);
11004            rc2 = sqlite3_test_control(testctrl, opt);
11005            isOk = 3;
11006          }
11007          break;
11008
11009        /* sqlite3_test_control(int, int, sqlite3*) */
11010        case SQLITE_TESTCTRL_PRNG_SEED:
11011          if( nArg==3 || nArg==4 ){
11012            int ii = (int)integerValue(azArg[2]);
11013            sqlite3 *db;
11014            if( ii==0 && strcmp(azArg[2],"random")==0 ){
11015              sqlite3_randomness(sizeof(ii),&ii);
11016              printf("-- random seed: %d\n", ii);
11017            }
11018            if( nArg==3 ){
11019              db = 0;
11020            }else{
11021              db = p->db;
11022              /* Make sure the schema has been loaded */
11023              sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
11024            }
11025            rc2 = sqlite3_test_control(testctrl, ii, db);
11026            isOk = 3;
11027          }
11028          break;
11029
11030        /* sqlite3_test_control(int, int) */
11031        case SQLITE_TESTCTRL_ASSERT:
11032        case SQLITE_TESTCTRL_ALWAYS:
11033          if( nArg==3 ){
11034            int opt = booleanValue(azArg[2]);
11035            rc2 = sqlite3_test_control(testctrl, opt);
11036            isOk = 1;
11037          }
11038          break;
11039
11040        /* sqlite3_test_control(int, int) */
11041        case SQLITE_TESTCTRL_LOCALTIME_FAULT:
11042        case SQLITE_TESTCTRL_NEVER_CORRUPT:
11043          if( nArg==3 ){
11044            int opt = booleanValue(azArg[2]);
11045            rc2 = sqlite3_test_control(testctrl, opt);
11046            isOk = 3;
11047          }
11048          break;
11049
11050        /* sqlite3_test_control(sqlite3*) */
11051        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
11052          rc2 = sqlite3_test_control(testctrl, p->db);
11053          isOk = 3;
11054          break;
11055
11056        case SQLITE_TESTCTRL_IMPOSTER:
11057          if( nArg==5 ){
11058            rc2 = sqlite3_test_control(testctrl, p->db,
11059                          azArg[2],
11060                          integerValue(azArg[3]),
11061                          integerValue(azArg[4]));
11062            isOk = 3;
11063          }
11064          break;
11065
11066        case SQLITE_TESTCTRL_SEEK_COUNT: {
11067          u64 x = 0;
11068          rc2 = sqlite3_test_control(testctrl, p->db, &x);
11069          utf8_printf(p->out, "%llu\n", x);
11070          isOk = 3;
11071          break;
11072        }
11073
11074#ifdef YYCOVERAGE
11075        case SQLITE_TESTCTRL_PARSER_COVERAGE: {
11076          if( nArg==2 ){
11077            sqlite3_test_control(testctrl, p->out);
11078            isOk = 3;
11079          }
11080          break;
11081        }
11082#endif
11083#ifdef SQLITE_DEBUG
11084        case SQLITE_TESTCTRL_TUNE: {
11085          if( nArg==4 ){
11086            int id = (int)integerValue(azArg[2]);
11087            int val = (int)integerValue(azArg[3]);
11088            sqlite3_test_control(testctrl, id, &val);
11089            isOk = 3;
11090          }else if( nArg==3 ){
11091            int id = (int)integerValue(azArg[2]);
11092            sqlite3_test_control(testctrl, -id, &rc2);
11093            isOk = 1;
11094          }else if( nArg==2 ){
11095            int id = 1;
11096            while(1){
11097              int val = 0;
11098              rc2 = sqlite3_test_control(testctrl, -id, &val);
11099              if( rc2!=SQLITE_OK ) break;
11100              if( id>1 ) utf8_printf(p->out, "  ");
11101              utf8_printf(p->out, "%d: %d", id, val);
11102              id++;
11103            }
11104            if( id>1 ) utf8_printf(p->out, "\n");
11105            isOk = 3;
11106          }
11107          break;
11108        }
11109#endif
11110        case SQLITE_TESTCTRL_SORTER_MMAP:
11111          if( nArg==3 ){
11112            int opt = (unsigned int)integerValue(azArg[2]);
11113            rc2 = sqlite3_test_control(testctrl, p->db, opt);
11114            isOk = 3;
11115          }
11116          break;
11117      }
11118    }
11119    if( isOk==0 && iCtrl>=0 ){
11120      utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
11121      rc = 1;
11122    }else if( isOk==1 ){
11123      raw_printf(p->out, "%d\n", rc2);
11124    }else if( isOk==2 ){
11125      raw_printf(p->out, "0x%08x\n", rc2);
11126    }
11127  }else
11128#endif /* !defined(SQLITE_UNTESTABLE) */
11129
11130  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
11131    open_db(p, 0);
11132    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
11133  }else
11134
11135  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
11136    if( nArg==2 ){
11137      enableTimer = booleanValue(azArg[1]);
11138      if( enableTimer && !HAS_TIMER ){
11139        raw_printf(stderr, "Error: timer not available on this system.\n");
11140        enableTimer = 0;
11141      }
11142    }else{
11143      raw_printf(stderr, "Usage: .timer on|off\n");
11144      rc = 1;
11145    }
11146  }else
11147
11148#ifndef SQLITE_OMIT_TRACE
11149  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
11150    int mType = 0;
11151    int jj;
11152    open_db(p, 0);
11153    for(jj=1; jj<nArg; jj++){
11154      const char *z = azArg[jj];
11155      if( z[0]=='-' ){
11156        if( optionMatch(z, "expanded") ){
11157          p->eTraceType = SHELL_TRACE_EXPANDED;
11158        }
11159#ifdef SQLITE_ENABLE_NORMALIZE
11160        else if( optionMatch(z, "normalized") ){
11161          p->eTraceType = SHELL_TRACE_NORMALIZED;
11162        }
11163#endif
11164        else if( optionMatch(z, "plain") ){
11165          p->eTraceType = SHELL_TRACE_PLAIN;
11166        }
11167        else if( optionMatch(z, "profile") ){
11168          mType |= SQLITE_TRACE_PROFILE;
11169        }
11170        else if( optionMatch(z, "row") ){
11171          mType |= SQLITE_TRACE_ROW;
11172        }
11173        else if( optionMatch(z, "stmt") ){
11174          mType |= SQLITE_TRACE_STMT;
11175        }
11176        else if( optionMatch(z, "close") ){
11177          mType |= SQLITE_TRACE_CLOSE;
11178        }
11179        else {
11180          raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
11181          rc = 1;
11182          goto meta_command_exit;
11183        }
11184      }else{
11185        output_file_close(p->traceOut);
11186        p->traceOut = output_file_open(azArg[1], 0);
11187      }
11188    }
11189    if( p->traceOut==0 ){
11190      sqlite3_trace_v2(p->db, 0, 0, 0);
11191    }else{
11192      if( mType==0 ) mType = SQLITE_TRACE_STMT;
11193      sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
11194    }
11195  }else
11196#endif /* !defined(SQLITE_OMIT_TRACE) */
11197
11198#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11199  if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
11200    int ii;
11201    int lenOpt;
11202    char *zOpt;
11203    if( nArg<2 ){
11204      raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
11205      rc = 1;
11206      goto meta_command_exit;
11207    }
11208    open_db(p, 0);
11209    zOpt = azArg[1];
11210    if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
11211    lenOpt = (int)strlen(zOpt);
11212    if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
11213      assert( azArg[nArg]==0 );
11214      sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
11215    }else{
11216      for(ii=1; ii<nArg; ii++){
11217        sqlite3_create_module(p->db, azArg[ii], 0, 0);
11218      }
11219    }
11220  }else
11221#endif
11222
11223#if SQLITE_USER_AUTHENTICATION
11224  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
11225    if( nArg<2 ){
11226      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
11227      rc = 1;
11228      goto meta_command_exit;
11229    }
11230    open_db(p, 0);
11231    if( strcmp(azArg[1],"login")==0 ){
11232      if( nArg!=4 ){
11233        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
11234        rc = 1;
11235        goto meta_command_exit;
11236      }
11237      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
11238                                     strlen30(azArg[3]));
11239      if( rc ){
11240        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
11241        rc = 1;
11242      }
11243    }else if( strcmp(azArg[1],"add")==0 ){
11244      if( nArg!=5 ){
11245        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
11246        rc = 1;
11247        goto meta_command_exit;
11248      }
11249      rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11250                            booleanValue(azArg[4]));
11251      if( rc ){
11252        raw_printf(stderr, "User-Add failed: %d\n", rc);
11253        rc = 1;
11254      }
11255    }else if( strcmp(azArg[1],"edit")==0 ){
11256      if( nArg!=5 ){
11257        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
11258        rc = 1;
11259        goto meta_command_exit;
11260      }
11261      rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
11262                              booleanValue(azArg[4]));
11263      if( rc ){
11264        raw_printf(stderr, "User-Edit failed: %d\n", rc);
11265        rc = 1;
11266      }
11267    }else if( strcmp(azArg[1],"delete")==0 ){
11268      if( nArg!=3 ){
11269        raw_printf(stderr, "Usage: .user delete USER\n");
11270        rc = 1;
11271        goto meta_command_exit;
11272      }
11273      rc = sqlite3_user_delete(p->db, azArg[2]);
11274      if( rc ){
11275        raw_printf(stderr, "User-Delete failed: %d\n", rc);
11276        rc = 1;
11277      }
11278    }else{
11279      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
11280      rc = 1;
11281      goto meta_command_exit;
11282    }
11283  }else
11284#endif /* SQLITE_USER_AUTHENTICATION */
11285
11286  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
11287    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
11288        sqlite3_libversion(), sqlite3_sourceid());
11289#if SQLITE_HAVE_ZLIB
11290    utf8_printf(p->out, "zlib version %s\n", zlibVersion());
11291#endif
11292#define CTIMEOPT_VAL_(opt) #opt
11293#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11294#if defined(__clang__) && defined(__clang_major__)
11295    utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
11296                    CTIMEOPT_VAL(__clang_minor__) "."
11297                    CTIMEOPT_VAL(__clang_patchlevel__) "\n");
11298#elif defined(_MSC_VER)
11299    utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
11300#elif defined(__GNUC__) && defined(__VERSION__)
11301    utf8_printf(p->out, "gcc-" __VERSION__ "\n");
11302#endif
11303  }else
11304
11305  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
11306    const char *zDbName = nArg==2 ? azArg[1] : "main";
11307    sqlite3_vfs *pVfs = 0;
11308    if( p->db ){
11309      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
11310      if( pVfs ){
11311        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
11312        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11313        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11314        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11315      }
11316    }
11317  }else
11318
11319  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
11320    sqlite3_vfs *pVfs;
11321    sqlite3_vfs *pCurrent = 0;
11322    if( p->db ){
11323      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
11324    }
11325    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
11326      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
11327           pVfs==pCurrent ? "  <--- CURRENT" : "");
11328      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
11329      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
11330      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
11331      if( pVfs->pNext ){
11332        raw_printf(p->out, "-----------------------------------\n");
11333      }
11334    }
11335  }else
11336
11337  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
11338    const char *zDbName = nArg==2 ? azArg[1] : "main";
11339    char *zVfsName = 0;
11340    if( p->db ){
11341      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
11342      if( zVfsName ){
11343        utf8_printf(p->out, "%s\n", zVfsName);
11344        sqlite3_free(zVfsName);
11345      }
11346    }
11347  }else
11348
11349  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
11350    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
11351    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
11352  }else
11353
11354  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
11355    int j;
11356    assert( nArg<=ArraySize(azArg) );
11357    p->nWidth = nArg-1;
11358    p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2);
11359    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
11360    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
11361    for(j=1; j<nArg; j++){
11362      p->colWidth[j-1] = (int)integerValue(azArg[j]);
11363    }
11364  }else
11365
11366  {
11367    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
11368      " \"%s\". Enter \".help\" for help\n", azArg[0]);
11369    rc = 1;
11370  }
11371
11372meta_command_exit:
11373  if( p->outCount ){
11374    p->outCount--;
11375    if( p->outCount==0 ) output_reset(p);
11376  }
11377  p->bSafeMode = p->bSafeModePersist;
11378  return rc;
11379}
11380
11381/* Line scan result and intermediate states (supporting scan resumption)
11382*/
11383#ifndef CHAR_BIT
11384# define CHAR_BIT 8
11385#endif
11386typedef enum {
11387  QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT,
11388  QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT,
11389  QSS_Start = 0
11390} QuickScanState;
11391#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask))
11392#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start)
11393#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start)
11394#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark)
11395#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi)
11396
11397/*
11398** Scan line for classification to guide shell's handling.
11399** The scan is resumable for subsequent lines when prior
11400** return values are passed as the 2nd argument.
11401*/
11402static QuickScanState quickscan(char *zLine, QuickScanState qss){
11403  char cin;
11404  char cWait = (char)qss; /* intentional narrowing loss */
11405  if( cWait==0 ){
11406  PlainScan:
11407    assert( cWait==0 );
11408    while( (cin = *zLine++)!=0 ){
11409      if( IsSpace(cin) )
11410        continue;
11411      switch (cin){
11412      case '-':
11413        if( *zLine!='-' )
11414          break;
11415        while((cin = *++zLine)!=0 )
11416          if( cin=='\n')
11417            goto PlainScan;
11418        return qss;
11419      case ';':
11420        qss |= QSS_EndingSemi;
11421        continue;
11422      case '/':
11423        if( *zLine=='*' ){
11424          ++zLine;
11425          cWait = '*';
11426          qss = QSS_SETV(qss, cWait);
11427          goto TermScan;
11428        }
11429        break;
11430      case '[':
11431        cin = ']';
11432        /* fall thru */
11433      case '`': case '\'': case '"':
11434        cWait = cin;
11435        qss = QSS_HasDark | cWait;
11436        goto TermScan;
11437      default:
11438        break;
11439      }
11440      qss = (qss & ~QSS_EndingSemi) | QSS_HasDark;
11441    }
11442  }else{
11443  TermScan:
11444    while( (cin = *zLine++)!=0 ){
11445      if( cin==cWait ){
11446        switch( cWait ){
11447        case '*':
11448          if( *zLine != '/' )
11449            continue;
11450          ++zLine;
11451          cWait = 0;
11452          qss = QSS_SETV(qss, 0);
11453          goto PlainScan;
11454        case '`': case '\'': case '"':
11455          if(*zLine==cWait){
11456            ++zLine;
11457            continue;
11458          }
11459          /* fall thru */
11460        case ']':
11461          cWait = 0;
11462          qss = QSS_SETV(qss, 0);
11463          goto PlainScan;
11464        default: assert(0);
11465        }
11466      }
11467    }
11468  }
11469  return qss;
11470}
11471
11472/*
11473** Return TRUE if the line typed in is an SQL command terminator other
11474** than a semi-colon.  The SQL Server style "go" command is understood
11475** as is the Oracle "/".
11476*/
11477static int line_is_command_terminator(char *zLine){
11478  while( IsSpace(zLine[0]) ){ zLine++; };
11479  if( zLine[0]=='/' )
11480    zLine += 1; /* Oracle */
11481  else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' )
11482    zLine += 2; /* SQL Server */
11483  else
11484    return 0;
11485  return quickscan(zLine, QSS_Start)==QSS_Start;
11486}
11487
11488/*
11489** We need a default sqlite3_complete() implementation to use in case
11490** the shell is compiled with SQLITE_OMIT_COMPLETE.  The default assumes
11491** any arbitrary text is a complete SQL statement.  This is not very
11492** user-friendly, but it does seem to work.
11493*/
11494#ifdef SQLITE_OMIT_COMPLETE
11495#define sqlite3_complete(x) 1
11496#endif
11497
11498/*
11499** Return true if zSql is a complete SQL statement.  Return false if it
11500** ends in the middle of a string literal or C-style comment.
11501*/
11502static int line_is_complete(char *zSql, int nSql){
11503  int rc;
11504  if( zSql==0 ) return 1;
11505  zSql[nSql] = ';';
11506  zSql[nSql+1] = 0;
11507  rc = sqlite3_complete(zSql);
11508  zSql[nSql] = 0;
11509  return rc;
11510}
11511
11512/*
11513** Run a single line of SQL.  Return the number of errors.
11514*/
11515static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
11516  int rc;
11517  char *zErrMsg = 0;
11518
11519  open_db(p, 0);
11520  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
11521  if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
11522  BEGIN_TIMER;
11523  rc = shell_exec(p, zSql, &zErrMsg);
11524  END_TIMER;
11525  if( rc || zErrMsg ){
11526    char zPrefix[100];
11527    const char *zErrorTail;
11528    const char *zErrorType;
11529    if( zErrMsg==0 ){
11530      zErrorType = "Error";
11531      zErrorTail = sqlite3_errmsg(p->db);
11532    }else if( strncmp(zErrMsg, "in prepare, ",12)==0 ){
11533      zErrorType = "Parse error";
11534      zErrorTail = &zErrMsg[12];
11535    }else if( strncmp(zErrMsg, "stepping, ", 10)==0 ){
11536      zErrorType = "Runtime error";
11537      zErrorTail = &zErrMsg[10];
11538    }else{
11539      zErrorType = "Error";
11540      zErrorTail = zErrMsg;
11541    }
11542    if( in!=0 || !stdin_is_interactive ){
11543      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
11544                       "%s near line %d:", zErrorType, startline);
11545    }else{
11546      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType);
11547    }
11548    utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail);
11549    sqlite3_free(zErrMsg);
11550    zErrMsg = 0;
11551    return 1;
11552  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
11553    char zLineBuf[2000];
11554    sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
11555            "changes: %lld   total_changes: %lld",
11556            sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
11557    raw_printf(p->out, "%s\n", zLineBuf);
11558  }
11559  return 0;
11560}
11561
11562static void echo_group_input(ShellState *p, const char *zDo){
11563  if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo);
11564}
11565
11566#ifdef SQLITE_SHELL_FIDDLE
11567/*
11568** Alternate one_input_line() impl for wasm mode. This is not in the primary impl
11569** because we need the global shellState and cannot access it from that function
11570** without moving lots of code around (creating a larger/messier diff).
11571*/
11572static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
11573  /* Parse the next line from shellState.wasm.zInput. */
11574  const char *zBegin = shellState.wasm.zPos;
11575  const char *z = zBegin;
11576  char *zLine = 0;
11577  int nZ = 0;
11578
11579  UNUSED_PARAMETER(in);
11580  UNUSED_PARAMETER(isContinuation);
11581  if(!z || !*z){
11582    return 0;
11583  }
11584  while(*z && isspace(*z)) ++z;
11585  zBegin = z;
11586  for(; *z && '\n'!=*z; ++nZ, ++z){}
11587  if(nZ>0 && '\r'==zBegin[nZ-1]){
11588    --nZ;
11589  }
11590  shellState.wasm.zPos = z;
11591  zLine = realloc(zPrior, nZ+1);
11592  shell_check_oom(zLine);
11593  memcpy(zLine, zBegin, (size_t)nZ);
11594  zLine[nZ] = 0;
11595  return zLine;
11596}
11597#endif /* SQLITE_SHELL_FIDDLE */
11598
11599/*
11600** Read input from *in and process it.  If *in==0 then input
11601** is interactive - the user is typing it it.  Otherwise, input
11602** is coming from a file or device.  A prompt is issued and history
11603** is saved only if input is interactive.  An interrupt signal will
11604** cause this routine to exit immediately, unless input is interactive.
11605**
11606** Return the number of errors.
11607*/
11608static int process_input(ShellState *p){
11609  char *zLine = 0;          /* A single input line */
11610  char *zSql = 0;           /* Accumulated SQL text */
11611  int nLine;                /* Length of current line */
11612  int nSql = 0;             /* Bytes of zSql[] used */
11613  int nAlloc = 0;           /* Allocated zSql[] space */
11614  int rc;                   /* Error code */
11615  int errCnt = 0;           /* Number of errors seen */
11616  int startline = 0;        /* Line number for start of current input */
11617  QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */
11618
11619  if( p->inputNesting==MAX_INPUT_NESTING ){
11620    /* This will be more informative in a later version. */
11621    utf8_printf(stderr,"Input nesting limit (%d) reached at line %d."
11622                " Check recursion.\n", MAX_INPUT_NESTING, p->lineno);
11623    return 1;
11624  }
11625  ++p->inputNesting;
11626  p->lineno = 0;
11627  while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
11628    fflush(p->out);
11629    zLine = one_input_line(p->in, zLine, nSql>0);
11630    if( zLine==0 ){
11631      /* End of input */
11632      if( p->in==0 && stdin_is_interactive ) printf("\n");
11633      break;
11634    }
11635    if( seenInterrupt ){
11636      if( p->in!=0 ) break;
11637      seenInterrupt = 0;
11638    }
11639    p->lineno++;
11640    if( QSS_INPLAIN(qss)
11641        && line_is_command_terminator(zLine)
11642        && line_is_complete(zSql, nSql) ){
11643      memcpy(zLine,";",2);
11644    }
11645    qss = quickscan(zLine, qss);
11646    if( QSS_PLAINWHITE(qss) && nSql==0 ){
11647      /* Just swallow single-line whitespace */
11648      echo_group_input(p, zLine);
11649      qss = QSS_Start;
11650      continue;
11651    }
11652    if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
11653      echo_group_input(p, zLine);
11654      if( zLine[0]=='.' ){
11655        rc = do_meta_command(zLine, p);
11656        if( rc==2 ){ /* exit requested */
11657          break;
11658        }else if( rc ){
11659          errCnt++;
11660        }
11661      }
11662      qss = QSS_Start;
11663      continue;
11664    }
11665    /* No single-line dispositions remain; accumulate line(s). */
11666    nLine = strlen30(zLine);
11667    if( nSql+nLine+2>=nAlloc ){
11668      /* Grow buffer by half-again increments when big. */
11669      nAlloc = nSql+(nSql>>1)+nLine+100;
11670      zSql = realloc(zSql, nAlloc);
11671      shell_check_oom(zSql);
11672    }
11673    if( nSql==0 ){
11674      int i;
11675      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
11676      assert( nAlloc>0 && zSql!=0 );
11677      memcpy(zSql, zLine+i, nLine+1-i);
11678      startline = p->lineno;
11679      nSql = nLine-i;
11680    }else{
11681      zSql[nSql++] = '\n';
11682      memcpy(zSql+nSql, zLine, nLine+1);
11683      nSql += nLine;
11684    }
11685    if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){
11686      echo_group_input(p, zSql);
11687      errCnt += runOneSqlLine(p, zSql, p->in, startline);
11688      nSql = 0;
11689      if( p->outCount ){
11690        output_reset(p);
11691        p->outCount = 0;
11692      }else{
11693        clearTempFile(p);
11694      }
11695      p->bSafeMode = p->bSafeModePersist;
11696      qss = QSS_Start;
11697    }else if( nSql && QSS_PLAINWHITE(qss) ){
11698      echo_group_input(p, zSql);
11699      nSql = 0;
11700      qss = QSS_Start;
11701    }
11702  }
11703  if( nSql ){
11704    /* This may be incomplete. Let the SQL parser deal with that. */
11705    echo_group_input(p, zSql);
11706    errCnt += runOneSqlLine(p, zSql, p->in, startline);
11707  }
11708  free(zSql);
11709  free(zLine);
11710  --p->inputNesting;
11711  return errCnt>0;
11712}
11713
11714/*
11715** Return a pathname which is the user's home directory.  A
11716** 0 return indicates an error of some kind.
11717*/
11718static char *find_home_dir(int clearFlag){
11719  static char *home_dir = NULL;
11720  if( clearFlag ){
11721    free(home_dir);
11722    home_dir = 0;
11723    return 0;
11724  }
11725  if( home_dir ) return home_dir;
11726
11727#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
11728     && !defined(__RTP__) && !defined(_WRS_KERNEL)
11729  {
11730    struct passwd *pwent;
11731    uid_t uid = getuid();
11732    if( (pwent=getpwuid(uid)) != NULL) {
11733      home_dir = pwent->pw_dir;
11734    }
11735  }
11736#endif
11737
11738#if defined(_WIN32_WCE)
11739  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
11740   */
11741  home_dir = "/";
11742#else
11743
11744#if defined(_WIN32) || defined(WIN32)
11745  if (!home_dir) {
11746    home_dir = getenv("USERPROFILE");
11747  }
11748#endif
11749
11750  if (!home_dir) {
11751    home_dir = getenv("HOME");
11752  }
11753
11754#if defined(_WIN32) || defined(WIN32)
11755  if (!home_dir) {
11756    char *zDrive, *zPath;
11757    int n;
11758    zDrive = getenv("HOMEDRIVE");
11759    zPath = getenv("HOMEPATH");
11760    if( zDrive && zPath ){
11761      n = strlen30(zDrive) + strlen30(zPath) + 1;
11762      home_dir = malloc( n );
11763      if( home_dir==0 ) return 0;
11764      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
11765      return home_dir;
11766    }
11767    home_dir = "c:\\";
11768  }
11769#endif
11770
11771#endif /* !_WIN32_WCE */
11772
11773  if( home_dir ){
11774    int n = strlen30(home_dir) + 1;
11775    char *z = malloc( n );
11776    if( z ) memcpy(z, home_dir, n);
11777    home_dir = z;
11778  }
11779
11780  return home_dir;
11781}
11782
11783/*
11784** Read input from the file given by sqliterc_override.  Or if that
11785** parameter is NULL, take input from ~/.sqliterc
11786**
11787** Returns the number of errors.
11788*/
11789static void process_sqliterc(
11790  ShellState *p,                  /* Configuration data */
11791  const char *sqliterc_override   /* Name of config file. NULL to use default */
11792){
11793  char *home_dir = NULL;
11794  const char *sqliterc = sqliterc_override;
11795  char *zBuf = 0;
11796  FILE *inSaved = p->in;
11797  int savedLineno = p->lineno;
11798
11799  if (sqliterc == NULL) {
11800    home_dir = find_home_dir(0);
11801    if( home_dir==0 ){
11802      raw_printf(stderr, "-- warning: cannot find home directory;"
11803                      " cannot read ~/.sqliterc\n");
11804      return;
11805    }
11806    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
11807    shell_check_oom(zBuf);
11808    sqliterc = zBuf;
11809  }
11810  p->in = fopen(sqliterc,"rb");
11811  if( p->in ){
11812    if( stdin_is_interactive ){
11813      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
11814    }
11815    if( process_input(p) && bail_on_error ) exit(1);
11816    fclose(p->in);
11817  }else if( sqliterc_override!=0 ){
11818    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
11819    if( bail_on_error ) exit(1);
11820  }
11821  p->in = inSaved;
11822  p->lineno = savedLineno;
11823  sqlite3_free(zBuf);
11824}
11825
11826/*
11827** Show available command line options
11828*/
11829static const char zOptions[] =
11830#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
11831  "   -A ARGS...           run \".archive ARGS\" and exit\n"
11832#endif
11833  "   -append              append the database to the end of the file\n"
11834  "   -ascii               set output mode to 'ascii'\n"
11835  "   -bail                stop after hitting an error\n"
11836  "   -batch               force batch I/O\n"
11837  "   -box                 set output mode to 'box'\n"
11838  "   -column              set output mode to 'column'\n"
11839  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
11840  "   -csv                 set output mode to 'csv'\n"
11841#if !defined(SQLITE_OMIT_DESERIALIZE)
11842  "   -deserialize         open the database using sqlite3_deserialize()\n"
11843#endif
11844  "   -echo                print inputs before execution\n"
11845  "   -init FILENAME       read/process named file\n"
11846  "   -[no]header          turn headers on or off\n"
11847#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
11848  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
11849#endif
11850  "   -help                show this message\n"
11851  "   -html                set output mode to HTML\n"
11852  "   -interactive         force interactive I/O\n"
11853  "   -json                set output mode to 'json'\n"
11854  "   -line                set output mode to 'line'\n"
11855  "   -list                set output mode to 'list'\n"
11856  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
11857  "   -markdown            set output mode to 'markdown'\n"
11858#if !defined(SQLITE_OMIT_DESERIALIZE)
11859  "   -maxsize N           maximum size for a --deserialize database\n"
11860#endif
11861  "   -memtrace            trace all memory allocations and deallocations\n"
11862  "   -mmap N              default mmap size set to N\n"
11863#ifdef SQLITE_ENABLE_MULTIPLEX
11864  "   -multiplex           enable the multiplexor VFS\n"
11865#endif
11866  "   -newline SEP         set output row separator. Default: '\\n'\n"
11867  "   -nofollow            refuse to open symbolic links to database files\n"
11868  "   -nonce STRING        set the safe-mode escape nonce\n"
11869  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
11870  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
11871  "   -quote               set output mode to 'quote'\n"
11872  "   -readonly            open the database read-only\n"
11873  "   -safe                enable safe-mode\n"
11874  "   -separator SEP       set output column separator. Default: '|'\n"
11875#ifdef SQLITE_ENABLE_SORTER_REFERENCES
11876  "   -sorterref SIZE      sorter references threshold size\n"
11877#endif
11878  "   -stats               print memory stats before each finalize\n"
11879  "   -table               set output mode to 'table'\n"
11880  "   -tabs                set output mode to 'tabs'\n"
11881  "   -version             show SQLite version\n"
11882  "   -vfs NAME            use NAME as the default VFS\n"
11883#ifdef SQLITE_ENABLE_VFSTRACE
11884  "   -vfstrace            enable tracing of all VFS calls\n"
11885#endif
11886#ifdef SQLITE_HAVE_ZLIB
11887  "   -zip                 open the file as a ZIP Archive\n"
11888#endif
11889;
11890static void usage(int showDetail){
11891  utf8_printf(stderr,
11892      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
11893      "FILENAME is the name of an SQLite database. A new database is created\n"
11894      "if the file does not previously exist.\n", Argv0);
11895  if( showDetail ){
11896    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
11897  }else{
11898    raw_printf(stderr, "Use the -help option for additional information\n");
11899  }
11900  exit(1);
11901}
11902
11903/*
11904** Internal check:  Verify that the SQLite is uninitialized.  Print a
11905** error message if it is initialized.
11906*/
11907static void verify_uninitialized(void){
11908  if( sqlite3_config(-1)==SQLITE_MISUSE ){
11909    utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
11910                        " initialization.\n");
11911  }
11912}
11913
11914/*
11915** Initialize the state information in data
11916*/
11917static void main_init(ShellState *data) {
11918  memset(data, 0, sizeof(*data));
11919  data->normalMode = data->cMode = data->mode = MODE_List;
11920  data->autoExplain = 1;
11921  data->pAuxDb = &data->aAuxDb[0];
11922  memcpy(data->colSeparator,SEP_Column, 2);
11923  memcpy(data->rowSeparator,SEP_Row, 2);
11924  data->showHeader = 0;
11925  data->shellFlgs = SHFLG_Lookaside;
11926  verify_uninitialized();
11927  sqlite3_config(SQLITE_CONFIG_URI, 1);
11928  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
11929  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
11930  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
11931  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
11932}
11933
11934/*
11935** Output text to the console in a font that attracts extra attention.
11936*/
11937#ifdef _WIN32
11938static void printBold(const char *zText){
11939#if !SQLITE_OS_WINRT
11940  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
11941  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
11942  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
11943  SetConsoleTextAttribute(out,
11944         FOREGROUND_RED|FOREGROUND_INTENSITY
11945  );
11946#endif
11947  printf("%s", zText);
11948#if !SQLITE_OS_WINRT
11949  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
11950#endif
11951}
11952#else
11953static void printBold(const char *zText){
11954  printf("\033[1m%s\033[0m", zText);
11955}
11956#endif
11957
11958/*
11959** Get the argument to an --option.  Throw an error and die if no argument
11960** is available.
11961*/
11962static char *cmdline_option_value(int argc, char **argv, int i){
11963  if( i==argc ){
11964    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
11965            argv[0], argv[argc-1]);
11966    exit(1);
11967  }
11968  return argv[i];
11969}
11970
11971#ifndef SQLITE_SHELL_IS_UTF8
11972#  if (defined(_WIN32) || defined(WIN32)) \
11973   && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__)))
11974#    define SQLITE_SHELL_IS_UTF8          (0)
11975#  else
11976#    define SQLITE_SHELL_IS_UTF8          (1)
11977#  endif
11978#endif
11979
11980#ifdef SQLITE_SHELL_FIDDLE
11981#  define main fiddle_main
11982#endif
11983
11984#if SQLITE_SHELL_IS_UTF8
11985int SQLITE_CDECL main(int argc, char **argv){
11986#else
11987int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
11988  char **argv;
11989#endif
11990#ifdef SQLITE_DEBUG
11991  sqlite3_int64 mem_main_enter = sqlite3_memory_used();
11992#endif
11993  char *zErrMsg = 0;
11994#ifdef SQLITE_SHELL_FIDDLE
11995#  define data shellState
11996#else
11997  ShellState data;
11998#endif
11999  const char *zInitFile = 0;
12000  int i;
12001  int rc = 0;
12002  int warnInmemoryDb = 0;
12003  int readStdin = 1;
12004  int nCmd = 0;
12005  char **azCmd = 0;
12006  const char *zVfs = 0;           /* Value of -vfs command-line option */
12007#if !SQLITE_SHELL_IS_UTF8
12008  char **argvToFree = 0;
12009  int argcToFree = 0;
12010#endif
12011
12012  setBinaryMode(stdin, 0);
12013  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
12014#ifdef SQLITE_SHELL_FIDDLE
12015  stdin_is_interactive = 0;
12016  stdout_is_console = 1;
12017#else
12018  stdin_is_interactive = isatty(0);
12019  stdout_is_console = isatty(1);
12020#endif
12021
12022#if !defined(_WIN32_WCE)
12023  if( getenv("SQLITE_DEBUG_BREAK") ){
12024    if( isatty(0) && isatty(2) ){
12025      fprintf(stderr,
12026          "attach debugger to process %d and press any key to continue.\n",
12027          GETPID());
12028      fgetc(stdin);
12029    }else{
12030#if defined(_WIN32) || defined(WIN32)
12031#if SQLITE_OS_WINRT
12032      __debugbreak();
12033#else
12034      DebugBreak();
12035#endif
12036#elif defined(SIGTRAP)
12037      raise(SIGTRAP);
12038#endif
12039    }
12040  }
12041#endif
12042
12043#if USE_SYSTEM_SQLITE+0!=1
12044  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
12045    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
12046            sqlite3_sourceid(), SQLITE_SOURCE_ID);
12047    exit(1);
12048  }
12049#endif
12050  main_init(&data);
12051
12052  /* On Windows, we must translate command-line arguments into UTF-8.
12053  ** The SQLite memory allocator subsystem has to be enabled in order to
12054  ** do this.  But we want to run an sqlite3_shutdown() afterwards so that
12055  ** subsequent sqlite3_config() calls will work.  So copy all results into
12056  ** memory that does not come from the SQLite memory allocator.
12057  */
12058#if !SQLITE_SHELL_IS_UTF8
12059  sqlite3_initialize();
12060  argvToFree = malloc(sizeof(argv[0])*argc*2);
12061  shell_check_oom(argvToFree);
12062  argcToFree = argc;
12063  argv = argvToFree + argc;
12064  for(i=0; i<argc; i++){
12065    char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
12066    int n;
12067    shell_check_oom(z);
12068    n = (int)strlen(z);
12069    argv[i] = malloc( n+1 );
12070    shell_check_oom(argv[i]);
12071    memcpy(argv[i], z, n+1);
12072    argvToFree[i] = argv[i];
12073    sqlite3_free(z);
12074  }
12075  sqlite3_shutdown();
12076#endif
12077
12078  assert( argc>=1 && argv && argv[0] );
12079  Argv0 = argv[0];
12080
12081  /* Make sure we have a valid signal handler early, before anything
12082  ** else is done.
12083  */
12084#ifdef SIGINT
12085  signal(SIGINT, interrupt_handler);
12086#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
12087  SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
12088#endif
12089
12090#ifdef SQLITE_SHELL_DBNAME_PROC
12091  {
12092    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
12093    ** of a C-function that will provide the name of the database file.  Use
12094    ** this compile-time option to embed this shell program in larger
12095    ** applications. */
12096    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
12097    SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename);
12098    warnInmemoryDb = 0;
12099  }
12100#endif
12101
12102  /* Do an initial pass through the command-line argument to locate
12103  ** the name of the database file, the name of the initialization file,
12104  ** the size of the alternative malloc heap,
12105  ** and the first command to execute.
12106  */
12107  verify_uninitialized();
12108  for(i=1; i<argc; i++){
12109    char *z;
12110    z = argv[i];
12111    if( z[0]!='-' ){
12112      if( data.aAuxDb->zDbFilename==0 ){
12113        data.aAuxDb->zDbFilename = z;
12114      }else{
12115        /* Excesss arguments are interpreted as SQL (or dot-commands) and
12116        ** mean that nothing is read from stdin */
12117        readStdin = 0;
12118        nCmd++;
12119        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
12120        shell_check_oom(azCmd);
12121        azCmd[nCmd-1] = z;
12122      }
12123    }
12124    if( z[1]=='-' ) z++;
12125    if( strcmp(z,"-separator")==0
12126     || strcmp(z,"-nullvalue")==0
12127     || strcmp(z,"-newline")==0
12128     || strcmp(z,"-cmd")==0
12129    ){
12130      (void)cmdline_option_value(argc, argv, ++i);
12131    }else if( strcmp(z,"-init")==0 ){
12132      zInitFile = cmdline_option_value(argc, argv, ++i);
12133    }else if( strcmp(z,"-batch")==0 ){
12134      /* Need to check for batch mode here to so we can avoid printing
12135      ** informational messages (like from process_sqliterc) before
12136      ** we do the actual processing of arguments later in a second pass.
12137      */
12138      stdin_is_interactive = 0;
12139    }else if( strcmp(z,"-heap")==0 ){
12140#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
12141      const char *zSize;
12142      sqlite3_int64 szHeap;
12143
12144      zSize = cmdline_option_value(argc, argv, ++i);
12145      szHeap = integerValue(zSize);
12146      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
12147      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
12148#else
12149      (void)cmdline_option_value(argc, argv, ++i);
12150#endif
12151    }else if( strcmp(z,"-pagecache")==0 ){
12152      sqlite3_int64 n, sz;
12153      sz = integerValue(cmdline_option_value(argc,argv,++i));
12154      if( sz>70000 ) sz = 70000;
12155      if( sz<0 ) sz = 0;
12156      n = integerValue(cmdline_option_value(argc,argv,++i));
12157      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
12158        n = 0xffffffffffffLL/sz;
12159      }
12160      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
12161                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
12162      data.shellFlgs |= SHFLG_Pagecache;
12163    }else if( strcmp(z,"-lookaside")==0 ){
12164      int n, sz;
12165      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
12166      if( sz<0 ) sz = 0;
12167      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12168      if( n<0 ) n = 0;
12169      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
12170      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
12171    }else if( strcmp(z,"-threadsafe")==0 ){
12172      int n;
12173      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
12174      switch( n ){
12175         case 0:  sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);  break;
12176         case 2:  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);   break;
12177         default: sqlite3_config(SQLITE_CONFIG_SERIALIZED);    break;
12178      }
12179#ifdef SQLITE_ENABLE_VFSTRACE
12180    }else if( strcmp(z,"-vfstrace")==0 ){
12181      extern int vfstrace_register(
12182         const char *zTraceName,
12183         const char *zOldVfsName,
12184         int (*xOut)(const char*,void*),
12185         void *pOutArg,
12186         int makeDefault
12187      );
12188      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
12189#endif
12190#ifdef SQLITE_ENABLE_MULTIPLEX
12191    }else if( strcmp(z,"-multiplex")==0 ){
12192      extern int sqlite3_multiple_initialize(const char*,int);
12193      sqlite3_multiplex_initialize(0, 1);
12194#endif
12195    }else if( strcmp(z,"-mmap")==0 ){
12196      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12197      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
12198#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12199    }else if( strcmp(z,"-sorterref")==0 ){
12200      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
12201      sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
12202#endif
12203    }else if( strcmp(z,"-vfs")==0 ){
12204      zVfs = cmdline_option_value(argc, argv, ++i);
12205#ifdef SQLITE_HAVE_ZLIB
12206    }else if( strcmp(z,"-zip")==0 ){
12207      data.openMode = SHELL_OPEN_ZIPFILE;
12208#endif
12209    }else if( strcmp(z,"-append")==0 ){
12210      data.openMode = SHELL_OPEN_APPENDVFS;
12211#ifndef SQLITE_OMIT_DESERIALIZE
12212    }else if( strcmp(z,"-deserialize")==0 ){
12213      data.openMode = SHELL_OPEN_DESERIALIZE;
12214    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12215      data.szMax = integerValue(argv[++i]);
12216#endif
12217    }else if( strcmp(z,"-readonly")==0 ){
12218      data.openMode = SHELL_OPEN_READONLY;
12219    }else if( strcmp(z,"-nofollow")==0 ){
12220      data.openFlags = SQLITE_OPEN_NOFOLLOW;
12221#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12222    }else if( strncmp(z, "-A",2)==0 ){
12223      /* All remaining command-line arguments are passed to the ".archive"
12224      ** command, so ignore them */
12225      break;
12226#endif
12227    }else if( strcmp(z, "-memtrace")==0 ){
12228      sqlite3MemTraceActivate(stderr);
12229    }else if( strcmp(z,"-bail")==0 ){
12230      bail_on_error = 1;
12231    }else if( strcmp(z,"-nonce")==0 ){
12232      free(data.zNonce);
12233      data.zNonce = strdup(argv[++i]);
12234    }else if( strcmp(z,"-safe")==0 ){
12235      /* no-op - catch this on the second pass */
12236    }
12237  }
12238  verify_uninitialized();
12239
12240
12241#ifdef SQLITE_SHELL_INIT_PROC
12242  {
12243    /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
12244    ** of a C-function that will perform initialization actions on SQLite that
12245    ** occur just before or after sqlite3_initialize(). Use this compile-time
12246    ** option to embed this shell program in larger applications. */
12247    extern void SQLITE_SHELL_INIT_PROC(void);
12248    SQLITE_SHELL_INIT_PROC();
12249  }
12250#else
12251  /* All the sqlite3_config() calls have now been made. So it is safe
12252  ** to call sqlite3_initialize() and process any command line -vfs option. */
12253  sqlite3_initialize();
12254#endif
12255
12256  if( zVfs ){
12257    sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
12258    if( pVfs ){
12259      sqlite3_vfs_register(pVfs, 1);
12260    }else{
12261      utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
12262      exit(1);
12263    }
12264  }
12265
12266  if( data.pAuxDb->zDbFilename==0 ){
12267#ifndef SQLITE_OMIT_MEMORYDB
12268    data.pAuxDb->zDbFilename = ":memory:";
12269    warnInmemoryDb = argc==1;
12270#else
12271    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
12272    return 1;
12273#endif
12274  }
12275  data.out = stdout;
12276#ifndef SQLITE_SHELL_FIDDLE
12277  sqlite3_appendvfs_init(0,0,0);
12278#endif
12279
12280  /* Go ahead and open the database file if it already exists.  If the
12281  ** file does not exist, delay opening it.  This prevents empty database
12282  ** files from being created if a user mistypes the database name argument
12283  ** to the sqlite command-line tool.
12284  */
12285  if( access(data.pAuxDb->zDbFilename, 0)==0 ){
12286    open_db(&data, 0);
12287  }
12288
12289  /* Process the initialization file if there is one.  If no -init option
12290  ** is given on the command line, look for a file named ~/.sqliterc and
12291  ** try to process it.
12292  */
12293  process_sqliterc(&data,zInitFile);
12294
12295  /* Make a second pass through the command-line argument and set
12296  ** options.  This second pass is delayed until after the initialization
12297  ** file is processed so that the command-line arguments will override
12298  ** settings in the initialization file.
12299  */
12300  for(i=1; i<argc; i++){
12301    char *z = argv[i];
12302    if( z[0]!='-' ) continue;
12303    if( z[1]=='-' ){ z++; }
12304    if( strcmp(z,"-init")==0 ){
12305      i++;
12306    }else if( strcmp(z,"-html")==0 ){
12307      data.mode = MODE_Html;
12308    }else if( strcmp(z,"-list")==0 ){
12309      data.mode = MODE_List;
12310    }else if( strcmp(z,"-quote")==0 ){
12311      data.mode = MODE_Quote;
12312      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
12313      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12314    }else if( strcmp(z,"-line")==0 ){
12315      data.mode = MODE_Line;
12316    }else if( strcmp(z,"-column")==0 ){
12317      data.mode = MODE_Column;
12318    }else if( strcmp(z,"-json")==0 ){
12319      data.mode = MODE_Json;
12320    }else if( strcmp(z,"-markdown")==0 ){
12321      data.mode = MODE_Markdown;
12322    }else if( strcmp(z,"-table")==0 ){
12323      data.mode = MODE_Table;
12324    }else if( strcmp(z,"-box")==0 ){
12325      data.mode = MODE_Box;
12326    }else if( strcmp(z,"-csv")==0 ){
12327      data.mode = MODE_Csv;
12328      memcpy(data.colSeparator,",",2);
12329#ifdef SQLITE_HAVE_ZLIB
12330    }else if( strcmp(z,"-zip")==0 ){
12331      data.openMode = SHELL_OPEN_ZIPFILE;
12332#endif
12333    }else if( strcmp(z,"-append")==0 ){
12334      data.openMode = SHELL_OPEN_APPENDVFS;
12335#ifndef SQLITE_OMIT_DESERIALIZE
12336    }else if( strcmp(z,"-deserialize")==0 ){
12337      data.openMode = SHELL_OPEN_DESERIALIZE;
12338    }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
12339      data.szMax = integerValue(argv[++i]);
12340#endif
12341    }else if( strcmp(z,"-readonly")==0 ){
12342      data.openMode = SHELL_OPEN_READONLY;
12343    }else if( strcmp(z,"-nofollow")==0 ){
12344      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
12345    }else if( strcmp(z,"-ascii")==0 ){
12346      data.mode = MODE_Ascii;
12347      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
12348      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
12349    }else if( strcmp(z,"-tabs")==0 ){
12350      data.mode = MODE_List;
12351      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
12352      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
12353    }else if( strcmp(z,"-separator")==0 ){
12354      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
12355                       "%s",cmdline_option_value(argc,argv,++i));
12356    }else if( strcmp(z,"-newline")==0 ){
12357      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
12358                       "%s",cmdline_option_value(argc,argv,++i));
12359    }else if( strcmp(z,"-nullvalue")==0 ){
12360      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
12361                       "%s",cmdline_option_value(argc,argv,++i));
12362    }else if( strcmp(z,"-header")==0 ){
12363      data.showHeader = 1;
12364      ShellSetFlag(&data, SHFLG_HeaderSet);
12365     }else if( strcmp(z,"-noheader")==0 ){
12366      data.showHeader = 0;
12367      ShellSetFlag(&data, SHFLG_HeaderSet);
12368    }else if( strcmp(z,"-echo")==0 ){
12369      ShellSetFlag(&data, SHFLG_Echo);
12370    }else if( strcmp(z,"-eqp")==0 ){
12371      data.autoEQP = AUTOEQP_on;
12372    }else if( strcmp(z,"-eqpfull")==0 ){
12373      data.autoEQP = AUTOEQP_full;
12374    }else if( strcmp(z,"-stats")==0 ){
12375      data.statsOn = 1;
12376    }else if( strcmp(z,"-scanstats")==0 ){
12377      data.scanstatsOn = 1;
12378    }else if( strcmp(z,"-backslash")==0 ){
12379      /* Undocumented command-line option: -backslash
12380      ** Causes C-style backslash escapes to be evaluated in SQL statements
12381      ** prior to sending the SQL into SQLite.  Useful for injecting
12382      ** crazy bytes in the middle of SQL statements for testing and debugging.
12383      */
12384      ShellSetFlag(&data, SHFLG_Backslash);
12385    }else if( strcmp(z,"-bail")==0 ){
12386      /* No-op.  The bail_on_error flag should already be set. */
12387    }else if( strcmp(z,"-version")==0 ){
12388      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
12389      return 0;
12390    }else if( strcmp(z,"-interactive")==0 ){
12391      stdin_is_interactive = 1;
12392    }else if( strcmp(z,"-batch")==0 ){
12393      stdin_is_interactive = 0;
12394    }else if( strcmp(z,"-heap")==0 ){
12395      i++;
12396    }else if( strcmp(z,"-pagecache")==0 ){
12397      i+=2;
12398    }else if( strcmp(z,"-lookaside")==0 ){
12399      i+=2;
12400    }else if( strcmp(z,"-threadsafe")==0 ){
12401      i+=2;
12402    }else if( strcmp(z,"-nonce")==0 ){
12403      i += 2;
12404    }else if( strcmp(z,"-mmap")==0 ){
12405      i++;
12406    }else if( strcmp(z,"-memtrace")==0 ){
12407      i++;
12408#ifdef SQLITE_ENABLE_SORTER_REFERENCES
12409    }else if( strcmp(z,"-sorterref")==0 ){
12410      i++;
12411#endif
12412    }else if( strcmp(z,"-vfs")==0 ){
12413      i++;
12414#ifdef SQLITE_ENABLE_VFSTRACE
12415    }else if( strcmp(z,"-vfstrace")==0 ){
12416      i++;
12417#endif
12418#ifdef SQLITE_ENABLE_MULTIPLEX
12419    }else if( strcmp(z,"-multiplex")==0 ){
12420      i++;
12421#endif
12422    }else if( strcmp(z,"-help")==0 ){
12423      usage(1);
12424    }else if( strcmp(z,"-cmd")==0 ){
12425      /* Run commands that follow -cmd first and separately from commands
12426      ** that simply appear on the command-line.  This seems goofy.  It would
12427      ** be better if all commands ran in the order that they appear.  But
12428      ** we retain the goofy behavior for historical compatibility. */
12429      if( i==argc-1 ) break;
12430      z = cmdline_option_value(argc,argv,++i);
12431      if( z[0]=='.' ){
12432        rc = do_meta_command(z, &data);
12433        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
12434      }else{
12435        open_db(&data, 0);
12436        rc = shell_exec(&data, z, &zErrMsg);
12437        if( zErrMsg!=0 ){
12438          utf8_printf(stderr,"Error: %s\n", zErrMsg);
12439          if( bail_on_error ) return rc!=0 ? rc : 1;
12440        }else if( rc!=0 ){
12441          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
12442          if( bail_on_error ) return rc;
12443        }
12444      }
12445#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12446    }else if( strncmp(z, "-A", 2)==0 ){
12447      if( nCmd>0 ){
12448        utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
12449                            " with \"%s\"\n", z);
12450        return 1;
12451      }
12452      open_db(&data, OPEN_DB_ZIPFILE);
12453      if( z[2] ){
12454        argv[i] = &z[2];
12455        arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
12456      }else{
12457        arDotCommand(&data, 1, argv+i, argc-i);
12458      }
12459      readStdin = 0;
12460      break;
12461#endif
12462    }else if( strcmp(z,"-safe")==0 ){
12463      data.bSafeMode = data.bSafeModePersist = 1;
12464    }else{
12465      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
12466      raw_printf(stderr,"Use -help for a list of options.\n");
12467      return 1;
12468    }
12469    data.cMode = data.mode;
12470  }
12471
12472  if( !readStdin ){
12473    /* Run all arguments that do not begin with '-' as if they were separate
12474    ** command-line inputs, except for the argToSkip argument which contains
12475    ** the database filename.
12476    */
12477    for(i=0; i<nCmd; i++){
12478      if( azCmd[i][0]=='.' ){
12479        rc = do_meta_command(azCmd[i], &data);
12480        if( rc ){
12481          free(azCmd);
12482          return rc==2 ? 0 : rc;
12483        }
12484      }else{
12485        open_db(&data, 0);
12486        rc = shell_exec(&data, azCmd[i], &zErrMsg);
12487        if( zErrMsg || rc ){
12488          if( zErrMsg!=0 ){
12489            utf8_printf(stderr,"Error: %s\n", zErrMsg);
12490          }else{
12491            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
12492          }
12493          sqlite3_free(zErrMsg);
12494          free(azCmd);
12495          return rc!=0 ? rc : 1;
12496        }
12497      }
12498    }
12499  }else{
12500    /* Run commands received from standard input
12501    */
12502    if( stdin_is_interactive ){
12503      char *zHome;
12504      char *zHistory;
12505      int nHistory;
12506      printf(
12507        "SQLite version %s %.19s\n" /*extra-version-info*/
12508        "Enter \".help\" for usage hints.\n",
12509        sqlite3_libversion(), sqlite3_sourceid()
12510      );
12511      if( warnInmemoryDb ){
12512        printf("Connected to a ");
12513        printBold("transient in-memory database");
12514        printf(".\nUse \".open FILENAME\" to reopen on a "
12515               "persistent database.\n");
12516      }
12517      zHistory = getenv("SQLITE_HISTORY");
12518      if( zHistory ){
12519        zHistory = strdup(zHistory);
12520      }else if( (zHome = find_home_dir(0))!=0 ){
12521        nHistory = strlen30(zHome) + 20;
12522        if( (zHistory = malloc(nHistory))!=0 ){
12523          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
12524        }
12525      }
12526      if( zHistory ){ shell_read_history(zHistory); }
12527#if HAVE_READLINE || HAVE_EDITLINE
12528      rl_attempted_completion_function = readline_completion;
12529#elif HAVE_LINENOISE
12530      linenoiseSetCompletionCallback(linenoise_completion);
12531#endif
12532      data.in = 0;
12533      rc = process_input(&data);
12534      if( zHistory ){
12535        shell_stifle_history(2000);
12536        shell_write_history(zHistory);
12537        free(zHistory);
12538      }
12539    }else{
12540      data.in = stdin;
12541      rc = process_input(&data);
12542    }
12543  }
12544#ifndef SQLITE_SHELL_FIDDLE
12545  /* In WASM mode we have to leave the db state in place so that
12546  ** client code can "push" SQL into it after this call returns. */
12547  free(azCmd);
12548  set_table_name(&data, 0);
12549  if( data.db ){
12550    session_close_all(&data, -1);
12551    close_db(data.db);
12552  }
12553  for(i=0; i<ArraySize(data.aAuxDb); i++){
12554    sqlite3_free(data.aAuxDb[i].zFreeOnClose);
12555    if( data.aAuxDb[i].db ){
12556      session_close_all(&data, i);
12557      close_db(data.aAuxDb[i].db);
12558    }
12559  }
12560  find_home_dir(1);
12561  output_reset(&data);
12562  data.doXdgOpen = 0;
12563  clearTempFile(&data);
12564#if !SQLITE_SHELL_IS_UTF8
12565  for(i=0; i<argcToFree; i++) free(argvToFree[i]);
12566  free(argvToFree);
12567#endif
12568  free(data.colWidth);
12569  free(data.zNonce);
12570  /* Clear the global data structure so that valgrind will detect memory
12571  ** leaks */
12572  memset(&data, 0, sizeof(data));
12573#ifdef SQLITE_DEBUG
12574  if( sqlite3_memory_used()>mem_main_enter ){
12575    utf8_printf(stderr, "Memory leaked: %u bytes\n",
12576                (unsigned int)(sqlite3_memory_used()-mem_main_enter));
12577  }
12578#endif
12579#endif /* !SQLITE_SHELL_FIDDLE */
12580  return rc;
12581}
12582
12583
12584#ifdef SQLITE_SHELL_FIDDLE
12585/* Only for emcc experimentation purposes. */
12586int fiddle_experiment(int a,int b){
12587   return a + b;
12588}
12589
12590/* Only for emcc experimentation purposes.
12591
12592  Define this function in JS using:
12593
12594  emcc ... --js-library somefile.js
12595
12596  containing:
12597
12598mergeInto(LibraryManager.library, {
12599    my_foo: function(){
12600        console.debug("my_foo()",arguments);
12601    }
12602});
12603*/
12604/*extern void my_foo(sqlite3 *);*/
12605/* Only for emcc experimentation purposes. */
12606sqlite3 * fiddle_the_db(){
12607    printf("fiddle_the_db(%p)\n", (const void*)globalDb);
12608    /*my_foo(globalDb);*/
12609    return globalDb;
12610}
12611/* Only for emcc experimentation purposes. */
12612sqlite3 * fiddle_db_arg(sqlite3 *arg){
12613    printf("fiddle_db_arg(%p)\n", (const void*)arg);
12614    return arg;
12615}
12616
12617/*
12618** Intended to be called via a SharedWorker() while a separate
12619** SharedWorker() (which manages the wasm module) is performing work
12620** which should be interrupted. Unfortunately, SharedWorker is not
12621** portable enough to make real use of.
12622*/
12623void fiddle_interrupt(void){
12624  if(globalDb) sqlite3_interrupt(globalDb);
12625}
12626
12627/*
12628** Returns the filename of the given db name, assuming "main" if
12629** zDbName is NULL. Returns NULL if globalDb is not opened.
12630*/
12631const char * fiddle_db_filename(const char * zDbName){
12632    return globalDb
12633      ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main")
12634      : NULL;
12635}
12636
12637/*
12638** Closes, unlinks, and reopens the db using its current filename (or
12639** the default if the db is currently closed). It is assumed, for
12640** purposes of the fiddle build, that the file is in a transient
12641** virtual filesystem within the browser.
12642*/
12643void fiddle_reset_db(void){
12644  char *zFilename = 0;
12645  if(0==globalDb){
12646    shellState.pAuxDb->zDbFilename = "/fiddle.sqlite3";
12647  }else{
12648    zFilename =
12649      sqlite3_mprintf("%s", sqlite3_db_filename(globalDb, "main"));
12650    shell_check_oom(zFilename);
12651    close_db(globalDb);
12652    shellDeleteFile(zFilename);
12653    shellState.db = 0;
12654    shellState.pAuxDb->zDbFilename = zFilename;
12655  }
12656  open_db(&shellState, 0);
12657  sqlite3_free(zFilename);
12658}
12659
12660/*
12661** Trivial exportable function for emscripten. Needs to be exported using:
12662**
12663** emcc ..flags... -sEXPORTED_FUNCTIONS=_fiddle_exec -sEXPORTED_RUNTIME_METHODS=ccall,cwrap
12664**
12665** (Note the underscore before the function name.) It processes zSql
12666** as if it were input to the sqlite3 shell and redirects all output
12667** to the wasm binding.
12668*/
12669void fiddle_exec(const char * zSql){
12670  static int once = 0;
12671  int rc = 0;
12672  if(!once){
12673    /* Simulate an argv array for main() */
12674    static char * argv[] = {"fiddle",
12675                            "-bail",
12676                            "-safe"};
12677    rc = fiddle_main((int)(sizeof(argv)/sizeof(argv[0])), argv);
12678    once = rc ? -1 : 1;
12679    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12680    printf(
12681        "SQLite version %s %.19s\n" /*extra-version-info*/,
12682        sqlite3_libversion(), sqlite3_sourceid()
12683    );
12684    puts("WASM shell");
12685    puts("Enter \".help\" for usage hints.");
12686    if(once>0){
12687      fiddle_reset_db();
12688    }
12689    if(shellState.db){
12690      printf("Connected to %s.\n", fiddle_db_filename(NULL));
12691    }else{
12692      fprintf(stderr,"ERROR initializing db!\n");
12693      return;
12694    }
12695  }
12696  if(once<0){
12697    puts("DB init failed. Not executing SQL.");
12698  }else if(zSql && *zSql){
12699    shellState.wasm.zInput = zSql;
12700    shellState.wasm.zPos = zSql;
12701    process_input(&shellState);
12702    memset(&shellState.wasm, 0, sizeof(shellState.wasm));
12703  }
12704}
12705#endif /* SQLITE_SHELL_FIDDLE */
12706